feat(kjoring): the run over the draws, the verdicts put together and the timeline

For every draw the seven solutions on every step of the ladder in six
scenarios, with the outcomes the verdicts need; the verdicts per target,
the step they are read on, part I and part II; S50 summarised over the
draws; and the ownership forms on that step. Tested on made-up draws and
invented outcomes only. Written and committed before the independent
reader's code was opened.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-13 15:22:09 +01:00
commit 8ab69c7619
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
2 changed files with 1227 additions and 0 deletions

View file

@ -0,0 +1,701 @@
"""The run over the draws (chapter 11; chapter 16, clarifications 95 to 102).
One draw is one set of values. For every draw the seven solutions are
computed on every step of the ladder and in every scenario, and the outcomes
the verdicts need are kept: whether the path can be built, the net present
value (S26), the sum of S42, the worst price effect (M3), the two conditions
of M4 and M6 in the first year of stable operation. The verdicts are put
together from them with ``dommer`` and ``miljo``, on the step the
pre-registration points to, and the timeline (S50) is summarised over the
draws. The ownership forms are compared on that step in a second pass.
Every draw is computed on its own and the outcomes are kept in the order of
the draws. Shares are counts over counts, medians and percentiles are read off
sorted values, and sums over the draws are exactly rounded. The figures are
therefore the same to the last digit however many processes the run is split
over (clarification 101).
Nothing here reads the frozen parameter file or the stored draws: the caller
passes the sets of values. Until the results are computed (part 6 of the plan)
that is the made-up set of the tests.
"""
from __future__ import annotations
import math
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from functools import partial
from typing import TYPE_CHECKING, Final
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.dommer import DOMSLOSNINGER, Dom, Forsyning, Trinnvalg
from tokenfabrikker.inndata import BORTFALL_EGNE_HOY, BORTFALL_EGNE_LAV, BORTFALL_KILDE
from tokenfabrikker.kontantstrom import Knapphet
from tokenfabrikker.utbygging import Kraft, Losning
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping, Sequence
from tokenfabrikker.eierskap import Eierkriterier, Eierresultat, Rangering
from tokenfabrikker.inndata import Inndata
from tokenfabrikker.miljo import Kildeverdier
STIGE: Final = (1, 5, 10, 20, 40)
"""The fixed ladder of programme sizes, in facilities (pre-registration, clarification 1)."""
PERSENTILER: Final = (0.1, 0.9)
"""The percentiles the timeline is reported with, next to the median (chapter 17.2)."""
MW_GRENSER: Final = (100.0, 1000.0)
"""The timeline gives the share of the draws with at least this many MW IT in operation."""
ALLE_TYPER: Final = "alle"
"""The key of the timeline for the sum over the types of power."""
MAAL_PER_LOSNING: Final = ("M1", "M2", "M3", "M4", "M6")
"""The targets that are judged from the draws for one solution; M5 is judged without draws."""
@dataclass(frozen=True)
class Scenario:
"""One scenario of the run: a price scenario, and possibly a marked loss of demand.
Attributes:
navn: the name the scenario is reported under.
knapphet: the price scenario for compute (S43).
bortfall: the marked scenario for AI use on the users' own machines (chapter 17.3),
a key of ``Inndata.bortfall``; None on the main path.
"""
navn: str
knapphet: Knapphet
bortfall: str | None = None
@property
def teller(self) -> bool:
"""True for the scenario whose verdict counts: «normalisering» on the main path."""
return self.knapphet is Knapphet.NORMALISERING and self.bortfall is None
SCENARIOER: Final = (
Scenario(Knapphet.VARER.value, Knapphet.VARER),
Scenario(Knapphet.NORMALISERING.value, Knapphet.NORMALISERING),
Scenario(Knapphet.OVERKAPASITET.value, Knapphet.OVERKAPASITET),
Scenario(BORTFALL_KILDE, Knapphet.NORMALISERING, BORTFALL_KILDE),
Scenario(BORTFALL_EGNE_LAV, Knapphet.NORMALISERING, BORTFALL_EGNE_LAV),
Scenario(BORTFALL_EGNE_HOY, Knapphet.NORMALISERING, BORTFALL_EGNE_HOY),
)
"""The six scenarios of the run (clarification 95): three price scenarios, three marked ones."""
# ------------------------------------------------------------------ one draw
@dataclass(frozen=True)
class Utfall:
"""What the verdicts need from one path that can be built, in one scenario and one draw.
Attributes:
NNV: net present value for Norway (S26), kr.
S42: the sum of S42 over the vintages, kr per MW IT.
M3: the largest relative price effect over price areas, weather and operating years.
M4: the two conditions of M4 over the operating years.
M6: the net contribution in the first year of stable operation as a share of the
petroleum cash flow; None when the path has no such year.
M6_snitt: the same for the average over L_H years from that year.
M6_median: M6 against the median of the ten years.
M6_2050: the share in 2050; None when the analysis ends before that.
M6_topp: the share in the year the contribution is highest.
stabilt_aar: the first year of stable operation, or None.
toppaar: the year the contribution is highest.
"""
NNV: float
S42: float
M3: float
M4: Forsyning
M6: float | None
M6_snitt: float | None
M6_median: float | None
M6_2050: float | None
M6_topp: float
stabilt_aar: int | None
toppaar: int
@dataclass(frozen=True)
class Bane:
"""One solution on one step of the ladder in one draw.
Attributes:
byggbar: True when every facility or module starts within the final year.
forste_aar: the first year of the timeline, T_0 + 1.
tidslinje: S50, MW IT in operation per year from ``forste_aar``, for the types of
power the path uses; a type that is left out is zero in every year. A path that
cannot be built is here with what was built.
utfall: the outcomes by the name of the scenario; empty when the path cannot be
built (clarification 96).
"""
byggbar: bool
forste_aar: int
tidslinje: Mapping[Kraft, tuple[float, ...]]
utfall: Mapping[str, Utfall]
Trekningsutfall = dict[tuple[Losning, int], Bane]
"""Every solution on every step in one draw."""
def _bortfall(inn: Inndata, scenario: Scenario) -> Callable[[int], float] | None:
return None if scenario.bortfall is None else ks.bortfall_i_scenario(inn, scenario.bortfall)
def _utfall(inn: Inndata, res: ks.Programresultat) -> Utfall:
S42 = nivaaisert.kraftkostnad(inn, res, bedrift=True).S42
if S42 is None: # pragma: no cover - the business version always has it
msg = "the business version of the levelised cost has no S42"
raise RuntimeError(msg)
m6 = skala.skala(inn, res)
return Utfall(
NNV=res.NNV,
S42=S42,
M3=dommer.m3_verste_prisvirkning(inn, res),
M4=dommer.m4_forsyning(inn, res),
M6=m6.M6,
M6_snitt=m6.M6_snitt,
M6_median=m6.M6_median,
M6_2050=m6.M6_2050,
M6_topp=m6.M6_topp,
stabilt_aar=m6.stabilt_aar,
toppaar=m6.toppaar,
)
def regn_bane(
inn: Inndata, losning: Losning, trinn: int, scenarioer: Sequence[Scenario] = SCENARIOER
) -> Bane:
"""One solution on one step in one draw: the build-out, the timeline and the outcomes.
The build-out is the same in every scenario (clarification 95). A set of
values the build-out rejects is an error and is not caught here: it is not
a path that cannot be built (clarification 96).
"""
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=trinn)
linje = ub.tidslinje(losning, plan, P_IT=inn["P_IT"])
utfall: dict[str, Utfall] = {}
if plan.gjennomforbar:
for scenario in scenarioer:
res = ks.regn_program(
inn, losning, plan, scenario.knapphet, dim=dim, bortfall=_bortfall(inn, scenario)
)
utfall[scenario.navn] = _utfall(inn, res)
return Bane(
byggbar=plan.gjennomforbar,
forste_aar=plan.T_0 + 1,
tidslinje={x: mw for x, mw in linje.items() if any(mw)},
utfall=utfall,
)
def regn_trekning(
inn: Inndata,
*,
stige: Sequence[int] = STIGE,
scenarioer: Sequence[Scenario] = SCENARIOER,
losninger: Sequence[Losning] = tuple(Losning),
) -> Trekningsutfall:
"""Every solution on every step of the ladder in one draw (clarification 95)."""
return {
(losning, trinn): regn_bane(inn, losning, trinn, scenarioer)
for losning in losninger
for trinn in stige
}
# ------------------------------------------------------------- over the draws
@dataclass(frozen=True)
class Kjoring:
"""The outcomes of every draw, in the order of the draws.
Attributes:
stige: the steps of the ladder, in facilities.
scenarioer: the scenarios.
losninger: the solutions.
trekninger: one entry per draw.
"""
stige: tuple[int, ...]
scenarioer: tuple[Scenario, ...]
losninger: tuple[Losning, ...]
trekninger: tuple[Trekningsutfall, ...]
@property
def antall(self) -> int:
"""The number of draws, the denominator of S37."""
return len(self.trekninger)
@property
def hovedscenario(self) -> Scenario:
"""The scenario whose verdict counts; the run must have exactly one."""
teller = [s for s in self.scenarioer if s.teller]
if len(teller) != 1:
msg = f"the run needs «normalisering» on the main path exactly once, got {len(teller)}"
raise ValueError(msg)
return teller[0]
def baner(self, losning: Losning, trinn: int) -> list[Bane]:
"""The path of one solution on one step, per draw."""
return [t[losning, trinn] for t in self.trekninger]
def utfall(self, scenario: Scenario, losning: Losning, trinn: int) -> list[Utfall | None]:
"""The outcomes per draw; None where the path cannot be built."""
return [b.utfall.get(scenario.navn) for b in self.baner(losning, trinn)]
def _entydige(verdier: Sequence[object], hva: str) -> None:
if not verdier or len(set(verdier)) != len(verdier):
msg = f"the run needs at least one of the {hva}, each of them once: {list(verdier)}"
raise ValueError(msg)
def kjor(
trekninger: Iterable[Inndata],
*,
stige: Sequence[int] = STIGE,
scenarioer: Sequence[Scenario] = SCENARIOER,
losninger: Sequence[Losning] = tuple(Losning),
prosesser: int = 1,
) -> Kjoring:
"""The run over the draws: every draw through ``regn_trekning``, kept in order.
``trekninger`` holds one set of values per draw (``inndata.fra_trekning``
builds it from the stored draws and the stored event stream). With
``prosesser`` above one the draws are shared out over that many
processes; the outcome is the same to the last digit.
"""
_entydige(stige, "steps")
_entydige([s.navn for s in scenarioer], "scenarios")
_entydige(losninger, "solutions")
en = partial(regn_trekning, stige=stige, scenarioer=scenarioer, losninger=losninger)
if prosesser > 1:
with ProcessPoolExecutor(max_workers=prosesser) as utforer:
utfall = tuple(utforer.map(en, trekninger))
else:
utfall = tuple(en(inn) for inn in trekninger)
if not utfall:
msg = "the run needs at least one draw"
raise ValueError(msg)
return Kjoring(
stige=tuple(stige),
scenarioer=tuple(scenarioer),
losninger=tuple(losninger),
trekninger=utfall,
)
# ------------------------------------------------------------------ the verdicts
@dataclass(frozen=True)
class Maaldom:
"""The verdict for one target, with the figures it is set from and those next to it.
Attributes:
dom: the verdict.
andel_holder: the share of all the draws that meets the condition for «holder» (S37).
andel_holder_ikke: the share that meets the condition for «holder ikke», for M3, M4
and M6, where that is a condition of its own; None for M1, M2 and M7, where
«holder ikke» is that too few draws reach the target.
ikke_byggbar: the share of all the draws in which the path cannot be built
(clarification 69); in M7 the path of A.
oppfylt_blant_byggbare: the share that meets the condition for «holder» among the
draws in which it can be built; None when there is none.
"""
dom: Dom
andel_holder: float
andel_holder_ikke: float | None
ikke_byggbar: float
oppfylt_blant_byggbare: float | None
@dataclass(frozen=True)
class Losningsdommer:
"""The verdicts for one solution on one step in one scenario.
Attributes:
maal: the verdicts for M1, M2, M3, M4 and M6.
M5: the verdict for M5, the same on every step and in every scenario.
median_M1: the median net present value over all the draws, kr; minus infinity when
the path cannot be built in more than half of them.
"""
maal: Mapping[str, Maaldom]
M5: Dom
median_M1: float
@property
def dommer(self) -> dict[str, Dom]:
"""The verdicts for M1 to M6, as ``dommer.del_I`` takes them."""
return {**{m: d.dom for m, d in self.maal.items()}, "M5": self.M5}
@property
def felt(self) -> bool:
"""True when the solution cannot carry part I (clarification 59)."""
return (
any(self.dommer[m] is Dom.HOLDER_IKKE for m in dommer.MAAL_SOM_FELLER)
or self.median_M1 < 0
)
@dataclass(frozen=True)
class Scenariodommer:
"""The verdicts in one scenario.
Attributes:
per_trinn: the verdicts per step of the ladder and solution.
M7: M7 per step, among the five solutions of the verdicts that are in the run.
del_I: part I on the step the verdicts are read on, as far as it follows from the
targets: where it is «holder under betingelser», whether the conditions can be
named is still to be decided (clarifications 93 and 97).
del_II: part II on that step; None when no step can be built, or when A is not in
the run (clarification 102).
"""
per_trinn: Mapping[int, Mapping[Losning, Losningsdommer]]
M7: Mapping[int, Maaldom]
del_I: Dom
del_II: Dom | None
@dataclass(frozen=True)
class Dommer:
"""The verdicts of the run.
Attributes:
valg: the step the verdicts are read on, set once from M6 in «normalisering» on the
main path (clarification 97).
scenarioer: the verdicts by the name of the scenario.
teller: the name of the scenario whose verdict counts.
"""
valg: Trinnvalg
scenarioer: Mapping[str, Scenariodommer]
teller: str
@property
def del_I(self) -> Dom:
"""Part I in the scenario that counts."""
return self.scenarioer[self.teller].del_I
@property
def del_II(self) -> Dom | None:
"""Part II in the scenario that counts."""
return self.scenarioer[self.teller].del_II
def dommer_m5(
losninger: Sequence[Losning],
kilder: Sequence[Kildeverdier],
*,
kjernekraft: float,
vind_direkte: float,
vind_plan: float,
) -> dict[Losning, Dom]:
"""M5 per solution from the sources' figures and the three areas (clarification 88).
The areas are per energy, in the same unit: nuclear power, the direct
area of onshore wind and its whole planning area. Nothing comes from a
path or a draw.
"""
return {
a: miljo.m5(
miljo.m5_utslipp(a, kilder),
miljo.m5_areal(
a, kjernekraft=kjernekraft, vind_direkte=vind_direkte, vind_plan=vind_plan
),
)
for a in losninger
}
def _maaldom(
dom: Dom, oppfylt: Sequence[bool | None], andel_holder_ikke: float | None = None
) -> Maaldom:
ikke_byggbar, blant_byggbare = dommer.ved_siden_av_dommen(oppfylt)
return Maaldom(
dom=dom,
andel_holder=lg.s37_andel([x is True for x in oppfylt]),
andel_holder_ikke=andel_holder_ikke,
ikke_byggbar=ikke_byggbar,
oppfylt_blant_byggbare=blant_byggbare,
)
def _m6_for_dommen(utfall: Sequence[Utfall | None]) -> list[float | None]:
return [None if u is None else u.M6 for u in utfall]
def losningsdommer(utfall: Sequence[Utfall | None], M5: Dom) -> Losningsdommer:
"""The verdicts for one solution from its outcome in every draw (S37, clarification 100)."""
nnv = [None if u is None else u.NNV for u in utfall]
s42 = [None if u is None else u.S42 for u in utfall]
m3 = [None if u is None else u.M3 for u in utfall]
m4 = [None if u is None else u.M4 for u in utfall]
m6 = _m6_for_dommen(utfall)
maal = {
"M1": _maaldom(dommer.dom_m1(nnv), [None if x is None else x > 0 for x in nnv]),
"M2": _maaldom(dommer.dom_m2(s42), [None if x is None else x >= 0.0 for x in s42]),
"M3": _maaldom(
dommer.dom_m3(m3),
[None if x is None else x <= dommer.M3_HOYST for x in m3],
lg.s37_andel([x is not None and x > dommer.M3_OVER for x in m3]),
),
"M4": _maaldom(
dommer.dom_m4(m4),
[None if f is None else f.ikke_svakere_uten_tiltak for f in m4],
lg.s37_andel([f is not None and f.svakere_ogsaa_med_tiltak for f in m4]),
),
"M6": _maaldom(
dommer.dom_m6(m6),
[None if u is None else u.M6 is not None and u.M6 >= dommer.M6_MINST for u in utfall],
lg.s37_andel([x is None or x < dommer.M6_UNDER for x in m6]),
),
}
return Losningsdommer(maal=maal, M5=M5, median_M1=dommer.median(nnv))
def _m7(nnv: Mapping[Losning, Sequence[float | None]]) -> Maaldom:
best = dommer.a_er_best(nnv)
oppfylt = [None if a is None else b for a, b in zip(nnv[Losning.A], best, strict=True)]
return _maaldom(dommer.dom_m7(nnv), oppfylt)
def sett_dommer(kjoring: Kjoring, M5: Mapping[Losning, Dom]) -> Dommer:
"""The verdicts of the run: per target, the step they are read on, part I and part II.
``M5`` holds the verdict for M5 per solution (``dommer_m5``). The step is
set once, from M6 in «normalisering» on the main path for A, B, C, T-F and
T-K, and the verdicts of every scenario are read on it (clarification 97).
B' and R get a verdict per target but are in neither the ladder, part I
nor M7. Part I is given as far as it follows from the targets.
"""
hoved = kjoring.hovedscenario
fem = [a for a in DOMSLOSNINGER if a in kjoring.losninger]
valg = dommer.trinn_for_dommene(
{
trinn: {a: _m6_for_dommen(kjoring.utfall(hoved, a, trinn)) for a in fem}
for trinn in kjoring.stige
}
)
scenarioer: dict[str, Scenariodommer] = {}
for scenario in kjoring.scenarioer:
per_trinn: dict[int, dict[Losning, Losningsdommer]] = {}
m7: dict[int, Maaldom] = {}
for trinn in kjoring.stige:
utfall = {a: kjoring.utfall(scenario, a, trinn) for a in kjoring.losninger}
per_trinn[trinn] = {a: losningsdommer(utfall[a], M5[a]) for a in kjoring.losninger}
if Losning.A in fem:
m7[trinn] = _m7({a: [None if u is None else u.NNV for u in utfall[a]] for a in fem})
paa_trinnet = {} if valg.trinn is None else per_trinn[valg.trinn]
scenarioer[scenario.navn] = Scenariodommer(
per_trinn=per_trinn,
M7=m7,
del_I=dommer.del_I(
{a: paa_trinnet[a].dommer for a in fem if a in paa_trinnet},
{a: paa_trinnet[a].median_M1 for a in fem if a in paa_trinnet},
valg,
),
del_II=dommer.del_II(m7[valg.trinn].dom) if valg.trinn in m7 else None,
)
return Dommer(valg=valg, scenarioer=scenarioer, teller=hoved.navn)
# ------------------------------------------------- the timeline over the draws
def persentil(verdier: Sequence[float], p: float) -> float:
"""The percentile ``p`` (0 to 1) of the values, linear between neighbours (clarification 99).
With the values sorted ascending, x_1 .. x_N, it is x_j + (h - j)(x_{j+1} - x_j)
with h = 1 + (N - 1) p and j the whole part of h. At p = 0.5 it is the median.
"""
if not verdier:
msg = "a percentile needs at least one value"
raise ValueError(msg)
if not 0.0 <= p <= 1.0:
msg = f"a percentile is asked for as a share between 0 and 1, got {p}"
raise ValueError(msg)
x = sorted(verdier)
h = (len(x) - 1) * p
j = math.floor(h)
if j + 1 >= len(x):
return x[-1]
return x[j] + (h - j) * (x[j + 1] - x[j])
@dataclass(frozen=True)
class Tidslinjeaar:
"""S50 in one year over the draws, for one type of power or for the sum over the types.
Attributes:
aar: the calendar year.
median: the median MW IT in operation over all the draws.
persentiler: the 10th and the 90th percentile.
andel_minst: the share of the draws with at least 100 MW and at least 1 000 MW.
"""
aar: int
median: float
persentiler: tuple[float, ...]
andel_minst: tuple[float, ...]
def tidslinje_over_trekningene(
kjoring: Kjoring, losning: Losning, trinn: int
) -> dict[str, tuple[Tidslinjeaar, ...]]:
"""S50 over the draws for one solution on one step (chapter 17.2, clarification 99).
Returns the years T_0 + 1 .. T_s for each type of power (by its name) and
for their sum (``ALLE_TYPER``). Draws in which the path cannot be built are
included, with what was built.
"""
baner = kjoring.baner(losning, trinn)
forste_aar = {b.forste_aar for b in baner}
antall_aar = {len(mw) for b in baner for mw in b.tidslinje.values()}
if len(forste_aar) != 1 or len(antall_aar) > 1:
msg = "the draws do not cover the same years, so they have no common timeline"
raise ValueError(msg)
start = forste_aar.pop()
n = antall_aar.pop() if antall_aar else 0
ut: dict[str, tuple[Tidslinjeaar, ...]] = {}
for navn in (*(x.value for x in Kraft), ALLE_TYPER):
rader = []
for j in range(n):
if navn == ALLE_TYPER:
mw = [math.fsum(linje[j] for linje in b.tidslinje.values()) for b in baner]
else:
mw = [
b.tidslinje[Kraft(navn)][j] if Kraft(navn) in b.tidslinje else 0.0
for b in baner
]
rader.append(
Tidslinjeaar(
aar=start + j,
median=persentil(mw, 0.5),
persentiler=tuple(persentil(mw, p) for p in PERSENTILER),
andel_minst=tuple(
lg.s37_andel([x >= g * (1.0 - lg.AVRUNDINGSTOLERANSE) for x in mw])
for g in MW_GRENSER
),
)
)
ut[navn] = tuple(rader)
return ut
# ----------------------------------------------------------- the ownership forms
@dataclass(frozen=True)
class Eierformtabell:
"""The ownership forms compared for one solution on one step (clarification 98).
Attributes:
losning: the solution.
trinn: the step, in facilities.
antall_byggbare: the draws in which the path can be built; only they are in the
criteria (clarification 50).
kriterier: the first three criteria per ownership form, in the order of the set.
rangering: the rule of the pre-registration applied to them.
"""
losning: Losning
trinn: int
antall_byggbare: int
kriterier: tuple[Eierkriterier, ...]
rangering: Rangering
def regn_eierformer(
inn: Inndata, losning: Losning, trinn: int, scenario: Scenario
) -> dict[str, tuple[Eierresultat, float]] | None:
"""S30 and the cost of compute per ownership form for one path in one draw.
Returns None when the path cannot be built. The cash flow carries the
factor of the additionality rule (S30), and the cost of compute is
computed with the form's required return before tax (clarification 66).
"""
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=trinn)
if not plan.gjennomforbar:
return None
res = ks.regn_program(
inn, losning, plan, scenario.knapphet, dim=dim, bortfall=_bortfall(inn, scenario)
)
strom = eierskap.bedriftsstrom(inn, res, tilleggsregel=True)
return {
navn: (
eierskap.eierresultat(inn, strom, form),
eierskap.lcoc_med_kapitalkostnad(inn, res, eierskap.krav_for_skatt(inn, form)),
)
for navn, form in inn.eierformer.items()
}
def eierformer_paa_trinnet(
trekninger: Sequence[Inndata],
valg: Trinnvalg,
eos: Mapping[str, str],
*,
scenario: Scenario = SCENARIOER[1],
losninger: Sequence[Losning] = DOMSLOSNINGER,
prosesser: int = 1,
) -> dict[Losning, Eierformtabell | None]:
"""The ownership forms for each solution on the step the verdicts are read on.
``eos`` holds the EEA assessment per form, decided outside the model.
The criteria are taken over the draws in which the solution's path can be
built. A solution has no table when its path cannot be built in any draw,
or when there is no step (clarification 98).
"""
if not scenario.teller:
msg = "the ownership forms are compared in «normalisering» on the main path"
raise ValueError(msg)
tabeller: dict[Losning, Eierformtabell | None] = {}
for losning in losninger:
if valg.trinn is None:
tabeller[losning] = None
continue
en = partial(regn_eierformer, losning=losning, trinn=valg.trinn, scenario=scenario)
if prosesser > 1:
with ProcessPoolExecutor(max_workers=prosesser) as utforer:
alle = list(utforer.map(en, trekninger))
else:
alle = [en(inn) for inn in trekninger]
byggbare = [u for u in alle if u is not None]
if not byggbare:
tabeller[losning] = None
continue
kriterier = tuple(
eierskap.eierkriterier(
navn, [u[navn][0] for u in byggbare], [u[navn][1] for u in byggbare]
)
for navn in byggbare[0]
)
tabeller[losning] = Eierformtabell(
losning=losning,
trinn=valg.trinn,
antall_byggbare=len(byggbare),
kriterier=kriterier,
rangering=eierskap.ranger_eierformer(kriterier, eos),
)
return tabeller

