feat(utbygging): build out solution T in modules and add S48-S54

utbyggingsplan_trinnvis follows chapter 17.1: the grid balance of the
first stage, the payment condition for a module's power plants, S49,
and in T-K the two stocks of chips and the queue for replacements.
tidslinje gives MW IT in operation per type of power (S50). S48-S54
are pure functions in ligninger.py, and Inndata carries the new
quantities, the scenarios for the loss of demand and the paths of
u_alt. lag_plan returns a Trinnvisplan for T-F and T-K; regn_program
refuses T until it is taken through the cash flow.

Tested on made-up numbers only (59 new tests, hand-computed build-outs).
Nothing is computed for the hypothesis.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-12 23:55:57 +01:00
commit bca6496c0a
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
12 changed files with 1271 additions and 31 deletions

View file

@ -45,6 +45,17 @@ KM2_PER_TWH_TIL_PER_MWH: Final = 1e-6
TOMT: Final = "tomt"
"""The entry of the area table that is per MW IT, not per TWh."""
G_PER_KWH_TIL_TONN_PER_MWH: Final = 1e-3
"""The paths of u_alt are in g CO2 per kWh; the equations use tonnes per MWh (17.4)."""
BORTFALL_KILDE: Final = "kildenes lave forlop"
BORTFALL_EGNE_LAV: Final = "80 % paa egne maskiner, lav"
BORTFALL_EGNE_HOY: Final = "80 % paa egne maskiner, hoy"
"""The marked scenarios for AI use on the users' own machines (17.3)."""
Bane = dict[int, float]
"""A path: the value at some years. One point means the same value in every year."""
@dataclass(frozen=True)
class Prislinje:
@ -103,6 +114,12 @@ class Inndata:
areal: km2 per MWh per year for nuclear power and wind, and km2 per MW IT for the plot.
petroleum_median: the median of the state's net cash flow from petroleum over the ten
years, kr in the kroner of the price year (shown next to M6; clarification 53).
bortfall: (d_30, d_35) per marked scenario for AI use on the users' own machines (17.3).
u_alt: the paths for the emissions of the power the compute would otherwise have used,
tonnes CO2 per MWh, by estimate: ``hoved``, ``lav``, ``hoy_nedre``, ``hoy_ovre``
and ``null`` (17.4).
kjoletaarn: nuclear power with cooling towers, shown next to the main figure:
(low, median, high) m3 per MWh for ``forbruk`` and ``uttak`` (17.5).
"""
v: Mapping[str, float]
@ -116,6 +133,9 @@ class Inndata:
eierformer: Mapping[str, Eierform] = field(default_factory=dict)
areal: Mapping[str, float] = field(default_factory=dict)
petroleum_median: float = 0.0
bortfall: Mapping[str, tuple[float, float]] = field(default_factory=dict)
u_alt: Mapping[str, Mapping[int, float]] = field(default_factory=dict)
kjoletaarn: Mapping[str, tuple[float, float, float]] = field(default_factory=dict)
def __getitem__(self, navn: str) -> float:
"""The scalar quantity with this id, in the units of the equations."""
@ -131,15 +151,19 @@ class Inndata:
def karbonpris_i(self, t: int) -> float:
"""The carbon price in year ``t``: linear between the years of the table."""
aar = sorted(self.karbonpris)
if t <= aar[0]:
return self.karbonpris[aar[0]]
if t >= aar[-1]:
return self.karbonpris[aar[-1]]
ovre = next(a for a in aar if a >= t)
nedre = aar[aar.index(ovre) - 1]
andel = (t - nedre) / (ovre - nedre)
return self.karbonpris[nedre] + andel * (self.karbonpris[ovre] - self.karbonpris[nedre])
return lg.lineaer_bane(punkter=self.karbonpris, t=t)
def u_alt_i(self, anslag: str, t: int) -> float:
"""u_alt in year ``t`` for one estimate, tonnes CO2 per MWh (17.4).
Linear between the years of the table and fixed after the last one.
"""
return lg.lineaer_bane(punkter=self.u_alt[anslag], t=t)
def bortfall_i(self, scenario: str, t_v: int) -> float:
"""The loss of demand for vintage ``t_v`` in one marked scenario (17.3)."""
d_30, d_35 = self.bortfall[scenario]
return lg.s51_bortfall(t_v=t_v, d_30=d_30, d_35=d_35)
def tilpass_prislinjer(scenarioer: Sequence[Prisscenario]) -> dict[str, Prislinje]:
@ -183,6 +207,62 @@ def tolk_areal(tabell: object) -> dict[str, float]:
}
def tolk_bortfall(
*, d_kilde: object, s_flytt: object, s_trening: object
) -> dict[str, tuple[float, float]]:
"""17.3: (d_30, d_35) per marked scenario, from the three tables of the parameter file.
The scenario "80 %" is s_flytt (1 - s_trening), with the high share of
training in the low version and the low share in the high version.
"""
kilde, flytt, trening = (_ordbok_av_tall(t) for t in (d_kilde, s_flytt, s_trening))
aar_30, aar_35 = (str(aar) for aar in lg.BORTFALL_AAR[1:])
def egne(andel_trening: float) -> tuple[float, float]:
return (
lg.s51_bortfall_egne_maskiner(s_flytt=flytt[aar_30], s_trening=andel_trening),
lg.s51_bortfall_egne_maskiner(s_flytt=flytt[aar_35], s_trening=andel_trening),
)
return {
BORTFALL_KILDE: (kilde[aar_30], kilde[aar_35]),
BORTFALL_EGNE_LAV: egne(trening["hoy"]),
BORTFALL_EGNE_HOY: egne(trening["lav"]),
}
def tolk_u_alt(tabell: object) -> dict[str, Bane]:
"""17.4: the paths of u_alt in tonnes CO2 per MWh, from the table in g CO2 per kWh.
The high estimate is two figures that are fixed over time and shown as a
range; they become two paths with one point each, and so does zero.
"""
raa = cast("dict[str, object]", tabell)
faktor = G_PER_KWH_TIL_TONN_PER_MWH
forste_aar = min(int(aar) for aar in cast("dict[str, float]", raa["hoved"]))
def bane(punkter: object) -> Bane:
return {int(aar): float(v) * faktor for aar, v in cast("dict[str, float]", punkter).items()}
hoy = _ordbok_av_tall(raa["hoy"])
return {
"hoved": bane(raa["hoved"]),
"lav": bane(raa["lav"]),
"hoy_nedre": {forste_aar: hoy["lav"] * faktor},
"hoy_ovre": {forste_aar: hoy["hoy"] * faktor},
"null": {forste_aar: float(cast("float", raa["null"])) * faktor},
}
def tolk_kjoletaarn(tabell: object) -> dict[str, tuple[float, float, float]]:
"""17.5: nuclear power with cooling towers, (low, median, high) m3 per MWh."""
ut = {}
for navn, verdier in cast("dict[str, list[float]]", tabell).items():
lav, median, hoy = (float(v) for v in verdier)
ut[navn] = (lav, median, hoy)
return ut
def fra_trekning(
sett: Parametersett,
trekninger: Trekninger,
@ -221,4 +301,11 @@ def fra_trekning(
eierformer=tolk_eierformer(sett.tabell("eierformer")),
areal=tolk_areal(sett.tabell("alpha")),
petroleum_median=statistics.median(sett.petroleumsinntekt(faste_kroner=True).values()),
bortfall=tolk_bortfall(
d_kilde=sett.tabell("d_kilde"),
s_flytt=sett.tabell("s_flytt"),
s_trening=sett.tabell("s_trening"),
),
u_alt=tolk_u_alt(sett.tabell("u_alt")),
kjoletaarn=tolk_kjoletaarn(sett.tabell("w_N_taarn")),
)

View file

@ -398,9 +398,11 @@ def dimensjoner(inn: Inndata, losning: Losning, *, rho_A: float | None = None) -
"""S7, S8, S10, S44 and S46 for one set of values.
``rho_A`` is the required return for the power plant in A; the main run
uses rho_D (clarification 8), and rho_N is a sensitivity.
uses rho_D (clarification 8), and rho_N is a sensitivity. In solution T
everything is per module, with P_m in place of P_IT (chapter 17.1).
"""
P_u, m, r, n_p, N_u, Gamma, P_G_N = 0.0, 0, 0, 0, 0, 1.0, 0.0
P_IT = inn["P_m"] if losning.trinnvis else inn["P_IT"]
if losning in {Losning.A, Losning.B_MERKET}:
P_u, m = lg.s7_enhetsstorrelse(
P_sett=inn.P_u_sett, chi=inn["chi"], lam=inn["lambda"], PUE=inn["PUE"], P_IT=inn["P_IT"]
@ -418,13 +420,13 @@ def dimensjoner(inn: Inndata, losning: Losning, *, rho_A: float | None = None) -
Gamma = lg.s44_inntektsfaktor(
m=m, r=r, o_f_A=_utfallsrate(inn, P_u), beta_F=inn["beta_F"]
)
elif losning is Losning.B:
elif losning in {Losning.B, Losning.T_K}:
P_u = inn["P_ref"]
P_G_N = lg.s22_reaktoreffekt_B(
lam=inn["lambda"], PUE=inn["PUE"], P_IT=inn["P_IT"], KF=_kapasitetsfaktor(inn)
lam=inn["lambda"], PUE=inn["PUE"], P_IT=P_IT, KF=_kapasitetsfaktor(inn)
)
return Dimensjonering(
E_D=lg.s10_energi_datasenter(lam=inn["lambda"], PUE=inn["PUE"], P_IT=inn["P_IT"]),
E_D=lg.s10_energi_datasenter(lam=inn["lambda"], PUE=inn["PUE"], P_IT=P_IT),
P_u=P_u,
m=m,
r=r,
@ -446,8 +448,12 @@ def _kapasitetsfaktor(inn: Inndata) -> float:
def _tidligste_aar(inn: Inndata, losning: Losning) -> int:
"""S33 and S12, rounded up to the first whole operating year (clarification 21)."""
if losning.kjernekraft:
"""S33, S12 and S48, rounded up to the first whole operating year (clarification 21)."""
if losning.trinnvis:
tidspunkt = lg.s48_tidligste_tidspunkt_trinnvis(
T_0=inn["T0"], tau_1=inn["tau_1"], tau_nett=inn["tau_nett"], tau_D=inn["tau_D"]
)
elif losning.kjernekraft:
tidspunkt = lg.s33_tidligste_tidspunkt_kjernekraft(
T_0=inn["T0"], tau_F=inn["tau_F"], tau_reg_min=inn["tau_reg_min"], tau_N=inn["tau_N"]
)
@ -458,9 +464,9 @@ def _tidligste_aar(inn: Inndata, losning: Losning) -> int:
def _kraftrom(inn: Inndata, losning: Losning, dim: Dimensjonering) -> Callable[[int], float]:
T_0 = inn.heltall("T0")
if losning.kjernekraft:
if losning.kjernekraft and not losning.trinnvis:
return ub.kraftrom_reaktor(n_reaktor=inn["n_reaktor"], P_G_N=dim.P_G_N, T_0=T_0)
if losning is Losning.C:
if losning is Losning.C or losning.trinnvis:
return ub.kraftrom_fornybar(
g_fornybar=inn["g_fornybar"],
w_tort_vann=inn["w_tort_vann"],
@ -480,16 +486,42 @@ def lag_plan(
N_anlegg: int,
eksportregel: bool = True,
brikker_fra_T0: bool = False,
uten_forste_trinn: bool = False,
uten_s49: bool = False,
) -> Plan:
"""The build-out of a path with ``N_anlegg`` facilities (S22, S33).
"""The build-out of a path with ``N_anlegg`` facilities (S22, S33; chapter 17.1 for T).
``eksportregel=False`` is the path given that no export rule is introduced
(shown next to the verdict, chapter 4). Deliveries of chips count from the
solution's first possible operating year (clarification 25);
``brikker_fra_T0=True`` saves them up from the decision year instead, the
reading the text had before the project owner decided.
In solution T the path is ``N_anlegg * P_IT / P_m`` modules, and the plan
is a ``Trinnvisplan``. Two sensitivities of chapter 17.8 are switches
here (clarification 73): ``uten_forste_trinn=True`` lets the first module
start in the year new grid can be in place at the earliest ("C built in
modules"), and ``uten_s49=True`` builds nuclear power in T-K whenever at
least one module remains when nuclear power can come.
"""
phi_X = inn["phi_X"] if eksportregel else 0.0
stopp = ub.eksportstopp(u=inn.u_eksport, phi_X=phi_X, D_X=inn["D_X"])
if losning.trinnvis:
if brikker_fra_T0:
msg = "the reading where chips are saved up from the decision year is not defined for T"
raise ValueError(msg)
return _lag_plan_trinnvis(
inn,
losning,
dim,
N_anlegg=N_anlegg,
stopp=stopp,
uten_forste_trinn=uten_forste_trinn,
uten_s49=uten_s49,
)
if uten_forste_trinn or uten_s49:
msg = "the switches for the first stage and for S49 only apply to solution T"
raise ValueError(msg)
t_min = _tidligste_aar(inn, losning)
return ub.utbyggingsplan(
N_anlegg=N_anlegg,
@ -504,7 +536,92 @@ def lag_plan(
s_brikker=inn["s_brikker"], G_server=inn["G_server"], utskifting=0.0
),
kraftrom=_kraftrom(inn, losning, dim),
stopp=ub.eksportstopp(u=inn.u_eksport, phi_X=phi_X, D_X=inn["D_X"]),
stopp=stopp,
)
def antall_moduler(inn: Inndata, N_anlegg: int) -> int:
"""Chapter 17.1: J = N* P_IT / P_m, the modules in a path of ``N_anlegg`` facilities."""
J = N_anlegg * inn["P_IT"] / inn["P_m"]
if abs(J - round(J)) > lg.AVRUNDINGSTOLERANSE * max(1.0, J):
msg = f"{N_anlegg} facilities of {inn['P_IT']} MW are not a whole number of modules"
raise ValueError(msg)
return round(J)
def forste_aar_kraft(inn: Inndata, dim: Dimensjonering) -> Callable[[int], int]:
"""Chapter 17.1, condition 4: the first year module j can start, given its power plants.
No payment for the plants in the module's portfolio may fall before the
year T_0 + 1. The portfolio of module j is what S39 adds when the number of
modules goes from j - 1 to j, and each plant is paid over its construction
time (clarification 21; hydropower in the year before start, clarification 10).
"""
T_0 = inn.heltall("T0")
def forste(j: int) -> int:
verkene = kraftverk_for_anlegg(inn, Losning.C, dim, j)
byggeaar = (len(lg.byggeaar_andeler(tau=verk.byggetid)) for verk in verkene)
return T_0 + 1 + max(byggeaar, default=0)
return forste
def _lag_plan_trinnvis(
inn: Inndata,
losning: Losning,
dim: Dimensjonering,
*,
N_anlegg: int,
stopp: Sequence[bool],
uten_forste_trinn: bool,
uten_s49: bool,
) -> ub.Trinnvisplan:
"""Chapter 17.1: the build-out of a path in T-F or T-K, in modules."""
T_0 = inn.heltall("T0")
J = antall_moduler(inn, N_anlegg)
t_nett = _tidligste_aar(inn, Losning.C)
t_forste = _tidligste_aar(inn, losning)
fase = None
if losning is Losning.T_K:
KF = _kapasitetsfaktor(inn)
def bygges(J_F: int) -> bool:
if uten_s49:
return J_F < J
return lg.s49_kjernekraft_bygges(
J=J,
J_F=J_F,
lam=inn["lambda"],
PUE=inn["PUE"],
P_m=inn["P_m"],
KF=KF,
P_ref=inn["P_ref"],
)
fase = ub.Kjernekraftfase(
t_N=_tidligste_aar(inn, Losning.B),
rom=ub.kraftrom_reaktor(n_reaktor=inn["n_reaktor"], P_G_N=dim.P_G_N, T_0=T_0),
bygges=bygges,
)
return ub.utbyggingsplan_trinnvis(
J=J,
T_0=T_0,
T_s=inn.heltall("T_slutt"),
t_forste=max(t_forste, t_nett) if uten_forste_trinn else t_forste,
t_nett=t_nett,
P_m=inn["P_m"],
PUE=inn["PUE"],
n_1=inn["n_1"],
L_H=inn.heltall("L_H"),
L_N=lg.avrundet_varighet(varighet=inn["L_N"]),
brikker_per_aar=lg.s22_grense_brikker(
s_brikker=inn["s_brikker"], G_server=inn["G_server"], utskifting=0.0
),
kraftrom=_kraftrom(inn, losning, dim),
forste_aar_kraft=forste_aar_kraft(inn, dim),
stopp=stopp,
kjernekraft=fase,
)
@ -1211,6 +1328,9 @@ def regn_program(
1). ``tilleggsregel=False`` credits power plants on the grid their surplus
(the figures without S45 are shown next to the verdict).
"""
if losning.trinnvis:
msg = "solution T is not taken through the cash flow yet (chapter 17 beyond the build-out)"
raise NotImplementedError(msg)
if not plan.gjennomforbar:
msg = "the path cannot be built within the final year, so it has no net present value"
raise ValueError(msg)

View file

@ -12,10 +12,11 @@ The parameter file states costs in other units (kr/kW, mill. kr ...);
This file covers every equation: the power plant, the data centre, the revenue,
the build-out (S22, S33, S39, S41), the power system (S23 to S25, S38, S47), the
cash flow (S26, S34, S35, S40, S45), business economics (S27, S28, S42),
ownership (S29, S30), scale (S31), environment (S32) and the share behind a
verdict (S37). The functions work on one year, one facility or one vintage at a
time; ``utbygging``, ``kraftsystem``, ``kontantstrom``, ``nivaaisert``,
``eierskap``, ``skala``, ``miljo`` and ``dommer`` put them together.
ownership (S29, S30), scale (S31), environment (S32), the share behind a
verdict (S37) and the addition to the direction in chapter 17 (S48 to S54). The
functions work on one year, one facility or one vintage at a time;
``utbygging``, ``kraftsystem``, ``kontantstrom``, ``nivaaisert``, ``eierskap``,
``skala``, ``miljo`` and ``dommer`` put them together.
"""
from __future__ import annotations
@ -25,7 +26,7 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, TypeVar
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from collections.abc import Callable, Mapping, Sequence
import numpy as np
import numpy.typing as npt
@ -60,6 +61,9 @@ HALVT_AAR = 0.5
HALVERINGSTOLERANSE = 1e-12
"""The interval for varsigma is halved until it is this narrow (S45, clarification 22)."""
BORTFALL_AAR = (2025, 2030, 2035)
"""The loss of demand: zero in the first year, d_30 in the second, d_35 from the third (17.3)."""
# --------------------------------------------------------------------------- S1
@ -1343,3 +1347,161 @@ def s37_andel(oppfylt: Sequence[bool]) -> float:
msg = "a share needs at least one draw"
raise ValueError(msg)
return sum(oppfylt) / len(oppfylt)
# ------------------------------- the addition to the direction (chapter 17): S48 to S54
def lineaer_bane(*, punkter: Mapping[int, float], t: float) -> float:
"""A path given at some years: linear between them, fixed before the first and after the last.
A path with one point is the same in every year.
"""
if not punkter:
msg = "a path needs at least one point"
raise ValueError(msg)
aar = sorted(punkter)
if t <= aar[0]:
return punkter[aar[0]]
if t >= aar[-1]:
return punkter[aar[-1]]
ovre = next(a for a in aar if a >= t)
nedre = aar[aar.index(ovre) - 1]
andel = (t - nedre) / (ovre - nedre)
return punkter[nedre] + andel * (punkter[ovre] - punkter[nedre])
def s48_tidligste_tidspunkt_trinnvis(
*, T_0: float, tau_1: float, tau_nett: float, tau_D: float
) -> float:
"""S48 (T): T_0 + max(min(tau_1, tau_nett), 1 + tau_D), a point in time, not yet a year."""
return T_0 + max(min(tau_1, tau_nett), 1.0 + tau_D)
def s48_nettsaldo(
*, saldo_forrige: float, brukt_forrige: float, n_1: float, PUE: float, P_m: float
) -> float:
"""Text under S48: the grid balance at the start of a year in the first stage, MW of draw.
N(t) = min(N(t-1) - brukt(t-1) + n_1, n_1 + PUE P_m): what is left over is
carried on, but never more than one module needs on top of the year's
allowance.
"""
return min(saldo_forrige - brukt_forrige + n_1, n_1 + PUE * P_m)
def s49_kjernekraft_bygges(
*, J: int, J_F: int, lam: float, PUE: float, P_m: float, KF: float, P_ref: float
) -> bool:
"""S49 (T-K): True when what is left of the path needs at least one whole unit.
(J - J_F) lam PUE P_m >= KF P_ref, with the tolerance of clarification 6.
``J`` is the number of modules in the path and ``J_F`` those that start
before nuclear power can come.
"""
if not 0 <= J_F <= J:
msg = f"J_F must lie between 0 and J = {J}, got {J_F}"
raise ValueError(msg)
return (J - J_F) * lam * PUE * P_m >= KF * P_ref * (1.0 - AVRUNDINGSTOLERANSE)
def s50_regnekraft_i_drift(
*, P: Sequence[float], har_aargang: Sequence[bool], kraft: Sequence[str], x: str
) -> float:
"""S50: MW IT in operation in one year on power of type ``x``.
One element per facility or module: its size ``P`` (MW IT), whether it has
a vintage in operation that year, and the type of power it runs on.
"""
if not len(P) == len(har_aargang) == len(kraft):
msg = "S50 needs one size, one flag and one type of power per facility or module"
raise ValueError(msg)
return math.fsum(
P_k for P_k, last, type_ in zip(P, har_aargang, kraft, strict=True) if last and type_ == x
)
def s51_bortfall(*, t_v: float, d_30: float, d_35: float) -> float:
"""17.3: the loss of demand for vintage ``t_v`` in a scenario.
Linear between d(2025) = 0, d(2030) = d_30 and d(2035) = d_35, and fixed
from 2035.
"""
for navn, d in (("d_30", d_30), ("d_35", d_35)):
if not 0.0 <= d <= 1.0:
msg = f"{navn} is a share between 0 and 1, got {d}"
raise ValueError(msg)
start, midt, slutt = BORTFALL_AAR
return lineaer_bane(punkter={start: 0.0, midt: d_30, slutt: d_35}, t=t_v)
def s51_bortfall_egne_maskiner(*, s_flytt: float, s_trening: float) -> float:
"""17.3, the scenario "80 % on the users' own machines": s_flytt (1 - s_trening)."""
return s_flytt * (1.0 - s_trening)
def s51_etterspoerselsfaktor(*, eps_d: float, d: float) -> float:
"""S51: mu_d = max(0, 1 - eps_d d), the factor on the share of capacity sold.
``d`` is the share of demand that falls away for the vintage, against the
main path; d = 0 gives the main path.
"""
if not 0.0 <= d <= 1.0:
msg = f"the loss of demand is a share between 0 and 1, got {d}"
raise ValueError(msg)
if eps_d < 0:
msg = f"eps_d cannot be negative, got {eps_d}"
raise ValueError(msg)
return max(0.0, 1.0 - eps_d * d)
def s52_bortfallsterskel(*, k_a: float | None, eps_d: float) -> float | None:
"""S52: d* = min(1, max(0, (1 - k_a) / eps_d)), the loss that gives median NPV zero.
``k_a`` is the price threshold of chapter 3.2; None when it does not exist
(clarification 60), and then the threshold for the loss does not exist either.
"""
if eps_d <= 0:
msg = f"eps_d must be positive, got {eps_d}"
raise ValueError(msg)
if k_a is None:
return None
return min(1.0, max(0.0, (1.0 - k_a) / eps_d))
def s53_unngaatt_utslipp(
*,
u_alt: float,
mu: float,
mu_d: float,
Gamma: float,
lam: float,
PUE_v: float,
P: float,
) -> float:
"""S53, one facility or module with a vintage in operation: avoided emissions, tonnes per year.
u_alt mu mu_d Gamma 8760 lam PUE_v P, with ``u_alt`` in tonnes per MWh and
``P`` in MW IT. Only compute that is sold and delivered replaces compute
elsewhere.
"""
return u_alt * mu * mu_d * Gamma * TIMER_PER_AAR * lam * PUE_v * P
def s53_utslipp_med_fradrag(*, U_liv: float, U_unngaatt: float) -> float:
"""S53: U_med = U_liv - U_unngaatt, tonnes; shown next to the main figure, never judged."""
return U_liv - U_unngaatt
def s54_it_energi(*, lam: float, P: float) -> float:
"""S54: 8760 lam P, the IT energy of facilities and modules with a vintage in operation, MWh."""
return TIMER_PER_AAR * lam * P
def s54_kjolevann(*, w_D: float, w_N: float, E_IT: float, E_N: float) -> float:
"""S54: w_D E_IT + w_N E_N, cubic metres of cooling water in one year.
Used for withdrawal and for consumption, each with its own ``w_D`` (m3 per
MWh IT) and ``w_N`` (m3 per MWh produced by the nuclear units).
"""
return w_D * E_IT + w_N * E_N

