Dokumentation · Beregningerne
The sources: the grid's mix in the hours of the consumption (B58)
The rules of docs/architecture/phase-2.md §3.3, once in SQL (the functions of migration 0270_mix, step 2 by families
since 0315_mix_fossil_split, B78, the geographic split since 0350_municipal_sources, B87) and once in
Python (elo_core.mix, the reference a reviewer reads). The sources of a selection are, by the geographic split
(docs/architecture/municipality-method.md §2.4), the rows of DeclarationGridmix (split "Prisområde", fx.mix_hour
dataset 1, B53) or of DeclarationTransmissionGridmix (split "Kommune", dataset 2, B82, after the municipal part: "The
municipal split" below) for each UTC hour and the metering point's price area on that local day,
applied to the E01 of that hour, and only for hours whose mix is complete. Nothing is stored (phase-2.md ruling 5): every
figure is computed from ts.reading, core.mp_geo, fx.mix_hour, ref.mix_group and ref.mix_code (and under the
municipal split fx.re_coverage_hour and the roots' municipalities) when it is asked for, so a reloaded hour changes the
next query's result.
The sources are the third calculation of one shape, after the emission (docs/emission.md) and the cost
(docs/cost.md): an input per hour that can be missing (here: a complete mix), a like-for-like comparison over matched
hour cells, the counts h and H and what was left out, the status shares. The mix is location-based and has no
allocation method (R2 §2.2.4): one calculation for every allocation, by the method's geography (price_area for
LB-PA-125 and LB-PA-200, municipality for LB-MU-125): the parameter is p_geo, price_area by default, and
every answer under it is what it was before B87, value for value.
services/api/tests/test_mix.py is the guarantee that SQL and Python agree to the last decimal (the same value
written with the same number of decimals): on the golden cases below and on the demo organisation (B53's generated
extract) over periods, grains, both bases, both kinds of part, every kind of comparison and selections, in session time
zones that must not matter. libs/core/tests/test_mix_reference.py asserts every golden case on the reference alone.
Units, scales, and where a figure is rounded
Energy in kWh. No binary float anywhere between a stored value and a result.
| Figure | Scale (decimals) | Why |
|---|---|---|
| The consumption of an hour, a bucket, a period | 3 | ts.reading.quantity is numeric(15,3); a sum keeps the scale |
| A part's energy (a group, a connected area, the municipal part, a municipality) | 9 | step 2: whole units of 10⁻⁹ kWh; the municipal part rounded once per hour (below) |
| E07, E07 + nuclear | 11 | 9 + the 2 of renewable_share (numeric(3,2)) |
| E11a, E11b, a part's share | 9 | one division, rounded once (below) |
Step 2 is computed in integers in both implementations, so that neither chooses a scale: with q the hour's energy
in Wh (q × 1000, a whole number for a sum of readings of three decimals), s the part's Σ share_ppm and S the
hour's, (2 × q × s × 10⁶ + S) div (2 × S) is the number of units of 10⁻⁹ kWh (under the municipal split q is the rest
G, a whole number of 10⁻⁹ kWh, and the formula is (2 × G × s + S) div (2 × S) with G in those units: the same
quotient), the exact quotient q × s ÷ S rounded
half away from zero (on |q|, the sign put back; div truncates, which on a non-negative dividend is the floor the
formula means). The units become kWh by a multiplication by 0.000000001, never by a division. The SQL does this in
numeric, which is exact at any size (for a large selection q × s × 10⁶ passes bigint); Python in int. A test
holds the two to each other and to the exact rational quotient on thousands of values.
The shares (E11a, E11b, a part's share of the consumption) are one division of two exact sums each, rounded once to
9 decimals half away from zero where they are made, as docs/queries.md has it for every ratio: calc.cost_ratio
(B56's, reused rather than restated) and elo_core.footprint.ratio; no figure (i.r.) when the denominator is not above
zero. The variance of a share in percentage points is (share − cmp_share) × 100, the query's (B59): for E11a and E11b
as for a part's share.
The rules, and where each lives
| Step | Rule | SQL | Python |
|---|---|---|---|
| 1 Complete hour | An hour and price area is complete when it has rows, none with a negative share, none with a NULL share or a NULL version (the lead's ruling to B53 of 23 November: the loader stores NULL where the service delivers none), and 999 900 ≤ Σ share_ppm ≤ 1 000 100. Otherwise it is pending (afventer elmix): it contributes consumption and no source. An hour with no row is pending | calc.mix_hours (complete) | complete, MixHour |
| 2 Source energy | Per price area and complete hour, q the selection's energy of the hour (summed first), the integer quotient above for every part. The residual q − Σ parts goes to the hour's largest part (the largest s), the lowest ref.mix_group.sort among equal groups: the parts of an hour sum to q exactly. The groups in two levels (B78): the hour into its families first (ref.mix_group.family: the eight groups of B53, fossil the family of gas and coal_oil; a family's s the Σ of its groups', its order the lowest sort of its groups), the residual to the largest family; then each family into its groups from the smallest up, each q × (its s + the smaller groups' s) ÷ S less q × (the smaller groups' s) ÷ S, so that a family's groups add to its energy and the largest takes its rounding (with two groups: each rounded alone, the remainder to the larger). A family of one group is that group | calc.mix_share; the residual in calc.mix_buckets (part_energy): by origin to the first element of the hour's parts in calc.mix_hours (ordered largest first); by source to the largest family's largest group (top: the largest cumulative share in a family, then the lowest family sort, the largest s, the lowest sort), the first element where every family is one group | share_energy, split, split_groups |
| 3 Groups | A report group code belongs to the group ref.mix_code gives it; a code the table does not know goes to other, counts as not renewable, and is listed by make status. The key is the code, never the name | calc.mix_hours (groups, group_shares) | mix_hour |
| 4 E07 | Σ group energy × the group's renewable_share (wind, solar, hydro, biomass 1; waste 0,55; the rest 0) | calc.mix_buckets (renewable) | _renewable |
| 5 Shares | E11a = E07 ÷ the consumption of the hours in the figures; E11b = (E07 + the energy of the groups with nuclear) ÷ the same. Sum first, divide last | calc.mix_buckets | share |
| 6 Origin | Step 2 with the connected areas in place of the groups; the residual to the largest, the lowest code (byte order) among equals. An area ref.code (list connected_area) does not know keeps its energy under its own code (part_known false) and is listed by make status | calc.mix_hours(…, p_origin => true) (origins, origin_shares) | mix_hour |
| 7 Status and basis | The status of an hour's consumption is the first that applies: no_price_area; pending (no rows, or not complete); otherwise the lowest version of its rows (initial, preliminary, final). An hour is in the figures when it has a price area and a complete mix, and under basis=final also version Final (every row Final). The status does not change with the basis; under basis=final a complete Preliminary hour is outside the figures (counted in pending_kwh and pending_hours) and stays preliminary in the status | calc.mix_buckets (hours) | hour_status, in_basis |
The municipal split (B87; municipality-method.md §2.4 to §2.6)
Under p_geo = 'municipality' (the method LB-MU-125's geography) the steps above hold with these changes, in both
implementations (elo_core.mix with geo="municipality"):
| Step | Rule under the municipal split |
|---|---|
| The rows | fx.mix_hour of dataset 2, DeclarationTransmissionGridmix (calc.mix_hours(…, p_dataset => 2)); the bounds of complete as step 1 |
| In the figures | A metering-point hour is in the figures when it has a price area, a wanted municipality (calc.mp_municipality, docs/emission.md: a usable code the setting wants) with a usable share for the UTC hour (a row of fx.re_coverage_hour, not NULL, 0 to 100) and a complete TM hour, of version Final under basis=final. A share has no version and never decides the basis. A missing share is never 0 %: the hour is pending, outside numerator and denominator, and counted in pending_kwh and pending_hours |
| Status | The first that applies: no_price_area; no_municipality (no usable code, or one the setting leaves out: a state of the install, not pending); pending (no share, or TM not complete); otherwise TM's version |
| The municipal part (before step 2) | Per side, price area and hour, over the point-hours in the figures, L = Σ q_p × R_p × 0.01, exact (11 decimals). The group local "Kommunal vedvarende energi" is L rounded half away from zero to 9 decimals: round(L, 9) in SQL, round_nano in Python, equal to the specification's integer formula (Σ q_Wh × R_micro + 50) div 100 units of 10⁻⁹ kWh on the absolute value (a test holds the two to each other on 5 000 values) |
| Step 2 on the rest | G = q − local in the place of q: families first with the residual to the largest family, then the groups (B78). The municipal part and the nine groups of an hour sum to q exactly, on both signs (both formulas on the absolute value, the sign put back) |
| E07, E11a, E11b | local counts whole in E07 (ref.mix_group.renewable_share 1); the denominator is the consumption of the hours in the figures |
| Origin | local is a part of its own, first (part_sort 0); the connected areas share G by step 6 |
| By municipality | p_by = 'municipality', only under this split: each hour's local divided among the municipalities of its point-hours in the order of their codes, each round₉(Σ L of the codes up to it) − round₉(Σ L of the codes before it), so that they add to local. A part is m1, m2, … (calc.municipality_parts: each municipality of the selection numbered by the lowest mp_id of its roots, never a code); every municipality of the selection is a row, the largest of the period first. part_ac_share is share A (of the selection's consumption in the figures), part_own_share share B (of its own points' consumption in the figures, part_own_kwh) |
ref.mix_group | A tenth row, local, with the new column municipal true: a part only under the municipal split. By price area the nine groups stay nine |
| The comparison | A cell is left out for either input (excluded_mix), as the emission's excluded_factor |
The order of the codes is inside the calculation; no column of any response holds a code. mixSource (any_generated,
any_real) is the mix rows' as before; whether a generated share is counted in it is the queries' (B88, §5: "a generated
share is never Energinet's"; the demo's shares and mix are both generated).
The bounds of "complete" live in two places and are one rule. The calculation's are elo_core.mix.COMPLETE_FROM
and COMPLETE_TO and the BETWEEN 999900 AND 1000100 of calc.mix_hours; make status counts the hours that are not
complete with elo_worker.eds.mix.COMPLETE_FROM, COMPLETE_TO and is_complete (B53, and its SQL in
status.mix_dataset). test_mix.py holds the reference to elo_worker.eds.mix.is_complete on both edges with and
without a negative or a missing share, and the SQL to the reference on the same edges: a change of one that is not made
in the others fails a test.
The price area is the metering point's on the hour's local day (docs/emission.md, "the price area of a day";
calc.price_areas). A quarter takes its hour's rows: it is summed into its UTC hour before the hour meets the mix.
A figure is computed for its selection. The source energy is rounded once per hour on the selection's sum, so the sources of two selections do not add to the ninth decimal. But the sum is per price area, so **a selection in both price areas equals the sum of its two halves** when no hour holds metering points of both halves in one area (a root that moved area is in neither half of a clean split; the test picks the roots whose area is constant over the period).
The wording (for B59 and B63)
The rules are the pages' (§3.3, "The wording"); they are stated here once so that the queries (B59) and the page (B63) read one text. The mix is the price area's, in the hours the consumption lay in; it is nobody's purchase.
| Rule | Text |
|---|---|
| The measures are called | "Elmix", "kilder"; E07 "VE i nettets elmix" (kWh); E11a "VE-andel i nettets elmix, uden atomkraft"; E11b "VE-andel i nettets elmix, med atomkraft" |
| Never in a fixed text (a label, a message's sentence, a tooltip, a file name) | grøn, din vedvarende, neutral, 100 % (manual §17). A share that is 100 % is a formatted number, not a text |
| Title line 2 of the page | "Elmix, andel af elforbruget fra nettet i %, lokationsbaseret, time, prisområde"; the table view gives the kWh |
| The fixed caveat under the title, on every page and card that shows a share | "Elmixet er nettets blanding i prisområdet i de timer, hvor forbruget lå. Det dokumenterer ikke køb af vedvarende el: det kræver oprindelsesgarantier." |
| The note at the foot | "Kilde: Energinet (www.energidataservice.dk). VE-andelen er beregnet efter Energinets regel: vind, sol, vandkraft, biomasse og 55 % af affald." Generated rows are never attributed to Energinet (mixSource; docs/queries.md, factorSource) |
| The pending note | basis=best: "x % af forbruget (n timer) har endnu intet fuldstændigt elmix". basis=final: "x % af forbruget (n timer) er uden for det endelige elmix". x = pending_kwh ÷ kwh, n = pending_hours (metering-point hours) |
| The comparison | "Sammenlignet over h af H timer"; the cells left out for the mix are excluded_mix |
| A period or bucket with no hour in the figures | Ikke tilgængelig, reason no_mix; never a share of zero |
| Polarity | E11a and E11b +1 (manual §3); a group's energy and share 0: no source is drawn as better or worse |
The group names are ref.mix_group.name_da (Vind, Sol, Vandkraft, Biomasse, Affald, Atomkraft, Naturgas, Kul og olie,
Øvrige: nine since B78, which split "Fossile brændsler" as Eloverblik's report has it); the connected areas' are
ref.code.name_da of the list connected_area, and an unknown area is shown as its code.
The split the figures are (B78). Eloverblik's report "Dit klimaaftryk" has two geographic splits; the sources and the
origin here are its split "Prisområde" (the lead compared the owner's report for 2025 by hand with the renewable share,
the sources and the areas of origin: equal; no tool compares these blocks yet, so no page claims it). A4 names the split,
without a claim, in the line after the fixed caveat, and every place that shows or documents the
sources and origin blocks of report.footprint says the same sentence:
Elmixet følger Eloverbliks geografiske opdeling »Prisområde«. Rapporten »Dit klimaaftryk« lavet med opdelingen »Kommune« viser andre andele, fordi den først medregner kommunens egen vedvarende produktion.
(The report made with "Kommune" counts the municipality's own renewable production first, "Kommunal vedvarende energi", and agreed with the application on the consumption alone.)
The functions
calc.mix_hours(p_from date, p_to date, p_areas text[] DEFAULT NULL, p_origin boolean DEFAULT false, p_dataset smallint DEFAULT 1)
Steps 1, 3 and 6, the one place of them in SQL: for the local days p_from..p_to, the price areas p_areas (NULL:
both) and the dataset p_dataset of fx.mix_hour (1 DeclarationGridmix, the default; 2
DeclarationTransmissionGridmix, the municipal split's: B87), one row per price area and UTC hour that has a row: share_sum (S: Σ share_ppm of the rows that have one),
complete, version (the lowest; NULL when a row has none), any_generated, any_real (a row is generated,
raw.fetch.source 9, or is not: a generated row is never Energinet's), and the hour's parts as arrays ordered **largest
first**: groups and group_shares (each group with rows by ref.mix_code, an unknown code in other, with its s;
equal s by ref.mix_group.sort; since B78 with group_sorts (each group's sort) and group_family_sorts (the lowest sort of its family, which names
the family) in the same order; the function has no window function, which kept calc.mix_buckets' two calls of it
parallel), and with p_origin origins and origin_shares (each connected area as delivered;
equal s by the lower code, byte order). The first element of the origins takes the hour's residual; of the groups, the largest family's largest group (B78; the first element where every family is one group). The areas are compared as
char(3)[], the column's type (compared as text the column is cast and loses its statistics: the planner estimated a year
of both areas at 2 300 rows for 230 000, and sorted where it should hash).
calc.mix_share(p_q numeric, p_s bigint, p_total bigint)
Step 2 for one part: q × s ÷ S in kWh at 9 decimals, by the integer formula above (p_q the hour's energy in kWh, a
whole number of Wh; p_s the part's Σ share_ppm; p_total the hour's). The residual is the caller's.
calc.municipality_parts(mp_ids int[]) (B87)
Per E17 root of mp_ids (NULL: every root) whose municipality is usable and wanted (calc.mp_municipality): part, the
number of its municipality among the selection's (m1, m2, … by the lowest mp_id of each municipality's roots: it
says nothing of the code) and label, the municipality's name (ref.municipality.name_da, "Kommune <kode>" where the
table has none) only when the setting ELO_MUNICIPALITY_NAMES is on (ingest.municipality_setting.names) and every
root of the selection in that municipality has a current version with protected_name IS FALSE AND protected_address IS FALSE (N4, the test an address has: a protection not known is not known to be unprotected); otherwise NULL. **The one
function that returns a municipality's label** (municipality-method.md §4): a query file that calls it reads personal
data and declares the column under personal (B88's guard). calc.mix_buckets takes its parts from it, so a query that
joins the labels by part with the same mp_ids meets the same numbers.
calc.mix_buckets
calc.mix_buckets(p_mp_ids int[], p_from date, p_to date, p_basis text, p_grain text,
p_by text DEFAULT 'source', p_cmp text DEFAULT 'py', p_cmp_date date DEFAULT NULL,
p_geo text DEFAULT 'price_area')
p_geo (B87) is the geographic split: price_area (every answer as before B87, nine groups) or municipality ("The
municipal split" above: the group local first by source, the part local first by origin, and p_by = 'municipality',
which under price_area is refused).
The sources of the local days p_from..p_to (both inclusive) of the E17 roots p_mp_ids (NULL: every root), under the
data basis p_basis (best, final), by bucket (p_grain period, day, month, hour: the 24 clock hours of
the day over the period, M4, "The clock-hour grain" below, or utc_hour: every hour of a window of at most 31 days, M5a,
"The hour grain" below) and part (p_by source: the
nine groups in ref.mix_group.sort, in every bucket, whatever their energy (a group without energy in a bucket with
a mix is 0.000000000); origin: every connected area with energy on either side of the response, in some bucket:
an area of exactly zero on both sides (a row of 0 ppm, complete hours of 0,000 kWh) is no row; the largest of the period
first and the lower code among equals, an area with energy only in the comparison after them; one row with a NULL part
per bucket when no area has energy), compared with the comparison p_cmp (py,
pp, from with p_cmp_date, none; calc.comparison_period, docs/time-rules.md). The signature is
calc.emission_buckets' without method and GWP, with p_by. One row per bucket and part, ordered by bucket and
part_sort; the bucket's figures are repeated on each of its rows. The reference is elo_core.mix.mix_buckets, whose
MixBucket has the columns in the same order.
| Columns | Meaning |
|---|---|
bucket_key, bucket_from, bucket_to | As calc.period_buckets |
part, part_sort, part_known | The group or connected area, its order, and whether ref.mix_group / ref.code knows it (false for an unknown connected area) |
part_ac_kwh, part_cp_kwh | The part's energy over each side's hours in the figures. NULL (never zero) when the side's bucket has no hour in the figures; 0.000000000 for a part without energy in a bucket that has a mix |
part_ac_share, part_cp_share | That energy ÷ the side's mix_kwh (the share of the consumption of the complete hours; the nine shares of a bucket sum to 1 within the rounding of each) |
part_kwh, part_share, part_cmp_kwh, part_cmp_share | The same over the bucket's matched cells; the share's variance in percentage points is (part_share − part_cmp_share) × 100 |
ac_…, cp_… | Each side's totals: kwh (every hour), mix_kwh and mix_hours (the hours in the figures; MP-hours with a quantity), e07_kwh, e07_nuclear_kwh (E07 + nuclear: the numerator of E11b), e11a, e11b, pending_kwh and pending_hours (metering-point hours: a price area, outside the figures under the |
basis), no_price_area_kwh, the status final_kwh, preliminary_kwh, initial_kwh, status_pending_kwh (with no_price_area_kwh: the five shares of basis.mixStatus, the same under either basis), generated and real (the mix of the hours in the figures), reason (no_mix when the bucket has consumption and no hour in the figures). A comparison day counts in the bucket of the period day it corresponds to (B55: every comparison day in one bucket at every grain) | |
cp_from, cp_to | The comparison days of the bucket |
matched_hours, hours_in_period, excluded_readings, excluded_mix, reason | h, H and the two exclusions ("Sammenlignet over h af H timer"); NULL without a comparison |
kwh, cmp_kwh, e07_kwh, cmp_e07_kwh, e07_nuclear_kwh, cmp_e07_nuclear_kwh, e11a, cmp_e11a, e11b, cmp_e11b, generated_mix | The matched figures of each side; the variances in percentage points are (e11a − cmp_e11a) × 100 and (e11b − cmp_e11b) × 100 |
p_… | The whole period, on every row: the period side's kwh, mix_kwh, mix_hours, pending_kwh, pending_hours (metering-point hours), no_price_area_kwh and the four status energies; any_generated, any_real over both sides (basis.mixSource); all_without_area (every MP-hour with a quantity has no price area; NULL when none has a quantity); the period's h, H, exclusions and reason |
part_own_kwh, part_own_share (B87) | By municipality: the consumption in the figures of the municipality's points in the bucket (NULL when the bucket has no hour in the figures; 0.000 for a municipality without one in a bucket that has some) and the part's energy over it (share B). NULL by source and origin |
clock_hour, clock_hour_count, clock_hour_repeated, clock_hour_absent (M4, migration 0432_mix_clock_hours) | Under the grain hour only (NULL under the others): the class's local clock hour 0 to 23, the local hours of the period's days in it, the days it occurs twice on (02A and 02B of the 25-hour day) and the days it does not occur on (02 of the 23-hour day). Under the grain utc_hour clock_hour is the hour's own local clock hour and the three counts are NULL |
hour_utc, hour_occurrence (M5a, migration 0433_mix_hours) | Under the grain utc_hour only (NULL under the others): the UTC instant the hour starts, and 2 for the second 02:00 of the 25-hour day (02B), 1 otherwise |
ac_no_municipality_kwh, ac_municipality_not_loaded_kwh, ac_no_local_share_kwh; cp_…; p_no_municipality_kwh, p_municipality_not_loaded_kwh, p_no_local_share_kwh (B87) | Under the municipal split, per side and for the period: the energy of status noMunicipality (a price area and no wanted municipality: not in pending_kwh), of it the energy of a usable code the setting leaves out (municipality_not_loaded), and of the pending the energy of a wanted municipality without a share for the hour (no_local_share). With no_price_area_kwh and the four status energies they are what basis.mixStatus and §5's reasons are made of (the queries order the reasons: B88). NULL under the price area's split, NULL when there is none |
The groups of a bucket in mix.series (M1, M2). The query gives each bucket's groups as groups, a list in
part_sort: kwh and share (part_ac_kwh, part_ac_share), cp_kwh_matched and cp_share_matched
(part_cmp_kwh, part_cmp_share: the same groups over the bucket's comparable hours, the matched cells, as the headline's
variance compares; the level the comparison's column draws, M1f), cp_kwh_all and cp_share_all (part_cp_kwh,
part_cp_share: the comparison's own hours in the figures, as cp_e11a is E11a's; in the answer and drawn nowhere in the
form), all four NULL, never zero, where those hours have no mix and NULL with cmp=none; the bucket's cp_kwh_matched
(cmp_kwh, the denominator of cp_share_matched) and its ac_provisional_share and cp_provisional_share,
(preliminary_kwh + initial_kwh) / mix_kwh of each side at 9 decimals, the comparison's from its own status energies (0
under basis=final, whose figures hold Final hours only). The rounding rule of a stack: each share is its
group's energy over the side's mix_kwh, rounded once to 9 decimals half away from zero; the energies sum to mix_kwh
exactly (the matched energies their cp_kwh_matched), so the nine shares (ten under the municipal split) sum to 1 within 9 × 0,5 × 10⁻⁹ (ten: 10 ×), and the page
draws them as they come and prints each at one decimal by itself, never forcing the printed shares to 100,0 %
(services/api/tests/test_queries_m1.py holds both sums on the demo against the reference). The page "Kilder i farver"
colours a group by its code (--mix-source-<code>, coal_oil as coal-oil), so a new group needs a colour in
web/packages/notation-tokens/tokens/groups/mix-source.json before it is drawn in its own.
The clock-hour grain (M4)
p_grain = 'hour' (migration 0432_mix_clock_hours; the reference elo_core.mix.mix_buckets(…, grain="hour")): the sources
by the 24 clock hours of the local day, Danish time, over the whole period, for the form "Hver kilde for sig" and the day
profile of "Kilder i farver" (proposal §2.1, §2.2). A grain of the function and not a function beside it: every rule
above (the hours in the figures, the like-for-like cells, step 2 by families and the residuals, the statuses, the municipal
split) is the same, and only the bucket an MP-hour counts in differs; a second function would be a second copy of the rules
that must stay one (the twin calc.export_series of B67 and B56). The other grains answer as before, value for value.
- One bucket per clock hour 0 to 23, always 24, in that order. An MP-hour counts in the class of its own local clock hour, on either side; a cell's counterpart has the same clock hour (cells correspond by the day, the clock hour and the occurrence), so a matched pair is in one class.
- The repeated hour and the missing hour (manual section 4, "the hour of the day is structure", and N29): the 25-hour
day's 02A and 02B are two observations of class 02 (both hours' energy is in it, and
clock_hour_countcounts both); the 23-hour day has no hour 02 and adds nothing to it. A period of the short day alone has a class 02 with no hour: every figure NULL as in a bucket with nothing stored,clock_hour_count0.clock_hour_repeatedandclock_hour_absentcount the days of each kind in the period, so that a page names them under its axis ("02 rummer 02A og 02B som to observationer (1 dag med 25 timer); 1 dag med 23 timer har ingen time 02"). bucket_keyandbucket_fromarep_from,bucket_toisp_toon every class (a class is not a span of days);cp_fromandcp_toare the comparison's days. Inside the function the key of class h is the datep_from + h, so that every CTE keeps its one key type; the reference does the same.- The shares of a class sum to 1 within the rounding of each (the rule of a stack above: each share once to 9 decimals, half away from zero; the nine energies sum to the class's consumption in the figures exactly).
- A point without a mix (no price area) is in no figure of any class: its energy is consumption and
no_price_area_kwh, never inmix_kwh, a part or a matched sum (the golden casewithout_mix_case). The countmatched_hourskeeps the rule of the other grains (M1fv-05, which concerns the count of matched cells of the whole response and is not this grain's to change).
The query mix.profile (A4) calls the function once by this grain, by source: one row per class with mix.series'
figures of a bucket (the groups' energy and share, the comparison's on the comparable hours and over all its hours, the
provisional shares, E11a and E11b with their matched pair and variance), hour_count, hour_repeated, hour_absent, and the
means per hour of the day profile ("kWh pr. time"): ac_kwh_per_hour, ac_mix_kwh_per_hour and each group's
kwh_per_hour, each energy over hour_count rounded once to 9 decimals half away from zero (so the mean of the parts may
differ from the mean of their sum by 9 × 0,5 × 10⁻⁹ kWh). A class with no hour has the reason no_hour.
How a period that holds a clock-change day is drawn in a 24-class profile: class 02 is one column like the others; its
share is over both 02 hours of the long day (and none of the short day), its mean per hour over hour_count (the days of the
period, the long day's two hours counted as two, the short day's none), and the line under the axis names both days. A class
with no hour at all is drawn as the heat map draws an hour that does not exist: empty, with a diagonal stroke.
The golden cases (elo_devtools.mix_cases): short_day_case (29 March 2026: class 02 count 0, absent 1, NULL figures; class
03 the third local hour), long_day_case (25 October 2026: class 02 is 02A of 3 kWh wind and 02B of 4 kWh natural gas: 7
kWh, E11a 3/7 = 0,428571429, count 2, repeated 1), both_days_case (29 March to 25 October 2026, readings on those two days
alone: class 02 count 211, repeated 1, absent 1; class 03 3 + 5 kWh), no_comparison_case (a June day against the previous
year, which has a reading in hour 10 alone: every other class's comparison NULL, never 0) and without_mix_case.
libs/core/tests/test_m4_reference.py asserts them on the reference; services/api/tests/test_m4_clock_hours.py holds the SQL
to the reference to the last decimal on them, on the demo (a year by its previous year, the window from the 23-hour to the
25-hour day of 2026 against the period before, final, by origin, one root across the 25-hour day of 2025) and through
mix.profile, under TZ=UTC and TZ=America/Los_Angeles.
The hour grain (M5a)
p_grain = 'utc_hour' (migration 0433_mix_hours; the reference elo_core.mix.mix_buckets(…, grain="utc_hour")): the sources
of every hour of a window of at most 31 days, for the form "Time for time (uge)" (proposal §2.3, Form 3), which draws a week's
hours. The same function for M4's reason: only the bucket an MP-hour counts in differs, and the other grains answer as before,
value for value.
- One bucket per hour of the window's local days, in time order, each its own UTC hour: 24 a day, **23 on the short day (no 02), 25 on the long day (02A and 02B, two buckets)**, so 31 days hold at most 31 × 24 + 1 = 745. An MP-hour counts in the bucket of its own UTC hour.
bucket_key,bucket_fromandbucket_toare the hour's local date;clock_hourits local clock hour;hour_occurrence2 for 02B and 1 otherwise;hour_utcthe instant it starts. Inside the function the key of the n-th hour of the window (0 the first) is the datep_from + n, as M4's classes, so that every CTE keeps its one key type.- At most 31 days, and no comparison: a longer window and any
p_cmpbutnoneare refused (22023). The form compares nothing hour by hour; the period's comparison is the other queries'. - An hour with consumption and no hour in the figures (its mix pending or incomplete, not Final under
basis=final, or no price area) has NULL parts, never zero, and the reasonno_mix: its consumption is known and its sources are not, which the page draws as the outline of the consumption:afventer elmixwhere the response'sac_pending_kwhis above zero,uden prisområdewhere the hour has no price area and nothing is awaited (M5av-01: the two are told apart by the response's own columns, never by the hour's consumption). - The hours add up to the period exactly. Step 2 splits each price area and UTC hour (sum first), so the parts of a window's
hours sum to the grain
period's parts of the same window to the last decimal, as do the consumption, the consumption in the figures and the status energies (a test on the golden cases and on October 2026 of the demo).
The query mix.hours (A4) calls the function once by this grain, by source or by origin (by): one row per hour with its
names (hour_utc, local_date, clock_hour, occurrence), the consumption, the consumption in the figures, E11a, E11b, the
pending energy, the energy without a price area, the provisional share (as mix.series') and parts (part, name, known,
kwh, share: the nine groups, or every connected area with energy in the window, an area ref.code does not know under its
code with name NULL). Its window is held to 31 days by the runner's 750 points at the grain hour (g is hour alone),
before anything is read.
The golden cases (elo_devtools.mix_cases): week_hours_case(WEEK_SHORT) (23–29 March 2026, 167 hours) and
week_hours_case(WEEK_LONG) (19–25 October 2026, 169 hours): one root in DK1 with n + 1 kWh in the n-th local hour of each
day, half wind and half natural gas, Final (02A wind alone, 02B natural gas alone); a root without a price area (0,500 kWh every
hour of Monday: consumption and no_price_area_kwh, never a part); Wednesday 22:00 and 23:00 without a mix row and Thursday
07:00 with rows summing to 480 000: pending, 23, 24 and 8 kWh, parts NULL; Friday 12:00 produced 60/30/10 % in DK1, DE and PL
(13 kWh: 7,8, 3,9 and 1,3 kWh; PL unknown, kept under its code); Saturday Preliminary and Sunday before 12:00 Initial: in the
figures under best, pending under final. With them short_day_case (23 buckets) and long_day_case (25: 02A 3 kWh of wind,
E11a 1; 02B 4 kWh of natural gas, E11a 0). libs/core/tests/test_m5a_reference.py asserts them on the reference;
services/api/tests/test_m5a_hours.py holds the SQL to the reference to the last decimal on them, by source and origin, best
and final, on the demo (the weeks of both clock changes, the 31 days of October 2026, one root) and through mix.hours, under
TZ=UTC and TZ=America/Los_Angeles.
The like-for-like comparison is the cost's (docs/cost.md, calc.cost_buckets) with "the hour is in the figures
under the basis" in place of "every interval has a price":
- Eligibility. One row per side, metering point and UTC hour. Complete readings (A3x-05): one hourly value or four
quarters, each with a quantity, none A02 or A05. In the figures: a price area on the day, a complete mix, of version
Final under
basis=final. 2. Cells correspond by the corresponding day, the clock hour and the occurrence (phase-2.md §3.4); a cell without a counterpart is unmatched, never moved. 3. Counting. H: the current MP-hours with at least one quantity. Of those, without a counterpart cell: neither matched nor excluded; with one,excluded_readingswhen either side's readings are not complete (or the earlier side has none), elseexcluded_mixwhen either side's hour is not in the figures, else matched (h). 4. Reason when h = 0:no_data(H = 0),missing_readingsorno_mix(whichever excluded more cells;missing_readingson a tie),no_counterpart; never a variance of −100 %. 5. The matched figures of each side are those of its matched MP-hours, **summed per price area and hour, then split**: the matched sources are computed for the matched selection, as every figure is for its own.
What the queries derive (B59; the function divides only for its shares):
basis.mixStatus: the five shares of the period's energy by status,p_final_kwh,p_preliminary_kwh,p_initial_kwh,p_status_pending_kwhandp_no_price_area_kwheach÷ p_kwhat 9 decimals, **each numerator withcoalesce(…, 0)where the period has energy** (p_kwh > 0): a period wholly Final hasfinal1 and the four others 0, never NULL (the cost'sbasis.pricerule, B56v-04). The same under either basis.no_price_area: every metering-point hour with a quantity, whatever the quantity, has no price area:p_all_without_area(true; NULL when no hour has a quantity). Energy without a price area exists whenp_no_price_area_kwh IS NOT NULL, including0.000kWh: test it so, never with> 0.report.footprint's mix blocks: two calls,p_grain = 'period',p_cmp = 'none', by source and by origin.completeis true when the readings are complete (the footprint'scovered_hours = expected_hours), the period has an hour in the figures (p_mix_hours > 0),p_pending_hours = 0andp_no_price_area_kwh IS NULL.reason, the first that applies, as the emission blocks' precedence (report/footprint.sql):no_data(p_kwh IS NULL); with no hour in the figuresno_price_areaifp_all_without_area, elseno_mix;missing_readings(the readings not complete);no_price_area(p_no_price_area_kwh IS NOT NULL);pending_mix(p_pending_hours > 0). A connected area's row is one with energy (the function returns no row for an area of exactly zero).
Refusals (SQLSTATE 22023): an empty period or a NULL date, an unknown basis, grain or part, an unknown cmp, a
from without its date or a date without from, a pp or from comparison that does not end before the period
starts.
Grants. elo_api may execute every function of the migration; elo_worker and PUBLIC may not.
The golden cases
The worked example (§3.3; one root in DK1, two hours). Hour 1: 4 kWh, rows summing to 1 000 000 (wind 500 000 as R18 300 000 and R19 200 000, solar 100 000, biomass 100 000, waste 100 000, nuclear 50 000, natural gas 100 000, R20 50 000), Final. Hour 2: 6 kWh, nine rows summing to 480 000, Initial: pending. The groups: wind 2,0, solar 0,4, biomass 0,4, waste 0,4, nuclear 0,2, gas 0,4 (coal and oil 0), other 0,2 kWh, together 4,0; consumption 10 kWh, of which 6 kWh (1 hour) pending: "60 % af forbruget (1 time) har endnu intet fuldstændigt elmix". E07 = 2,0 + 0,4 + 0,4 + 0,55 × 0,4 = **3,02 kWh; E11a = 3,02 ÷ 4 = **75,5 %; E11b = 3,22 ÷ 4 = 80,5 %. Not 30,2 %: the pending hour is outside numerator and denominator.
The edges of step 1: an hour of one row summing to 999 899 is pending, 999 900 complete; 1 000 100 complete, 1 000 101 pending; a storage row of −1 200 ppm in an hour summing to 1 000 000 is pending; a NULL share beside rows summing to 1 000 000 is pending; a NULL version likewise; an hour without rows is pending.
The residual: 1 kWh in an hour of wind 333 330 (DK1), solar 333 330 (DE) and natural gas 333 329 (SE3), Σ 999 989.
Alone each part is 1 000 Wh × 333 330 ÷ 999 989 = 0,333 333 667 kWh (gas 0,333 332 667), together 1,000 000 001:
the residual of −0,000 000 001 goes to wind, equal to solar and lower in sort: wind 0,333 333 666, and the groups sum to
1,000 exactly. By origin the same residual goes to DE, equal to DK1 and the lower code.
The residual of a family (B78, family_case): 1 kWh in an hour of wind 333 330 (DK1), natural gas 333 330 (DK1) and
coal 333 329 (DE), Σ 999 989. As the eight groups of before, fossil (666 659) is the largest: wind 0,333 333 667, fossil
0,666 666 333. Split plainly into nine groups, wind and gas would be the largest and equal, wind (the lower sort) would
take the residual of −0,000 000 001 and become 0,333 333 666, and gas + coal would be 0,666 666 334. By families wind keeps
0,333 333 667; inside fossil coal is 1 000 Wh × 333 329 ÷ 999 989 = 0,333 332 667 and gas 1 000 Wh × 666 659 ÷ 999 989
less that, 0,666 666 333 − 0,333 332 667 = 0,333 333 666: gas + coal = 0,666 666 333, the old fossil. A second case holds
a family that is not the largest (wind 599 829, gas 200 035, coal 200 036, Σ 999 900): the families round to 0,599 888 989
and 0,400 111 011, coal is 0,400 111 011 − 0,200 055 006 = 0,200 056 005; plainly, wind would have taken −10⁻⁹.
The basis: a complete Final hour of 1 kWh and a complete Preliminary hour of 2 kWh. best: 3 kWh in the figures;
final: 1 kWh, and 2 kWh (1 hour) outside; the status is 1 kWh Final and 2 kWh Preliminary under both.
All are in elo_devtools.mix_cases, with two price areas (a quarter-hourly hour, an unknown code and an unknown
connected area) and a comparison with one cell matched, one left out for the mix of each side and one for the readings.
The municipal split (municipality-method.md §2.6; elo_devtools.mix_cases, B87). Each case's hour also has a grid mix
(dataset 1) with other shares, so a figure taken from the wrong dataset fails.
- The worked hour at 25 % (
municipal_worked_hour): 4 kWh, a share of 25 %, the TM rows of hour 1 above:local1,0; wind 1,5, solar 0,3, biomass 0,3, waste 0,3, nuclear 0,15, gas 0,3, other 0,15: together 4,0. E07 = 1,0 + 1,5 + 0,3 + 0,3 + 0,55 × 0,3 = 3,265 kWh; E11a 81,625 %; E11b 85,375 %. By originlocal1,0 first, DK1 3,0. - The residual (
municipal_residual_case): 1 kWh at 33,333333 %, TM rows wind 333 330, gas 333 330, coal 333 329 (Σ 999 989):local0,333 333 330;G0,666 666 670; wind 0,222 222 446, fossil 0,444 444 224 (coal 0,222 221 779, gas 0,222 222 445): together 1,000 exactly. - Two municipalities in one hour (
two_municipalities_case): two roots of 0,001 kWh in DK1, 999 at 33,333333 % and 998 at 66,666666 %:L0,000 999 999 99,local0,001 000 000; 998 (the lower code) 0,000 666 667, 999 0,000 333 333;G0,001. By municipality (root 1 in 999 ism1, root 2 in 998m2): share A 33,3 % and 16,7 %, share B 66,7 % and 33,3 %. - A point without a municipality beside one with (
without_municipality_case): the first isnoMunicipalityand outside every figure (its energy inno_municipality_kwh, not inpending_kwh); the second's figures are its own, and its hour without a share is pending (no_local_share_kwh). - Shares of 100 % (every kWh
local, the groups 0) and 0 % (the TM rows' own split, not GM's) are figures; no share, a NULL share and shares of 100,000001 and −0,000001 are pending; an hour with GM and no TM is pending under the municipal split and has its figure under the price area's; a municipality the list leaves out ismunicipality_not_loaded.
How it stays fast
The brief's point 4 and phase-2.md §4 ("How the sources and the cost stay inside the budget"): **a reading never meets the rows of its hour.**
The readings are summed per metering point and UTC hour first (
raw_hours, the cost's statement), and the like-for-like eligibility is decided on those hours.Each MP-hour meets its price area (
calc.price_areas, once per point and day) and its hour's one row ofcalc.mix_hours(one row per price area and hour, about 17 500 a year for both areas, the parts in arrays) by hash joins: 1 to 1.Only the selection's energy per side, price area and UTC hour (
sums: at most 8 784 rows a year and side, the matched MP-hours' energy of the hour beside the whole's: a matched MP-hour is in the figures, so its hour has a row) unnests the parts of its hour (the nine groups, then by origin the connected areas, in one array): each part's share is computed once for both sums (once in all when they are equal, a third of the demo's hours), with their totals for the residuals, and the part-hours are summed to the buckets by one hash aggregation. A test reads the function's text:fx.mix_houris read only throughcalc.mix_hours, an MP-hour meets it on its key, and the parts are unnested only forsums.The hour cells (local date, clock hour, occurrence) are made once per hour of each side's window from
generate_seriesover the side's bounds, which the planner counts exactly, each hour converted to local time once. B56'scalc.window_hoursgives the same cells but is estimated at 1 000 hours a day; on that estimate the MP-hours' join to their price areas hashed 150 000 rows in 2 048 batches (2,6 s of a first version's 6,1 s). The demo calls over both clock-change days hold the result to the reference (the comparison's counterparts included).B77's rule and B56's planner settings: the series in a variable first, read by
calc.cost_readings;enable_nestloop = off,enable_mergejoin = off,jit = off,plan_cache_mode = force_custom_plan; onlyPARALLEL SAFEhelpers, so the buckets are inlined. One root reads every monthly partition by its key (a test).Every root's series are named when no root is selected (
p_mp_idsNULL:calc.selection_seriesof every E17 root), where B77'scalc.selection_readingskeeps NULL for "every root". It follows fromcalc.cost_readings, which scans named series only, for B56's reason (docs/build/B56-report.md, deviation 2):calc.selection_readingsjoinscore.metering_pointwith the root condition, which the planner estimates at one row, and on that estimate it hashed and sorted a year of the demo's readings on disk; by the series alone the estimate is the partitions' own. B77 kept NULL because an index scan of whole partitions by the array of every series took the heat map 15–22 % longer at 50 to 420 roots; with the series named the planner reads each partition as it judges (sequentially for every root of the demo). The lead measures it at 50 and 80 roots (ADR-004, item 4).The municipal split (B87) adds per MP-hour one hash join to the root's municipality (once per root) and one to the share of its hour (
shares: the wanted municipalities' usable rows of each side's window, one per municipality and hour), and per sum the municipal part as a column: no reading meets the mix's rows, and the division by municipality is a grouping of the MP-hours. A price-area call plans none of it (B87f):calc.municipality_partsandcalc.mp_municipalityare called once each, before the query and only under the municipal split, into variables;hoursis aUNION ALLof one arm per split over the MP-hours (hour_base), and underforce_custom_planthe other split's arm is a constant false and is not planned (a test reads the plan of a price-area call: no municipal CTE, table or join). Measured on one analysed demo database, the calls alternated (docs/build/B87-report.md, B87f): the price-area call is level with B78's text, and the municipal call by source is about 1,1 to 1,2 times the price area's.
Measured on the demo organisation (18 E17 roots, 496 096 readings, 485 074 mix rows; PostgreSQL 18 in the Colima VM), the best of three, a year to 31 October 2026 of every root against its previous year, by month:
| Call, and the state of the tables | calc.emission_buckets | calc.mix_buckets by source | by origin |
|---|---|---|---|
Analysed (ANALYZE, as autovacuum leaves the product's tables; interleaved calls) | 2,66–2,72 s | 1,71–1,75 s | 2,21–2,24 s |
| Never analysed (the test's fresh database) | 2,40–2,41 s | 1,89–1,95 s (by day 1,95 s) | 2,42–2,45 s |
One root, the same year, by day, against pp (never analysed) | 0,22 s | 0,61 s | – |
test_mix.py prints every figure above for a year of every root with its previous year by month. Until P1 it also asserted
that calc.mix_buckets by source stayed within one and a half times calc.emission_buckets; migration 0441 made the
emission function three to six times faster (0,92 s for that call against 2,98 s by source, P1g), and the race stood for
nothing. The test now pins what it stood for on the plan of that call, by counts
(test_a_year_of_every_root_sums_the_readings_before_they_meet_the_source_rows): each reading read once, no reading row met
with the source rows of its hour before the sum, the source rows scanned once (docs/build/P1-report.md, "P1g"). By origin every hour is
also split by its connected areas (about 3,5 more parts an hour): below the emission on analysed tables, level with it on
tables never analysed. One root costs more than the emission's: the mix of the root's price area is read and split for every
hour whatever the selection's size (a fixed 0,3–0,4 s a year with its comparison).
The tests
| Where | What |
|---|---|
elo_devtools.mix_cases | The stores of facts, each defined once: the worked example, the edges of step 1, the residual, the basis, two price areas, the comparison; the seeds as the reference is given them; reading the reference's inputs back from the tables (read_mix_inputs); the SQL in the reference's shape (sql_mix_buckets) |
libs/core/tests/test_mix_reference.py | Every golden case on the reference, without a database; step 2's integer quotient against the exact rational quotient rounded half away from zero (5 000 values), and the parts summing to the hour's energy (2 000 hours); by origin no row for an area of exactly zero energy (B58f) |
libs/core/tests/test_b87_reference.py (B87) | The municipal split's golden cases on the reference, figure by figure; 2 000 seeded hours of both signs in two municipalities and both price areas: the municipal part and the groups (and the areas) sum to each hour's energy, the municipalities' parts to the municipal part; round_nano against the integer formula and step 2 on units of 10⁻⁹ kWh against the exact quotient (5 000 values each); nine groups and no local under the price area's split |
services/api/tests/test_b87_municipal_sources.py (B87) | The same cases through the SQL, equal to the reference to the last decimal; the 2 000 seeded hours through the SQL; the demo organisation under geo=municipality by source, origin and municipality, both bases, every kind of comparison, in three session time zones; price_area (and no p_geo) as before; calc.municipality_parts (no label with the setting off, none for a municipality with a protected root with it on, no code in any column, both tests of N4 in its text); the function's text (fx.mix_hour through calc.mix_hours alone, the parts unnested for the sums alone, the share read once and met on its key, no division); the refusals, grants and settings; the time beside the price area's |
services/api/tests/test_mix.py | The same cases through the SQL as elo_api, equal to the reference to the last decimal; calc.mix_share against the reference on 3 000 values; the seeds; the bounds against make status's; the demo organisation against the reference over 17 calls (the October cases, the Initial tail, final by month, the short Final hour, both clock-change days, a py period that overlaps its own comparison, a year of every root, and seeded random ones), each bucket's parts summing to its consumption in the figures; the two halves of a selection in both price areas; sum first on the function's text; the one division; the refusals, the grants and the planner settings; one root read by the partitions' key; the time beside calc.emission_buckets; by origin no row for an area of exactly zero energy, by source always the nine groups (B58f; nine since B78) |
Kilde: docs/mix.md i løsningens
repository.