526
tests/test_kjoring.py Normal file
View file

@ -0,0 +1,526 @@
"""The run over the draws (chapter 11; clarifications 95 to 102).
Made-up draws only: variants of the made-up set of ``conftest.py``, and invented outcomes per
draw for the verdicts and the timeline. Nothing here says anything about the hypothesis.
The slow nuclear path used below is solution A with reactor deliveries of 100 MW a year: one
facility needs 1 500 MW of reactors, so the facilities start in 2042 and 2057, and a third
does not start within the final year 2060.
"""
from __future__ import annotations
import math
import statistics
from typing import TYPE_CHECKING
import pytest
from tokenfabrikker import dommer, eierskap, nivaaisert, skala
from tokenfabrikker import kjoring as kj
from tokenfabrikker import kontantstrom as ks
from tokenfabrikker.dommer import Dom, Forsyning, Grunnlag
from tokenfabrikker.kjoring import Bane, Kjoring, Scenario, Utfall
from tokenfabrikker.kontantstrom import Knapphet
from tokenfabrikker.miljo import Kildeverdier
from tokenfabrikker.utbygging import Kraft, Losning
if TYPE_CHECKING:
from conftest import LagInndata
from tokenfabrikker.inndata import Inndata
NORM = Scenario("normalisering", Knapphet.NORMALISERING)
VARER = Scenario("knapphet varer", Knapphet.VARER)
LAVT = Scenario("lavt", Knapphet.NORMALISERING, "lavt")
SCENARIOER = (VARER, NORM, LAVT)
"""Two price scenarios and one marked scenario of the made-up set."""
EOS = {
"direkte": "består",
"heleid_selskap": "består",
"majoritet_boers": "usikker",
"petroleumsmodell": "består",
}
def _trekninger(oppdiktet: LagInndata) -> list[Inndata]:
"""Four made-up draws: the set itself and three variants."""
return [
oppdiktet(),
oppdiktet(p_v=3000.0),
oppdiktet(n_reaktor=100.0),
oppdiktet(c_H0=150e6, g_fornybar=3e6),
]
# ------------------------------------------------------------------ one draw
def test_utfallene_er_de_samme_som_modulene_gir_hver_for_seg(oppdiktet: LagInndata) -> None:
inn = oppdiktet(p_v=3000.0)
bane = kj.regn_bane(inn, Losning.C, 2, SCENARIOER)
dim = ks.dimensjoner(inn, Losning.C)
plan = ks.lag_plan(inn, Losning.C, dim, N_anlegg=2)
res = ks.regn_program(
inn, Losning.C, plan, Knapphet.NORMALISERING, bortfall=ks.bortfall_i_scenario(inn, "lavt")
)
m6 = skala.skala(inn, res)
u = bane.utfall["lavt"]
assert bane.byggbar
assert u.NNV == res.NNV
assert u.S42 == nivaaisert.kraftkostnad(inn, res, bedrift=True).S42
assert u.M3 == dommer.m3_verste_prisvirkning(inn, res)
assert u.M4 == dommer.m4_forsyning(inn, res)
assert (u.M6, u.M6_snitt, u.M6_median, u.M6_2050, u.M6_topp) == (
m6.M6,
m6.M6_snitt,
m6.M6_median,
m6.M6_2050,
m6.M6_topp,
)
assert (u.stabilt_aar, u.toppaar) == (m6.stabilt_aar, m6.toppaar)
def test_scenarioene_deler_utbyggingen_og_skiller_seg_i_inntekten(oppdiktet: LagInndata) -> None:
bane = kj.regn_bane(oppdiktet(), Losning.C, 2, SCENARIOER)
varer, norm, lavt = (bane.utfall[s.navn] for s in SCENARIOER)
assert varer.NNV > norm.NNV > lavt.NNV
assert varer.M3 == norm.M3 == lavt.M3
assert varer.M4 == norm.M4 == lavt.M4
assert varer.stabilt_aar == norm.stabilt_aar == lavt.stabilt_aar == 2032
assert bane.forste_aar == 2028
# facilities of 1 000 MW start in 2030 and 2032 and are operated for twenty years each:
# both from 2032 to 2049, the second alone in 2050 and 2051, none from 2052 to 2060
assert bane.tidslinje == {
Kraft.NY_FORNYBAR: (0.0,) * 2 + (1000.0,) * 2 + (2000.0,) * 18 + (1000.0,) * 2 + (0.0,) * 9
}
def test_en_bane_som_ikke_lar_seg_bygge_har_ingen_utfall_men_en_tidslinje(
oppdiktet: LagInndata,
) -> None:
inn = oppdiktet(n_reaktor=100.0)
to, tre = (kj.regn_bane(inn, Losning.A, n, SCENARIOER) for n in (2, 3))
assert to.byggbar
assert set(to.utfall) == {s.navn for s in SCENARIOER}
assert not tre.byggbar
assert tre.utfall == {}
# what was built is reported: 1 000 MW from 2042 and 2 000 MW from 2057
linje = tre.tidslinje[Kraft.EGET_KJERNEKRAFTVERK]
assert linje == (0.0,) * 14 + (1000.0,) * 15 + (2000.0,) * 4
assert linje == to.tidslinje[Kraft.EGET_KJERNEKRAFTVERK]
def test_en_bane_uten_aar_med_stabil_drift_har_alt_unntatt_M6(oppdiktet: LagInndata) -> None:
# with ten years of operation the first facility (2042 to 2051) is out before the second starts
bane = kj.regn_bane(oppdiktet(n_reaktor=100.0, L_N=10.0), Losning.A, 2, (NORM,))
u = bane.utfall[NORM.navn]
assert bane.byggbar
assert (u.M6, u.M6_snitt, u.M6_median, u.stabilt_aar) == (None, None, None, None)
assert math.isfinite(u.NNV)
assert math.isfinite(u.S42)
assert math.isfinite(u.M6_topp)
def test_et_tallsett_utbyggingen_avviser_stanser_kjoringen(oppdiktet: LagInndata) -> None:
# one facility of 1 000 MW is not a whole number of modules of 300 MW (clarification 90)
inn = oppdiktet().med({"P_m": 300.0})
with pytest.raises(ValueError, match="whole number of modules"):
kj.kjor([inn], stige=(1,), scenarioer=(NORM,), losninger=(Losning.T_F,))
# ------------------------------------------------------------- over the draws
def test_kjoringen_holder_trekningenes_rekkefolge(oppdiktet: LagInndata) -> None:
trekninger = _trekninger(oppdiktet)
kjoring = kj.kjor(trekninger, stige=(1, 2), scenarioer=SCENARIOER, losninger=(Losning.A,))
assert kjoring.antall == 4
for inn, utfall in zip(trekninger, kjoring.trekninger, strict=True):
assert utfall == kj.regn_trekning(
inn, stige=(1, 2), scenarioer=SCENARIOER, losninger=(Losning.A,)
)
assert [u is not None for u in kjoring.utfall(NORM, Losning.A, 2)] == [True] * 4
assert [b.byggbar for b in kjoring.baner(Losning.A, 2)] == [True] * 4
def test_kjoringen_er_lik_paa_flere_prosesser_og_i_annen_rekkefolge(oppdiktet: LagInndata) -> None:
trekninger = _trekninger(oppdiktet)
losninger = (Losning.A, Losning.C, Losning.T_K)
en = kj.kjor(trekninger, stige=(1, 3), scenarioer=SCENARIOER, losninger=losninger)
to = kj.kjor(trekninger, stige=(1, 3), scenarioer=SCENARIOER, losninger=losninger, prosesser=2)
snudd = kj.kjor(
trekninger, stige=(3, 1), scenarioer=SCENARIOER[::-1], losninger=losninger[::-1]
)
assert en == to
assert en.trekninger == snudd.trekninger
M5 = dict.fromkeys(losninger, Dom.HOLDER)
assert kj.sett_dommer(en, M5) == kj.sett_dommer(to, M5)
a, b = kj.sett_dommer(en, M5), kj.sett_dommer(snudd, M5)
assert a.valg == b.valg
assert a.scenarioer == b.scenarioer
@pytest.mark.parametrize(
("stige", "scenarioer", "losninger"),
[
((1, 1), (NORM,), (Losning.A,)),
((1,), (NORM, NORM), (Losning.A,)),
((1,), (NORM,), (Losning.A, Losning.A)),
((), (NORM,), (Losning.A,)),
],
)
def test_trinn_scenarioer_og_losninger_staar_en_gang_hver(
oppdiktet: LagInndata,
stige: tuple[int, ...],
scenarioer: tuple[Scenario, ...],
losninger: tuple[Losning, ...],
) -> None:
with pytest.raises(ValueError, match="each of them once"):
kj.kjor([oppdiktet()], stige=stige, scenarioer=scenarioer, losninger=losninger)
def test_kjoringen_trenger_en_trekning() -> None:
with pytest.raises(ValueError, match="at least one draw"):
kj.kjor([], stige=(1,), scenarioer=(NORM,), losninger=(Losning.A,))
# ---------------------------------------- the verdicts, on invented outcomes per draw
def _u(
NNV: float = 1.0,
*,
S42: float = 1.0,
M3: float = 0.0,
M4: bool = True,
M6: float | None = 0.3,
) -> Utfall:
return Utfall(
NNV=NNV,
S42=S42,
M3=M3,
M4=Forsyning(ikke_svakere_uten_tiltak=M4, svakere_ogsaa_med_tiltak=not M4),
M6=M6,
M6_snitt=M6,
M6_median=M6,
M6_2050=None,
M6_topp=0.0 if M6 is None else M6,
stabilt_aar=None if M6 is None else 2040,
toppaar=2040,
)
def _bane(utfall: dict[str, Utfall] | None, mw: tuple[float, ...] = ()) -> Bane:
linje = {Kraft.NY_FORNYBAR: mw} if any(mw) else {}
return Bane(byggbar=utfall is not None, forste_aar=2028, tidslinje=linje, utfall=utfall or {})
def _kjoring(
per_trekning: list[dict[tuple[Losning, int], dict[str, Utfall] | None]],
scenarioer: tuple[Scenario, ...] = (NORM, VARER),
) -> Kjoring:
"""A run put together from invented outcomes: ``per_trekning[omega][losning, trinn]``."""
nokler = list(per_trekning[0])
return Kjoring(
stige=tuple(dict.fromkeys(n for _, n in nokler)),
scenarioer=scenarioer,
losninger=tuple(dict.fromkeys(a for a, _ in nokler)),
trekninger=tuple({k: _bane(v) for k, v in t.items()} for t in per_trekning),
)
def _alle(u: Utfall) -> dict[str, Utfall]:
return {NORM.navn: u, VARER.navn: u}
def test_dommene_per_maal_teller_trekninger_som_ikke_lar_seg_bygge_i_nevneren() -> None:
# ten draws: three cannot be built, one can but has no year of stable operation
utfall: list[Utfall | None] = [
None,
None,
None,
_u(-1.0, S42=-1.0, M3=0.2, M4=False, M6=None),
*[_u(2.0, M3=0.05, M6=0.25)] * 6,
]
d = kj.losningsdommer(utfall, Dom.BETINGELSER)
assert {m: x.dom for m, x in d.maal.items()} == dict.fromkeys(
("M1", "M2", "M3", "M4", "M6"), Dom.BETINGELSER
)
for maal in d.maal.values():
assert maal.andel_holder == 0.6
assert maal.ikke_byggbar == 0.3
assert maal.oppfylt_blant_byggbare == pytest.approx(6 / 7)
assert d.maal["M1"].andel_holder_ikke is None
assert d.maal["M2"].andel_holder_ikke is None
assert d.maal["M3"].andel_holder_ikke == 0.1
assert d.maal["M4"].andel_holder_ikke == 0.1
# in M6 a draw without a value does not reach 5 %: three that cannot be built and one without
assert d.maal["M6"].andel_holder_ikke == 0.4
assert d.median_M1 == 2.0
assert d.dommer["M5"] is Dom.BETINGELSER
assert not d.felt
def test_en_losning_er_felt_av_negativ_median_eller_et_maal_som_ikke_holder() -> None:
negativ = kj.losningsdommer([_u(-1.0)] * 3 + [_u(1.0)] * 2, Dom.HOLDER)
assert negativ.maal["M1"].dom is Dom.BETINGELSER
assert negativ.median_M1 == -1.0
assert negativ.felt
assert kj.losningsdommer([_u()] * 5, Dom.HOLDER_IKKE).felt
assert not kj.losningsdommer([_u()] * 5, Dom.HOLDER).felt
# more than half cannot be built: the median ranks below every value
assert kj.losningsdommer([None, None, _u()], Dom.HOLDER).median_M1 == -math.inf
def test_trinnet_settes_i_normalisering_og_gjelder_alle_scenarioene() -> None:
# C reaches 25 % on step 5 in «normalisering»; in «knapphet varer» it would on step 1
def trekning() -> dict[tuple[Losning, int], dict[str, Utfall] | None]:
return {
(Losning.A, 1): _alle(_u(-1.0, M6=0.01)),
(Losning.A, 5): _alle(_u(-1.0, M6=0.02)),
(Losning.C, 1): {NORM.navn: _u(M6=0.1), VARER.navn: _u(M6=0.4)},
(Losning.C, 5): {NORM.navn: _u(M6=0.3), VARER.navn: _u(M6=0.9)},
# R is not part of the ladder, even where it reaches 25 % on step 1
(Losning.R, 1): _alle(_u(M6=0.5)),
(Losning.R, 5): _alle(_u(M6=0.6)),
}
M5 = dict.fromkeys((Losning.A, Losning.C, Losning.R), Dom.HOLDER)
d = kj.sett_dommer(_kjoring([trekning() for _ in range(5)]), M5)
assert (d.valg.trinn, d.valg.grunnlag) == (5, Grunnlag.TRINN_25)
assert d.teller == NORM.navn
assert (d.del_I, d.del_II) == (Dom.HOLDER, Dom.HOLDER_IKKE)
varer = d.scenarioer[VARER.navn]
assert (varer.del_I, varer.del_II) == (Dom.HOLDER, Dom.HOLDER_IKKE)
assert varer.per_trinn[1][Losning.C].maal["M6"].dom is Dom.HOLDER
assert d.scenarioer[NORM.navn].per_trinn[1][Losning.C].maal["M6"].dom is Dom.BETINGELSER
assert set(varer.per_trinn[5]) == {Losning.A, Losning.C, Losning.R}
assert varer.per_trinn[5][Losning.R].maal["M6"].dom is Dom.HOLDER
assert set(varer.M7) == {1, 5}
assert varer.M7[5].andel_holder == 0.0
def test_del_I_leses_paa_trinnet_fra_normalisering_ogsaa_naar_scenarioet_er_svakere() -> None:
# on the main path A holds on step 2; in the marked scenario its net present value is negative
def trekning() -> dict[tuple[Losning, int], dict[str, Utfall] | None]:
return {
(Losning.A, 1): {NORM.navn: _u(M6=0.2), LAVT.navn: _u(-1.0, M6=0.0)},
(Losning.A, 2): {NORM.navn: _u(M6=0.3), LAVT.navn: _u(-1.0, M6=0.0)},
}
kjoring = _kjoring([trekning() for _ in range(4)], scenarioer=(LAVT, NORM))
d = kj.sett_dommer(kjoring, {Losning.A: Dom.HOLDER})
assert (d.valg.trinn, d.valg.grunnlag) == (2, Grunnlag.TRINN_25)
assert (d.del_I, d.del_II) == (Dom.HOLDER, Dom.HOLDER)
lavt = d.scenarioer[LAVT.navn]
assert lavt.per_trinn[2][Losning.A].felt
# part II follows M7: A is alone in the run and is best wherever it can be built
assert (lavt.del_I, lavt.del_II) == (Dom.HOLDER_IKKE, Dom.HOLDER)
def test_M7_teller_A_mot_de_som_lar_seg_bygge_og_viser_tallene_for_A() -> None:
# A is best in draws 0, 2 (C cannot be built there) and 4; equal in 1; not built in 3
per_trekning: list[dict[tuple[Losning, int], dict[str, Utfall] | None]] = [
{(Losning.A, 1): _alle(_u(5.0)), (Losning.C, 1): _alle(_u(1.0))},
{(Losning.A, 1): _alle(_u(1.0)), (Losning.C, 1): _alle(_u(1.0))},
{(Losning.A, 1): _alle(_u(-3.0)), (Losning.C, 1): None},
{(Losning.A, 1): None, (Losning.C, 1): _alle(_u(1.0))},
{(Losning.A, 1): _alle(_u(5.0)), (Losning.C, 1): _alle(_u(1.0))},
]
M5 = {Losning.A: Dom.HOLDER, Losning.C: Dom.HOLDER}
d = kj.sett_dommer(_kjoring(per_trekning), M5)
m7 = d.scenarioer[NORM.navn].M7[1]
assert m7.andel_holder == 0.6
assert m7.dom is Dom.HOLDER
assert m7.andel_holder_ikke is None
assert m7.ikke_byggbar == 0.2
assert m7.oppfylt_blant_byggbare == 0.75
# step 1 holds 25 % but a single facility cannot give «holder» for part I
assert (d.valg.trinn, d.del_I, d.del_II) == (1, Dom.BETINGELSER, Dom.HOLDER)
def test_uten_noe_trinn_holder_ikke_del_I_og_del_II_har_ingen_dom() -> None:
# the path is built in half the draws on both steps: no step can be built in 80 %
per_trekning: list[dict[tuple[Losning, int], dict[str, Utfall] | None]] = [
{(Losning.A, 1): _alle(_u()), (Losning.A, 2): _alle(_u())},
{(Losning.A, 1): None, (Losning.A, 2): None},
]
d = kj.sett_dommer(_kjoring(per_trekning), {Losning.A: Dom.HOLDER})
assert (d.valg.trinn, d.valg.grunnlag) == (None, Grunnlag.INGEN)
assert d.del_I is Dom.HOLDER_IKKE
assert d.del_II is None
# M7 is still shown on every step
assert d.scenarioer[NORM.navn].M7[2].andel_holder == 0.5
def test_dommene_trenger_normalisering_paa_hovedforlopet_en_gang() -> None:
kjoring = _kjoring([{(Losning.A, 1): {VARER.navn: _u()}}], scenarioer=(VARER,))
with pytest.raises(ValueError, match="exactly once"):
kj.sett_dommer(kjoring, {Losning.A: Dom.HOLDER})
def test_M5_per_losning_fra_kildenes_tall_og_arealene() -> None:
# invented figures: nuclear power above the lower of wind and hydro in one source
kilder = (Kildeverdier("X", 12.0, 11.0, 24.0, 56.0), Kildeverdier("Y", 5.0, 12.0, 11.0, 16.0))
M5 = kj.dommer_m5(tuple(Losning), kilder, kjernekraft=1.0, vind_direkte=2.0, vind_plan=30.0)
assert M5 == {
Losning.A: Dom.BETINGELSER,
Losning.B: Dom.BETINGELSER,
Losning.B_MERKET: Dom.BETINGELSER,
Losning.C: Dom.HOLDER,
Losning.R: Dom.HOLDER,
Losning.T_F: Dom.HOLDER,
Losning.T_K: Dom.BETINGELSER,
}
bredt = kj.dommer_m5((Losning.A,), kilder, kjernekraft=3.0, vind_direkte=2.0, vind_plan=30.0)
assert bredt == {Losning.A: Dom.HOLDER_IKKE}
def test_dommene_paa_oppdiktede_trekninger_henger_sammen_med_utfallene(
oppdiktet: LagInndata,
) -> None:
trekninger = _trekninger(oppdiktet)
losninger = (Losning.A, Losning.C, Losning.R)
kjoring = kj.kjor(trekninger, stige=(1, 2), scenarioer=SCENARIOER, losninger=losninger)
d = kj.sett_dommer(kjoring, dict.fromkeys(losninger, Dom.HOLDER))
for scenario in SCENARIOER:
for trinn in (1, 2):
for a in losninger:
utfall = kjoring.utfall(scenario, a, trinn)
nnv = [None if u is None else u.NNV for u in utfall]
maal = d.scenarioer[scenario.navn].per_trinn[trinn][a].maal
assert maal["M1"].dom is dommer.dom_m1(nnv)
assert maal["M1"].andel_holder == dommer.andel_positiv(nnv)
assert maal["M1"].ikke_byggbar == 0.0
# nothing in the made-up set reaches 5 % of the petroleum cash flow
assert d.valg.grunnlag is Grunnlag.HOYESTE
assert d.valg.trinn == 2
# ------------------------------------------------- the timeline over the draws
def test_persentilen_er_lineaer_mellom_naboverdiene() -> None:
x = [4.0, 1.0, 3.0, 2.0]
# h = 1 + 3 p: 1.3 gives 1 + 0.3 (2 - 1); 3.7 gives 3 + 0.7 (4 - 3)
assert kj.persentil(x, 0.1) == pytest.approx(1.3)
assert kj.persentil(x, 0.9) == pytest.approx(3.7)
assert kj.persentil(x, 0.5) == statistics.median(x) == 2.5
assert (kj.persentil(x, 0.0), kj.persentil(x, 1.0)) == (1.0, 4.0)
# a whole h is the value itself: five values, p = 0.25 gives the second
assert kj.persentil([10.0, 20.0, 30.0, 40.0, 50.0], 0.25) == 20.0
assert kj.persentil([7.0], 0.1) == kj.persentil([7.0], 0.9) == 7.0
with pytest.raises(ValueError, match="at least one value"):
kj.persentil([], 0.5)
with pytest.raises(ValueError, match="between 0 and 1"):
kj.persentil([1.0], 10.0)
def test_tidslinjen_over_trekningene_har_med_baner_som_ikke_lar_seg_bygge() -> None:
# five draws, two years; the second and the last path cannot be built
mw = [(0.0, 1000.0), (0.0, 500.0), (100.0, 1000.0), (50.0, 2000.0), (0.0, 0.0)]
byggbar = [True, False, True, True, False]
kjoring = Kjoring(
stige=(1,),
scenarioer=(NORM,),
losninger=(Losning.T_F,),
trekninger=tuple(
{(Losning.T_F, 1): _bane({NORM.navn: _u()} if ok else None, linje)}
for linje, ok in zip(mw, byggbar, strict=True)
),
)
linje = kj.tidslinje_over_trekningene(kjoring, Losning.T_F, 1)
assert set(linje) == {x.value for x in Kraft} | {kj.ALLE_TYPER}
assert linje[kj.ALLE_TYPER] == linje[Kraft.NY_FORNYBAR.value]
forste, andre = linje[kj.ALLE_TYPER]
# 2028: 0, 0, 0, 50, 100: h = 1.4 gives 0, h = 4.6 gives 50 + 0.6 * 50
assert (forste.aar, forste.median) == (2028, 0.0)
assert forste.persentiler == pytest.approx((0.0, 80.0))
assert forste.andel_minst == (0.2, 0.0)
# 2029: 0, 500, 1000, 1000, 2000: h = 1.4 gives 200, h = 4.6 gives 1000 + 0.6 * 1000
assert (andre.aar, andre.median) == (2029, 1000.0)
assert andre.persentiler == pytest.approx((200.0, 1600.0))
assert andre.andel_minst == (0.8, 0.6)
ingen = linje[Kraft.KJERNEKRAFT_PAA_NETTET.value]
assert [(x.median, x.persentiler, x.andel_minst) for x in ingen] == [
(0.0, (0.0, 0.0), (0.0, 0.0))
] * 2
def test_tidslinjen_summerer_typene_av_kraft_i_T_K(oppdiktet: LagInndata) -> None:
trekninger = [oppdiktet(), oppdiktet(g_fornybar=3e6)]
kjoring = kj.kjor(trekninger, stige=(5,), scenarioer=(NORM,), losninger=(Losning.T_K,))
linje = kj.tidslinje_over_trekningene(kjoring, Losning.T_K, 5)
assert [x.aar for x in linje[kj.ALLE_TYPER]] == list(range(2028, 2061))
baner = kjoring.baner(Losning.T_K, 5)
assert all(set(b.tidslinje) == {Kraft.KJERNEKRAFT_PAA_NETTET, Kraft.NY_FORNYBAR} for b in baner)
for j, rad in enumerate(linje[kj.ALLE_TYPER]):
summer = [sum(mw[j] for mw in b.tidslinje.values()) for b in baner]
assert rad.median == statistics.median(summer)
assert rad.andel_minst[1] == sum(s >= 1000.0 for s in summer) / 2
# in the made-up set itself all fifty modules are in operation in 2036: 5 000 MW IT
assert sum(mw[2036 - 2028] for mw in baner[0].tidslinje.values()) == 5000.0
# ----------------------------------------------------------- the ownership forms
def test_eierformene_regnes_paa_trinnet_over_trekningene_som_lar_seg_bygge(
oppdiktet: LagInndata,
) -> None:
trekninger = [oppdiktet(), oppdiktet(p_v=3000.0), oppdiktet(n_reaktor=40.0)]
valg = dommer.Trinnvalg(trinn=2, grunnlag=Grunnlag.HOYESTE)
tabeller = kj.eierformer_paa_trinnet(
trekninger, valg, EOS, scenario=NORM, losninger=(Losning.A, Losning.C)
)
a, c = tabeller[Losning.A], tabeller[Losning.C]
assert a is not None
assert c is not None
# with 40 MW of reactors a year the second facility of A does not start by 2060
assert (a.antall_byggbare, c.antall_byggbare) == (2, 3)
assert (a.trinn, a.losning) == (2, Losning.A)
assert [k.navn for k in a.kriterier] == list(EOS)
# the same figures as the functions of chapter 8 give one by one
utfall, lcoc = [], []
for inn in trekninger[:2]:
dim = ks.dimensjoner(inn, Losning.A)
plan = ks.lag_plan(inn, Losning.A, dim, N_anlegg=2)
res = ks.regn_program(inn, Losning.A, plan, Knapphet.NORMALISERING, dim=dim)
form = inn.eierformer["majoritet_boers"]
strom = eierskap.bedriftsstrom(inn, res, tilleggsregel=True)
utfall.append(eierskap.eierresultat(inn, strom, form))
lcoc.append(eierskap.lcoc_med_kapitalkostnad(inn, res, eierskap.krav_for_skatt(inn, form)))
assert a.kriterier[2] == eierskap.eierkriterier("majoritet_boers", utfall, lcoc)
assert a.rangering == eierskap.ranger_eierformer(a.kriterier, EOS)
flere = kj.eierformer_paa_trinnet(
trekninger, valg, EOS, scenario=NORM, losninger=(Losning.A,), prosesser=2
)
assert flere[Losning.A] == a
def test_eierformene_har_ingen_tabell_uten_trinn_eller_uten_baner(oppdiktet: LagInndata) -> None:
trekninger = [oppdiktet(n_reaktor=40.0)]
uten = dommer.Trinnvalg(trinn=None, grunnlag=Grunnlag.INGEN)
assert kj.eierformer_paa_trinnet(trekninger, uten, EOS, scenario=NORM) == dict.fromkeys(
dommer.DOMSLOSNINGER
)
valg = dommer.Trinnvalg(trinn=2, grunnlag=Grunnlag.HOYESTE)
ingen = kj.eierformer_paa_trinnet(trekninger, valg, EOS, scenario=NORM, losninger=(Losning.A,))
assert ingen == {Losning.A: None}
with pytest.raises(ValueError, match="main path"):
kj.eierformer_paa_trinnet(trekninger, valg, EOS, scenario=VARER)
def test_de_seks_scenarioene_og_stigen_er_de_forhaandsregistrerte() -> None:
assert kj.STIGE == (1, 5, 10, 20, 40)
assert [(s.knapphet, s.bortfall is None) for s in kj.SCENARIOER] == [
(Knapphet.VARER, True),
(Knapphet.NORMALISERING, True),
(Knapphet.OVERKAPASITET, True),
(Knapphet.NORMALISERING, False),
(Knapphet.NORMALISERING, False),
(Knapphet.NORMALISERING, False),
]
assert [s.teller for s in kj.SCENARIOER] == [False, True, False, False, False, False]
assert len({s.navn for s in kj.SCENARIOER}) == 6