View file

@ -22,6 +22,23 @@ How the limit in S22 is read (specification, chapter 16):
- While an export rule is in force nothing is delivered, and neither a new
facility nor a new vintage can start.
Solution T, "stepwise" (chapter 17.1), is built in modules. ``utbyggingsplan_trinnvis``
follows the same rules per module, and adds what chapter 17.1 says:
- First stage: in the years before new grid can be in place, a module can only
start when the programme's grid balance has room for its draw. The balance
grows by n_1 each year from the first possible operating year (S48), and what
is left over is carried on, but never more than one module needs.
- A module can only start when no payment for the power plants in its
portfolio falls before the year T_0 + 1.
- T-K: modules that start before nuclear power can come (t_N) are renewable
modules. When what is left of the path needs at least one whole unit (S49),
no new renewable portfolios are built from t_N, and the remaining modules
are nuclear modules, limited by the reactors built. The stock of chips is
then split in two at the start of t_N: the old stock can only replace
vintages in renewable modules, and nuclear modules can only use chips
delivered from t_N. When S49 is not met, T-K is T-F in every year.
Nothing here reads the parameter file or draws random numbers.
"""
@ -46,6 +63,8 @@ class Losning(enum.StrEnum):
B_MERKET = "B'"
C = "C"
R = "R"
T_F = "T-F"
T_K = "T-K"
@property
def paa_nett(self) -> bool:
@ -54,8 +73,22 @@ class Losning(enum.StrEnum):
@property
def kjernekraft(self) -> bool:
"""True for the solutions with nuclear power."""
return self in {Losning.A, Losning.B, Losning.B_MERKET}
"""True for the solutions with nuclear power (T-K also where S49 is seldom met)."""
return self in {Losning.A, Losning.B, Losning.B_MERKET, Losning.T_K}
@property
def trinnvis(self) -> bool:
"""True for the two versions of solution T, built in modules (chapter 17.1)."""
return self in {Losning.T_F, Losning.T_K}
class Kraft(enum.StrEnum):
"""The types of power the timeline tells apart (S50)."""
EGET_KJERNEKRAFTVERK = "eget kjernekraftverk uten nett"
KJERNEKRAFT_PAA_NETTET = "kjernekraft paa nettet"
NY_FORNYBAR = "ny fornybar kraft"
KJOP_FRA_NETTET = "kjop fra nettet uten ny kraft"
@dataclass(frozen=True)
@ -135,6 +168,72 @@ class Plan:
return sum(self.har_last(k, t) for k in range(len(self.anlegg)))
@dataclass(frozen=True)
class Trinnvisplan(Plan):
"""The build-out of one path in solution T (chapter 17.1). ``anlegg`` holds the modules.
Attributes:
P_m: MW IT per module.
t_forste: the first possible operating year of the first module (S48, rounded up).
t_nett: the year new grid can be in place at the earliest (S33, rounded up). The first
stage is the years before it.
t_N: the year nuclear power can come at the earliest; None in T-F.
J_F: the number of modules that start before ``t_N``; None in T-F.
kjernekraft_bygges: True in T-K when S49 is met. False in T-F, and in T-K when S49 is
not met; the plan is then that of T-F.
"""
P_m: float
t_forste: int
t_nett: int
t_N: int | None
J_F: int | None
kjernekraft_bygges: bool
def er_kjernekraftmodul(self, k: int) -> bool:
"""True when module ``k`` (0 is the first) gets nuclear power on the grid."""
return self.kjernekraft_bygges and self.J_F is not None and k >= self.J_F
def i_forste_trinn(self, k: int) -> bool:
"""True when module ``k`` started within the grid that exists, before new grid can come."""
return self.anlegg[k].start < self.t_nett
def krafttype(losning: Losning, plan: Plan, k: int) -> Kraft:
"""S50: the type of power facility or module ``k`` (0 is the first) runs on."""
if losning.trinnvis:
if not isinstance(plan, Trinnvisplan):
msg = "solution T needs a plan from utbyggingsplan_trinnvis"
raise TypeError(msg)
return Kraft.KJERNEKRAFT_PAA_NETTET if plan.er_kjernekraftmodul(k) else Kraft.NY_FORNYBAR
if losning is Losning.A:
return Kraft.EGET_KJERNEKRAFTVERK
if losning.kjernekraft:
return Kraft.KJERNEKRAFT_PAA_NETTET
return Kraft.NY_FORNYBAR if losning is Losning.C else Kraft.KJOP_FRA_NETTET
def tidslinje(losning: Losning, plan: Plan, *, P_IT: float) -> dict[Kraft, tuple[float, ...]]:
"""S50 for one path: MW IT in operation per type of power, for each year T_0 + 1 .. T_s.
``P_IT`` is the size of one facility; a plan for solution T uses its own
module size. A path that cannot be built is reported with what was built.
"""
storrelse = plan.P_m if isinstance(plan, Trinnvisplan) else P_IT
antall = len(plan.anlegg)
typer = [krafttype(losning, plan, k) for k in range(antall)]
med_last = [
[plan.har_last(k, t) for k in range(antall)] for t in range(plan.T_0 + 1, plan.T_s + 1)
]
return {
x: tuple(
lg.s50_regnekraft_i_drift(P=[storrelse] * antall, har_aargang=flagg, kraft=typer, x=x)
for flagg in med_last
)
for x in Kraft
}
def eksportstopp(*, u: Sequence[float], phi_X: float, D_X: float) -> tuple[bool, ...]:
"""Chapter 4: the years in which an export rule stops the delivery of chips.
@ -265,3 +364,181 @@ def utbyggingsplan(
anlegg=tuple(Anleggsplan(a.start, a.siste_driftsaar, tuple(a.aarganger)) for a in anlegg),
stopp=tuple(stopp),
)
# ------------------------------------------------ solution T, "stepwise" (chapter 17.1)
@dataclass(frozen=True)
class Kjernekraftfase:
"""What the build-out of T-K needs to know about nuclear power (chapter 17.1).
Attributes:
t_N: the first year nuclear power can come (S33, rounded up).
rom: the number of nuclear modules the reactors built have room for in year t
(the reactor term of S22, accumulated from T_0; clarification 23).
bygges: S49 as a function of J_F, the number of modules that start before ``t_N``.
"""
t_N: int
rom: Callable[[int], float]
bygges: Callable[[int], bool]
@dataclass
class _Brikkelager:
"""The stock of chips in T, MW IT. In T-F and before t_N everything lies in ``nytt``."""
gammelt: float = 0.0
nytt: float = 0.0
def del_i_to(self) -> None:
"""At the start of t_N: the stock so far can only replace vintages in renewable modules."""
self.gammelt, self.nytt = self.gammelt + self.nytt, 0.0
def ta(self, mengde: float, *, ogsaa_gammelt: bool) -> bool:
"""Take ``mengde`` if the stocks allowed have room for it; the old stock first."""
tilgjengelig = self.nytt + (self.gammelt if ogsaa_gammelt else 0.0)
if not _rommer(tilgjengelig, mengde):
return False
fra_gammelt = min(self.gammelt, mengde) if ogsaa_gammelt else 0.0
self.gammelt -= fra_gammelt
self.nytt -= mengde - fra_gammelt
return True
def _skift_ut(
moduler: Sequence[_Anlegg],
lager: _Brikkelager,
*,
t: int,
L_H: int,
P_m: float,
forste_kjernekraftmodul: int | None,
) -> None:
"""Replace the expired vintages the stocks have room for, the one that expired first first.
A replacement that cannot be made from the stocks it may use waits, and the
next ones in the queue are replaced if their stocks have room.
"""
venter = [
(k, m) for k, m in enumerate(moduler) if m.aarganger[-1] + L_H <= t <= m.siste_driftsaar
]
for k, modul in sorted(venter, key=lambda par: par[1].aarganger[-1]):
kjernekraft = forste_kjernekraftmodul is not None and k >= forste_kjernekraftmodul
if lager.ta(P_m, ogsaa_gammelt=not kjernekraft):
modul.aarganger.append(t)
def _kontroller_trinnvis(
*,
antall_stopp: int,
antall_aar: int,
t_forste: int,
t_nett: int,
kjernekraft: Kjernekraftfase | None,
) -> None:
if antall_stopp != antall_aar:
msg = f"expected one export flag per year after T_0 ({antall_aar}), got {antall_stopp}"
raise ValueError(msg)
if kjernekraft is not None and kjernekraft.t_N < max(t_forste, t_nett):
msg = (
f"nuclear power in {kjernekraft.t_N} would come before new grid ({t_nett}) or before "
f"the first module ({t_forste}); chapter 17.1 has no rule for that"
)
raise ValueError(msg)
def utbyggingsplan_trinnvis(
*,
J: int,
T_0: int,
T_s: int,
t_forste: int,
t_nett: int,
P_m: float,
PUE: float,
n_1: float,
L_H: int,
L_N: int,
brikker_per_aar: float,
kraftrom: Callable[[int], float],
forste_aar_kraft: Callable[[int], int],
stopp: Sequence[bool],
kjernekraft: Kjernekraftfase | None = None,
) -> Trinnvisplan:
"""Chapter 17.1: the year each module of a path in solution T starts, and its vintages.
``J`` is the number of modules in the path, ``t_forste`` the first possible
operating year of the first module (S48, rounded up) and ``t_nett`` the
year new grid can be in place at the earliest. ``n_1`` is the MW of draw
that can be connected per year in the first stage, and a module draws
``PUE * P_m``. ``kraftrom(t)`` is the number of modules the renewable power
built by year t has room for, and ``forste_aar_kraft(j)`` the first year
module number j (1 is the first) can start without any payment for its
power plants falling before T_0 + 1. ``kjernekraft`` is given for T-K and
left out for T-F. The rest is as in ``utbyggingsplan``.
The text takes for granted that nuclear power cannot come before new grid
can be in place or before the first module can start; a set of values
where it can is refused.
"""
_kontroller_trinnvis(
antall_stopp=len(stopp),
antall_aar=T_s - T_0,
t_forste=t_forste,
t_nett=t_nett,
kjernekraft=kjernekraft,
)
uttak = PUE * P_m
lager = _Brikkelager()
moduler: list[_Anlegg] = []
saldo, brukt = 0.0, 0.0
J_F: int | None = None
bygges = False
def kan_starte(t: int) -> bool:
"""The power and grid conditions for the next module in year ``t``."""
nummer = len(moduler) + 1
if kjernekraft is not None and J_F is not None and bygges:
return _rommer(kjernekraft.rom(t), nummer - J_F)
kraft_rekker = _rommer(kraftrom(t), nummer) and t >= forste_aar_kraft(nummer)
return kraft_rekker and (t >= t_nett or _rommer(saldo - brukt, uttak))
for t in range(T_0 + 1, T_s + 1):
if kjernekraft is not None and t == kjernekraft.t_N:
J_F = len(moduler)
bygges = kjernekraft.bygges(J_F)
if bygges:
lager.del_i_to()
if t_forste <= t < t_nett:
saldo = lg.s48_nettsaldo(
saldo_forrige=saldo, brukt_forrige=brukt, n_1=n_1, PUE=PUE, P_m=P_m
)
brukt = 0.0
if stopp[t - T_0 - 1] or t < t_forste:
continue
lager.nytt += brikker_per_aar
_skift_ut(
moduler, lager, t=t, L_H=L_H, P_m=P_m, forste_kjernekraftmodul=J_F if bygges else None
)
while len(moduler) < J and kan_starte(t) and lager.ta(P_m, ogsaa_gammelt=False):
moduler.append(_Anlegg(start=t, siste_driftsaar=t + L_N - 1, aarganger=[t]))
brukt += uttak if t < t_nett else 0.0
if kjernekraft is not None and J_F is None:
J_F = len(moduler)
bygges = kjernekraft.bygges(J_F)
return Trinnvisplan(
N_anlegg=J,
T_0=T_0,
T_s=T_s,
L_H=L_H,
anlegg=tuple(Anleggsplan(m.start, m.siste_driftsaar, tuple(m.aarganger)) for m in moduler),
stopp=tuple(stopp),
P_m=P_m,
t_forste=t_forste,
t_nett=t_nett,
t_N=None if kjernekraft is None else kjernekraft.t_N,
J_F=J_F,
kjernekraft_bygges=bygges,
)

