Dokumentation · Beregningerne
The cost calculation (B56)
The rules of docs/architecture/phase-2.md §3.2, once in SQL (the functions of migration 0245_cost) and once in
Python (elo_core.cost, the reference a reviewer reads). The cost is the energy at the day-ahead price, **without
tariffs, taxes and VAT** ("til spotpris"; every page that shows it says "uden tariffer, afgifter og moms"). Nothing is
stored: every figure is computed when it is asked for, from ts.reading, core.mp_geo and price.spot, so a changed
price row changes the next query's result (phase-2.md §2.4, ruling 5). calc holds functions only.
The cost is the emission calculation's twin (docs/emission.md): an input per interval that can be missing, a
like-for-like comparison over matched hour cells, the counts h and H and what was left out. The reference shares the
emission reference's inputs (metering points, readings, price-area periods) and helpers.
services/api/tests/test_cost.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 worked example of §3.2 and its effects, on the four readings at the
seam, and on the demo organisation (B52's generated prices: negative prices on both sides of the seam, an hour with
three quarters, a null price, no price for the last two days) over periods, grains, every kind of comparison,
selections and the export series, in session time zones that must not matter. libs/core/tests/test_cost_reference.py
asserts every figure of the worked example on the reference alone.
Units, scales, and where a figure is rounded
Energy in kWh, prices in DKK per MWh, costs in DKK. No binary float anywhere between a stored value and a result: every
operation is +, − or × on numeric (SQL) or Decimal (Python, in a context that raises rather than rounds),
which are exact for those three, so both give the same digits and the same scale. A conversion is a multiplication,
never a division by a power of ten: the cost of an interval is kWh × DKK per MWh × 0.001, the mean of four quarters
(p₁ + p₂ + p₃ + p₄) × 0.25.
| Figure | Scale (decimals) | Why |
|---|---|---|
| kWh | 3 | ts.reading.quantity is numeric(15,3) |
| A price from one row | 6 | price.spot.dkk_per_mwh is numeric(14,6) |
| The mean of four quarters | 8 | 6 + the 2 of 0.25 |
| The cost of an interval | 12, or 14 at the mean of four | 3 + 6 (or 8) + the 3 of 0.001 |
| A sum (an hour, a bucket, a period, a side) | the largest of its terms | a sum of exact decimals keeps the largest scale |
| The volume effect of a cell | 12 or 14 | (q_AC − q_CP) (3) × P_CP (6 or 8) × 0.001 (3) |
| The price effect of a cell | the larger of its cost and its volume | a difference |
| K03 and its two matched sides | 9 | the one division (below) |
Nothing is rounded but K03. K03 is cost ÷ the energy of the priced intervals, rounded once, to 9 decimals, half
away from zero, where it is made (calc.cost_ratio; the reference's elo_core.footprint.ratio), as docs/queries.md
has it for every ratio; no figure (i.r.) when that energy is not above zero. It is the one division of the cost
functions (a test reads their source). The SQL gives the numerator 42 decimals before it divides, so that PostgreSQL's
division and round() make one rounding, not two. A cost in DKK is rounded to øre once, for display, by the page's
formatting module, as docs/emission.md has it for emissions; a share of energy (basis.price) is the query's ratio
(B57), from the energies these functions return, each numerator with coalesce(…, 0) where the period has energy
(p_kwh > 0: a period wholly priced has priced 1 and unpriced 0, never NULL). A relative variance (ΔCP %) is the
query's too, and is i.r. when its reference is zero or negative, for K01 and K02 as for K03 (§3.2, manual §3): a
comparison that cost −1,00 has no relative variance (elo_core.cost.relative_variance, the reference of the rule;
test_a_comparison_that_cost_minus_1_00_has_no_relative_variance).
The rules
| Rule | Detail |
|---|---|
| What is counted | K01: the series of the selected E17 roots (E01), all of their series. K02: the series of their children of role 3 (D06, ref.mp_type; E03), each counted for its root, as calc.consumption_buckets(p_export) counts it |
| Price area | The metering point's price area on the interval's local day (core.mp_geo: of its periods, the latest with valid_from <= day, if valid_to is NULL or after the day), the emission factor's rule (docs/emission.md), never today's area for every day. An export child is priced by its own area. No row or a NULL area: no price, never zero |
| The price of an interval | The table below (phase-2.md §3.2; R2 §2.5.1, §4.2 rule 3). An hourly reading is never split into quarters, so the same energy costs differently read hourly and in quarters: the data's resolution, not an error |
| Without a price | The interval keeps its energy and has no cost: never free. A priced quarter keeps its cost when another quarter of its hour has none. K01, K02 and K03 are made of the priced intervals; the unpriced energy and hours are counted beside them |
| Negative prices | Kept with their sign: a cost can be negative and sums are signed; nothing is clamped at zero |
| Provenance | price_generated (and the buckets' generated/real) is true for a generated price (raw.fetch.source = 9): never Energinet's (basis.priceSource, B57) |
| Version | A price has none: a cost is provisional only where its reading is estimated (A03); estimated_cost_dkk is that part |
The price of an interval. The seam is local midnight of 1 October 2025, 2025-09-30T22:00Z: hourly rows of
Elspotprices before it, quarter rows of DayAheadPrices from it (a check of price.spot, B52).
| Reading | Price rows | The interval's price | price_resolution, price_rows |
|---|---|---|---|
| Hourly, before the seam | Hourly | The row of its hour | 60, 1 |
| Quarter-hourly, before the seam | Hourly | The row of its hour (as it takes its hour's factor, P1 §2) | 60, 1 |
| Quarter-hourly, from the seam | Quarter-hourly | The row of its own quarter | 15, 1 |
| Hourly, from the seam | Quarter-hourly | (p₁ + p₂ + p₃ + p₄) × 0.25; all four are needed, with fewer the hour has no price | 15, 4 |
The functions
calc.spot_price(price_area text, interval_start timestamptz, resolution smallint)
The price of one interval: one row (dkk_per_mwh, price_resolution, price_rows, price_generated), or no row
when the interval has no price. Its definition is calc.interval_prices of the interval's local day. A function that
prices many intervals joins the prices itself and never calls this per row.
calc.hour_prices(from date, to date, areas text[] DEFAULT NULL) and calc.interval_prices(…)
calc.hour_prices is the one place of the table above: for the local days from..to and the price areas areas
(NULL: both), one row per price area and UTC hour that has a price row, with hour_dkk (the price of an hourly interval
of the hour, P), hour_rows (1 or 4), rows_resolution (60 before the seam, 15 from it), the four quarters' prices
q0_dkk…q3_dkk (qN starts N × 15 minutes into the hour: before the seam each is the hour's row) and a generated
flag for each. A NULL price is no price. calc.interval_prices is the same, one row per (price area, interval start,
resolution) that has a price.
calc.cost_intervals(mp_id, from, to, grain, today DEFAULT NULL, window_days DEFAULT NULL)
The cost per interval of one metering point of any tree (an E17 or E18 root, a D06 child named directly), for B68's
mp.cost_intervals, so that the query computes nothing. Its rows are those of calc.series_intervals (the signature of
calc.emission_series_intervals): each series of the point, one row per interval of the local days from..to at the
grain (15: as stored; 60: shorter stored intervals summed to their UTC hour, with that function's quantity and
quality rule), one row per gap at the resolution of the series' day (stored false: "mangler", never "afventer
pris"), and whether each is expected (expected, not_expected_reason, expected_from, expected_to). A point that
is not chartable as a load is the query's not_a_load. Ordered by business type and interval start.
| Column | Meaning |
|---|---|
business_type, series_id, interval_start, interval_end, local_date, resolution, kwh, quality, stored, expected, … | calc.series_intervals' |
price_area | Of the row's local day; NULL: none |
dkk_per_mwh, price_resolution, price_rows, price_generated | The price of the row's interval (the table above). At the hour's grain it is the hour's own price P: its row before the seam (60/1), the mean of its four quarters from it (15/4), none with fewer; never a quotient of cost and energy. As stored, a quarter's own (15/1, or its hour's row before the seam, 60/1). A gap has its slot's price. NULL: "afventer pris" |
cost_dkk | The sum of the costs of the row's intervals that have a price and a quantity; NULL for a gap and when none has |
unpriced_kwh | The energy of the row's intervals with a price area and no price |
An hour of four quarters can cost other than kWh × P: the cost is the sum of its quarters' costs, each at its own
price. The worked example's hour 1 read in quarters is 2,0 kWh at P = 1 000 and costs 2,12, not 2,00; an hour whose
fourth quarter has no price has no P and keeps the cost of its three priced quarters. The golden cases
(elo_devtools.cost_cases): 745 hours for 1 to 31 October 2026 of a quarter-hourly point (the 25-hour day of 25
October), the hour of three quarters, a gap, a D06 child.
calc.cost_point_status(mp_id, from, to)
The price status of one point of any tree over the local days from..to, from its stored intervals at their own
resolution: B68's basis.price and priceSource of mp.cost_intervals. One row: kwh, priced_kwh, cost_dkk,
unpriced_kwh, unpriced_hours, no_price_area_kwh, any_generated, any_real, all_without_area (as
calc.cost_buckets' p_… columns); every figure NULL when nothing is stored.
calc.cost_buckets
calc.cost_buckets(p_mp_ids int[], p_from date, p_to date, p_grain text,
p_export boolean DEFAULT false, p_cmp text DEFAULT 'py', p_cmp_date date DEFAULT NULL)
The cost of the local days p_from..p_to (both inclusive) of the E17 roots p_mp_ids (NULL: every root) or, with
p_export, of their export children (K02), by bucket (p_grain period, day, month), 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' with calc.consumption_buckets' p_export. One row per bucket, in key order; the reference
is elo_core.cost.cost_buckets, whose CostBucket has the columns in the same order.
| Columns | Meaning |
|---|---|
bucket_key, bucket_from, bucket_to | As calc.period_buckets |
ac_…, cp_… | Each side's totals over every interval of the side's days: kwh (all), priced_kwh, cost_dkk (K01 or K02: the priced intervals), estimated_cost_dkk (of A03 readings), unpriced_kwh and unpriced_hours (n: hours with an interval that has a quantity and a price area and no price; per metering point and hour when several are selected, as h, H and phase 1's pending hours count (P1 §9.3), since one page shows the two notes side by side), no_price_area_kwh, k03, generated, real. 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_price, reason | h, H and the two exclusions ("Sammenlignet over h af H timer"); NULL without a comparison |
kwh, cost_dkk, cmp_kwh, cmp_cost_dkk, k03, cmp_k03 | The matched energy and cost of each side, and K03 of each (the matched cost ÷ the matched energy) |
volume_effect_dkk, price_effect_dkk | The two effects, summed over the bucket's matched cells |
generated_prices | A price behind the matched figures is generated; NULL when h = 0 |
p_… | The whole period, on every row: the period side's kwh, priced_kwh, unpriced_kwh, unpriced_hours, no_price_area_kwh; any_generated, any_real over both sides (basis.priceSource); all_without_area (every interval with a quantity, whatever the quantity, has no price area; NULL when no interval has a quantity, B56v-02); the period's h, H, exclusions and reason |
The like-for-like comparison is the emission's (docs/emission.md, calc.emission_matched), with "every interval
of the hour has a price" in place of the factor:
- Eligibility. One row per side, metering point and UTC hour. Complete readings (A3x-05): the intervals cover
exactly 60 minutes without overlap, each with a quantity, none A02 or A05; one hourly value or four quarters. Priced:
every interval of the hour has a price. For complete readings that is "the hour has
P": an hourly value takesP, and four quarters each have a price exactly when the four price rows of the hour exist. 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 metering-point 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_pricewhen either side has an interval without a price, else matched (h). 4. Reason when h = 0:no_data(H = 0),missing_readingsorno_price(whichever excluded more cells;missing_readingson a tie),no_counterpart; never a variance of −100 %. A metering point without a price area is the query'sIkke tilgængelig, reasonno_price_area(p_all_without_area).
The two effects split the variance of the matched cost at the hour's grain, whatever the resolution of either side.
Per matched cell and side: q the hour's energy, c its cost (the sum of its intervals' costs), P its price as an
hourly interval (hour_dkk). volume = (q_AC − q_CP) × P_CP × 0.001 and price = (c_AC − c_CP) − volume, so the two
sum to the cell's variance exactly, and each bucket's to cost_dkk − cmp_cost_dkk. No price is a quotient of cost and
energy, so an hour of zero energy on either side has its effects like any other (zero now: the whole variance is volume;
zero then: volume at the comparison's price). For an hour read hourly on both sides the price effect is
q_AC × (P_AC − P_CP) × 0.001; for an hour read in quarters it also holds what the quarters' own prices add over the
hour's mean.
Worked example (§3.2; one root in DK1 after the seam): hour 1, 2 kWh hourly at the mean of 800, 1 000, 1 200 and 1 000
costs 2,00; hour 2, 3 kWh at −100 costs −0,30; hour 3, 1 kWh, has three quarters and no price. K01 = 1,70 over 5 priced
kWh, 1 of 6 kWh (1 hour) unpriced, K03 = 0,34; the export child's quarter at 1 200 costs 1,20 (K02); KNET = 0,50. Hour 1
read as quarters of 0,2, 0,4, 0,8 and 0,6 kWh costs 2,12. A cell of 2 kWh at 1 000 then and 3 kWh at 800 now: 2,40
against 2,00, volume +1,00, price −0,60. All are golden cases (elo_devtools.cost_cases).
Refusals (SQLSTATE 22023): an empty period or a NULL date, an unknown grain, 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, a NULL
p_export; calc.cost_intervals refuses an empty period and a grain other than 15 or 60, calc.cost_point_status an
empty period.
Grants. elo_api may execute every function of the migration; elo_worker and PUBLIC may not.
How it stays fast
The brief's point 4 (ADR-004): the time of the emission functions is in their joins of readings to a per-interval input. The cost functions:
- never meet a reading by a subquery per row: the prices are made once, one row per price area and UTC hour
(
calc.hour_prices, about 17 500 a year for both areas, read by their key for the areas the selection has had), and the price area once per metering point and day (calc.price_areas); - sum the readings per metering point and hour first, by the position of each interval in the hour (the hourly value
and the four quarters), and meet the areas and prices on those hours by hash joins; each position's cost is its energy
× its price × 0.001, summed over the positions that have both (
calc.cost_sum, exact: the sum of the intervals' costs, with their scale); - decide the like-for-like eligibility on those hours before anything is summed over the cells, and test completeness
on the positions the intervals cover (a bit per quarter), so the hours are grouped by hashing, not by sorting every
reading as
count(DISTINCT …)makes them; - make every per-hour fact (local day, bucket day, cell, counterpart) once per hour of the windows
(
calc.window_hours, fromref.calendar_day; a test holds it tocalc.hour_cellfor every hour of 2015 to 2040), not once per metering-point hour. Its series has constant bounds (migration 0256, B57): the hours of a day were made with agenerate_serieswhose bounds come from the calendar row, which the planner takes for 1 000 rows each, so that on analysed tables the windows' hours were estimated at 2 110 000 for 17 520, the join to the readings' hours at 313 million rows and hashed in 4 096 batches (3.0 s for a year of the demo's roots by month instead of 1.1 s, which is what B56 measured on tables never analysed);generate_series(0, 24)cut by the day's length gives the same rows and the planner an estimate within a factor of 3 to 20 of the truth, analysed or not (test_queries_b57.py: no hash of the call in more than 256 batches (4 096 before), the estimate within 30 times, in both states); - keep B77's rule on
calc.cost_buckets, which reads a selection's readings (the series computed into a variable first, read bycalc.cost_readings;enable_nestloop = off,jit = off,plan_cache_mode = force_custom_plan; onlyPARALLEL SAFEhelpers, so the buckets are inlined rather thancalc.period_buckets), and plan it **without merge joins** (enable_mergejoin = off): the planner cannot see how many hours a grouping of readings makes and sorted the 150 000 hours of the demo's year three times on disk to merge them. The two functions of one point (calc.cost_intervals,calc.cost_point_status) name the point's series in a variable too but allow nested loops, ascalc.series_intervals, whichcalc.cost_intervalsbuilds on, does: with nested loops off inside it, it would read whole partitions (B77).
Measured on the demo organisation (18 E17 roots, 472 076 readings in the two years, PostgreSQL 18 in the Colima VM): a
year to 31 October 2026 of every root against its previous year, by month, takes 1.3 to 1.5 s with
calc.cost_buckets against 2.4 to 2.6 s with calc.emission_buckets for the same call, and the export series
0.5 s; one root by day against pp, 0.16 to 0.18 s against 0.21 to 0.22 s. Those emission times are from before P1:
migration 0441 made calc.emission_buckets three to six times faster (0.89 s for the same call, P1g), so the cost is no
longer faster than it, and test_cost.py no longer races the two. It prints both and pins what the race stood for on the
plan of that call, by counts (test_a_year_of_every_root_sums_the_readings_before_it_meets_a_price): each reading read
once, the readings summed per point and hour before any price row meets them, the prices scanned once, and no node that has
met them larger than the points' hours (docs/build/P1-report.md, "P1g").
The tests
| Where | What |
|---|---|
elo_devtools.cost_cases | The stores of facts, each defined once: the worked example (and hour 1 in quarters), the cells of the effects, the four readings at the seam; reading the reference's inputs back from the tables (read_cost_inputs); the SQL in the reference's shape |
libs/core/tests/test_cost_reference.py | Every figure of the worked example and the effects on the reference, without a database; the seam; the scales |
services/api/tests/test_cost.py | The same cases through the SQL as elo_api, equal to the reference to the last decimal; the demo organisation against the reference over 19 calls (the seam, the last two days without a price, months over the seam, the export series, both clock-change days, a py period that overlaps its own comparison, and seeded random ones); the effects summing to the variance in every bucket; calc.window_hours against calc.hour_cell; the one division; the refusals, the grants and the planner settings; one root read by the partitions' key; the time beside calc.emission_buckets. B56f: the 745 hours of a quarter-hourly point with the hour of three quarters and a gap, hour 1 in quarters at 2,12 against P 1 000, a D06 child and an E18 root named directly with their price status, zero energy without a price area, a comparison that cost −1,00, and one point of any tree against the reference on the demo |
Kilde: docs/cost.md i løsningens
repository.