tokenfabrikker/src/tokenfabrikker/dommer.py
Kjell Tore Guttormsen 6a51c4f4d2
feat(grunnlag): the approved EEA assessment as a fixed table, and M7 rejects a net present value that is not a number (clarifications 136 and 139)
fra_frys takes the assessment of clarification 136 («usikker» for all
four ownership forms) and has no guard any more; it is still not called
before part 6. beste_per_trekning raises on NaN, where the best would
depend on the order of the solutions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 06:43:45 +01:00

414 lines
17 KiB
Python

"""The verdicts (chapter 11 of the specification and the pre-registration).
A verdict is read from the share of the draws in which a condition is met
(S37). This module holds the condition per draw for each target, the verdict
from the shares (the table in chapter 11), the step of the ladder the verdicts
are read on (pre-registration, clarification 1), part I, and which of the five
solutions are best in a draw (M7, the comparison on equal terms; no verdict).
A draw in which the path cannot be built has no values; it is passed in as
None. It counts in the denominator and never meets the condition for «holder».
In M1, M2 and M6, where «holder ikke» is that too few draws reach the target,
it counts as a draw that does not reach it. In M3 and M4, where «holder ikke»
is a harm that occurs, it meets neither condition. In M7 a solution that
cannot be built is not best in that draw. That reading, and which step counts
as one that can be built, stand in chapter 16 of the specification
(clarifications 56, 57, 135 and 137); they touch clarification 1 of the
pre-registration and are the project owner's to approve.
The thresholds are those of the pre-registration. Nothing here is computed
from the parameter file: the functions take outcomes per draw.
"""
from __future__ import annotations
import enum
import math
import statistics
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final
from tokenfabrikker import kraftsystem
from tokenfabrikker import ligninger as lg
from tokenfabrikker.utbygging import Losning
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from tokenfabrikker.inndata import Inndata
from tokenfabrikker.kontantstrom import Programresultat
Utfall = Sequence[float | None]
ANDEL_HOLDER: Final = 0.8
"""«Holder» needs the condition met in at least this share of the draws."""
ANDEL_HOLDER_IKKE: Final = 0.2
"""M1 and M2: «holder ikke» when the target is reached in less than this share."""
M3_HOYST: Final = 0.05
M3_OVER: Final = 0.15
"""M3: at most 5 % increase holds; more than 15 % in one price area does not."""
M6_MINST: Final = 0.25
M6_UNDER: Final = 0.05
"""M6: at least 25 % of the petroleum cash flow holds; under 5 % does not."""
DOMSLOSNINGER: Final = (Losning.A, Losning.B, Losning.C, Losning.T_F, Losning.T_K)
"""The solutions the ladder, part I and the comparison in M7 are about (clarifications 13, 135).
Pre-registration, clarifications 3 and 13; chapter 16, clarification 135: the
comparison is reported in this order, then «ingen».
"""
MAAL_DEL_I: Final = ("M1", "M2", "M3", "M4", "M5", "M6")
MAAL_SOM_FELLER: Final = ("M1", "M2", "M3", "M4", "M5")
class Dom(enum.StrEnum):
"""The three verdicts of the pre-registration."""
HOLDER = "holder"
BETINGELSER = "holder under betingelser"
HOLDER_IKKE = "holder ikke"
class Grunnlag(enum.StrEnum):
"""Which step of the ladder the verdicts are read on (clarification 1)."""
TRINN_25 = "25 %-trinnet"
TRINN_5 = "5 %-trinnet"
HOYESTE = "høyeste trinn (skalaen nås ikke)"
INGEN = "ingen trinn lar seg bygge"
# -------------------------------------------------------------- the shares of S37
def andel(utfall: Utfall, vilkaar: float, *, minst: bool) -> float:
"""S37 for a threshold: the share of all draws with a value at least / below ``vilkaar``.
``minst=True`` counts values >= the threshold; a draw without a value does
not count. ``minst=False`` counts values strictly below it.
"""
if minst:
return lg.s37_andel([x is not None and x >= vilkaar for x in utfall])
return lg.s37_andel([x is not None and x < vilkaar for x in utfall])
def andel_positiv(utfall: Utfall) -> float:
"""The share of all draws with a strictly positive value."""
return lg.s37_andel([x is not None and x > 0 for x in utfall])
def median(utfall: Utfall) -> float:
"""The median over all draws, with a draw without a value ranked below every value."""
return statistics.median(-math.inf if x is None else x for x in utfall)
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.
It is computed in floating point as the formula stands (clarification 103): exact
rational arithmetic, or numpy's percentile, can differ in the last digit.
"""
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])
def ved_siden_av_dommen(oppfylt: Sequence[bool | None]) -> tuple[float, float | None]:
"""Clarification 69: how much of a verdict comes from paths that cannot be built.
``oppfylt`` says per draw whether the condition for «holder» is met, with
None for a draw in which the path cannot be built. Returns the share of
all the draws that cannot be built, and the share that meets the condition
among those that can; the second is None when no draw can be built. The
figures change no verdict (clarification 56).
"""
byggbare = [x for x in oppfylt if x is not None]
ikke_byggbar = lg.s37_andel([x is None for x in oppfylt])
return ikke_byggbar, lg.s37_andel(byggbare) if byggbare else None
def dom_av_andeler(andel_holder: float, andel_holder_ikke: float) -> Dom:
"""M3, M4 and M6: the verdict from the shares of the two conditions (clarification 2)."""
if andel_holder >= ANDEL_HOLDER:
return Dom.HOLDER
if andel_holder_ikke >= ANDEL_HOLDER:
return Dom.HOLDER_IKKE
return Dom.BETINGELSER
def dom_av_andel_som_naar(andel_naar: float) -> Dom:
"""M1 and M2: the verdict from the share of the draws that reach the target."""
if andel_naar >= ANDEL_HOLDER:
return Dom.HOLDER
if andel_naar < ANDEL_HOLDER_IKKE:
return Dom.HOLDER_IKKE
return Dom.BETINGELSER
# ----------------------------------------------------------------- the targets
def dom_m1(nnv: Utfall) -> Dom:
"""M1: net present value positive in at least 80 % of the draws and a positive median."""
dom = dom_av_andel_som_naar(andel_positiv(nnv))
if dom is Dom.HOLDER and not median(nnv) > 0:
return Dom.BETINGELSER
return dom
def dom_m2(s42: Utfall) -> Dom:
"""M2: S42 not negative in at least 80 % of the draws; «holder ikke» under 20 %."""
return dom_av_andel_som_naar(andel(s42, 0.0, minst=True))
def m3_verste_prisvirkning(inn: Inndata, res: Programresultat) -> float:
"""M3 in one draw: the largest Delta p_z / p_z^0 over price areas, weather and operating years.
A negative number is a price fall. Years in which no facility of the path
is operated do not count.
"""
verst = -math.inf
sett: dict[tuple[float, bool], float] = {}
for j, t in enumerate(res.aar):
if res.plan.antall_i_drift(t) == 0:
continue
rad = res.kraftaar[j]
for Delta_Q, tort in ((rad.Delta_Q, False), (rad.Delta_Q_tort, True)):
if (Delta_Q, tort) not in sett:
andeler = kraftsystem.relativ_prisvirkning(inn, Delta_Q=Delta_Q, tort=tort)
sett[Delta_Q, tort] = max(andeler.values())
verst = max(verst, sett[Delta_Q, tort])
return verst
def dom_m3(verste: Utfall) -> Dom:
"""M3: at most 5 % in every area in 80 % of the draws; over 15 % in one area in 80 %."""
holder = lg.s37_andel([x is not None and x <= M3_HOYST for x in verste])
holder_ikke = lg.s37_andel([x is not None and x > M3_OVER for x in verste])
return dom_av_andeler(holder, holder_ikke)
@dataclass(frozen=True)
class Forsyning:
"""M4 in one draw, over the operating years (pre-registration, clarification 4).
Attributes:
ikke_svakere_uten_tiltak: the power balance for the rest of the country is not weaker
in a normal or in the dry year (Delta Q <= 0), and the capacity balance with the
largest new unit out is not weaker (Delta R^-1 >= 0), in every operating year.
svakere_ogsaa_med_tiltak: the power balance is weaker in at least one operating year.
The measures of S47 cover missing capacity, without an upper limit, but not energy.
"""
ikke_svakere_uten_tiltak: bool
svakere_ogsaa_med_tiltak: bool
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"] * res.P_enhet
energi_svakere = effekt_svakere = False
for j, t in enumerate(res.aar):
if res.plan.antall_i_drift(t) == 0:
continue
rad = res.kraftaar[j]
energi_svakere |= max(rad.Delta_Q, rad.Delta_Q_tort) > slakk_energi
effekt_svakere |= rad.Delta_R_utfall < -slakk_effekt
return Forsyning(
ikke_svakere_uten_tiltak=not (energi_svakere or effekt_svakere),
svakere_ogsaa_med_tiltak=energi_svakere,
)
def dom_m4(forsyning: Sequence[Forsyning | None]) -> Dom:
"""M4: not weaker without measures in 80 % of the draws; weaker also with measures in 80 %."""
holder = lg.s37_andel([f is not None and f.ikke_svakere_uten_tiltak for f in forsyning])
holder_ikke = lg.s37_andel([f is not None and f.svakere_ogsaa_med_tiltak for f in forsyning])
return dom_av_andeler(holder, holder_ikke)
def dom_m6(m6: Utfall) -> Dom:
"""M6: at least 25 % in 80 % of the draws holds; under 5 % in 80 % does not.
A draw in which the path cannot be built, or never has every facility in
operation at once, does not reach 5 %.
"""
holder = andel(m6, M6_MINST, minst=True)
under = lg.s37_andel([x is None or x < M6_UNDER for x in m6])
return dom_av_andeler(holder, under)
def beste_per_trekning(nnv: Mapping[Losning, Utfall]) -> list[tuple[Losning, ...]]:
"""M7 per draw: the best of the five solutions (clarification 137 a, correcting 135 a).
``nnv[losning]`` holds the net present value per draw, None where the path
cannot be built. The best are those that can be built and have the highest
net present value among those that can be built, in the order A, B, C, T-F,
T-K. One is best alone; several with exactly the same value share the
place; an empty tuple is a draw in which none can be built. The rule is the
same for all five; a solution that is not passed in is not compared (a run
without it). The reference run R and B' are not part of M7. A net present
value that is not a number is rejected (clarification 139): the comparison
would depend on the order.
"""
ukjent = [a for a in nnv if a not in DOMSLOSNINGER]
if not nnv or ukjent:
msg = f"M7 compares A, B, C, T-F and T-K; got {sorted(nnv)}"
raise ValueError(msg)
losninger = [a for a in DOMSLOSNINGER if a in nnv]
beste: list[tuple[Losning, ...]] = []
for omega, rad in enumerate(zip(*(nnv[a] for a in losninger), strict=True)):
byggbare = [(v, a) for v, a in zip(rad, losninger, strict=True) if v is not None]
if any(math.isnan(v) for v, _ in byggbare):
msg = f"M7: net present value that is not a number in draw {omega} (clarification 139)"
raise ValueError(msg)
hoyest = max((v for v, _ in byggbare), default=None)
beste.append(tuple(a for v, a in byggbare if v == hoyest))
return beste
# ------------------------------------------------- the step of the ladder
@dataclass(frozen=True)
class Trinnvalg:
"""The step the verdicts are read on.
Attributes:
trinn: the number of facilities; None when no step can be built.
grunnlag: why that step.
"""
trinn: int | None
grunnlag: Grunnlag
def _laveste_trinn(
m6: Mapping[int, Mapping[Losning, Utfall]], minst: float, *, over: int = 0
) -> int | None:
for trinn in sorted(m6):
if trinn > over and any(
andel(m6[trinn][a], minst, minst=True) >= ANDEL_HOLDER
for a in DOMSLOSNINGER
if a in m6[trinn]
):
return trinn
return None
def trinn_for_dommene(m6: Mapping[int, Mapping[Losning, Utfall]]) -> Trinnvalg:
"""Pre-registration, clarification 1: which step of the ladder the verdicts are read on.
``m6[trinn][losning]`` holds M6 per draw in «normalisering» (None where the
path cannot be built or has no year of stable operation). The 25 % step is
the lowest step with more than one facility where at least 80 % of the
draws reach 25 % for one of A, B, C, T-F and T-K: the step with a single
facility cannot be the 25 % step (pre-registration, clarification 19;
chapter 16, clarification 104). The 5 % step is the lowest step, also the
one with a single facility, where 80 % reach 5 %. Without either, the
verdicts are read on the highest step that can be built: the highest where
one of the five has a value in at least 80 % of the draws (chapter 16,
clarification 57; chapter 17.1). A step is a number of facilities; in
solution T it is the same MW IT in modules, whatever their size.
"""
for minst, grunnlag, over in (
(M6_MINST, Grunnlag.TRINN_25, 1),
(M6_UNDER, Grunnlag.TRINN_5, 0),
):
trinn = _laveste_trinn(m6, minst, over=over)
if trinn is not None:
return Trinnvalg(trinn=trinn, grunnlag=grunnlag)
for trinn in sorted(m6, reverse=True):
byggbar = [
lg.s37_andel([x is not None for x in m6[trinn][a]])
for a in DOMSLOSNINGER
if a in m6[trinn]
]
if any(b >= ANDEL_HOLDER for b in byggbar):
return Trinnvalg(trinn=trinn, grunnlag=Grunnlag.HOYESTE)
return Trinnvalg(trinn=None, grunnlag=Grunnlag.INGEN)
# ------------------------------------------------------------ the overall verdicts
def er_felt(dommer: Mapping[str, Dom], median_m1: float) -> bool:
"""A solution cannot carry part I with one of M1 to M5 not holding or a negative median."""
return any(dommer[m] is Dom.HOLDER_IKKE for m in MAAL_SOM_FELLER) or median_m1 < 0
def maal_under_betingelser(dommer: Mapping[str, Dom]) -> tuple[str, ...]:
"""The targets among M1 to M5 that hold under conditions for a solution.
M6 is left out: a solution needs no threshold for M6, because M6 cannot
alone fell that a programme pays off (pre-registration; clarification 109).
"""
return tuple(m for m in MAAL_SOM_FELLER if dommer[m] is Dom.BETINGELSER)
def kan_navngis(dommer: Mapping[str, Dom], har_terskel: Mapping[str, bool]) -> bool:
"""Whether the conditions can be named for one solution (clarifications 93 and 109).
Every target among M1 to M5 that holds under conditions must have a
condition that can be named: for M1 to M4 a threshold that counts
(``har_terskel[maal]``), for M5 the condition that the sources in which
nuclear power is not higher are used, which is named by definition. A
solution with none of M1 to M5 under conditions has conditions that can be
named without any threshold (clarification 103 g): what is missing is the
scale.
"""
return all(m == "M5" or har_terskel.get(m, False) for m in maal_under_betingelser(dommer))
def del_I(
dommer: Mapping[Losning, Mapping[str, Dom]],
median_m1: Mapping[Losning, float],
valg: Trinnvalg,
*,
har_terskel: Mapping[Losning, Mapping[str, bool]] | None = None,
) -> Dom:
"""The verdict for part I (the programme).
``dommer[losning]`` holds the verdicts for M1 to M6 on the step in ``valg``,
``median_m1`` the median net present value. «Holder»: one of A, B, C, T-F
and T-K has M1 to M6 all holding, on the 25 % step (which has more than
one facility, clarification 104). «Holder ikke»: each of them has at least
one of M1 to M5 not holding, or a negative median in M1. Otherwise it
holds under conditions, and only when the conditions can be named within
the range of the sources for at least one solution that is not felled
(pre-registration, clarifications 5, 12 and 17; chapter 16, clarifications
59, 93 and 109). ``har_terskel[losning][maal]`` says whether the target has
a threshold that counts; when the conditions cannot be named for any such
solution, the verdict is «holder ikke». Left out, the verdict is given as
far as it follows from the targets: «holder under betingelser» then still
needs the thresholds.
"""
if valg.trinn is None:
return Dom.HOLDER_IKKE
losninger = [a for a in DOMSLOSNINGER if a in dommer]
ikke_felt = [a for a in losninger if not er_felt(dommer[a], median_m1[a])]
if not ikke_felt:
return Dom.HOLDER_IKKE
alle_holder = any(all(dommer[a][m] is Dom.HOLDER for m in MAAL_DEL_I) for a in losninger)
if alle_holder and valg.grunnlag is Grunnlag.TRINN_25 and valg.trinn > 1:
return Dom.HOLDER
if har_terskel is None:
return Dom.BETINGELSER
navngitt = any(kan_navngis(dommer[a], har_terskel.get(a, {})) for a in ikke_felt)
return Dom.BETINGELSER if navngitt else Dom.HOLDER_IKKE