View file

@ -155,6 +155,15 @@ GRUNNVERDIER: Mapping[str, float] = {
"u_vann": 0.004,
"u_H": 1000.0,
"eta_N": 3e-6,
# the addition to the direction (chapter 17): modules, first stage, own machines, water
"P_m": 100.0,
"tau_1": 2.0,
"n_1": 150.0,
"eps_d": 1.0,
"w_D_uttak": 0.1,
"w_N_uttak": 150.0,
"w_N_forbruk": 0.0,
"w_D_sjo": 100.0,
}
"""Round, invented values in the units of the equations (kr, MW, MWh, kr/MWh, years)."""
@ -191,6 +200,13 @@ def lag_inndata(*, u_eksport: tuple[float, ...] | None = None, **endringer: floa
eierformer=EIERFORMER,
areal={"kjernekraft": 0.1e-6, "vind_direkte": 1.5e-6, "vind_plan": 30e-6, "tomt": 0.001},
petroleum_median=250e9,
bortfall={"lavt": (0.1, 0.2), "hoyt": (0.3, 0.6)},
u_alt={
"hoved": {2025: 0.4, 2035: 0.2, 2045: 0.1},
"fast": {2025: 0.5},
"null": {2025: 0.0},
},
kjoletaarn={"forbruk": (2.0, 2.5, 3.0), "uttak": (3.0, 4.0, 10.0)},
)

