tokenfabrikker/tests/test_fasit.py
Kjell Tore Guttormsen a63f66c416
feat(kode): add the levelised equations, the parameter reader and the draws
One pure function per equation for chapters 1 to 3 of the specification
(S1-S21, S36, S43-S47), a strict reader for the frozen parameter file with
checksum, validation and unit conversion, and the 10 000 Monte Carlo draws of
the 87 drawn quantities, stored in data/ and reproducible bit for bit.

Tests: unit tests and edge cases per equation, the reader, the draws, and
known answers from Argonne, NOU 2026: 4, Epoch and NVE with the sources' own
assumptions. Five comparisons miss the 5 % tolerance and are kept as strict
expected failures with the measured deviation. No result for the hypothesis
is computed. ruff ALL and mypy strict pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:08:47 +01:00

456 lines
17 KiB
Python

"""Known answers: the model's own functions, fed with a source's assumptions, against its result.
None of these tests uses the frozen parameters, and none computes a result for
the hypothesis. Each one takes the inputs a published calculation states, runs
them through the same functions the model uses, and compares with the number
the source reports. The tolerance is 5 %, the one the specification sets for
the Argonne test (chapter 1.3).
A comparison that misses the tolerance is kept as an expected failure with the
measured deviation and the cause where it is known. No parameter and no
equation is tuned to make a test pass.
"""
from __future__ import annotations
import pytest
from tokenfabrikker import ligninger as lg
pytestmark = pytest.mark.fasit
TOLERANSE = 0.05
def _avvik(beregnet: float, fasit: float) -> float:
return beregnet / fasit - 1.0
# --------------------------------------------------------------------------- Argonne
# Stauff et al. (ANL/NSE-25/47, 2025), table 6-1 (curves) and table 6-3 (results);
# source entry K12-001. Method: Hanna et al. (Energies 17, 5073, 2024). 2022 USD, 6 %, 40 years.
#
# What the two sources state, and how it is mapped onto the model's functions:
# - overnight cost 18 562 P^-0.16 USD/kW: S2 with c_N_ref at 1 000 MW and nu = 0.84
# - learning rate 0.145 P^-0.083, "renormalized to start from the 2nd unit" (Hanna): S2 with
# n_0 = 1, so that the first unit on the site costs the between-of-a-kind figure
# - construction time 16 P^0.25 months, interest during construction at 6 %: S3
# - capacity factor from refuelling only, four weeks every 2 years (5 P^-0.17 years below
# 200 MW) (Hanna, section 3)
# - number of units without grid: 1 + demand / unit size (ANL p. 51)
# - O&M with fuel 181 P^-0.28 USD/MWh, times 0.53/N + 0.47 with N units on the site
# The equations of the article are images that could not be read, and the link to its code
# was not recoverable, so two points are this project's reading: n_0 = 1, and whether the
# O&M of a unit follows its capacity or the energy delivered (both are tested below).
ARGONNE_MED_NETT = ( # demand MWe, unit MWe, units, USD/MWh (option 1)
(50, 50, 1, 147),
(100, 50, 2, 129),
(500, 500, 1, 97),
(1000, 1000, 1, 87),
(2000, 1000, 2, 79),
(6000, 1000, 6, 72),
)
ARGONNE_UTEN_NETT = ( # option 4
(50, 5, 11, 174),
(100, 10, 11, 153),
(500, 50, 11, 116),
(1000, 50, 21, 103),
(2000, 100, 21, 92),
(6000, 400, 16, 77),
)
ARGONNE_RENTE = 0.06
ARGONNE_AAR = 40.0
GRENSE_BRENSELSBYTTE_MW = 200.0
UKER_STANS = 4.0
UKER_PER_AAR = 365.25 / 7.0
def _argonne_kapasitetsfaktor(P: float) -> float:
intervall: float = 2.0 if P >= GRENSE_BRENSELSBYTTE_MW else 5.0 * P**-0.17
return 1.0 - UKER_STANS / UKER_PER_AAR / intervall
def _argonne_drift(P: float, N: int) -> float:
return float(181.0 * P**-0.28 * (0.53 / N + 0.47))
def _argonne_enheter(P: float, N: int, n_0: int) -> list[float]:
c_ref = 18562.0 * 1000.0**-0.16 * 1e3 # USD per MW at 1 000 MW
return [
lg.s3_investering_med_renter(
xi_N=1.0,
c_N=lg.s2_investering_per_mw(
c_N_ref=c_ref,
P_u=P,
P_ref=1000.0,
nu=0.84,
ell=0.145 * P**-0.083,
n_0=n_0,
n=n,
),
P_u=P,
rho=ARGONNE_RENTE,
tau_N=16.0 * P**0.25 / 12.0,
)
for n in range(1, N + 1)
]
def argonne_med_nett(P: float, N: int, *, n_0: int = 1) -> float:
"""Option 1 (through the grid): S5 with the study's curves, USD/MWh."""
kf = _argonne_kapasitetsfaktor(P)
return lg.s5_lcoe_kjernekraft(
I_N=_argonne_enheter(P, N, n_0),
rho=ARGONNE_RENTE,
L_N=ARGONNE_AAR,
f_N_enhet=0.0,
D_avv=0.0,
P_u=P,
E_N=lg.s4_energi_kjernekraft(KF=kf, N_u=N, P_u=P),
v_N=_argonne_drift(P, N),
u_N=0.0,
d_N=0.0,
q_N=0.0,
)
def argonne_uten_nett(last: float, P: float, N: int, *, n_0: int = 1, drift_fast: bool) -> float:
"""Option 4 (no grid): S9 without buffer and external supply, USD/MWh delivered.
``drift_fast=True`` charges the O&M of every unit as a fixed yearly cost at
the unit's own capacity factor; ``False`` charges it per MWh delivered.
"""
kf = _argonne_kapasitetsfaktor(P)
drift = _argonne_drift(P, N)
return lg.s9_kraftkostnad_dedikert(
I_N=_argonne_enheter(P, N, n_0),
rho_A=ARGONNE_RENTE,
L_N=ARGONNE_AAR,
f_N_enhet=drift * lg.TIMER_PER_AAR * kf if drift_fast else 0.0,
D_avv=0.0,
P_u=P,
P_buf=0.0,
c_buf=0.0,
f_buf=0.0,
L_buf=20.0,
I_g_aar=0.0,
E_D=lg.s10_energi_datasenter(lam=1.0, PUE=1.0, P_IT=last),
v_N=0.0 if drift_fast else drift,
u_N_A=0.0,
d_N=0.0,
q_N=0.0,
)
@pytest.mark.parametrize(("last", "P", "N", "fasit"), ARGONNE_MED_NETT)
def test_argonne_med_nett(last: int, P: int, N: int, fasit: int) -> None:
"""Table 6-3, option 1: all six rows within 5 % (87 USD/MWh at 1 000 MWe is hit to 0.1 %)."""
assert last == N * P
assert abs(_avvik(argonne_med_nett(P, N), fasit)) <= TOLERANSE
@pytest.mark.parametrize(("last", "P", "N", "fasit"), ARGONNE_UTEN_NETT)
def test_argonne_uten_nett_drift_etter_kapasitet(last: int, P: int, N: int, fasit: int) -> None:
"""Table 6-3, option 4, with O&M following installed capacity: all six rows within 5 %."""
assert 1 + last // P == N
assert abs(_avvik(argonne_uten_nett(last, P, N, drift_fast=True), fasit)) <= TOLERANSE
_FOR_LAVT = "O&M charged per MWh delivered gives a result more than 5 % below the study"
@pytest.mark.parametrize(
("last", "P", "N", "fasit"),
[
pytest.param(50, 5, 11, 174, marks=pytest.mark.xfail(strict=True, reason=_FOR_LAVT)),
pytest.param(100, 10, 11, 153, marks=pytest.mark.xfail(strict=True, reason=_FOR_LAVT)),
pytest.param(500, 50, 11, 116, marks=pytest.mark.xfail(strict=True, reason=_FOR_LAVT)),
(1000, 50, 21, 103),
(2000, 100, 21, 92),
(6000, 400, 16, 77),
],
)
def test_argonne_uten_nett_drift_etter_energi(last: int, P: int, N: int, fasit: int) -> None:
"""Table 6-3, option 4, with O&M per MWh delivered: three of six rows miss by 6 to 7 %."""
assert abs(_avvik(argonne_uten_nett(last, P, N, drift_fast=False), fasit)) <= TOLERANSE
def test_argonne_uten_laering_fra_andre_enhet_feiler() -> None:
"""With n_0 = 0 (learning from the first unit) the 103 USD/MWh row is missed by about 10 %."""
lavt = argonne_uten_nett(1000, 50, 21, n_0=0, drift_fast=False)
assert _avvik(lavt, 103) < -TOLERANSE
def test_argonne_nett_er_billigere_enn_uten_nett() -> None:
"""The study's headline: 87 with grid against 103 without, for 1 000 MWe."""
med = argonne_med_nett(1000, 1)
uten = argonne_uten_nett(1000, 50, 21, drift_fast=True)
assert uten / med == pytest.approx(103 / 87, rel=TOLERANSE)
# ------------------------------------------------------------- NOU 2026: 4, appendix 4
# The Nuclear Power Committee's own spreadsheet (digital appendix 4, sheets "Forutsetninger"
# and "Kontantstrøm"; source entries K16-011, K16-012, K16-013, K03-021). 1 400 MW, start 2040,
# investment spread evenly over 14 years, 80 years of operation, 7 600 full-load hours, 5 %.
# The NOU text reports the power price needed for a positive present value: 132 øre/kWh ("Lav")
# and 219 øre/kWh ("Høy"). Revenue per MWh in the sheet is price x value factor 1.05, plus 5 %
# for heat and 1 % for system services on top of that, plus 10 kr/MWh for guarantees of origin.
NOU_EFFEKT = 1400.0
NOU_TIMER = 7600.0
NOU_RENTE = 0.05
NOU_BYGGEAAR = 14
NOU_DRIFTSAAR = 80
NOU_VERDIFAKTOR = 1.05
NOU_TILLEGG = 0.05 + 0.01
NOU_OPPRINNELSE = 10.0 # kr/MWh
NOU_SCENARIOER = { # kr/kW, kr/kW per year, kr/MWh (variable, fuel, waste and decommissioning)
"Lav": (109_000.0, 1610.0, 115.0, 60.0, 70.0),
"Høy": (177_000.0, 2515.0, 187.0, 100.0, 200.0),
}
def nou_balansepris_modell(scenario: str) -> float:
"""Break-even power price from the model's S3 and S5, øre/kWh."""
investering, fast, variabel, brensel, avfall = NOU_SCENARIOER[scenario]
enhet = lg.s3_investering_med_renter(
xi_N=1.0, c_N=investering * 1e3, P_u=NOU_EFFEKT, rho=NOU_RENTE, tau_N=NOU_BYGGEAAR
)
lcoe = lg.s5_lcoe_kjernekraft(
I_N=[enhet],
rho=NOU_RENTE,
L_N=NOU_DRIFTSAAR,
f_N_enhet=fast * 1e3,
D_avv=0.0,
P_u=NOU_EFFEKT,
E_N=NOU_TIMER * NOU_EFFEKT,
v_N=variabel,
u_N=brensel,
d_N=avfall,
q_N=0.0,
)
return (lcoe - NOU_OPPRINNELSE) / (NOU_VERDIFAKTOR * (1.0 + NOU_TILLEGG)) / 10.0
def nou_regneark_naaverdi(scenario: str, kraftpris: float) -> float:
"""The spreadsheet's own present value (cell Kontantstrøm!B32), mill. kr.
Written out here from the sheet's formulas, independently of the model:
yearly amounts from 2026, discounted with Excel's NPV (first year one period).
``kraftpris`` in øre/kWh.
"""
investering, fast, variabel, brensel, avfall = NOU_SCENARIOER[scenario]
gwh = NOU_TIMER * NOU_EFFEKT / 1e3
salg = kraftpris * NOU_VERDIFAKTOR * gwh / 100.0
inntekt = salg * (1.0 + NOU_TILLEGG) + gwh * NOU_OPPRINNELSE / 1e3
drift = variabel + fast * 1e3 / NOU_TIMER
kostnad = gwh * (brensel + avfall + drift) / 1e3
strom = [-investering * NOU_EFFEKT / 1e3 / NOU_BYGGEAAR] * NOU_BYGGEAAR
strom += [inntekt - kostnad] * NOU_DRIFTSAAR
return sum(belop / (1.0 + NOU_RENTE) ** (aar + 1) for aar, belop in enumerate(strom))
def nou_regneark_balansepris(scenario: str) -> float:
"""The price at which the spreadsheet's present value is zero, øre/kWh."""
ved_null = nou_regneark_naaverdi(scenario, 0.0)
ved_hundre = nou_regneark_naaverdi(scenario, 100.0)
return -ved_null / (ved_hundre - ved_null) * 100.0
def test_nou_regnearket_er_gjengitt_riktig() -> None:
"""The replica gives the sheet's own number: -84 626.139 mill. kr at 60 øre/kWh ("Lav")."""
assert nou_regneark_naaverdi("Lav", 60.0) == pytest.approx(-84626.139055439344, rel=1e-12)
def test_nou_regnearket_gir_132_men_222() -> None:
"""The sheet gives 132.2 for "Lav", as the NOU says, but 222.1 for "Høy", not 219.
The NOU text (p. 381-382) says 219. With all three choices on "Høy" the
sheet's formulas give 222.1; the difference of 1.4 % is not explained.
"""
assert nou_regneark_balansepris("Lav") == pytest.approx(132.2, abs=0.05)
assert nou_regneark_balansepris("Høy") == pytest.approx(222.1, abs=0.05)
@pytest.mark.parametrize(("scenario", "fasit"), [("Lav", 132.0), ("Høy", 219.0)])
def test_nou_balansepris(scenario: str, fasit: float) -> None:
"""S3 and S5 with the committee's assumptions: 134.5 and 225.8 against 132 and 219.
The model is 1.7 % above the sheet because S3 counts interest from the
middle of each construction year and the sheet from the end of it.
"""
assert abs(_avvik(nou_balansepris_modell(scenario), fasit)) <= TOLERANSE
assert nou_balansepris_modell(scenario) == pytest.approx(
nou_regneark_balansepris(scenario), rel=0.02
)
# ----------------------------------------------------------------------------- Epoch
# Epoch AI (14 May 2026), "Servers account for 60% of the total cost of ownership of a
# one-gigawatt AI data center"; source entries K08-K03 and K01-043. USD million per GW IT.
# Capital: servers 21 188, network 4 925 (5 years); facility 11 433, land 172, utility works
# 164 (14 years). Operation without power: taxes 143, maintenance 120, labour 40, water 6.
# Power: 8.34 cents/kWh, PUE 1.14, utilisation 71 %. Total 8 514 per year.
# The page does not state the discount rate. It says land is annualised as the opportunity
# cost of capital at the same rate, and reports 13 per year on 172: 7.56 %. That is used here.
def test_epoch_aarskostnad() -> None:
"""S15 with Epoch's inputs gives 8.76 against 8.51 bn USD per GW and year (+2.8 %).
The difference lies in the capital recovery factor for servers: Epoch
reports 0.24, S1 gives 0.248 at 7.56 % and five years.
"""
lcoc = lg.s15_lcoc(
c_bygg=(11433.0 + 172.0 + 164.0) * 1e3,
d_bygg=0.0,
c_H=(21188.0 + 4925.0) * 1e3,
rho_D=13.0 / 172.0,
L_B=14.0,
L_H=5.0,
o_D=(143.0 + 120.0 + 40.0 + 6.0) * 1e3,
d_o_D=0.0,
lam=0.71,
PUE=1.14,
c_a=83.4,
)
assert abs(_avvik(lcoc, 8514.0 * 1e3)) <= TOLERANSE
assert lcoc / 1e6 == pytest.approx(8.756, abs=0.001)
def test_epoch_kraftandel() -> None:
"""Power is about 7 % of the yearly cost, as the specification says under S19."""
kraft = lg.TIMER_PER_AAR * 0.71 * 1.14 * 83.4
assert kraft / 8514e3 == pytest.approx(0.07, abs=0.005)
# ------------------------------------------------------------------------------- NVE
# NVE's LCOE spreadsheet 2026 (source entries K11-002, K11-003, K11-004, K11-006): 6 %, 2025
# kroner. NVE counts interest during construction from the start of each year, S3 from the
# middle of it; that alone puts S3 about 3 % of the capital cost lower. NVE also lets
# production fall every year (0.42 % for wind, 0.1 % for nuclear), which the model does not.
# For hydro NVE's investment figure already includes interest during construction.
NVE_RENTE = 0.06
def _nve_fornybar(
investering: float,
drift_mwh: float,
drift_kw: float,
timer: float,
levetid: float,
byggetid: float,
*,
renter_med: bool,
) -> float:
"""LCOE in øre/kWh from the model's function, with NVE's inputs."""
return (
lg.lcoe_fornybar(
investering=investering * 1e3,
drift_per_mwh=drift_mwh,
drift_per_mw=drift_kw * 1e3,
fullasttimer=timer,
levetid=levetid,
byggetid=byggetid,
rho=NVE_RENTE,
renter_i_investeringen=renter_med,
)
/ 10.0
)
def _nve_kjernekraft() -> float:
enhet = lg.s3_investering_med_renter(
xi_N=1.0, c_N=126874.7 * 1e3, P_u=1600.0, rho=NVE_RENTE, tau_N=10.0
)
return (
lg.s5_lcoe_kjernekraft(
I_N=[enhet],
rho=NVE_RENTE,
L_N=40.0,
f_N_enhet=1846.23 * 1e3,
D_avv=0.0,
P_u=1600.0,
E_N=7884.0 * 1600.0,
v_N=51.753252816351818,
u_N=75.0,
d_N=60.0,
q_N=0.0,
)
/ 10.0
)
def test_nve_kjernekraft() -> None:
"""S3 and S5 with NVE's inputs: 187.3 against 193.9 øre/kWh (-3.4 %)."""
assert abs(_avvik(_nve_kjernekraft(), 193.94)) <= TOLERANSE
def test_nve_vannkraft_uten_renter_paa_nytt() -> None:
"""Hydro: 48.94 against 48.94 øre/kWh when S3 is not applied on top of NVE's figure."""
verdi = _nve_fornybar(18749.0, 70.0, 0.0, 2971.0, 40.0, 3.0, renter_med=True)
assert verdi == pytest.approx(48.94, abs=0.01)
def test_nve_vannkraft_med_s3_teller_rentene_to_ganger() -> None:
"""Hydro with S3 on top of NVE's figure gives 52.8 øre/kWh, 7.9 % above NVE.
NVE's sheet says interest during construction is included in the investment
figure for hydro ("Inkludert i modulkostnader"). The parameter file holds
that figure together with a construction time of three years.
"""
verdi = _nve_fornybar(18749.0, 70.0, 0.0, 2971.0, 40.0, 3.0, renter_med=False)
assert _avvik(verdi, 48.94) == pytest.approx(0.079, abs=0.002)
@pytest.mark.xfail(
strict=True,
reason="43.9 against 46.9 øre/kWh (-6.3 %): interest from mid-year, and no yearly loss",
)
def test_nve_vindkraft() -> None:
"""Wind on land with NVE's inputs."""
verdi = _nve_fornybar(13915.0, 120.0, 0.0, 3357.0, 30.0, 2.0, renter_med=False)
assert abs(_avvik(verdi, 46.91)) <= TOLERANSE
@pytest.mark.xfail(
strict=True,
reason="114.0 against 120.6 øre/kWh (-5.5 %): interest from mid-year; the rest not found",
)
def test_nve_havvind() -> None:
"""Bottom-fixed offshore wind with NVE's inputs (investment with grid and contingency)."""
verdi = _nve_fornybar(52800.0, 0.0, 900.0, 4467.0, 30.0, 3.0, renter_med=False)
assert abs(_avvik(verdi, 120.61)) <= TOLERANSE
def _nve_metode(
investering: float,
byggetid: int,
levetid: int,
timer: float,
tap: float,
drift_ore: float,
fast: float,
) -> float:
"""NVE's own convention, written out independently of the model, øre/kWh.
Interest from the start of each construction year, production falling by
``tap`` per year, operation cost on the first year's production.
"""
renter = sum((1.0 + NVE_RENTE) ** k for k in range(1, byggetid + 1)) / byggetid
aar = range(1, levetid + 1)
energi = sum(timer * (1.0 - tap) ** (t - 1) / (1.0 + NVE_RENTE) ** t for t in aar)
drift = sum((drift_ore * timer / 100.0 + fast) / (1.0 + NVE_RENTE) ** t for t in aar)
return (investering * renter + drift) / energi * 100.0
def test_nve_avviket_er_forklart_for_vind_og_kjernekraft() -> None:
"""With NVE's two conventions the same inputs give NVE's numbers within 0.2 %."""
vind = _nve_metode(13915.0, 2, 30, 3357.0, 0.0042, 12.0, 0.0)
kjernekraft = _nve_metode(
126874.7, 10, 40, 7884.0, 0.001, 7.5 + 6.0 + 5.1753252816351818, 1846.23
)
assert vind == pytest.approx(46.913, rel=0.002)
assert kjernekraft == pytest.approx(193.945, rel=0.002)