tokenfabrikker/tests/test_folsomheter_naaverdi.py
Kjell Tore Guttormsen 45aaffcb69
feat(folsomheter): the sensitivity list through the run over the draws, with eleven new switches in the model code
42 rows from the 37 lines: each row is the main run with one change, run
on the main run's step for the solutions it applies to and put in the
fixed table next to the main run. New switches in dimensjoner and
regn_program for lines 4, 7, 8, 10, 12, 13, 16, 17, 18, 20 and 21, the
cost factor of line 28 in the ownership pass, and the state's cash flow
next to M6. With the switches off every figure is unchanged to the last
digit. Made-up draws only; nothing is computed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 20:31:12 +01:00

446 lines
19 KiB
Python

"""The switches of the sensitivity list in S26 and the ownership forms: lines 16, 17, 18 and 28.
Clarifications 118 b to d, 122 and 123 of the specification, and that every
switch at its default gives the main run's figures to the last digit.
Everything is computed on the made-up set in ``conftest.py``; the numbers say
nothing about the hypothesis.
"""
from __future__ import annotations
import math
from dataclasses import replace
from typing import TYPE_CHECKING
import numpy as np
import pytest
from tokenfabrikker import eierskap as ei
from tokenfabrikker import kontantstrom as ks
from tokenfabrikker import ligninger as lg
from tokenfabrikker import nivaaisert as nv
from tokenfabrikker import skala
from tokenfabrikker.kontantstrom import Diskontering, Knapphet, Paaslagsform, Skattekostnad
from tokenfabrikker.utbygging import Losning
if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
NORM = Knapphet.NORMALISERING
def _crf(rho: float, levetid: float) -> float:
return float(rho / (1.0 - (1.0 + rho) ** -levetid))
def _D(res: ks.Programresultat, rho: float) -> np.ndarray:
return np.array([(1.0 + rho) ** -(t - res.plan.T_0) for t in res.aar])
def _D_R(res: ks.Programresultat) -> np.ndarray:
"""The circular's rate, by hand: 4 % for years 1 to 40, 3 % to 75, 2 % after (118 b)."""
ut = []
for t in res.aar:
j = t - res.plan.T_0
ut.append(1.04 ** -min(j, 40) * 1.03 ** -min(max(j - 40, 0), 35) * 1.02 ** -max(j - 75, 0))
return np.array(ut)
def _pv(D: np.ndarray, tabell: np.ndarray) -> float:
return math.fsum(D * tabell)
def _sett(
oppdiktet: LagInndata,
losning: Losning,
*,
L_N: float = 20.0,
mu_rel: float = 1.0,
T_slutt: float = 2060.0,
) -> Inndata:
"""The made-up set; solution T with a later grid and a slower pace, so T-K builds nuclear."""
if losning.trinnvis:
return oppdiktet(tau_nett=6.0, g_fornybar=0.5e6, L_N=L_N, mu_rel=mu_rel, T_slutt=T_slutt)
return oppdiktet(L_N=L_N, mu_rel=mu_rel, T_slutt=T_slutt)
def _regn(
inn: Inndata,
losning: Losning,
*,
N_anlegg: int = 2,
knapphet: Knapphet = NORM,
**program: object,
) -> ks.Programresultat:
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=N_anlegg)
return ks.regn_program(inn, losning, plan, knapphet, dim=dim, **program) # type: ignore[arg-type]
def _alt(inn: Inndata, res: ks.Programresultat) -> dict[str, object]:
"""Every figure the run reads from a path, as bytes or numbers, for an exact comparison."""
ut: dict[str, object] = {
felt: getattr(res, felt)
for felt in ("NNV", "SE", "RV", "RV_anlegg", "RV_felles", "NV_kraft", "NV_datasenter")
}
for felt in ("KS_D", "KS_N", "F_a", "Delta_W", "V"):
ut[felt] = getattr(res, felt).tobytes()
ut["varsigma"] = dict(res.varsigma)
for bedrift in (False, True):
kost = nv.kraftkostnad(inn, res, bedrift=bedrift)
ut[f"c_a{bedrift}"] = kost.c_a.tobytes()
ut[f"S42{bedrift}"] = kost.S42
ut["B_6"] = skala.skala(inn, res).B_6.tobytes()
strom = ei.bedriftsstrom(inn, res, tilleggsregel=True)
ut["NK"] = strom.NK.tobytes()
for form in inn.eierformer.values():
e = ei.eierresultat(inn, strom, form)
ut[form.navn] = (e.NV_stat, e.KS_stat.tobytes())
ut[f"LCOC {form.navn}"] = ei.lcoc_med_kapitalkostnad(inn, res, ei.krav_for_skatt(inn, form))
return ut
# ------------------------------------------------------ off is the main run
@pytest.mark.parametrize("knapphet", list(Knapphet))
@pytest.mark.parametrize("losning", list(Losning))
def test_alle_brytere_av_gir_hovedkjoringen(
oppdiktet: LagInndata, losning: Losning, knapphet: Knapphet
) -> None:
"""Every switch given at its default value gives the main run to the last digit."""
inn = _sett(oppdiktet, losning, L_N=30.0)
hoved = _regn(inn, losning, knapphet=knapphet)
dim = ks.dimensjoner(
inn,
losning,
rho_A=None,
minstelast=None,
fritt_enhetsvalg=False,
gamma_trinn=False,
paaslag_kjernekraft=0.0,
skaler_K_U=True,
bare_over_dimensjonerende_feil=False,
)
assert dim == hoved.dim
av = ks.regn_program(
inn,
losning,
hoved.plan,
knapphet,
dim=dim,
paaslag=Paaslagsform.SCENARIO,
diskontering=Diskontering.MARKED,
skattekostnad=Skattekostnad.SUBSIDIE,
)
assert _alt(inn, av) == _alt(inn, hoved)
assert (av.K_inn, av.SE_stat, av.skattegrunnlag) == (None, None, av.SE)
strom = ei.bedriftsstrom(inn, av, tilleggsregel=True)
med_en = ei.bedriftsstrom(inn, av, tilleggsregel=True, kostnadsfaktor=1.0)
assert med_en.NK.tobytes() == strom.NK.tobytes()
assert med_en.avskrivning.tobytes() == strom.avskrivning.tobytes()
# -------------------------------------------------------------------- line 16
def test_linje_16_rundskrivets_rente_for_haand() -> None:
"""118 b: D_R(j) = 1.04^-min(j,40) 1.03^-min(max(j-40,0),35) 1.02^-max(j-75,0)."""
assert lg.s26_diskontering_rundskriv(j=0) == 1.0
assert lg.s26_diskontering_rundskriv(j=1) == pytest.approx(1 / 1.04)
assert lg.s26_diskontering_rundskriv(j=40) == pytest.approx(1.04**-40)
assert lg.s26_diskontering_rundskriv(j=41) == pytest.approx(1.04**-40 / 1.03)
assert lg.s26_diskontering_rundskriv(j=75) == pytest.approx(1.04**-40 * 1.03**-35)
assert lg.s26_diskontering_rundskriv(j=76) == pytest.approx(1.04**-40 * 1.03**-35 / 1.02)
assert lg.s26_diskontering_rundskriv(j=80) == pytest.approx(1.04**-40 * 1.03**-35 * 1.02**-5)
def test_linje_16_restverdien_med_rundskrivets_rente_for_haand() -> None:
"""118 b: every amount after the final year from the year it falls; T_s - T_0 = 73."""
D = [lg.s26_diskontering_rundskriv(j=73 + x) for x in range(5)]
assert lg.s40_restverdi_rundskriv(
NK_snitt=10.0, L_rest=4, avvikling=5.0, T_s=2100, T_0=2027
) == pytest.approx(10.0 * (D[1] + D[2] + D[3] + D[4]) - 5.0 * D[4])
# a facility that loses money gets no value, but the decommissioning is deducted
assert lg.s40_restverdi_rundskriv(
NK_snitt=-10.0, L_rest=4, avvikling=5.0, T_s=2100, T_0=2027
) == pytest.approx(-5.0 * D[4])
assert (
lg.s40_restverdi_rundskriv(NK_snitt=10.0, L_rest=0, avvikling=5.0, T_s=2100, T_0=2027) == 0
)
@pytest.mark.parametrize("losning", list(Losning))
def test_linje_16_bare_naaverdien_i_s26_regnes_om(oppdiktet: LagInndata, losning: Losning) -> None:
"""118 b: S26 with D_R everywhere, in A too; S45, S42, M3, M4 and M6 with the market's rates."""
inn = _sett(oppdiktet, losning, T_slutt=2100.0)
hoved = _regn(inn, losning)
rund = _regn(inn, losning, diskontering=Diskontering.RUNDSKRIV)
assert rund.diskontering is Diskontering.RUNDSKRIV
assert dict(rund.varsigma) == dict(hoved.varsigma)
for felt in ("KS_D", "KS_N", "F_a", "Delta_W", "V"):
assert getattr(rund, felt).tobytes() == getattr(hoved, felt).tobytes()
assert rund.kraftaar == hoved.kraftaar # M3 and M4
a, b = nv.kraftkostnad(inn, rund, bedrift=True), nv.kraftkostnad(inn, hoved, bedrift=True)
assert a.S42 == b.S42 # M2
assert skala.skala(inn, rund).B_6.tobytes() == skala.skala(inn, hoved).B_6.tobytes() # M6
D_R = _D_R(rund)
assert rund.NV_datasenter == pytest.approx(_pv(D_R, rund.KS_D), rel=1e-12)
assert rund.NV_kraft == pytest.approx(_pv(D_R, rund.KS_N), rel=1e-12, abs=1e-3)
ovrige = rund.Delta_W - rund.utslipp - rund.K_prog - rund.V
assert rund.NV_ovrige == pytest.approx(_pv(D_R, ovrige), rel=1e-12, abs=1e-3)
assert rund.SE == lg.s26_subsidieelement(
naaverdi_prosjekt=rund.NV_datasenter + rund.NV_kraft + rund.RV
)
assert rund.NNV == pytest.approx(
rund.NV_datasenter + rund.NV_kraft + rund.NV_ovrige - 0.2 * rund.SE + rund.RV
)
assert rund.NNV != hoved.NNV
@pytest.mark.parametrize("losning", [Losning.A, Losning.B])
def test_linje_16_restverdien_i_s26(oppdiktet: LagInndata, losning: Losning) -> None:
"""118 b: S40 with D_R. The average NK is found from the main run's S40 (positive here)."""
inn = oppdiktet(L_N=30.0)
hoved = _regn(inn, losning)
rund = _regn(inn, losning, diskontering=Diskontering.RUNDSKRIV)
rho_avv = 0.08 if losning is Losning.A else 0.06
for a, rv_h, rv_r in zip(hoved.anlegg, hoved.RV_anlegg, rund.RV_anlegg, strict=True):
assert a.L_rest > 0
assert rv_h > 0
avv = math.fsum(a.avvikling_etter.values())
NK = (rv_h * 1.08**33 + avv * (1 + rho_avv) ** -a.L_rest) * _crf(0.08, a.L_rest)
D = [lg.s26_diskontering_rundskriv(j=33 + x) for x in range(1, a.L_rest + 1)]
assert rv_r == pytest.approx(max(0.0, NK * math.fsum(D)) - avv * D[-1], rel=1e-9)
ventet = math.fsum(
-f.avvikling_etter * lg.s26_diskontering_rundskriv(j=33 + f.L_rest)
for f in rund.felles
if f.L_rest > 0
)
assert rund.RV_felles == pytest.approx(ventet)
if losning is Losning.B:
assert ventet < 0
# ------------------------------------------------------------- line 17, row 2
def _investeringer(res: ks.Programresultat, inn: Inndata) -> tuple[np.ndarray, ...]:
"""Every investment of S34 and S35 by hand: data centre, power (without nuclear), nuclear.
The buffer's table in the cash flow also holds f_buf P_buf in each operating year;
that is operation and is taken out here.
"""
datasenter, kraft, kjerne = (np.zeros(len(res.aar)) for _ in range(3))
for k, a in enumerate(res.anlegg):
datasenter += a.I_bygg + a.I_H
for i, investering in a.investering.items():
if i == ks.KJERNEKRAFT:
kjerne += investering
else:
kraft += investering
kraft += a.I_nett + a.I_g
if not res.losning.paa_nett:
drift = np.array([1.0 if res.plan.i_drift(k, t) else 0.0 for t in res.aar])
kraft += a.buffer - drift * inn["f_buf"] * ks.bufferstorrelse(inn, res.dim)
for f in res.felles:
kjerne += f.investering
return datasenter, kraft, kjerne
@pytest.mark.parametrize("losning", list(Losning))
def test_linje_17_all_innskutt_kapital(oppdiktet: LagInndata, losning: Losning) -> None:
"""118 c: varphi K_inn in place of varphi SE; K_inn as each term is discounted in S26."""
inn = _sett(oppdiktet, losning)
hoved = _regn(inn, losning)
alle = _regn(inn, losning, skattekostnad=Skattekostnad.ALL_KAPITAL)
datasenter, kraft, kjerne = _investeringer(alle, inn)
rho_kraft = 0.08 if losning is Losning.A else 0.06
K_inn = (
_pv(_D(alle, 0.08), datasenter)
+ _pv(_D(alle, rho_kraft), kraft)
+ _pv(_D(alle, rho_kraft), kjerne)
)
assert alle.K_inn is not None
assert alle.K_inn == pytest.approx(K_inn, rel=1e-12)
assert alle.K_inn > alle.SE > 0
assert alle.skattegrunnlag == alle.K_inn
assert alle.SE == hoved.SE
assert alle.SE_stat is None
assert alle.NNV == pytest.approx(hoved.NNV - 0.2 * (alle.K_inn - hoved.SE), rel=1e-12)
if losning is Losning.A:
assert kjerne.any()
assert (alle.anlegg[0].buffer - kraft).any()
# -------------------------------------------------------------------- line 18
@pytest.mark.parametrize("losning", list(Losning))
def test_linje_18_subsidieelementet_med_statens_laanerente(
oppdiktet: LagInndata, losning: Losning
) -> None:
"""118 d: SE = max(0, -[sum D_stat (KS_D + KS_N) + RV^stat]) with r_stat = 0.02 for S40 too.
With L_N = 30 the facilities and units run past 2060; the average NK of each facility is
found from the main run's S40. A lower share sold in «overkapasitet» makes SE positive.
"""
inn = _sett(oppdiktet, losning, L_N=30.0, mu_rel=0.8)
hoved = _regn(inn, losning, knapphet=Knapphet.OVERKAPASITET)
stat = _regn(
inn, losning, knapphet=Knapphet.OVERKAPASITET, skattekostnad=Skattekostnad.STATENS_RENTE
)
rho_avv = 0.08 if losning is Losning.A else 0.06
RV_stat = []
for a, rv in zip(hoved.anlegg, hoved.RV_anlegg, strict=True):
avv = math.fsum(a.avvikling_etter.values())
if a.L_rest == 0:
RV_stat.append(0.0)
continue
# the value part of the main run's S40; zero when the facility loses money
verdi = rv * 1.08**33 + avv * (1 + rho_avv) ** -a.L_rest
NK = verdi * _crf(0.08, a.L_rest) if verdi > 1e-6 * max(1.0, avv) else 0.0
RV_stat.append((NK / _crf(0.02, a.L_rest) - avv * 1.02**-a.L_rest) * 1.02**-33)
if losning is not Losning.R:
assert any(rv > 0 for rv in RV_stat), "a facility with value after the final year"
RV_stat += [
-f.avvikling_etter * 1.02**-f.L_rest * 1.02**-33 for f in stat.felles if f.L_rest > 0
]
D = _D(stat, 0.02)
SE_stat = max(0.0, -(_pv(D, stat.KS_D) + _pv(D, stat.KS_N) + math.fsum(RV_stat)))
assert stat.SE_stat is not None
assert stat.SE_stat == pytest.approx(SE_stat, rel=1e-9)
assert stat.SE_stat > 0
assert stat.SE == hoved.SE
assert stat.skattegrunnlag == stat.SE_stat
assert stat.RV == hoved.RV
assert stat.NNV == pytest.approx(hoved.NNV - 0.2 * (stat.SE_stat - hoved.SE), rel=1e-12)
# -------------------------------------------------------------------- line 28
@pytest.mark.parametrize("losning", [Losning.A, Losning.B, Losning.C, Losning.R, Losning.T_K])
def test_linje_28_kostnadene_ganges_med_faktoren(oppdiktet: LagInndata, losning: Losning) -> None:
"""122: investments (I^bud too) and operation times 1.1; the excepted items are not.
Excepted: power bought, electricity tax, grid tariff, q_N E and the capacity cost.
Fuel, waste fee and decommissioning are multiplied; sales are not costs.
"""
inn = _sett(oppdiktet, losning, L_N=30.0)
res = _regn(inn, losning)
en = ei.bedriftsstrom(inn, res, tilleggsregel=True)
med = ei.bedriftsstrom(inn, res, tilleggsregel=True, kostnadsfaktor=1.1)
assert med.investering == pytest.approx(1.1 * en.investering)
assert med.budsjett == pytest.approx(1.1 * en.budsjett)
assert med.avskrivning == pytest.approx(1.1 * en.avskrivning)
assert med.avskrivning_fast == pytest.approx(1.1 * en.avskrivning_fast)
# zero at the end of the final year, up to the last digits of the sums
assert med.kapital == pytest.approx(1.1 * en.kapital, abs=1e-2)
assert med.inntekt.tobytes() == en.inntekt.tobytes()
assert med.elavgift.tobytes() == en.elavgift.tobytes()
ganges = np.zeros(len(res.aar))
for k, a in enumerate(res.anlegg):
ganges += a.drift + sum(a.kraftdrift.values(), np.zeros(len(res.aar)))
ganges += sum(a.avvikling.values(), np.zeros(len(res.aar)))
if not res.losning.paa_nett:
drives = np.array([1.0 if res.plan.i_drift(k, t) else 0.0 for t in res.aar])
ganges += drives * inn["f_buf"] * ks.bufferstorrelse(inn, res.dim)
for f in res.felles:
ganges += f.drift + f.avvikling
assert ganges.any()
assert med.drift - en.drift == pytest.approx(0.1 * ganges, abs=1e-3)
# the residual value follows the cash flow with the factor, the decommissioning too
RV_anlegg, RV_felles = ei.restverdi_bedrift(inn, res, tilleggsregel=True, kostnadsfaktor=1.1)
assert med.restverdi_anlegg == RV_anlegg
assert RV_felles == pytest.approx(1.1 * en.restverdi_felles)
netto = ei.netto_per_anlegg(inn, res, tilleggsregel=True, kostnadsfaktor=1.1)
assert (
sum(netto, np.zeros(len(res.aar))).sum()
< sum(ei.netto_per_anlegg(inn, res, tilleggsregel=True), np.zeros(len(res.aar))).sum()
)
def test_linje_28_kostnaden_for_regnekraft_med_faktoren(oppdiktet: LagInndata) -> None:
"""122: LCOC^bed with the factor on building, IT hardware and operation.
R's power cost is the price, tax, tariff and the disconnection arm, which are not
multiplied. gamma_H = 0, so every vintage moves by the same amount.
"""
inn = oppdiktet()
res = _regn(inn, Losning.R)
r = 0.05
en = ei.lcoc_med_kapitalkostnad(inn, res, r)
med = ei.lcoc_med_kapitalkostnad(inn, res, r, kostnadsfaktor=1.1)
endring = 0.1 * (100e6 * 1.1 * _crf(r, 15) + 200e6 * _crf(r, 5) + 2e6 + 0.5e6)
assert med - en == pytest.approx(endring)
with pytest.raises(ValueError, match="business version"):
nv.kraftkostnad(inn, res, kostnadsfaktor=1.1)
@pytest.mark.parametrize("losning", [Losning.A, Losning.B_MERKET, Losning.C])
def test_linje_28_kraftverkenes_kostnad_med_faktoren(
oppdiktet: LagInndata, losning: Losning
) -> None:
"""122: in S9 and S5 every cost but q_N times the factor; in LCOE_i investment and operation."""
inn = oppdiktet()
res = _regn(inn, losning, N_anlegg=1)
if losning is Losning.A:
en = ks.kraftkostnad_dedikert(inn, res.dim, 0, 0.08)
med = ks.kraftkostnad_dedikert(inn, res.dim, 0, 0.08, kostnadsfaktor=1.1)
q_N = lg.s6_ulykkeskostnad(
N_u=30, phi_U=1e-5, K_U=1e12, D_fors=8e9, P_u=50.0, P_ref=1000.0, E=res.dim.E_D
)
assert med == pytest.approx(1.1 * (en - q_N) + q_N)
elif losning is Losning.B_MERKET:
numre = ks.enhetsnumre(res.dim, 1)
E_N = res.verk[0][0].energi
en = nv.lcoe_kjernekraft(inn, res, numre=numre, E_N=E_N, rho=0.06)
med = nv.lcoe_kjernekraft(inn, res, numre=numre, E_N=E_N, rho=0.06, kostnadsfaktor=1.1)
q_N = nv.ulykkeskostnad_per_mwh(inn, res, N_u=30, E_N=E_N)
assert med == pytest.approx(1.1 * (en - q_N) + q_N)
else:
for teknologi in ("vann", "vind", "havvind"):
en = nv.lcoe_fornybar(inn, teknologi, 0.06)
assert nv.lcoe_fornybar(inn, teknologi, 0.06, kostnadsfaktor=1.1) == pytest.approx(
1.1 * en
)
# ------------------------------------------------------------ clarification 123
def test_123_statens_kontantstrom_ved_m6(oppdiktet: LagInndata) -> None:
"""S30 for the wholly owned company in the first year of stable operation over SNKS_snitt."""
inn = oppdiktet()
res = _regn(inn, Losning.R)
strom = ei.bedriftsstrom(inn, res, tilleggsregel=True)
heleid = ei.eierresultat(inn, strom, inn.eierformer["heleid_selskap"])
stabilt = skala.forste_aar_med_stabil_drift(res)
assert stabilt is not None
assert ei.statens_kontantstrom_ved_m6(inn, res, heleid) == pytest.approx(
float(heleid.KS_stat[stabilt - 2027]) / 500e9
)
with pytest.raises(ValueError, match="heleid_selskap"):
ei.statens_kontantstrom_ved_m6(
inn, res, ei.eierresultat(inn, strom, inn.eierformer["direkte"])
)
def test_123_uten_aar_med_stabil_drift(oppdiktet: LagInndata) -> None:
"""Facilities of three years that are never in operation together have no such year."""
inn = oppdiktet(s_brikker=0.01, L_N=3.0)
res = _regn(inn, Losning.R)
strom = ei.bedriftsstrom(inn, res, tilleggsregel=True)
heleid = ei.eierresultat(inn, strom, inn.eierformer["heleid_selskap"])
assert ei.statens_kontantstrom_ved_m6(inn, res, heleid) is None
def test_gamma_trinn_tabellen_er_tom_i_det_oppdiktede_settet(oppdiktet: LagInndata) -> None:
"""The table is only carried by a set used for line 10; without it the row cannot be run."""
inn = oppdiktet()
assert inn.Gamma_trinn == {}
with pytest.raises(KeyError):
ks.dimensjoner(inn, Losning.A, gamma_trinn=True)
assert ks.dimensjoner(replace(inn, Gamma_trinn={"A>=A*": 1.0}), Losning.A, gamma_trinn=True)