View file

@ -23,6 +23,9 @@ if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
I_KONTANTSTROMMEN = tuple(a for a in Losning if not a.trinnvis)
"""The solutions the cash flow is coded for. Solution T only has its build-out so far."""
E_D = 8760.0 * 0.75 * 1.2 * 1000.0
"""Yearly energy to one made-up data centre: 7 884 000 MWh."""
@ -202,7 +205,7 @@ def test_R_bedriftsstrom_haandregnet(oppdiktet: LagInndata) -> None:
)
@pytest.mark.parametrize("losning", list(Losning))
@pytest.mark.parametrize("losning", I_KONTANTSTROMMEN)
@pytest.mark.parametrize(
"endringer", [{}, {"T_slutt": 2045, "u_xi": 0.1}, {"L_N": 12.0, "L_B": 7.0}]
)
@ -666,7 +669,7 @@ def test_private_eiere_betaler_det_andelen_er_verdt(oppdiktet: LagInndata) -> No
assert lav[0].NV_stat > utfall[0].NV_stat
@pytest.mark.parametrize("losning", list(Losning))
@pytest.mark.parametrize("losning", I_KONTANTSTROMMEN)
def test_anleggenes_kontantstrom_summerer_seg_til_programmets(
oppdiktet: LagInndata, losning: Losning
) -> None:

