feat(kontantstrom): take solution T through the power system and the cash flow

Everything per module, renewable modules with their own portfolio, the nuclear
modules of T-K on shared units, S41 counted to the first unit. The factor of
S51 enters the revenue and the disconnection arm of S47. S53 and S54 are put
together over a programme for all solutions. Present values are exactly
rounded sums, so the same computation gives the same last digit every time.
The chapters after the cash flow refuse T and a loss of demand for now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-13 00:37:50 +01:00
commit 1e7273b4b0
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
9 changed files with 809 additions and 55 deletions

View file

@ -197,7 +197,7 @@ class Forsyning:
def m4_forsyning(inn: Inndata, res: Programresultat) -> Forsyning:
"""M4 in one draw from the power system year by year (S23, S24)."""
slakk_energi = lg.AVRUNDINGSTOLERANSE * res.plan.N_anlegg * res.dim.E_D
slakk_effekt = lg.AVRUNDINGSTOLERANSE * res.plan.N_anlegg * inn["PUE"] * inn["P_IT"]
slakk_effekt = lg.AVRUNDINGSTOLERANSE * res.plan.N_anlegg * inn["PUE"] * res.P_enhet
energi_svakere = effekt_svakere = False
for j, t in enumerate(res.aar):
if res.plan.antall_i_drift(t) == 0:

View file