View file

@ -156,6 +156,34 @@ def test_karbonprisen_er_lineaer_mellom_aarene_i_tabellen(
assert inn.karbonpris_i(2025) == 1588.0
def test_stoerrelsene_for_tillegget_til_retningen_foelger_parameterfila(
forste_trekning: inndata.Inndata,
) -> None:
"""Chapter 17.8: units and tables only; nothing is computed with them."""
inn = forste_trekning
assert (inn["P_m"], inn["eps_d"], inn["w_N_forbruk"], inn["w_D_sjo"]) == (100.0, 1.0, 0.0, 98.0)
assert 3.0 <= inn["tau_1"] <= 7.0
assert 18.0 <= inn["n_1"] <= 268.0
assert 0.07 <= inn["w_D_uttak"] <= 0.10
assert 119.0 <= inn["w_N_uttak"] <= 168.0
# the table of 17.3
assert inn.bortfall[inndata.BORTFALL_KILDE] == (0.119, 0.21)
assert inn.bortfall[inndata.BORTFALL_EGNE_LAV] == pytest.approx((0.188, 0.376))
assert inn.bortfall[inndata.BORTFALL_EGNE_HOY] == pytest.approx((0.32, 0.64))
assert inn.bortfall_i(inndata.BORTFALL_KILDE, 2040) == 0.21
# the table of 17.4, g CO2 per kWh converted to tonnes per MWh
assert set(inn.u_alt) == {"hoved", "lav", "hoy_nedre", "hoy_ovre", "null"}
assert inn.u_alt_i("hoved", 2024) == pytest.approx(0.43)
assert inn.u_alt_i("hoved", 2045) == pytest.approx((0.2012 + 0.1312) / 2)
assert inn.u_alt_i("hoved", 2100) == pytest.approx(0.1312)
assert inn.u_alt_i("lav", 2100) == pytest.approx(0.09)
assert (inn.u_alt_i("hoy_nedre", 2050), inn.u_alt_i("hoy_ovre", 2050)) == pytest.approx(
(0.41, 0.626)
)
assert inn.u_alt_i("null", 2050) == 0.0
assert inn.kjoletaarn == {"forbruk": (2.2, 2.5, 3.2), "uttak": (3.0, 4.2, 9.8)}
def test_heltall_avviser_tall_som_ikke_er_hele(forste_trekning: inndata.Inndata) -> None:
with pytest.raises(ValueError, match="should be a whole number"):
forste_trekning.heltall("rho_N")

View file

@ -21,6 +21,9 @@ if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
I_KONTANTSTROMMEN = tuple(a for a in Losning if not a.trinnvis)
"""The solutions the cash flow is coded for. Solution T only has its build-out so far."""
E_D = 8760.0 * 0.75 * 1.2 * 1000.0
"""Yearly energy to one made-up data centre: 7 884 000 MWh."""
@ -202,7 +205,7 @@ def test_R_ett_anlegg_aar_for_aar(oppdiktet: LagInndata) -> None:
def test_nnv_er_summen_av_delene_i_alle_losninger(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
for losning in Losning:
for losning in I_KONTANTSTROMMEN:
for knapphet in Knapphet:
res = _regn(inn, losning, N_anlegg=2, knapphet=knapphet)
D_D = np.array([1.08 ** -(t - 2027) for t in res.aar])

View file

@ -22,6 +22,9 @@ if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
I_KONTANTSTROMMEN = tuple(a for a in Losning if not a.trinnvis)
"""The solutions the cash flow is coded for. Solution T only has its build-out so far."""
E_D = 8760.0 * 0.75 * 1.2 * 1000.0
"""Yearly energy to one made-up data centre: 7 884 000 MWh."""
@ -373,7 +376,7 @@ def test_M2_bruker_bare_utkoblingsarmen(oppdiktet: LagInndata) -> None:
assert nv.effektkostnad_bedrift(inn, res)[j] == pytest.approx(_utkobling(600.0))
@pytest.mark.parametrize("losning", list(Losning))
@pytest.mark.parametrize("losning", I_KONTANTSTROMMEN)
@pytest.mark.parametrize("knapphet", list(Knapphet))
def test_s19_er_en_regnskapsidentitet(
oppdiktet: LagInndata, losning: Losning, knapphet: Knapphet

View file

@ -21,6 +21,9 @@ if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
I_KONTANTSTROMMEN = tuple(a for a in Losning if not a.trinnvis)
"""The solutions the cash flow is coded for. Solution T only has its build-out so far."""
E_D = 8760.0 * 0.75 * 1.2 * 1000.0
"""Yearly energy to one made-up data centre: 7 884 000 MWh."""
@ -206,7 +209,7 @@ def test_kraftverk_som_tilleggsregelen_binder_for_teller_bare_ulykkeskostnaden(
assert skala.overskudd_utover_avkastning(inn, uten)[j] > ut[j]
@pytest.mark.parametrize("losning", list(Losning))
@pytest.mark.parametrize("losning", I_KONTANTSTROMMEN)
@pytest.mark.parametrize(
"endringer",
[{}, {"c_N_ref": 10e6, "f_N": 0.3e6}, {"T_slutt": 2045, "L_B": 7.0, "mu_rel": 0.9}],

536
tests/test_trinnvis.py Normal file
View file

@ -0,0 +1,536 @@
"""The addition to the direction (chapter 17): solution T in modules, and S48 to S54.
Made-up round numbers only. The hand-computed build-outs follow chapter 17.1 line by line.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
import pytest
from tokenfabrikker import inndata as idt
from tokenfabrikker import kontantstrom as ks
from tokenfabrikker import ligninger as lg
from tokenfabrikker import utbygging as ub
from tokenfabrikker.kontantstrom import Knapphet
from tokenfabrikker.utbygging import Kraft, Losning
if TYPE_CHECKING:
from collections.abc import Callable
from conftest import LagInndata
# ------------------------------------------------------------------- S48 and S49
@pytest.mark.parametrize(
("tau_1", "tau_nett", "tau_D", "tidspunkt"),
[
(3.0, 10.0, 2.5, 2030.5), # the module itself takes longest: one year plus tau_D
(5.0, 10.0, 2.5, 2032.0), # the connection within the grid that exists takes longest
(5.0, 4.0, 1.0, 2031.0), # new grid comes before the first-stage connection would
],
)
def test_s48_tidligste_tidspunkt(
tau_1: float, tau_nett: float, tau_D: float, tidspunkt: float
) -> None:
assert lg.s48_tidligste_tidspunkt_trinnvis(
T_0=2027.0, tau_1=tau_1, tau_nett=tau_nett, tau_D=tau_D
) == pytest.approx(tidspunkt)
def test_s48_saldoen_tar_med_rest_men_aldri_mer_enn_en_modul_trenger() -> None:
felles = {"n_1": 100.0, "PUE": 1.2, "P_m": 100.0}
assert lg.s48_nettsaldo(saldo_forrige=0.0, brukt_forrige=0.0, **felles) == 100.0
assert lg.s48_nettsaldo(saldo_forrige=200.0, brukt_forrige=120.0, **felles) == 180.0
# 300 would be carried on, but the balance stops at n_1 + PUE P_m = 220
assert lg.s48_nettsaldo(saldo_forrige=200.0, brukt_forrige=0.0, **felles) == 220.0
def test_s49_krever_en_hel_enhet_for_det_som_gjenstaar() -> None:
felles = {"lam": 0.75, "PUE": 1.2, "P_m": 100.0, "P_ref": 1000.0}
# seven modules left draw 630 MW on average, less than one unit gives (800 MW)
assert not lg.s49_kjernekraft_bygges(J=10, J_F=3, KF=0.8, **felles)
assert lg.s49_kjernekraft_bygges(J=20, J_F=3, KF=0.8, **felles)
assert lg.s49_kjernekraft_bygges(J=13, J_F=3, KF=0.9, **felles) # exactly one unit
assert not lg.s49_kjernekraft_bygges(J=10, J_F=10, KF=0.8, **felles)
with pytest.raises(ValueError, match="J_F must lie"):
lg.s49_kjernekraft_bygges(J=10, J_F=11, KF=0.8, **felles)
# ------------------------------------------------------ the build-out in modules
def _trinnvis(**endringer: object) -> ub.Trinnvisplan:
argumenter: dict[str, object] = {
"J": 4,
"T_0": 2027,
"T_s": 2045,
"t_forste": 2030,
"t_nett": 2034,
"P_m": 100.0,
"PUE": 1.2,
"n_1": 100.0,
"L_H": 20,
"L_N": 20,
"brikker_per_aar": 1000.0,
"kraftrom": ub.kraftrom_ubegrenset,
"forste_aar_kraft": lambda _j: 2028,
"stopp": (False,) * 18,
}
argumenter.update(endringer)
return ub.utbyggingsplan_trinnvis(**argumenter) # type: ignore[arg-type]
def _start(plan: ub.Plan) -> list[int]:
return [modul.start for modul in plan.anlegg]
def test_forste_trinn_folger_nettsaldoen() -> None:
"""Hand-computed: 100 MW of draw a year, a module draws 120, the balance stops at 220.
2030: 100, no module. 2031: 200, module 1 (80 left). 2032: 180, module 2 (60 left).
2033: 160, module 3. 2034: new grid can be in place, no limit, module 4.
"""
plan = _trinnvis()
assert _start(plan) == [2031, 2032, 2033, 2034]
assert [plan.i_forste_trinn(k) for k in range(4)] == [True, True, True, False]
assert plan.gjennomforbar
assert (plan.t_N, plan.J_F, plan.kjernekraft_bygges) == (None, None, False)
def test_saldoen_samles_ikke_opp_mens_krafta_holder_igjen() -> None:
"""No power before 2033. The balance is 100, 200, then 220 and 220: one module, not three."""
plan = _trinnvis(kraftrom=lambda t: math.inf if t >= 2033 else 0.0)
assert _start(plan) == [2033, 2034, 2034, 2034]
def test_flere_moduler_kan_starte_samme_aar() -> None:
"""250 MW a year: 2030 has room for two modules (240), 2031 has 10 + 250 = 260, two more."""
assert _start(_trinnvis(n_1=250.0)) == [2030, 2030, 2031, 2031]
def test_saldoen_vokser_ogsaa_i_et_aar_med_eksportstopp() -> None:
"""Stop in 2031: balance 100, 200 (nothing starts), 220 (module 1), 200 (module 2)."""
stopp = tuple(t == 2031 for t in range(2028, 2046))
assert _start(_trinnvis(stopp=stopp)) == [2032, 2033, 2034, 2034]
def test_ingen_modul_starter_for_kraftverkene_kan_betales() -> None:
plan = _trinnvis(n_1=1000.0, forste_aar_kraft=lambda j: 2030 if j == 1 else 2032)
assert _start(plan) == [2030, 2032, 2032, 2032]
def test_brikkene_telles_fra_forste_mulige_aar_for_modulene() -> None:
"""100 MW of chips a year from 2030 and no other limit: one module a year."""
plan = _trinnvis(n_1=1000.0, brikker_per_aar=100.0)
assert _start(plan) == [2030, 2031, 2032, 2033]
def test_uten_forste_trinn_starter_modulene_naar_nytt_nett_kan_komme() -> None:
assert _start(_trinnvis(t_forste=2034)) == [2034, 2034, 2034, 2034]
def _fase(t_N: int, *, per_aar: float = math.inf, bygges: bool = True) -> ub.Kjernekraftfase:
return ub.Kjernekraftfase(
t_N=t_N, rom=lambda t: per_aar * (t - t_N + 1), bygges=lambda _J_F: bygges
)
def test_tk_bygger_kjernekraftmoduler_i_reaktorenes_takt() -> None:
"""Power for two renewable modules only; from 2035 the reactors have room for two a year."""
plan = _trinnvis(
J=6, n_1=1000.0, t_nett=2031, kraftrom=lambda _t: 2.0, kjernekraft=_fase(2035, per_aar=2.0)
)
assert _start(plan) == [2030, 2030, 2035, 2035, 2036, 2036]
assert (plan.t_N, plan.J_F, plan.kjernekraft_bygges) == (2035, 2, True)
assert [plan.er_kjernekraftmodul(k) for k in range(6)] == [False, False, True, True, True, True]
uten_kjernekraft = _trinnvis(J=6, n_1=1000.0, t_nett=2031, kraftrom=lambda _t: 2.0)
assert _start(uten_kjernekraft) == [2030, 2030]
assert not uten_kjernekraft.gjennomforbar
def test_tk_kjernekraftmodulene_bruker_bare_brikker_levert_fra_t_N() -> None:
"""Hand-computed: 100 MW of chips a year, vintages of three years, one renewable module.
2030: module 1 (stock 0). 2031 and 2032: the stock grows to 200. 2033 = t_N: the 200
become the old stock; module 1's vintage is replaced from it (100 left) and the year's
delivery starts module 2. Had the old stock been open to nuclear modules, modules 2 and
3 would both have started in 2033. 2034: module 3. 2035: module 4. 2036: modules 1 and 2
expired the same year; module 1 takes the last of the old stock, module 2 the delivery.
2037: module 3. 2038: module 4. 2039: module 1 takes the delivery (no old stock left),
module 2 waits. 2040: module 2 before module 3, which waits.
"""
plan = _trinnvis(
T_s=2040,
stopp=(False,) * 13,
t_nett=2030,
L_H=3,
brikker_per_aar=100.0,
kraftrom=lambda _t: 1.0,
kjernekraft=_fase(2033),
)
assert [m.aarganger for m in plan.anlegg] == [
(2030, 2033, 2036, 2039),
(2033, 2036, 2040),
(2034, 2037),
(2035, 2038),
]
assert plan.J_F == 1
def test_tk_en_utskifting_som_maa_vente_holder_ikke_de_neste_i_koen_tilbake() -> None:
"""Hand-computed: the old stock is 400 at t_N = 2035, deliveries 100 a year, vintages 3 years.
Module 1 (renewable) starts in 2034, modules 2 to 4 (nuclear) in 2035, 2036 and 2037.
Replacements: 2037 module 1 (old stock 300), 2038 module 2, 2039 module 3, 2040 module 1
(old stock 200) and module 4. Export stop in 2041 and 2042. In 2043 four vintages wait,
in this order: module 2, 3, 1, 4. Module 2 takes the delivery. Module 3 has no chips it
may use and waits. Module 1, behind it in the queue, is replaced from the old stock.
Module 4 waits. 2044: module 3.
"""
plan = _trinnvis(
T_s=2044,
stopp=tuple(t in {2041, 2042} for t in range(2028, 2045)),
t_nett=2030,
L_H=3,
brikker_per_aar=100.0,
kraftrom=lambda t: 1.0 if t >= 2034 else 0.0,
kjernekraft=_fase(2035),
)
assert [m.aarganger for m in plan.anlegg] == [
(2034, 2037, 2040, 2043),
(2035, 2038, 2043),
(2036, 2039, 2044),
(2037, 2040),
]
def test_tk_er_tf_naar_s49_ikke_er_oppfylt() -> None:
felles: dict[str, object] = {"J": 6, "L_H": 3, "brikker_per_aar": 100.0}
tf = _trinnvis(**felles)
tk = _trinnvis(**felles, kjernekraft=_fase(2036, bygges=False))
assert tk.anlegg == tf.anlegg
assert (tk.J_F, tk.kjernekraft_bygges) == (4, False)
assert not any(tk.er_kjernekraftmodul(k) for k in range(len(tk.anlegg)))
def test_kjernekraft_for_nytt_nett_har_ingen_regel() -> None:
with pytest.raises(ValueError, match="no rule for that"):
_trinnvis(kjernekraft=_fase(2033))
def test_trinnvis_krever_ett_stoppflagg_per_aar() -> None:
with pytest.raises(ValueError, match="one export flag per year"):
_trinnvis(stopp=(False,) * 3)
# --------------------------------------------------------- the timeline, S50
def test_s50_summerer_per_krafttype() -> None:
felles: dict[str, object] = {
"P": [100.0, 100.0, 1000.0],
"har_aargang": [True, False, True],
"kraft": ["ny", "ny", "kjerne"],
}
assert lg.s50_regnekraft_i_drift(**felles, x="ny") == 100.0 # type: ignore[arg-type]
assert lg.s50_regnekraft_i_drift(**felles, x="kjerne") == 1000.0 # type: ignore[arg-type]
assert lg.s50_regnekraft_i_drift(**felles, x="annet") == 0.0 # type: ignore[arg-type]
with pytest.raises(ValueError, match="one size, one flag and one type"):
lg.s50_regnekraft_i_drift(P=[1.0], har_aargang=[], kraft=[], x="ny")
def test_tidslinjen_skiller_fornybar_kraft_og_kjernekraft_i_tk() -> None:
plan = _trinnvis(
J=6, n_1=1000.0, t_nett=2031, kraftrom=lambda _t: 2.0, kjernekraft=_fase(2035, per_aar=2.0)
)
linje = ub.tidslinje(Losning.T_K, plan, P_IT=1000.0)
aar = range(2028, 2046)
fornybar = dict(zip(aar, linje[Kraft.NY_FORNYBAR], strict=True))
kjernekraft = dict(zip(aar, linje[Kraft.KJERNEKRAFT_PAA_NETTET], strict=True))
assert (fornybar[2029], fornybar[2030], fornybar[2045]) == (0.0, 200.0, 200.0)
assert (kjernekraft[2034], kjernekraft[2035], kjernekraft[2036]) == (0.0, 200.0, 400.0)
assert not any(linje[Kraft.EGET_KJERNEKRAFTVERK])
assert not any(linje[Kraft.KJOP_FRA_NETTET])
def test_tidslinjen_teller_ikke_en_modul_uten_brikker() -> None:
"""One module, vintages of three years, and no chips after the first: 100 MW in 2030 to 2032."""
plan = _trinnvis(
J=1, n_1=1000.0, L_H=3, stopp=tuple(t > 2030 for t in range(2028, 2046)), t_nett=2030
)
linje = ub.tidslinje(Losning.T_F, plan, P_IT=1000.0)[Kraft.NY_FORNYBAR]
assert linje == (0.0, 0.0, 100.0, 100.0, 100.0) + (0.0,) * 13
@pytest.mark.parametrize(
("losning", "kraft"),
[
(Losning.A, Kraft.EGET_KJERNEKRAFTVERK),
(Losning.B, Kraft.KJERNEKRAFT_PAA_NETTET),
(Losning.B_MERKET, Kraft.KJERNEKRAFT_PAA_NETTET),
(Losning.C, Kraft.NY_FORNYBAR),
(Losning.R, Kraft.KJOP_FRA_NETTET),
],
)
def test_tidslinjen_for_losningene_med_hele_anlegg(losning: Losning, kraft: Kraft) -> None:
plan = ub.utbyggingsplan(
N_anlegg=2,
T_0=2027,
T_s=2032,
t_min=2030,
P_IT=1000.0,
L_H=5,
L_N=20,
brikker_per_aar=1000.0,
kraftrom=ub.kraftrom_ubegrenset,
stopp=(False,) * 5,
)
linje = ub.tidslinje(losning, plan, P_IT=1000.0)
assert linje[kraft] == (0.0, 0.0, 1000.0, 2000.0, 2000.0)
assert all(not any(verdier) for x, verdier in linje.items() if x is not kraft)
def test_krafttype_i_t_krever_en_trinnvisplan(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
plan = ks.lag_plan(inn, Losning.C, ks.dimensjoner(inn, Losning.C), N_anlegg=1)
with pytest.raises(TypeError, match="utbyggingsplan_trinnvis"):
ub.krafttype(Losning.T_F, plan, 0)
# ------------------------------------------- the plan from a set of values
def _lag(inn: idt.Inndata, losning: Losning, N_anlegg: int, **brytere: bool) -> ub.Trinnvisplan:
plan = ks.lag_plan(inn, losning, ks.dimensjoner(inn, losning), N_anlegg=N_anlegg, **brytere)
assert isinstance(plan, ub.Trinnvisplan)
return plan
def test_dimensjoneringen_i_t_er_per_modul(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
tf, tk = ks.dimensjoner(inn, Losning.T_F), ks.dimensjoner(inn, Losning.T_K)
assert tf.E_D == pytest.approx(8760 * 0.75 * 1.2 * 100.0)
assert (tf.P_u, tf.P_G_N) == (0.0, 0.0)
assert tk.P_u == 1000.0
assert tk.P_G_N == pytest.approx(0.75 * 1.2 * 100.0 / 0.8)
assert ks.antall_moduler(inn, 3) == 30
with pytest.raises(ValueError, match="whole number of modules"):
ks.antall_moduler(oppdiktet(P_m=300.0), 1)
def test_tf_fra_det_oppdiktede_tallsettet(oppdiktet: LagInndata) -> None:
"""Hand-computed: new grid in 2033, first module in 2030 (S48: one year plus tau_D = 2).
150 MW of draw a year, a module draws 120: 2030 one module (30 left), 2031 180, one
module, 2032 210, one module. From 2033 no limit: chips and power have room for the
seven that remain.
"""
plan = _lag(oppdiktet(tau_nett=6.0), Losning.T_F, 1)
assert (plan.t_forste, plan.t_nett, plan.P_m, plan.N_anlegg) == (2030, 2033, 100.0, 10)
assert _start(plan) == [2030, 2031, 2032] + [2033] * 7
uten = _lag(oppdiktet(tau_nett=6.0), Losning.T_F, 1, uten_forste_trinn=True)
assert _start(uten) == [2033] * 10
def test_forste_aar_kraft_folger_byggetidene_i_portefoljen(oppdiktet: LagInndata) -> None:
"""Modules 1 and 2 get hydropower (paid the year before start), 3 to 5 wind (two years).
Module 6 is the first that needs offshore wind, with three years of construction.
"""
inn = oppdiktet()
forste = ks.forste_aar_kraft(inn, ks.dimensjoner(inn, Losning.T_F))
assert [forste(j) for j in (1, 2, 3, 5, 6)] == [2029, 2029, 2030, 2030, 2031]
def test_tk_fra_det_oppdiktede_tallsettet(oppdiktet: LagInndata) -> None:
"""Hand-computed, with renewable power for three modules before nuclear power in 2035.
0.5 TWh a year of new renewable power has room for 1 module in 2030, 2 in 2031 and 3 in
2033. S49 for two facilities: 17 modules left draw 1 530 MW on average, more than the
800 MW one unit gives, so nuclear power is built. 1 000 MW of chips a year from 2035:
ten modules in 2035 and seven in 2036; the replacements in the renewable modules take
from the old stock. For one facility 7 modules are left, 630 MW: no nuclear power.
"""
inn = oppdiktet(tau_nett=6.0, g_fornybar=0.5e6)
plan = _lag(inn, Losning.T_K, 2)
assert (plan.t_N, plan.J_F, plan.kjernekraft_bygges) == (2035, 3, True)
assert _start(plan) == [2030, 2031, 2033] + [2035] * 10 + [2036] * 7
assert plan.anlegg[0].aarganger[:2] == (2030, 2035)
assert plan.gjennomforbar
ett_anlegg = _lag(inn, Losning.T_K, 1)
assert (ett_anlegg.J_F, ett_anlegg.kjernekraft_bygges) == (3, False)
assert ett_anlegg.anlegg == _lag(inn, Losning.T_F, 1).anlegg
uten_vilkaaret = _lag(inn, Losning.T_K, 1, uten_s49=True)
assert uten_vilkaaret.kjernekraft_bygges
assert _start(uten_vilkaaret) == [2030, 2031, 2033] + [2035] * 7
def test_bryterne_for_t_gjelder_bare_t(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
dim = ks.dimensjoner(inn, Losning.C)
with pytest.raises(ValueError, match="only apply to solution T"):
ks.lag_plan(inn, Losning.C, dim, N_anlegg=1, uten_s49=True)
with pytest.raises(ValueError, match="not defined for T"):
ks.lag_plan(
inn, Losning.T_F, ks.dimensjoner(inn, Losning.T_F), N_anlegg=1, brikker_fra_T0=True
)
@pytest.mark.parametrize("losning", [Losning.T_F, Losning.T_K])
def test_t_gaar_ikke_gjennom_kontantstrommen_ennaa(oppdiktet: LagInndata, losning: Losning) -> None:
inn = oppdiktet(tau_nett=6.0)
plan = _lag(inn, losning, 1)
with pytest.raises(NotImplementedError, match="not taken through the cash flow yet"):
ks.regn_program(inn, losning, plan, Knapphet.NORMALISERING)
# ----------------------------------------- AI use on the users' own machines, S51 and S52
@pytest.mark.parametrize(
("t_v", "d"),
[(2020, 0.0), (2025, 0.0), (2028, 0.06), (2030, 0.1), (2033, 0.16), (2035, 0.2), (2060, 0.2)],
)
def test_bortfallet_er_lineaert_mellom_tre_punkter_og_fast_etterpaa(t_v: int, d: float) -> None:
assert lg.s51_bortfall(t_v=t_v, d_30=0.1, d_35=0.2) == pytest.approx(d)
def test_bortfallet_er_en_andel() -> None:
with pytest.raises(ValueError, match="d_35 is a share"):
lg.s51_bortfall(t_v=2030, d_30=0.1, d_35=1.2)
def test_s51_uten_bortfall_er_hovedforlopet() -> None:
assert lg.s51_etterspoerselsfaktor(eps_d=1.0, d=0.0) == 1.0
assert lg.s51_etterspoerselsfaktor(eps_d=2.0, d=0.0) == 1.0
def test_s51_faktoren() -> None:
assert lg.s51_etterspoerselsfaktor(eps_d=1.0, d=0.21) == pytest.approx(0.79)
assert lg.s51_etterspoerselsfaktor(eps_d=0.5, d=0.64) == pytest.approx(0.68)
assert lg.s51_etterspoerselsfaktor(eps_d=2.0, d=0.64) == 0.0 # never below zero
with pytest.raises(ValueError, match="share between 0 and 1"):
lg.s51_etterspoerselsfaktor(eps_d=1.0, d=1.5)
with pytest.raises(ValueError, match="cannot be negative"):
lg.s51_etterspoerselsfaktor(eps_d=-1.0, d=0.5)
def test_bortfallet_i_scenarioet_med_egne_maskiner() -> None:
assert lg.s51_bortfall_egne_maskiner(s_flytt=0.8, s_trening=0.5) == pytest.approx(0.4)
assert lg.s51_bortfall_egne_maskiner(s_flytt=0.8, s_trening=1.0) == 0.0
def test_s52_terskelen_er_pristerskelen_uttrykt_som_bortfall() -> None:
assert lg.s52_bortfallsterskel(k_a=0.7, eps_d=1.0) == pytest.approx(0.3)
assert lg.s52_bortfallsterskel(k_a=0.7, eps_d=2.0) == pytest.approx(0.15)
assert lg.s52_bortfallsterskel(k_a=0.3, eps_d=0.5) == 1.0 # never above one
assert lg.s52_bortfallsterskel(k_a=1.0, eps_d=1.0) == 0.0 # tolerates no loss
assert lg.s52_bortfallsterskel(k_a=1.4, eps_d=1.0) == 0.0
assert lg.s52_bortfallsterskel(k_a=None, eps_d=1.0) is None
with pytest.raises(ValueError, match="must be positive"):
lg.s52_bortfallsterskel(k_a=0.7, eps_d=0.0)
@pytest.mark.parametrize("eps_d", [0.5, 1.0, 2.0])
def test_s52_gir_samme_faktor_som_pristerskelen(eps_d: float) -> None:
"""A loss of d* for every vintage is the same as multiplying the price by k_a (17.3)."""
k_a = 0.6
d = lg.s52_bortfallsterskel(k_a=k_a, eps_d=eps_d)
assert d is not None
assert lg.s51_etterspoerselsfaktor(eps_d=eps_d, d=d) == pytest.approx(k_a)
# ------------------------------------------- emissions with deduction and water
def test_s53_unngaatte_utslipp_for_ett_anlegg() -> None:
"""1 000 MW IT at load 0.7 and PUE 1.14 uses 6 990 480 MWh; at 0.34 tonnes per MWh."""
felles = {"u_alt": 0.34, "Gamma": 1.0, "lam": 0.7, "PUE_v": 1.14, "P": 1000.0}
assert lg.s53_unngaatt_utslipp(mu=1.0, mu_d=1.0, **felles) == pytest.approx(2_376_763.2)
# only compute that is sold and delivered replaces compute elsewhere
assert lg.s53_unngaatt_utslipp(mu=0.9, mu_d=0.5, **felles) == pytest.approx(0.45 * 2_376_763.2)
assert lg.s53_unngaatt_utslipp(mu=1.0, mu_d=1.0, **{**felles, "u_alt": 0.0}) == 0.0
def test_s53_med_fradrag_kan_bli_negativt() -> None:
assert lg.s53_utslipp_med_fradrag(U_liv=100.0, U_unngaatt=30.0) == 70.0
assert lg.s53_utslipp_med_fradrag(U_liv=100.0, U_unngaatt=250.0) == -150.0
def test_s54_kjolevann() -> None:
E_IT = lg.s54_it_energi(lam=0.7, P=1000.0)
assert E_IT == pytest.approx(6_132_000.0)
E_N = 8760 * 0.84 * 1000.0
assert lg.s54_kjolevann(w_D=0.085, w_N=145.0, E_IT=E_IT, E_N=E_N) == pytest.approx(
521_220.0 + 1_066_968_000.0
)
# consumption of fresh water with sea-water cooling: only the data centre's
assert lg.s54_kjolevann(w_D=0.085, w_N=0.0, E_IT=E_IT, E_N=E_N) == pytest.approx(521_220.0)
# ------------------------------------------------------------------ the paths
def test_lineaer_bane() -> None:
bane = {2030: 10.0, 2040: 30.0, 2050: 0.0}
verdier = [lg.lineaer_bane(punkter=bane, t=t) for t in (2020, 2030, 2035, 2040, 2045, 2060)]
assert verdier == pytest.approx([10.0, 10.0, 20.0, 30.0, 15.0, 0.0])
assert lg.lineaer_bane(punkter={2024: 0.5}, t=2090) == 0.5
with pytest.raises(ValueError, match="at least one point"):
lg.lineaer_bane(punkter={}, t=2030)
def test_banene_i_det_oppdiktede_tallsettet(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
assert inn.u_alt_i("hoved", 2030) == pytest.approx(0.3)
assert inn.u_alt_i("hoved", 2090) == pytest.approx(0.1)
assert inn.u_alt_i("fast", 2090) == 0.5
assert inn.bortfall_i("hoyt", 2032) == pytest.approx(0.3 + 0.4 * 0.3)
assert inn.karbonpris_i(2050) == 1000.0
def test_tabellene_for_bortfall_tolkes_som_i_17_3() -> None:
"""The table of 17.3, built from tables in the layout of the parameter file."""
bortfall = idt.tolk_bortfall(
d_kilde={"2030": 0.119, "2035": 0.21},
s_flytt={"2030": 0.4, "2035": 0.8},
s_trening={"hoy": 0.53, "lav": 0.2},
)
assert bortfall[idt.BORTFALL_KILDE] == (0.119, 0.21)
assert bortfall[idt.BORTFALL_EGNE_LAV] == pytest.approx((0.188, 0.376))
assert bortfall[idt.BORTFALL_EGNE_HOY] == pytest.approx((0.32, 0.64))
def test_tabellen_for_u_alt_regnes_om_til_tonn_per_mwh() -> None:
baner = idt.tolk_u_alt(
{
"hoved": {"2024": 400, "2030": 300},
"lav": {"2025": 200, "2030": 100},
"hoy": {"lav": 410, "hoy": 626},
"null": 0,
}
)
assert baner["hoved"] == pytest.approx({2024: 0.4, 2030: 0.3})
assert baner["lav"] == pytest.approx({2025: 0.2, 2030: 0.1})
assert baner["hoy_nedre"] == pytest.approx({2024: 0.41})
assert baner["hoy_ovre"] == pytest.approx({2024: 0.626})
assert baner["null"] == {2024: 0.0}
def test_tabellen_for_kjoletaarn() -> None:
taarn = idt.tolk_kjoletaarn({"forbruk": [2.2, 2.5, 3.2], "uttak": [3.0, 4.2, 9.8]})
assert taarn == {"forbruk": (2.2, 2.5, 3.2), "uttak": (3.0, 4.2, 9.8)}
def _alle(funksjon: Callable[[int], bool], antall: int) -> list[bool]:
return [funksjon(k) for k in range(antall)]
def test_modulene_i_forste_trinn_er_de_som_startet_for_nytt_nett(oppdiktet: LagInndata) -> None:
plan = _lag(oppdiktet(tau_nett=6.0), Losning.T_F, 1)
assert _alle(plan.i_forste_trinn, 10) == [True] * 3 + [False] * 7

View file

@ -302,4 +302,6 @@ def test_losningenes_egenskaper() -> None:
ub.Losning.A,
ub.Losning.B,
ub.Losning.B_MERKET,
ub.Losning.T_K,
]
assert [a for a in ub.Losning if a.trinnvis] == [ub.Losning.T_F, ub.Losning.T_K]