@ -249,6 +249,7 @@ def bedriftsstrom(
S45; that is the cash flow S30 is computed on, while M2 and S28 use the
sales as they are.
"""
ks.krev_uten_tillegget(res)
plan = res.plan
null = np.zeros(len(res.aar), dtype=np.float64)
med_last = np.array([plan.antall_med_last(t) for t in res.aar], dtype=np.float64)
@ -301,6 +302,7 @@ def netto_per_anlegg(
programme's nuclear units is shared equally among the facilities operated
that year; in a year without any, it is not shared.
"""
ks.krev_uten_tillegget(res)
plan = res.plan
pris = np.array([rad.pris for rad in res.kraftaar], dtype=np.float64)
med_last = np.array([max(1, plan.antall_med_last(t)) for t in res.aar], dtype=np.float64)
@ -342,6 +344,7 @@ def restverdi_bedrift(
falls after the final year is always deducted, discounted with rho_N
(rho_A in A).
"""
ks.krev_uten_tillegget(res)
vindu = min(res.plan.L_H, len(res.aar))
rho_avvikling = inn["rho_N"] if res.losning.paa_nett else res.dim.rho_A
anlegg = tuple(
@ -399,6 +402,7 @@ def lcoc_med_kapitalkostnad(inn: Inndata, res: Programresultat, r_e: float) -> f
criterion of the pre-registration uses the requirement before tax,
``krav_for_skatt`` (clarification 66).
"""
ks.krev_uten_tillegget(res)
kost = nivaaisert.kraftkostnad(
inn, res, bedrift=True, renter=Renter(rho_D=r_e, rho_N=r_e, rho_A=r_e)
)

View file

@ -11,6 +11,16 @@ first operating year. An asset without a construction time in the parameter
file (later vintages of IT hardware, buffer, gensets, lines and grid
connection) is paid in the year before it enters operation.
Solution T (chapter 17.1) goes through the same functions with a module in
the place of a facility: everything per facility is per module, with P_m for
P_IT. A renewable module has its own portfolio, as a facility in C. The
nuclear modules of T-K share the programme's units, as the facilities in B,
and the fixed cost of becoming a nuclear country counts from the first unit.
The loss of demand of chapter 17.3 enters through the factor mu_d of S51,
which follows the vintage: in the revenue (S16, S34) and in the
disconnection arm of S47. Without a loss the factor is exactly one.
Nothing here reads the parameter file or draws random numbers: everything
comes from an ``Inndata``.
"""
@ -312,6 +322,8 @@ class Programresultat:
RV: their sum.
SE: the subsidy element.
NNV: net present value for Norway (S26).
P_enhet: MW IT per facility: P_IT, and P_m per module in solution T.
mu_d: the factor of S51 per vintage (exactly one on the main path).
"""
losning: Losning
@ -340,6 +352,27 @@ class Programresultat:
RV: float
SE: float
NNV: float
P_enhet: float
mu_d: Etterspoersel
def paa_felles_kjernekraft(self, k: int) -> bool:
"""True when facility or module ``k`` (0 is the first) runs on the programme's units."""
return paa_felles_kjernekraft(self.losning, self.plan, k)
def krev_uten_tillegget(res: Programresultat) -> None:
"""Refuse a result the chapters after the cash flow cannot take yet.
The levelised cost, the ownership forms and scale are not taken through
chapter 17: they neither know modules nor carry the factor of S51 (S19,
S27, S31 and S42).
"""
if res.losning.trinnvis:
msg = "solution T is not taken through the levelised cost, ownership and scale yet"
raise NotImplementedError(msg)
if not res.mu_d.hovedforlop:
msg = "the loss of demand (S51) is not in the levelised cost, ownership and scale yet"
raise NotImplementedError(msg)
# ---------------------------------------------------------------- dimensioning
@ -716,22 +749,41 @@ def _portefolje(inn: Inndata, dim: Dimensjonering, antall: int) -> lg.Fornybarpo
)
def enheter_i_B(inn: Inndata, dim: Dimensjonering, plan: Plan) -> tuple[Enhetsgruppe, ...]:
"""S39 year by year: the nuclear units of the programme in B (clarification 29).
def paa_felles_kjernekraft(losning: Losning, plan: Plan, k: int) -> bool:
"""True when facility or module ``k`` (0 is the first) runs on the programme's nuclear units.
Every facility in B, and the nuclear modules in T-K (chapter 17.1).
"""
if isinstance(plan, ub.Trinnvisplan):
return plan.er_kjernekraftmodul(k)
return losning is Losning.B
def enheter_i_B(
inn: Inndata, dim: Dimensjonering, plan: Plan, *, losning: Losning = Losning.B
) -> tuple[Enhetsgruppe, ...]:
"""S39 year by year: the nuclear units of the programme (clarification 29).
Each year the units required are S39 for the facilities operated that year.
When fewer are in operation, new units enter operation that year with the
next numbers in the series. A unit is operated for L_N years; one that is
no longer required still runs and sells until its lifetime is out, and one
that goes out while still required is followed by a new one the year after.
In T-K the sum goes over the nuclear modules operated that year (chapter
17.1); a plan without nuclear modules has no units.
"""
KF = _kapasitetsfaktor(inn)
levetid = lg.avrundet_varighet(varighet=inn["L_N"])
per_enhet = lg.TIMER_PER_AAR * KF * dim.P_u
paa_felles = [k for k in range(len(plan.anlegg)) if paa_felles_kjernekraft(losning, plan, k)]
if not paa_felles:
return ()
grupper: list[Enhetsgruppe] = []
bygd = 0
for t in range(plan.T_0 + 1, plan.T_s + 1):
krav = lg.s39_enheter_B(E_D_sum=plan.antall_i_drift(t) * dim.E_D, KF=KF, P_ref=dim.P_u)
antall = sum(plan.i_drift(k, t) for k in paa_felles)
krav = lg.s39_enheter_B(E_D_sum=antall * dim.E_D, KF=KF, P_ref=dim.P_u)
i_drift = sum(len(g.numre) for g in grupper if g.start <= t <= g.siste_driftsaar)
if krav <= i_drift:
continue
@ -773,6 +825,25 @@ def kraftverk_for_anlegg(
return ()
def kraftverk_per_anlegg(
inn: Inndata, losning: Losning, dim: Dimensjonering, plan: Plan
) -> tuple[tuple[Kraftverk, ...], ...]:
"""The power plants that belong to each facility or module of the path, in order.
In solution T a renewable module has the portfolio S39 adds when the
number of modules goes from j - 1 to j, as a facility in C; a nuclear
module has none, as a facility in B (chapter 17.1). The nuclear modules
come after the renewable ones, so the number of a renewable module is also
its number among the portfolios.
"""
if isinstance(plan, ub.Trinnvisplan):
return tuple(
() if plan.er_kjernekraftmodul(k) else kraftverk_for_anlegg(inn, Losning.C, dim, k + 1)
for k in range(plan.N_anlegg)
)
return tuple(kraftverk_for_anlegg(inn, losning, dim, k) for k in range(1, plan.N_anlegg + 1))
# --------------------------------------------------------------- the price of compute
@ -829,6 +900,44 @@ def regnekraftpris(inn: Inndata, knapphet: Knapphet, t_1: int) -> Regnekraftpris
return Regnekraftpris(inn=inn, paaslag_g=paaslag, siste=t_1 + inn["T_knapp"])
@dataclass(frozen=True)
class Etterspoersel:
"""S51: the factor mu_d(t_v) on the share of capacity sold, per vintage (chapter 17.3).
Attributes:
eps_d: the fall in revenue per MW per fall in demand.
d: the share of demand that falls away for the vintage that enters operation in
t_v, against the main path; None on the main path.
"""
eps_d: float
d: Callable[[int], float] | None = None
@property
def hovedforlop(self) -> bool:
"""True when no demand falls away: every figure is as without chapter 17.3."""
return self.d is None
def __call__(self, t_v: int) -> float:
"""S51: mu_d for the vintage that enters operation in ``t_v``; one without a loss."""
if self.d is None:
return 1.0
return lg.s51_etterspoerselsfaktor(eps_d=self.eps_d, d=self.d(t_v))
def bortfall_i_scenario(inn: Inndata, scenario: str) -> Callable[[int], float]:
"""17.3: d(t_v) in one of the marked scenarios for AI use on the users' own machines."""
if scenario not in inn.bortfall:
msg = f"unknown scenario for the loss of demand: {scenario!r}"
raise KeyError(msg)
return lambda t_v: inn.bortfall_i(scenario, t_v)
def fast_bortfall(d: float) -> Callable[[int], float]:
"""17.3: the same loss of demand for every vintage (what the threshold of S52 is about)."""
return lambda _t_v: d
# ------------------------------------------------------------- the yearly amounts
@ -843,6 +952,7 @@ class _Program:
verk: tuple[tuple[Kraftverk, ...], ...]
felles: tuple[Enhetsgruppe, ...]
y: Regnekraftpris
mu_d: Etterspoersel
T_0: int
T_s: int
@ -850,6 +960,32 @@ class _Program:
def antall_aar(self) -> int:
return self.T_s - self.T_0 + 1
@property
def P_enhet(self) -> float:
"""MW IT per facility: P_IT, and P_m per module in solution T (chapter 17.1)."""
return self.plan.P_m if isinstance(self.plan, ub.Trinnvisplan) else self.inn["P_IT"]
def paa_felles(self, k: int) -> bool:
"""True when facility ``k`` runs on the programme's nuclear units (B, nuclear modules)."""
return paa_felles_kjernekraft(self.losning, self.plan, k)
def reaktoreffekt(self, k: int) -> float:
"""P_G^N for facility ``k``, MW (clarification 14); zero for a renewable module in T."""
if isinstance(self.plan, ub.Trinnvisplan) and not self.plan.er_kjernekraftmodul(k):
return 0.0
return self.dim.P_G_N
def forste_kjernekraftaar(self) -> int | None:
"""The year S41 counts to, or None when the programme builds no nuclear power.
The first facility's first operating year in A, B and B'. In T-K the
first operating year of the first nuclear unit, and only when S49 is
met (chapter 17.1).
"""
if self.losning.trinnvis:
return min((g.start for g in self.felles), default=None)
return self.plan.t_1 if self.losning.kjernekraft else None
def null(self) -> Tabell:
return np.zeros(self.antall_aar, dtype=np.float64)
@ -885,6 +1021,15 @@ class _Program:
return float(np.mean(tabell[-min(self.plan.L_H, self.antall_aar) :]))
def _naaverdi(diskontering: Tabell, tabell: Tabell) -> float:
"""The present value of a yearly table: the exactly rounded sum of the discounted amounts.
Not a dot product: numpy hands that to a library whose last digit depends on where the
arrays lie in memory, so the same computation twice would not give the same number.
"""
return math.fsum(diskontering * tabell)
def _spre(p: _Program, tabell: Tabell, *, forste_driftsaar: int, belop: float, tau: float) -> None:
"""Add an investment to the years just before the first operating year (clarification 21)."""
for j, andel in enumerate(lg.byggeaar_andeler(tau=tau)):
@ -948,7 +1093,7 @@ def _kraftsystem_per_aar(p: _Program) -> tuple[Kraftaar, ...]:
Q_G_nett=math.fsum(v.energi for v in paa_nett),
Q_G_nett_tort=math.fsum(v.w_tort * v.energi for v in paa_nett),
effektbidrag=[v.effektbidrag for v in paa_nett],
P_IT_sum=antall * p.inn["P_IT"],
P_IT_sum=antall * p.P_enhet,
storste_enhet=max((v.storste_enhet for v in paa_nett), default=0.0),
)
)
@ -956,13 +1101,17 @@ def _kraftsystem_per_aar(p: _Program) -> tuple[Kraftaar, ...]:
def _effektkostnad(p: _Program, kraftaar: Sequence[Kraftaar]) -> Tabell:
"""S47 per year for the programme (clarification 13). Zero in A."""
"""S47 per year for the programme (clarification 13). Zero in A.
The price in the disconnection arm is the average of mu_d * y over the
vintages in operation (chapter 17.3).
"""
F_a = p.null()
if not p.losning.paa_nett:
return F_a
for t in range(p.T_0 + 1, p.T_s + 1):
aarganger = [p.plan.aargang(k, t) for k in range(len(p.plan.anlegg))]
priser = [p.y(v) for v in aarganger if v is not None]
priser = [p.mu_d(v) * p.y(v) for v in aarganger if v is not None]
rad = kraftaar[t - p.T_0]
F_a[t - p.T_0] = lg.s47_effektkostnad(
Delta_R=rad.Delta_R,
@ -989,12 +1138,15 @@ def _datasenter(
aargang = p.plan.aargang(k, t)
if aargang is not None:
inntekt[j] = lg.s16_inntekt(
mu=inn["mu_rel"], Gamma=p.dim.Gamma, y=p.y(aargang), P_IT=inn["P_IT"]
mu=inn["mu_rel"] * p.mu_d(aargang),
Gamma=p.dim.Gamma,
y=p.y(aargang),
P_IT=p.P_enhet,
)
drift[j] = (inn["o_D"] + inn["d_o_D"]) * inn["P_IT"]
drift[j] = (inn["o_D"] + inn["d_o_D"]) * p.P_enhet
if p.losning.paa_nett and aargang is not None:
kraftkjop[j] = (1.0 + inn["n_tap"]) * pris[j] * p.dim.E_D
bygg = inn["c_bygg"] * (1.0 + inn["d_bygg"]) * inn["P_IT"]
bygg = inn["c_bygg"] * (1.0 + inn["d_bygg"]) * p.P_enhet
L_B = lg.avrundet_varighet(varighet=inn["L_B"])
for t in _fornyet(p, k, L_B):
_betal(
@ -1009,7 +1161,7 @@ def _datasenter(
siste_driftsaar=siste,
)
for nr, t_v in enumerate(anlegg.aarganger):
maskinvare = inn["P_IT"] * lg.s13_it_kostnad(
maskinvare = p.P_enhet * lg.s13_it_kostnad(
c_H0=inn["c_H0"], gamma_H=inn["gamma_H"], t_v=t_v
)
# a vintage is in operation until the next one replaces it, at most L_H years
@ -1125,8 +1277,8 @@ def _nett_buffer_og_forsyning(
)
if p.losning.paa_nett:
uttak = (1.0 - inn["delta_V"]) * inn["PUE"] * inn["P_IT"]
betal(I_nett, NETT, inn["I_nett"] * (uttak + dim.P_G_N), L_nett)
uttak = (1.0 - inn["delta_V"]) * inn["PUE"] * p.P_enhet
betal(I_nett, NETT, inn["I_nett"] * (uttak + p.reaktoreffekt(k)), L_nett)
return I_nett, buffer, I_g
P_buf = lg.s36_buffer(delta_L=inn["delta_L"], PUE=inn["PUE"], P_IT=inn["P_IT"])
betal(buffer, BUFFER, P_buf * inn["c_buf"], L_buf)
@ -1210,8 +1362,8 @@ def _tilleggsfaktor(
(f.salg, f.investering + f.drift, f.avvikling, f.avvikling_etter, f.L_rest)
for f in felles
]
salg = math.fsum(float(D_N @ v[0]) for v in verk)
kostnad = math.fsum(float(D_N @ (v[1] + v[2])) for v in verk)
salg = math.fsum(_naaverdi(D_N, v[0]) for v in verk)
kostnad = math.fsum(_naaverdi(D_N, v[1] + v[2]) for v in verk)
rest = [(p.vindu(v[0]), p.vindu(v[1]), v[3], v[4]) for v in verk if v[4] > 0]
def naaverdi(varsigma: float) -> float:
@ -1245,16 +1397,17 @@ def _ovrige_virkninger(
V[j] = inn["delta_V"] * p.plan.antall_med_last(t) * p.dim.E_D * inn["t_el"]
for a in anlegg:
for t in a.bygg_i_drift:
utslipp[t - p.T_0] += inn.karbonpris_i(t) * inn["s_B_NO"] * inn["u_B"] * inn["P_IT"]
if p.losning.kjernekraft:
utslipp[t - p.T_0] += inn.karbonpris_i(t) * inn["s_B_NO"] * inn["u_B"] * p.P_enhet
t_1 = p.forste_kjernekraftaar()
if t_1 is not None:
per_aar = lg.s41_programkostnad(
andel_myndighet=inn["andel_myndighet"],
aarsverk_prog=inn["aarsverk_prog"],
c_aarsverk=inn["c_aarsverk"],
t_1=p.plan.t_1,
t_1=t_1,
T_0=p.T_0,
)
K_prog[1 : p.plan.t_1 - p.T_0 + 1] = per_aar
K_prog[1 : t_1 - p.T_0 + 1] = per_aar
return Delta_W, utslipp, K_prog, V
@ -1271,23 +1424,31 @@ def _restverdier(
energy use (clarification 13): equally among the facilities that use power
that year. In B it also holds its share of the programme's nuclear power:
that year's cash flow of the units, shared equally among the facilities
operated that year (clarification 29). The decommissioning of the
operated that year (clarification 29); in T-K among the nuclear modules
operated that year (chapter 17.1). The decommissioning of the
programme's units that falls after the final year is deducted per group of
units, each with its own operating years left.
"""
aar = range(p.T_0, p.T_s + 1)
antall = range(len(p.plan.anlegg))
paa_felles = [
np.array(
[1.0 if p.paa_felles(k) and p.plan.i_drift(k, t) else 0.0 for t in aar],
dtype=np.float64,
)
for k in antall
]
med_last = np.array([max(1, p.plan.antall_med_last(t)) for t in aar], dtype=np.float64)
i_drift = np.array([max(1, p.plan.antall_i_drift(t)) for t in aar], dtype=np.float64)
i_drift = np.maximum(1.0, sum(paa_felles, p.null()))
kjernekraft = sum((f.netto(varsigma[KJERNEKRAFT]) for f in felles), p.null())
rho_avvikling = p.inn["rho_N"] if p.losning.paa_nett else p.dim.rho_A
verdier = []
for k, a in enumerate(anlegg):
last = np.array([1.0 if p.plan.har_last(k, t) else 0.0 for t in aar], dtype=np.float64)
drift = np.array([1.0 if p.plan.i_drift(k, t) else 0.0 for t in aar], dtype=np.float64)
netto = a.datasenter() + a.kraft(varsigma, F_a * last / med_last)
verdier.append(
lg.s40_restverdi(
NK_snitt=p.vindu(netto + kjernekraft * drift / i_drift),
NK_snitt=p.vindu(netto + kjernekraft * paa_felles[k] / i_drift),
L_rest=a.L_rest,
rho_D=p.inn["rho_D"],
rho_avvikling=rho_avvikling,
@ -1319,6 +1480,7 @@ def regn_program(
*,
dim: Dimensjonering | None = None,
tilleggsregel: bool = True,
bortfall: Callable[[int], float] | None = None,
) -> Programresultat:
"""S26 for one path: the yearly cash flows and the net present value for Norway.
@ -1327,10 +1489,15 @@ def regn_program(
cannot be built has no net present value (pre-registration, clarification
1). ``tilleggsregel=False`` credits power plants on the grid their surplus
(the figures without S45 are shown next to the verdict).
``bortfall`` is d(t_v) of chapter 17.3, the share of demand that falls
away for the vintage that enters operation in t_v (``bortfall_i_scenario``
or ``fast_bortfall``). Left out, nothing falls away. The build-out and the
costs are the same with and without it.
"""
if losning.trinnvis:
msg = "solution T is not taken through the cash flow yet (chapter 17 beyond the build-out)"
raise NotImplementedError(msg)
if losning.trinnvis != isinstance(plan, ub.Trinnvisplan):
msg = "solution T, and only solution T, takes a plan built in modules"
raise TypeError(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)
@ -1340,9 +1507,10 @@ def regn_program(
losning=losning,
dim=dim,
plan=plan,
verk=tuple(kraftverk_for_anlegg(inn, losning, dim, k) for k in range(1, plan.N_anlegg + 1)),
felles=enheter_i_B(inn, dim, plan) if losning is Losning.B else (),
verk=kraftverk_per_anlegg(inn, losning, dim, plan),
felles=enheter_i_B(inn, dim, plan, losning=losning),
y=regnekraftpris(inn, knapphet, plan.t_1),
mu_d=Etterspoersel(eps_d=inn["eps_d"], d=bortfall),
T_0=plan.T_0,
T_s=plan.T_s,
)
@ -1361,9 +1529,9 @@ def regn_program(
KS_N += sum((f.netto(varsigma[KJERNEKRAFT]) for f in felles), p.null())
Delta_W, utslipp, K_prog, V = _ovrige_virkninger(p, kraftaar, anlegg)
rho_kraft = inn["rho_N"] if losning.paa_nett else dim.rho_A
NV_datasenter = float(p.diskontering(inn["rho_D"]) @ KS_D)
NV_kraft = float(p.diskontering(rho_kraft) @ KS_N)
NV_ovrige = float(p.diskontering(inn["rho_N"]) @ (Delta_W - utslipp - K_prog - V))
NV_datasenter = _naaverdi(p.diskontering(inn["rho_D"]), KS_D)
NV_kraft = _naaverdi(p.diskontering(rho_kraft), KS_N)
NV_ovrige = _naaverdi(p.diskontering(inn["rho_N"]), Delta_W - utslipp - K_prog - V)
RV_anlegg, RV_felles = _restverdier(p, anlegg, felles, varsigma, F_a)
RV = math.fsum(RV_anlegg) + RV_felles
SE = lg.s26_subsidieelement(naaverdi_prosjekt=NV_datasenter + NV_kraft + RV)
@ -1401,4 +1569,6 @@ def regn_program(
SE=SE,
RV=RV,
),
P_enhet=p.P_enhet,
mu_d=p.mu_d,
)

View file

@ -4,6 +4,11 @@ Emissions are reported in tonnes per year without any deduction for compute
that would otherwise have been made with dirtier power. M5 (i) and (ii) are
properties of the technology and are decided without draws, source by source,
from values that are passed in; nothing here looks up a source.
Two things are shown next to the main figures and enter no verdict (chapter
17.4 and 17.5): the emissions "with deduction" (S53), where the emissions of
the power the same compute would have used elsewhere are deducted, and
cooling water (S54), as withdrawal and consumption.
"""
from __future__ import annotations
@ -35,14 +40,19 @@ def kraftutslipp_per_mwh(inn: Inndata, res: Programresultat, k: int) -> float:
Nuclear power in A, B and B'. In C the average of the facility's own
portfolio, weighted by production in a normal year (clarification 24). R
uses the same figure as C: the portfolio the same facility has in C.
uses the same figure as C: the portfolio the same facility has in C. In
solution T a renewable module is as a facility in C and a nuclear module
as one in B (chapter 17.1).
"""
if res.losning.kjernekraft:
if res.losning.trinnvis:
if res.paa_felles_kjernekraft(k):
return inn["u_kjerne"]
elif res.losning.kjernekraft:
return inn["u_kjerne"]
verkene = (
res.verk[k]
if res.losning is Losning.C
else ks.kraftverk_for_anlegg(inn, Losning.C, res.dim, k + 1)
ks.kraftverk_for_anlegg(inn, Losning.C, res.dim, k + 1)
if res.losning is Losning.R
else res.verk[k]
)
samlet = math.fsum(verk.energi for verk in verkene)
return math.fsum(inn[f"u_{verk.teknologi}"] * verk.energi for verk in verkene) / samlet
@ -62,33 +72,124 @@ def utslipp_livslop(inn: Inndata, res: Programresultat) -> Tabell:
kraft=math.fsum(u * res.dim.E_D for k, u in enumerate(per_mwh) if plan.har_last(k, t)),
u_H=inn["u_H"],
u_B=inn["u_B"],
P_IT=inn["P_IT"],
P_IT=res.P_enhet,
nye_aarganger=sum(t in anlegg.aarganger for anlegg in plan.anlegg),
nye_bygg=sum(t in a.bygg_i_drift for a in res.anlegg),
)
return U
def brukt_brensel(inn: Inndata, res: Programresultat) -> Tabell:
"""Chapter 10: spent fuel per year, eta_N E_N, tonnes of uranium (reported, not judged)."""
def kjernekraftproduksjon(res: Programresultat) -> Tabell:
"""E_N per year: what the nuclear units in operation produce, MWh (index t - T_0).
Everything the units produce, also what is sold to others. In A it is the
energy the data centre uses, E_D, and nothing in a year the facility
stands without chips (clarifications 35 and 54).
"""
plan = res.plan
tonn = np.zeros(len(res.aar), dtype=np.float64)
if not res.losning.kjernekraft:
return tonn
E_N = np.zeros(len(res.aar), dtype=np.float64)
for j, t in enumerate(res.aar):
egne = math.fsum(
verk.energi
for k, verkene in enumerate(res.verk)
for verk in verkene
if (plan.har_last(k, t) if not verk.selges else plan.i_drift(k, t))
if verk.teknologi == ks.KJERNEKRAFT
and (plan.har_last(k, t) if not verk.selges else plan.i_drift(k, t))
)
felles = math.fsum(
f.gruppe.verk.energi
for f in res.felles
if f.gruppe.start <= t <= f.gruppe.siste_driftsaar
)
tonn[j] = inn["eta_N"] * (egne + felles)
return tonn
E_N[j] = egne + felles
return E_N
def brukt_brensel(inn: Inndata, res: Programresultat) -> Tabell:
"""Chapter 10: spent fuel per year, eta_N E_N, tonnes of uranium (reported, not judged)."""
return inn["eta_N"] * kjernekraftproduksjon(res)
# ------------------------------------ shown next to the main figures: S53 and S54
def unngaatt_utslipp(inn: Inndata, res: Programresultat, *, anslag: str = "hoved") -> Tabell:
"""S53: the emissions the same compute would have had elsewhere, tonnes per year.
The sum goes over the facilities and modules with a vintage in operation.
Only compute that is sold and delivered counts, so the factor of S51 is
that of the vintage in operation. ``anslag`` picks the path of u_alt.
"""
plan = res.plan
U = np.zeros(len(res.aar), dtype=np.float64)
for j, t in enumerate(res.aar):
aarganger = [plan.aargang(k, t) for k in range(len(plan.anlegg))]
U[j] = math.fsum(
lg.s53_unngaatt_utslipp(
u_alt=inn.u_alt_i(anslag, t),
mu=inn["mu_rel"],
mu_d=res.mu_d(t_v),
Gamma=res.dim.Gamma,
lam=inn["lambda"],
PUE_v=inn["PUE_v"],
P=res.P_enhet,
)
for t_v in aarganger
if t_v is not None
)
return U
def utslipp_med_fradrag(inn: Inndata, res: Programresultat, *, anslag: str = "hoved") -> Tabell:
"""S53: U_med = U_liv - U_unngaatt per year, tonnes; never part of M5 or any verdict."""
return utslipp_livslop(inn, res) - unngaatt_utslipp(inn, res, anslag=anslag)
def it_energi(inn: Inndata, res: Programresultat) -> Tabell:
"""S54: E_IT per year, 8760 lam P_k over facilities and modules with a vintage in operation."""
per_enhet = lg.s54_it_energi(lam=inn["lambda"], P=res.P_enhet)
return np.array([res.plan.antall_med_last(t) * per_enhet for t in res.aar], dtype=np.float64)
def vannmengde(inn: Inndata, res: Programresultat, *, w_D: float, w_N: float) -> Tabell:
"""S54 with the factors given: w_D E_IT + w_N E_N per year, cubic metres.
For the figures shown next to the main ones (cooling towers, a data centre
cooled with sea water) the caller passes those factors.
"""
E_IT, E_N = it_energi(inn, res), kjernekraftproduksjon(res)
return np.array(
[
lg.s54_kjolevann(w_D=w_D, w_N=w_N, E_IT=e_it, E_N=e_n)
for e_it, e_n in zip(E_IT, E_N, strict=True)
],
dtype=np.float64,
)
@dataclass(frozen=True)
class Kjolevann:
"""S54 per year for one path, cubic metres (index t - T_0). Enters no verdict.
Attributes:
uttak: withdrawal: the data centres' water and the sea water through the nuclear units.
forbruk_kjernekraft: fresh water consumed by the nuclear units.
forbruk_hoyst: consumption when the data centres consume all they withdraw. No Nordic
source gives their consumption, so it is reported as at most this.
"""
uttak: Tabell
forbruk_kjernekraft: Tabell
forbruk_hoyst: Tabell
def kjolevann(inn: Inndata, res: Programresultat) -> Kjolevann:
"""S54 with the main figures: sea water in once-through cooling for nuclear power."""
return Kjolevann(
uttak=vannmengde(inn, res, w_D=inn["w_D_uttak"], w_N=inn["w_N_uttak"]),
forbruk_kjernekraft=vannmengde(inn, res, w_D=0.0, w_N=inn["w_N_forbruk"]),
forbruk_hoyst=vannmengde(inn, res, w_D=inn["w_D_uttak"], w_N=inn["w_N_forbruk"]),
)
def areal(inn: Inndata, *, teknologi: str, energi: float, P_IT: float) -> float:

View file

@ -109,6 +109,7 @@ def renter_i_hovedkjoringen(inn: Inndata, res: Programresultat) -> Renter:
def effektkostnad_bedrift(inn: Inndata, res: Programresultat) -> Tabell:
"""Chapter 7: the disconnection arm of S47 per year for the programme, kr. Zero in A."""
ks.krev_uten_tillegget(res)
plan = res.plan
F = np.zeros(len(res.aar), dtype=np.float64)
if not res.losning.paa_nett:
@ -178,6 +179,7 @@ def lcoe_fornybar(inn: Inndata, teknologi: str, rho_N: float) -> float:
def kraftkostnad_dedikert(inn: Inndata, res: Programresultat, k: int, rho_A: float) -> float:
"""S9 for facility ``k`` (0 is the first) in A, kr per MWh delivered to the data centre."""
ks.krev_uten_tillegget(res)
dim = res.dim
numre = ks.enhetsnumre(dim, k + 1)
return lg.s9_kraftkostnad_dedikert(
@ -425,6 +427,7 @@ def kraftkostnad(
``renter`` replaces the required returns of the main run (used for the
cost of capital of an ownership form, chapter 8).
"""
ks.krev_uten_tillegget(res)
r = renter_i_hovedkjoringen(inn, res) if renter is None else renter
F = effektkostnad_bedrift(inn, res) if bedrift else res.F_a
c_a = _kraftkostnad_per_aar(inn, res, r, F, bedrift=bedrift)

View file

@ -143,6 +143,7 @@ def overskudd_utover_avkastning(
plants, and grid connection or buffer and external supply. In B the
programme's units count in every year they are in operation.
"""
ks.krev_uten_tillegget(res)
r = nivaaisert.renter_i_hovedkjoringen(inn, res) if renter is None else renter
plan = res.plan
rho_kraft = r.rho_N if res.losning.paa_nett else r.rho_A
@ -217,6 +218,7 @@ def skala(inn: Inndata, res: Programresultat, *, u_e: float = 0.0) -> Skala:
``u_e`` is the share owned outside Norway; it is zero in the verdict, which
is computed with one wholly state-owned company.
"""
ks.krev_uten_tillegget(res)
B_6 = lg.s31_nettobidrag(
u_e=u_e,
overskudd_utover_avkastning=overskudd_utover_avkastning(inn, res),

View file

@ -21,7 +21,7 @@ if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
I_KONTANTSTROMMEN = tuple(a for a in Losning if not a.trinnvis)
I_KONTANTSTROMMEN = tuple(Losning)
"""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

View file

@ -14,7 +14,6 @@ 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:
@ -381,14 +380,6 @@ def test_bryterne_for_t_gjelder_bare_t(oppdiktet: LagInndata) -> None:
)
@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

View file

@ -0,0 +1,483 @@
"""Solution T through the power system and the cash flow, the loss of demand, S53 and S54.
Made-up round numbers only; nothing here says anything about the hypothesis. The path used
most is T-K with two facilities' worth of modules from the made-up set with new grid in
2033 and 0.5 TWh of new renewable power a year (hand-computed in ``test_trinnvis.py``):
three renewable modules (2030, 2031, 2033), then ten nuclear modules in 2035 and seven in
2036. A module uses 8760 * 0.75 * 1.2 * 100 = 788 400 MWh a year, and one unit of
1 000 MW gives 8760 * 0.8 * 1000 = 7 008 000 MWh.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
import numpy as np
import pytest
from tokenfabrikker import dommer, eierskap, miljo, nivaaisert, skala
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 Losning
if TYPE_CHECKING:
from collections.abc import Callable
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
E_MODUL = 8760.0 * 0.75 * 1.2 * 100.0
"""Yearly energy to one made-up module: 788 400 MWh."""
E_ENHET = 8760.0 * 0.8 * 1000.0
"""Yearly production of one made-up unit on the grid: 7 008 000 MWh."""
GAMLE = (Losning.A, Losning.B, Losning.B_MERKET, Losning.C, Losning.R)
"""The solutions of chapters 0 to 16."""
def _regn(
inn: Inndata,
losning: Losning,
*,
N_anlegg: int = 1,
bortfall: Callable[[int], float] | None = None,
**brytere: bool,
) -> ks.Programresultat:
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=N_anlegg, **brytere)
return ks.regn_program(inn, losning, plan, Knapphet.NORMALISERING, dim=dim, bortfall=bortfall)
def _tk(oppdiktet: LagInndata, *, L_N: float = 20.0) -> tuple[Inndata, ks.Programresultat]:
inn = oppdiktet(tau_nett=6.0, g_fornybar=0.5e6, L_N=L_N)
return inn, _regn(inn, Losning.T_K, N_anlegg=2)
def _lik(a: ks.Programresultat, b: ks.Programresultat) -> None:
"""Every yearly table and every present value of the two results is the same number."""
for navn in ("KS_D", "KS_N", "F_a", "Delta_W", "utslipp", "K_prog", "V"):
assert np.array_equal(getattr(a, navn), getattr(b, navn)), navn
for navn in ("NV_datasenter", "NV_kraft", "NV_ovrige", "RV", "SE", "NNV"):
assert getattr(a, navn) == getattr(b, navn), navn
assert a.RV_anlegg == b.RV_anlegg
assert a.varsigma == b.varsigma
def test_samme_regning_to_ganger_gir_samme_tall_til_siste_siffer(oppdiktet: LagInndata) -> None:
"""The present values are exactly rounded sums, not dot products (which are not repeatable)."""
inn = oppdiktet(tau_nett=6.0)
for losning in (Losning.A, Losning.T_F):
forste = _regn(inn, losning, N_anlegg=2)
for _ in range(5):
_lik(_regn(inn, losning, N_anlegg=2), forste)
# ------------------------------------------------------- everything per module
def test_alt_i_datasenteret_er_per_modul(oppdiktet: LagInndata) -> None:
"""Module 1 of T-F starts in 2030: 100 MW, built over two years, connected the year before."""
inn = oppdiktet(tau_nett=6.0)
res = _regn(inn, Losning.T_F)
assert res.P_enhet == 100.0
assert len(res.anlegg) == 10
modul = res.anlegg[0]
assert modul.inntekt[2030 - 2027] == pytest.approx(res.y(2030) * 100.0)
assert modul.drift[2030 - 2027] == pytest.approx(2.5e6 * 100.0)
# building: 100 mill. kr per MW plus ten per cent, half in 2028 and half in 2029
assert modul.I_bygg[2028 - 2027] == pytest.approx(5.5e9)
assert modul.I_bygg[2029 - 2027] == pytest.approx(5.5e9)
# first vintage with the building, the next one paid in 2034
assert modul.I_H[2028 - 2027] == pytest.approx(10e9)
assert modul.I_H[2034 - 2027] == pytest.approx(20e9)
# grid: 5 mill. kr per MW for the half of 120 MW that is not taken from others
assert modul.I_nett[2029 - 2027] == pytest.approx(5e6 * 0.5 * 120.0)
assert modul.kraftkjop[2030 - 2027] == pytest.approx(
1.05 * res.kraftaar[2030 - 2027].pris * E_MODUL
)
# the emissions from building in Norway follow the module's size
assert res.utslipp[2030 - 2027] == pytest.approx(1000.0 * 0.5 * 2000.0 * 100.0)
def test_fornybarmodulene_har_portefoljen_s39_legger_til(oppdiktet: LagInndata) -> None:
"""Hydropower fills the first two modules and part of the third; then wind.
2 TWh of hydropower gives 1.6 TWh in a dry year: modules 1 and 2 use 1 576 800 MWh of
it, module 3 the 23 200 MWh that are left (29 000 MWh in a normal year) and wind.
"""
inn = oppdiktet(tau_nett=6.0)
res = _regn(inn, Losning.T_F)
dim = ks.dimensjoner(inn, Losning.T_F)
assert res.verk == tuple(ks.kraftverk_for_anlegg(inn, Losning.C, dim, j) for j in range(1, 11))
(vann,) = res.verk[0]
assert vann.teknologi == "vann"
assert vann.energi == pytest.approx(E_MODUL / 0.8)
tredje = {verk.teknologi: verk.energi for verk in res.verk[2]}
assert tredje["vann"] == pytest.approx(2e6 - 2 * E_MODUL / 0.8)
assert tredje["vind"] == pytest.approx(E_MODUL - 23_200.0)
# ten modules have the portfolio of one facility of 1 000 MW in C
c = ks.kraftverk_for_anlegg(inn, Losning.C, ks.dimensjoner(inn, Losning.C), 1)
for verk in c:
i_moduler = math.fsum(
v.energi for modul in res.verk for v in modul if v.teknologi == verk.teknologi
)
assert i_moduler == pytest.approx(verk.energi)
def test_tf_i_moduler_paa_ett_anlegg_uten_forste_trinn_er_c(oppdiktet: LagInndata) -> None:
"""A module the size of a facility, started when new grid can come, is a facility in C."""
inn = oppdiktet(tau_nett=6.0, P_m=1000.0)
for N_anlegg in (1, 3):
c = _regn(inn, Losning.C, N_anlegg=N_anlegg)
tf = _regn(inn, Losning.T_F, N_anlegg=N_anlegg, uten_forste_trinn=True)
assert tf.plan.anlegg == c.plan.anlegg
_lik(tf, c)
def test_kraftsystemet_teller_modulene(oppdiktet: LagInndata) -> None:
"""2031: two modules, both on hydropower that gives all they use in a dry year."""
inn = oppdiktet(tau_nett=6.0)
res = _regn(inn, Losning.T_F)
rad = res.kraftaar[2031 - 2027]
# half of the use takes the place of others; production in a normal year is use / 0.8
assert rad.Delta_Q == pytest.approx(0.5 * 2 * E_MODUL - 2 * E_MODUL / 0.8)
assert rad.Delta_Q_tort == pytest.approx(0.5 * 2 * E_MODUL - 2 * E_MODUL)
effekt = 2 * E_MODUL / 0.8 / 3000.0
assert rad.Delta_R == pytest.approx(0.9 * effekt - 0.5 * 1.2 * 200.0)
assert res.V[2031 - 2027] == pytest.approx(0.5 * 2 * E_MODUL * 70.0)
def test_m4_leses_av_kraftsystemet_ogsaa_for_t(oppdiktet: LagInndata) -> None:
inn = oppdiktet(tau_nett=6.0)
forsyning = dommer.m4_forsyning(inn, _regn(inn, Losning.T_F))
assert not forsyning.svakere_ogsaa_med_tiltak
def test_en_plan_i_moduler_horer_til_t(oppdiktet: LagInndata) -> None:
inn = oppdiktet(tau_nett=6.0)
plan_c = ks.lag_plan(inn, Losning.C, ks.dimensjoner(inn, Losning.C), N_anlegg=1)
plan_t = ks.lag_plan(inn, Losning.T_F, ks.dimensjoner(inn, Losning.T_F), N_anlegg=1)
with pytest.raises(TypeError, match="built in modules"):
ks.regn_program(inn, Losning.T_F, plan_c, Knapphet.NORMALISERING)
with pytest.raises(TypeError, match="built in modules"):
ks.regn_program(inn, Losning.C, plan_t, Knapphet.NORMALISERING)
# ----------------------------------------------------- nuclear power in T-K
def test_tk_uten_kjernekraft_er_tf_i_alle_tall(oppdiktet: LagInndata) -> None:
"""One facility's worth of modules: S49 is not met, so T-K is T-F in every year."""
inn = oppdiktet(tau_nett=6.0, g_fornybar=0.5e6)
tk, tf = _regn(inn, Losning.T_K), _regn(inn, Losning.T_F)
assert isinstance(tk.plan, ub.Trinnvisplan)
assert not tk.plan.kjernekraft_bygges
assert tk.felles == ()
assert not tk.K_prog.any()
_lik(tk, tf)
def test_enhetene_i_tk_folger_kjernekraftmodulene(oppdiktet: LagInndata) -> None:
"""Ten nuclear modules in 2035 need 7.884 TWh, more than one unit gives: two units.
Seventeen need 13.4 TWh, still two. The units go out after 2054, while the seven
modules from 2036 are operated one more year and need one unit: a third from 2055.
The three renewable modules do not count.
"""
inn, res = _tk(oppdiktet)
grupper = [(f.gruppe.start, f.gruppe.siste_driftsaar, f.gruppe.numre) for f in res.felles]
assert grupper == [(2035, 2054, (1, 2)), (2055, 2074, (3,))]
assert res.felles[0].gruppe.verk.energi == pytest.approx(2 * E_ENHET)
assert [len(verk) for verk in res.verk] == [1, 1, 2] + [0] * 17
assert [res.paa_felles_kjernekraft(k) for k in (0, 2, 3, 19)] == [False, False, True, True]
tf = _regn(inn, Losning.T_F, N_anlegg=2)
assert ks.enheter_i_B(inn, tf.dim, tf.plan, losning=Losning.T_F) == ()
def test_kjernekraften_i_tk_selger_som_i_b(oppdiktet: LagInndata) -> None:
_, res = _tk(oppdiktet)
j = 2040 - 2027
assert res.felles[0].salg[j] == pytest.approx(res.kraftaar[j].pris * 2 * E_ENHET)
# two units of 1 000 MW, the largest of them out in the scarcest hour
rad = res.kraftaar[j]
assert rad.Delta_R - rad.Delta_R_utfall == pytest.approx(0.98 * 1000.0)
assert set(res.varsigma) == {"kjernekraft", "vann", "vind"}
def test_nettet_til_en_kjernekraftmodul_baerer_ogsaa_reaktoreffekten(
oppdiktet: LagInndata,
) -> None:
"""A nuclear module pays for its draw and for 0.75 * 1.2 * 100 / 0.8 = 112.5 MW of reactor."""
_, res = _tk(oppdiktet)
assert res.anlegg[3].I_nett[2034 - 2027] == pytest.approx(5e6 * (0.5 * 120.0 + 112.5))
assert res.anlegg[2].I_nett[2032 - 2027] == pytest.approx(5e6 * 0.5 * 120.0)
def test_s41_i_tk_regnes_til_forste_kjernekraftenhet(oppdiktet: LagInndata) -> None:
"""200 man-years at 1 mill. kr, spread over 2028 to 2035, the first unit's first year."""
_, res = _tk(oppdiktet)
assert res.plan.t_1 == 2030
assert res.K_prog[1 : 2035 - 2027 + 1] == pytest.approx(0.2 * 1000.0 * 1e6 / 8.0)
assert not res.K_prog[2036 - 2027 :].any()
assert res.K_prog[0] == 0.0
def test_knappheten_i_t_regnes_fra_forste_modul(oppdiktet: LagInndata) -> None:
"""S43: the markup lasts ten years from the first module, not from the first unit."""
inn = oppdiktet(tau_nett=6.0, g_fornybar=0.5e6)
dim = ks.dimensjoner(inn, Losning.T_K)
plan = ks.lag_plan(inn, Losning.T_K, dim, N_anlegg=2)
res = ks.regn_program(inn, Losning.T_K, plan, Knapphet.VARER, dim=dim)
assert res.y(2039) == pytest.approx(150e6)
assert res.y(2040) < 150e6
def test_restverdien_deler_kjernekraften_paa_kjernekraftmodulene(oppdiktet: LagInndata) -> None:
"""With 30 operating years the modules run past 2060, and S40 gives each a residual value.
In the last five years all seventeen nuclear modules are operated, so each carries a
seventeenth of the units' cash flow; a renewable module carries none of it.
"""
_, res = _tk(oppdiktet, L_N=30.0)
assert [a.L_rest for a in (res.anlegg[0], res.anlegg[3], res.anlegg[19])] == [0, 4, 5]
kjerne = sum(f.netto(res.varsigma["kjernekraft"]) for f in res.felles)
# module 1 goes out after 2059, so the capacity cost is shared by 20 and then by 19
med_last = np.array([max(1, res.plan.antall_med_last(t)) for t in res.aar])
assert list(med_last[-5:]) == [20, 20, 20, 20, 19]
def restverdi(k: int, andel_kjerne: float) -> float:
a = res.anlegg[k]
netto = a.datasenter() + a.kraft(res.varsigma, res.F_a / med_last) + andel_kjerne * kjerne
return lg.s40_restverdi(
NK_snitt=float(np.mean(netto[-5:])),
L_rest=a.L_rest,
rho_D=0.08,
rho_avvikling=0.06,
avvikling=0.0,
T_s=2060,
T_0=2027,
)
assert res.RV_anlegg[3] == pytest.approx(restverdi(3, 1.0 / 17.0))
assert res.RV_anlegg[19] == pytest.approx(restverdi(19, 1.0 / 17.0))
assert res.RV_anlegg[2] == pytest.approx(restverdi(2, 0.0))
assert res.RV_anlegg[3] != pytest.approx(restverdi(3, 1.0 / 20.0))
# the units from 2035 go out in 2064: their decommissioning falls after the final year
assert res.felles[0].avvikling_etter == pytest.approx(5e6 * 2000.0)
assert res.RV_felles < 0
assert res.RV == pytest.approx(math.fsum(res.RV_anlegg) + res.RV_felles)
def test_nnv_er_summen_av_delene_i_t(oppdiktet: LagInndata) -> None:
_, res = _tk(oppdiktet)
D_D = np.array([1.08 ** -(t - 2027) for t in res.aar])
D_N = np.array([1.06 ** -(t - 2027) for t in res.aar])
egne = sum(a.kraft(res.varsigma, np.zeros(len(res.aar))) for a in res.anlegg)
felles = sum(f.netto(res.varsigma["kjernekraft"]) for f in res.felles)
assert res.KS_N == pytest.approx(egne + felles - res.F_a)
assert res.NV_datasenter == pytest.approx(float(D_D @ res.KS_D))
assert res.NV_kraft == pytest.approx(float(D_N @ res.KS_N))
assert res.NNV == pytest.approx(
res.NV_datasenter + res.NV_kraft + res.NV_ovrige - 0.2 * res.SE + res.RV
)
# ------------------------------------------------ the loss of demand (S51)
@pytest.mark.parametrize("losning", [*GAMLE, Losning.T_F])
def test_uten_bortfall_er_alle_tall_uendret(oppdiktet: LagInndata, losning: Losning) -> None:
inn = oppdiktet(tau_nett=6.0)
uten = _regn(inn, losning, N_anlegg=2)
assert uten.mu_d.hovedforlop
assert uten.mu_d(2030) == 1.0
_lik(_regn(inn, losning, N_anlegg=2, bortfall=ks.fast_bortfall(0.0)), uten)
def test_bortfallet_folger_aargangen_og_endrer_bare_inntekten(oppdiktet: LagInndata) -> None:
"""The made-up scenario: d is 0.1 for the vintage of 2030 and 0.2 from 2035."""
inn = oppdiktet()
uten = _regn(inn, Losning.C)
med = _regn(inn, Losning.C, bortfall=ks.bortfall_i_scenario(inn, "lavt"))
assert med.plan == uten.plan
assert not med.mu_d.hovedforlop
a, b = med.anlegg[0], uten.anlegg[0]
assert a.inntekt[2030 - 2027 : 2035 - 2027] == pytest.approx(
0.9 * b.inntekt[2030 - 2027 : 2035 - 2027]
)
assert a.inntekt[2035 - 2027 :] == pytest.approx(0.8 * b.inntekt[2035 - 2027 :])
for navn in ("drift", "kraftkjop", "I_bygg", "I_H", "I_nett"):
assert np.array_equal(getattr(a, navn), getattr(b, navn)), navn
assert med.NNV < uten.NNV
with pytest.raises(KeyError, match="unknown scenario"):
ks.bortfall_i_scenario(inn, "finnes ikke")
def test_eps_d_skalerer_bortfallet(oppdiktet: LagInndata) -> None:
inn = oppdiktet(eps_d=2.0)
uten = _regn(inn, Losning.R)
med = _regn(inn, Losning.R, bortfall=ks.fast_bortfall(0.2))
assert med.mu_d(2030) == pytest.approx(0.6)
assert med.anlegg[0].inntekt == pytest.approx(0.6 * uten.anlegg[0].inntekt)
@pytest.mark.parametrize("losning", [Losning.A, Losning.B, Losning.R, Losning.T_K])
def test_likt_bortfall_er_det_samme_som_lavere_solgt_andel(
oppdiktet: LagInndata, losning: Losning
) -> None:
"""17.3: the factor stands everywhere mu stands with the price, so d = 0.2 is mu = 0.8."""
inn = oppdiktet(tau_nett=6.0, g_fornybar=0.5e6)
med = _regn(inn, losning, N_anlegg=2, bortfall=ks.fast_bortfall(0.2))
lavere = _regn(oppdiktet(tau_nett=6.0, g_fornybar=0.5e6, mu_rel=0.8), losning, N_anlegg=2)
assert med.NNV == pytest.approx(lavere.NNV)
assert med.KS_D == pytest.approx(lavere.KS_D)
assert med.F_a == pytest.approx(lavere.F_a)
def test_bortfallet_staar_i_utkoblingsarmen(oppdiktet: LagInndata) -> None:
"""R builds no power, so capacity is missing; disconnecting is the cheaper arm here.
The arm is the revenue lost in the scarce hours, so it falls with the revenue.
"""
inn = oppdiktet()
uten = _regn(inn, Losning.R)
med = _regn(inn, Losning.R, bortfall=ks.fast_bortfall(0.2))
j = 2032 - 2027
mangler = 0.5 * 1.2 * 1000.0
assert uten.F_a[j] == pytest.approx(100.0 * uten.y(2030) / (8760.0 * 1.2) * mangler)
assert uten.F_a[j] < 1.4e6 * mangler
assert med.F_a[j] == pytest.approx(0.8 * uten.F_a[j])
def test_kapitlene_etter_kontantstrommen_avviser_det_de_ikke_kan_ennaa(
oppdiktet: LagInndata,
) -> None:
inn = oppdiktet(tau_nett=6.0)
t = _regn(inn, Losning.T_F)
med = _regn(inn, Losning.C, bortfall=ks.fast_bortfall(0.2))
for res, melding in ((t, "solution T is not taken"), (med, "loss of demand")):
with pytest.raises(NotImplementedError, match=melding):
nivaaisert.kraftkostnad(inn, res)
with pytest.raises(NotImplementedError, match=melding):
eierskap.bedriftsstrom(inn, res)
with pytest.raises(NotImplementedError, match=melding):
skala.skala(inn, res)
# ------------------------------------------------- S32, S53 and S54 over a programme
def test_utslippene_i_t_folger_modulens_egen_kraft(oppdiktet: LagInndata) -> None:
"""Module 1 has hydropower only; a nuclear module has the figure for nuclear power."""
inn, res = _tk(oppdiktet)
assert miljo.kraftutslipp_per_mwh(inn, res, 0) == pytest.approx(0.004)
assert miljo.kraftutslipp_per_mwh(inn, res, 3) == pytest.approx(0.012)
U = miljo.utslipp_livslop(inn, res)
# 2030: one module on hydropower, with its building and its first vintage
assert U[2030 - 2027] == pytest.approx(0.004 * E_MODUL + (1000.0 + 2000.0) * 100.0)
tf = _regn(inn, Losning.T_F, N_anlegg=2)
assert miljo.kraftutslipp_per_mwh(inn, tf, 3) < 0.012
assert not miljo.brukt_brensel(inn, tf).any()
def test_kjernekraftproduksjonen_teller_bare_kjernekraft(oppdiktet: LagInndata) -> None:
"""T-K: nothing before 2035, two units to 2054 and one from 2055; renewables never count."""
inn, res = _tk(oppdiktet)
E_N = miljo.kjernekraftproduksjon(res)
assert not E_N[: 2035 - 2027].any()
assert E_N[2035 - 2027 : 2055 - 2027] == pytest.approx(2 * E_ENHET)
assert E_N[2055 - 2027 :] == pytest.approx(E_ENHET)
assert miljo.brukt_brensel(inn, res) == pytest.approx(3e-6 * E_N)
# A: the plant only produces what the data centre uses
a = _regn(inn, Losning.A)
assert miljo.kjernekraftproduksjon(a)[a.plan.t_1 - 2027] == pytest.approx(10 * E_MODUL)
assert not miljo.kjernekraftproduksjon(_regn(inn, Losning.C)).any()
def test_s53_unngaatte_utslipp_over_et_program(oppdiktet: LagInndata) -> None:
"""u_alt falls from 0.4 in 2025 to 0.2 in 2035: 0.3 tonnes per MWh in 2030.
One facility of 1 000 MW that sells everything: 8760 * 0.75 * 1.2 * 1000 MWh with the
competitor's PUE.
"""
inn = oppdiktet()
res = _regn(inn, Losning.C)
unngaatt = miljo.unngaatt_utslipp(inn, res)
assert not unngaatt[: 2030 - 2027].any()
assert unngaatt[2030 - 2027] == pytest.approx(0.3 * 7_884_000.0)
assert unngaatt[2045 - 2027] == pytest.approx(0.1 * 7_884_000.0)
assert unngaatt[2049 - 2027] == pytest.approx(0.1 * 7_884_000.0)
assert unngaatt[2050 - 2027] == 0.0 # the facility went out after 20 years
assert miljo.unngaatt_utslipp(inn, res, anslag="fast")[2040 - 2027] == pytest.approx(
0.5 * 7_884_000.0
)
assert not miljo.unngaatt_utslipp(inn, res, anslag="null").any()
med = miljo.utslipp_med_fradrag(inn, res)
assert med == pytest.approx(miljo.utslipp_livslop(inn, res) - unngaatt)
def test_s53_teller_bare_det_som_er_solgt_og_levert(oppdiktet: LagInndata) -> None:
inn = oppdiktet(PUE_v=1.5)
c = _regn(inn, Losning.C)
assert miljo.unngaatt_utslipp(inn, c)[2030 - 2027] == pytest.approx(
0.3 * 8760.0 * 0.75 * 1.5 * 1000.0
)
# the loss of demand follows the vintage: 0.1 for the one of 2030, 0.2 from 2035
med = _regn(inn, Losning.C, bortfall=ks.bortfall_i_scenario(inn, "lavt"))
forhold = miljo.unngaatt_utslipp(inn, med) / np.maximum(1.0, miljo.unngaatt_utslipp(inn, c))
assert forhold[2034 - 2027] == pytest.approx(0.9)
assert forhold[2035 - 2027] == pytest.approx(0.8)
# A delivers the share Gamma of the year
a = _regn(inn, Losning.A)
assert a.dim.Gamma < 1.0
assert miljo.unngaatt_utslipp(inn, a)[2045 - 2027] == pytest.approx(
a.dim.Gamma * 0.1 * 8760.0 * 0.75 * 1.5 * 1000.0
)
# a share that is not sold replaces nothing
halv = oppdiktet(PUE_v=1.5, mu_rel=0.5)
assert miljo.unngaatt_utslipp(halv, _regn(halv, Losning.C))[2030 - 2027] == pytest.approx(
0.5 * 0.3 * 8760.0 * 0.75 * 1.5 * 1000.0
)
def test_s53_i_t_summerer_over_modulene(oppdiktet: LagInndata) -> None:
"""2036: all twenty modules have a vintage in operation, 2 000 MW; u_alt is 0.19."""
inn, res = _tk(oppdiktet)
assert miljo.unngaatt_utslipp(inn, res)[2036 - 2027] == pytest.approx(0.19 * 2 * 7_884_000.0)
assert miljo.unngaatt_utslipp(inn, res)[2031 - 2027] == pytest.approx(0.28 * 2 * 788_400.0)
def test_s54_kjolevann_over_et_program(oppdiktet: LagInndata) -> None:
"""T-K in 2036: 2 000 MW IT use 13.14 TWh, and two units produce 14.016 TWh."""
inn, res = _tk(oppdiktet)
j = 2036 - 2027
E_IT = 20 * 8760.0 * 0.75 * 100.0
assert miljo.it_energi(inn, res)[j] == pytest.approx(E_IT)
vann = miljo.kjolevann(inn, res)
assert vann.uttak[j] == pytest.approx(0.1 * E_IT + 150.0 * 2 * E_ENHET)
assert not vann.forbruk_kjernekraft.any()
assert vann.forbruk_hoyst[j] == pytest.approx(0.1 * E_IT)
# 2031: two renewable modules, no nuclear power yet
assert vann.uttak[2031 - 2027] == pytest.approx(0.1 * 2 * 8760.0 * 0.75 * 100.0)
# the figures shown next to the main ones take their own factors
taarn = miljo.vannmengde(inn, res, w_D=0.0, w_N=inn.kjoletaarn["forbruk"][1])
assert taarn[j] == pytest.approx(2.5 * 2 * E_ENHET)
@pytest.mark.parametrize("losning", GAMLE)
def test_s54_i_losningene_fra_for(oppdiktet: LagInndata, losning: Losning) -> None:
inn = oppdiktet(w_N_forbruk=1.0)
res = _regn(inn, losning)
j = res.plan.t_1 - 2027
E_IT = 8760.0 * 0.75 * 1000.0
E_N = miljo.kjernekraftproduksjon(res)[j]
vann = miljo.kjolevann(inn, res)
assert vann.uttak[j] == pytest.approx(0.1 * E_IT + 150.0 * E_N)
assert vann.forbruk_kjernekraft[j] == pytest.approx(E_N)
assert vann.forbruk_hoyst[j] == pytest.approx(0.1 * E_IT + E_N)
assert (E_N > 0) == losning.kjernekraft
assert not vann.uttak[:j].any()