feat(kjoring): thresholds, the conditions of part I, Sobol indices and threshold surfaces

Clarifications 105 to 111, on invented outcomes and made-up draws only. The price
threshold runs the model with the price multiplied by a factor; the thresholds in
a quantity, the indices and two of the surfaces are read from the outcomes per draw.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-13 17:57:52 +01:00
commit 8d13501653
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
10 changed files with 1561 additions and 79 deletions

View file

@ -103,6 +103,28 @@ def median(utfall: Utfall) -> float:
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.
@ -318,39 +340,70 @@ def trinn_for_dommene(m6: Mapping[int, Mapping[Losning, Utfall]]) -> Trinnvalg:
# ------------------------------------------------------------ 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,
*,
betingelser_kan_navngis: bool = True,
har_terskel: Mapping[Losning, Mapping[str, bool]] | None = None,
) -> Dom:
"""The verdict for part I (the programme), as far as it follows from the targets.
"""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, with more than one
facility (step 1 is ten modules in T and counts as a single facility).
«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
(pre-registration, clarification 5); ``betingelser_kan_navngis=False``
says they cannot, and the verdict is then «holder ikke» (chapter 16,
clarification 59).
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]
felt = [
any(dommer[a][m] is Dom.HOLDER_IKKE for m in MAAL_SOM_FELLER) or median_m1[a] < 0
for a in losninger
]
if all(felt):
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
return Dom.BETINGELSER if betingelser_kan_navngis else Dom.HOLDER_IKKE
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
def del_II(m7: Dom) -> Dom:

View file

@ -1,4 +1,4 @@
"""The run over the draws (chapter 11; chapter 16, clarifications 95 to 104).
"""The run over the draws (chapter 11; chapter 16, clarifications 95 to 111).
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
@ -9,6 +9,13 @@ 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.
With the drawn values of the quantities passed in, the thresholds behind
«holder under betingelser» are found and part I is decided (clarifications 108
and 109), and the first-order Sobol indices and the threshold surfaces are
read from the same outcomes (clarifications 110 and 111). The price threshold
of chapter 3.2 needs the model run again with the price multiplied by a
factor (clarification 105).
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
@ -28,11 +35,11 @@ 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 dommer, eierskap, miljo, nivaaisert, skala, sobol, terskler
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.dommer import DOMSLOSNINGER, Dom, Forsyning, Trinnvalg, persentil
from tokenfabrikker.inndata import BORTFALL_EGNE_HOY, BORTFALL_EGNE_LAV, BORTFALL_KILDE
from tokenfabrikker.kontantstrom import Knapphet
from tokenfabrikker.utbygging import Kraft, Losning
@ -43,6 +50,7 @@ if TYPE_CHECKING:
from tokenfabrikker.eierskap import Eierkriterier, Eierresultat, Rangering
from tokenfabrikker.inndata import Inndata
from tokenfabrikker.miljo import Kildeverdier
from tokenfabrikker.terskler import Pristerskel, Rute, Terskel
STIGE: Final = (1, 5, 10, 20, 40)
"""The fixed ladder of programme sizes, in facilities (pre-registration, clarification 1)."""
@ -112,6 +120,9 @@ class Utfall:
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.
c_snitt: the power cost the business pays, kr/MWh, as the average over the vintage
terms of S42 with their weights D_D(t_v) (clarification 111 b); None when it
is not computed (invented outcomes).
"""
NNV: float
@ -125,6 +136,7 @@ class Utfall:
M6_topp: float
stabilt_aar: int | None
toppaar: int
c_snitt: float | None = None
@dataclass(frozen=True)
@ -156,10 +168,17 @@ def _bortfall(inn: Inndata, scenario: Scenario) -> Callable[[int], float] | None
def _utfall(inn: Inndata, res: ks.Programresultat) -> Utfall:
S42 = nivaaisert.kraftkostnad(inn, res, bedrift=True).S42
kraft = nivaaisert.kraftkostnad(inn, res, bedrift=True)
S42 = kraft.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)
vekter = [
lg.diskonteringsfaktor(rho=inn["rho_D"], t=a.t_v, T_0=res.plan.T_0) for a in kraft.aarganger
]
c_snitt = math.fsum(
w * a.c_a for w, a in zip(vekter, kraft.aarganger, strict=True)
) / math.fsum(vekter)
m6 = skala.skala(inn, res)
return Utfall(
NNV=res.NNV,
@ -173,6 +192,7 @@ def _utfall(inn: Inndata, res: ks.Programresultat) -> Utfall:
M6_topp=m6.M6_topp,
stabilt_aar=m6.stabilt_aar,
toppaar=m6.toppaar,
c_snitt=c_snitt,
)
@ -356,6 +376,30 @@ class Losningsdommer:
)
@dataclass(frozen=True)
class Betingelser:
"""The conditions behind «holder under betingelser» for one solution (clarification 109).
Attributes:
felt: True when the solution cannot carry part I.
maal: the targets among M1 to M5 that hold under conditions for it.
kan_navngis: True when each of them has a condition that can be named: a threshold
that counts for M1 to M4, and by definition for M5.
terskler: the thresholds per target that holds under conditions, also M6, which
needs none; those that count and those in quantities without a source.
"""
felt: bool
maal: tuple[str, ...]
kan_navngis: bool
terskler: Mapping[str, tuple[Terskel, ...]]
@property
def bare_skalaen_mangler(self) -> bool:
"""True when M1 to M5 all hold: no threshold is needed (clarification 103 g)."""
return not self.felt and not self.maal
@dataclass(frozen=True)
class Scenariodommer:
"""The verdicts in one scenario.
@ -363,17 +407,29 @@ class Scenariodommer:
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_I: part I on the step the verdicts are read on. Without the drawn values of
the quantities it is given as far as it follows from the targets: where it is
«holder under betingelser», whether the conditions can be named is then still
to be decided (clarifications 93, 97 and 109).
del_II: part II on that step; None when no step can be built, or when A is not in
the run (clarification 102).
betingelser: the conditions per solution on that step; None without the drawn
values, or when there is no step.
terskler_M7: the thresholds for M7 when it holds under conditions; they are shown
and change nothing.
"""
per_trinn: Mapping[int, Mapping[Losning, Losningsdommer]]
M7: Mapping[int, Maaldom]
del_I: Dom
del_II: Dom | None
betingelser: Mapping[Losning, Betingelser] | None = None
terskler_M7: tuple[Terskel, ...] = ()
@property
def del_I_avgjort(self) -> bool:
"""False when part I holds under conditions and the thresholds are not yet found."""
return self.del_I is not Dom.BETINGELSER or self.betingelser is not None
@dataclass(frozen=True)
@ -444,50 +500,121 @@ 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 vilkaar_holder(utfall: Sequence[Utfall | None]) -> dict[str, list[bool | None]]:
"""The condition for «holder» per draw for M1, M2, M3, M4 and M6 (clarification 69).
None where the path cannot be built: such a draw never meets the condition.
"""
return {
"M1": [None if u is None else u.NNV > 0 for u in utfall],
"M2": [None if u is None else u.S42 >= 0.0 for u in utfall],
"M3": [None if u is None else u.M3 <= dommer.M3_HOYST for u in utfall],
"M4": [None if u is None else u.M4.ikke_svakere_uten_tiltak for u in utfall],
"M6": [None if u is None else u.M6 is not None and u.M6 >= dommer.M6_MINST for u in utfall],
}
def vilkaar_holder_ikke(utfall: Sequence[Utfall | None]) -> dict[str, list[bool]]:
"""The condition for «holder ikke» per draw for M3, M4 and M6, as S37 counts it.
A path that cannot be built meets neither condition in M3 and M4, and
counts as under 5 % in M6 (clarification 56).
"""
return {
"M3": [u is not None and u.M3 > dommer.M3_OVER for u in utfall],
"M4": [u is not None and u.M4.svakere_ogsaa_med_tiltak for u in utfall],
"M6": [u is None or u.M6 is None or u.M6 < dommer.M6_UNDER 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)
holder, holder_ikke = vilkaar_holder(utfall), vilkaar_holder_ikke(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]),
),
"M1": _maaldom(dommer.dom_m1(nnv), holder["M1"]),
"M2": _maaldom(dommer.dom_m2(s42), holder["M2"]),
"M3": _maaldom(dommer.dom_m3(m3), holder["M3"], lg.s37_andel(holder_ikke["M3"])),
"M4": _maaldom(dommer.dom_m4(m4), holder["M4"], lg.s37_andel(holder_ikke["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]),
dommer.dom_m6(_m6_for_dommen(utfall)), holder["M6"], lg.s37_andel(holder_ikke["M6"])
),
}
return Losningsdommer(maal=maal, M5=M5, median_M1=dommer.median(nnv))
def _m7(nnv: Mapping[Losning, Sequence[float | None]]) -> Maaldom:
MAAL_MED_TERSKEL: Final = ("M1", "M2", "M3", "M4", "M6")
"""The targets a threshold in a quantity is looked for in, per solution (clarification 108)."""
def betingelser_for_losning(
utfall: Sequence[Utfall | None],
dom: Losningsdommer,
storrelser: Mapping[str, Sequence[float]],
status: Mapping[str, str],
) -> Betingelser:
"""The thresholds for one solution and whether its conditions can be named.
``storrelser`` holds the drawn values per quantity, one per draw, and
``status`` the status of each in the parameter file. Thresholds are looked
for in every target that holds under conditions, also M6, which needs
none (clarification 109).
"""
holder = vilkaar_holder(utfall)
funnet = {
m: terskler.terskler_for_maal(storrelser, status, holder[m])
for m in MAAL_MED_TERSKEL
if dom.maal[m].dom is Dom.BETINGELSER
}
har_terskel = {m: any(t.teller for t in rad) for m, rad in funnet.items()}
return Betingelser(
felt=dom.felt,
maal=dommer.maal_under_betingelser(dom.dommer),
kan_navngis=dommer.kan_navngis(dom.dommer, har_terskel),
terskler=funnet,
)
def vilkaar_m7(nnv: Mapping[Losning, Sequence[float | None]]) -> list[bool | None]:
"""Whether A is best per draw; None where A cannot be built (clarification 69)."""
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)
return [None if a is None else b for a, b in zip(nnv[Losning.A], best, strict=True)]
def sett_dommer(kjoring: Kjoring, M5: Mapping[Losning, Dom]) -> Dommer:
def _m7(nnv: Mapping[Losning, Sequence[float | None]]) -> Maaldom:
return _maaldom(dommer.dom_m7(nnv), vilkaar_m7(nnv))
def sett_dommer(
kjoring: Kjoring,
M5: Mapping[Losning, Dom],
*,
storrelser: Mapping[str, Sequence[float]] | None = None,
status: Mapping[str, str] | None = None,
) -> 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.
nor M7.
``storrelser`` holds the drawn values of the quantities, one per draw in
the order of the run, and ``status`` the status of each in the parameter
file. With them the thresholds are found on the step, in every scenario,
and part I is decided (clarifications 108 and 109). Without them part I
is given as far as it follows from the targets.
"""
if (storrelser is None) != (status is None):
msg = "the thresholds need both the drawn values and the status of the quantities"
raise ValueError(msg)
if storrelser is not None and any(len(x) != kjoring.antall for x in storrelser.values()):
msg = "the drawn values must have one value per draw of the run"
raise ValueError(msg)
hoved = kjoring.hovedscenario
fem = [a for a in DOMSLOSNINGER if a in kjoring.losninger]
valg = dommer.trinn_for_dommene(
@ -506,6 +633,30 @@ def sett_dommer(kjoring: Kjoring, M5: Mapping[Losning, Dom]) -> Dommer:
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]
betingelser: dict[Losning, Betingelser] | None = None
terskler_M7: tuple[Terskel, ...] = ()
if storrelser is not None and status is not None and valg.trinn is not None:
betingelser = {
a: betingelser_for_losning(
kjoring.utfall(scenario, a, valg.trinn), paa_trinnet[a], storrelser, status
)
for a in kjoring.losninger
}
if valg.trinn in m7 and m7[valg.trinn].dom is Dom.BETINGELSER:
terskler_M7 = terskler.terskler_for_maal(
storrelser,
status,
vilkaar_m7(
{
a: [
None if u is None else u.NNV
for u in kjoring.utfall(scenario, a, valg.trinn)
]
for a in fem
}
),
grense=dommer.ANDEL_M7,
)
scenarioer[scenario.navn] = Scenariodommer(
per_trinn=per_trinn,
M7=m7,
@ -513,35 +664,288 @@ def sett_dommer(kjoring: Kjoring, M5: Mapping[Losning, Dom]) -> Dommer:
{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,
har_terskel=None
if betingelser is None
else {
a: {m: any(t.teller for t in rad) for m, rad in betingelser[a].terskler.items()}
for a in fem
},
),
del_II=dommer.del_II(m7[valg.trinn].dom) if valg.trinn in m7 else None,
betingelser=betingelser,
terskler_M7=terskler_M7,
)
return Dommer(valg=valg, scenarioer=scenarioer, teller=hoved.navn)
# ------------------------------------------------- the timeline over the draws
# ------------------------------------------------ the figures next to M6 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).
@dataclass(frozen=True)
class Sidetall:
"""One of the figures next to M6 over the draws that have it (clarification 103 c).
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.
Attributes:
antall: the draws with a value.
median: the median among them; None without any.
persentiler: the 10th and the 90th percentile among them; None without any.
"""
if not verdier:
msg = "a percentile needs at least one value"
antall: int
median: float | None
persentiler: tuple[float, ...] | None
def ved_siden_av_m6(utfall: Sequence[Utfall | None]) -> dict[str, Sidetall]:
"""The four figures next to M6, each over the draws in which it has a value.
The average over L_H years and M6 against the median of the ten years
follow the year of stable operation and have no value without it; 2050
and the peak year have a value for every path that can be built and
covers the year.
"""
tall: dict[str, list[float | None]] = {
"snitt": [u.M6_snitt for u in utfall if u is not None],
"median av ti aar": [u.M6_median for u in utfall if u is not None],
"2050": [u.M6_2050 for u in utfall if u is not None],
"toppaar": [u.M6_topp for u in utfall if u is not None],
}
ut = {}
for navn, rad in tall.items():
verdier = [x for x in rad if x is not None]
ut[navn] = Sidetall(
antall=len(verdier),
median=persentil(verdier, 0.5) if verdier else None,
persentiler=tuple(persentil(verdier, p) for p in PERSENTILER) if verdier else None,
)
return ut
# ------------------------------------------------------------- the Sobol indices
def utfall_for_indeksene(
kjoring: Kjoring, losning: Losning, trinn: int, scenario: Scenario | None = None
) -> dict[str, list[float | None]]:
"""The outcomes Y the Sobol indices are given for, per draw (clarification 110).
The net present value among the draws in which the path can be built
(None elsewhere), whether it can be built, the condition for «holder» in
M1, M2, M3, M4 and M6, the condition for «holder ikke» in M3, M4 and M6,
and for A whether A is best. The conditions are one or zero over all the
draws, as S37 counts them.
"""
scenario = kjoring.hovedscenario if scenario is None else scenario
utfall = kjoring.utfall(scenario, losning, trinn)
y: dict[str, list[float | None]] = {
"NNV": [None if u is None else u.NNV for u in utfall],
"byggbar": [float(u is not None) for u in utfall],
}
for maal, rad in vilkaar_holder(utfall).items():
y[f"{maal} holder"] = [float(x is True) for x in rad]
for maal, ikke in vilkaar_holder_ikke(utfall).items():
y[f"{maal} holder ikke"] = [float(x) for x in ikke]
fem = [a for a in DOMSLOSNINGER if a in kjoring.losninger]
if losning is Losning.A and Losning.A in fem:
nnv: dict[Losning, list[float | None]] = {
a: [None if u is None else u.NNV for u in kjoring.utfall(scenario, a, trinn)]
for a in fem
}
y["M7"] = [float(x) for x in dommer.a_er_best(nnv)]
return y
def sobol_indekser(
kjoring: Kjoring,
storrelser: Mapping[str, Sequence[float]],
losning: Losning,
trinn: int,
scenario: Scenario | None = None,
) -> dict[str, dict[str, float | None]]:
"""The first-order index of every drawn quantity for every outcome of one solution.
Returned by the name of the outcome and then of the quantity. The step is
the one the verdicts are read on, and the scenario «normalisering» on the
main path unless another is passed.
"""
return {
navn: sobol.indekser(storrelser, y)
for navn, y in utfall_for_indeksene(kjoring, losning, trinn, scenario).items()
}
# ------------------------------------------------------------ the price threshold
def nnv_med_prisfaktor(
inn: Inndata, *, losning: Losning, trinn: int, knapphet: Knapphet, k: float
) -> float | None:
"""S26 for one path in one draw with the price multiplied by k; None when not buildable."""
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=trinn)
if not plan.gjennomforbar:
return None
return ks.regn_program(inn, losning, plan, knapphet, dim=dim, prisfaktor=k).NNV
def pristerskel_for_losning(
trekninger: Sequence[Inndata],
losning: Losning,
trinn: int,
scenario: Scenario,
*,
prosesser: int = 1,
) -> Pristerskel:
"""The price threshold k of chapter 3.2 for one solution on one step (clarification 105).
The median is taken over the draws passed in, with a draw in which the
path cannot be built ranked below every value. The scenario is one of the
three price scenarios on the main path. Every factor that is tried runs
the model once per draw; the build-out is the same for all of them.
"""
if scenario.bortfall is not None:
msg = "the price threshold is given for the price scenarios on the main path"
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}"
if not trekninger:
msg = "the price threshold needs at least one draw"
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])
if prosesser > 1:
with ProcessPoolExecutor(max_workers=prosesser) as utforer:
def median(k: float) -> float:
en = partial(
nnv_med_prisfaktor,
losning=losning,
trinn=trinn,
knapphet=scenario.knapphet,
k=k,
)
return dommer.median(list(utforer.map(en, trekninger)))
return terskler.pristerskel(median)
planer = []
for inn in trekninger:
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=trinn)
planer.append((inn, dim, plan if plan.gjennomforbar else None))
def median_en_prosess(k: float) -> float:
return dommer.median(
[
None
if plan is None
else ks.regn_program(
inn, losning, plan, scenario.knapphet, dim=dim, prisfaktor=k
).NNV
for inn, dim, plan in planer
]
)
return terskler.pristerskel(median_en_prosess)
def lcoc_v_2025(inn: Inndata) -> float:
"""The competitor's cost of compute for the vintage of 2025, kr per MW IT and year (S43)."""
return ks.regnekraftpris(inn, Knapphet.NORMALISERING, 0).lcoc_v(lg.BASISAAR_IT_PRIS)
@dataclass(frozen=True)
class Prisflatepunkt:
"""One class of the reactor cost on the surface price against reactor cost (111 a).
Attributes:
antall: the draws in the class.
c_N_ref: the median reactor cost among them, in the unit the draws are passed in.
terskel: the price threshold with the median taken over the draws of the class.
"""
antall: int
c_N_ref: float
terskel: Pristerskel
def prisflate(
trekninger: Sequence[Inndata],
c_N_ref: Sequence[float],
losning: Losning,
trinn: int,
scenario: Scenario,
*,
prosesser: int = 1,
) -> tuple[Prisflatepunkt | None, ...]:
"""The price threshold per class of the reactor cost (clarification 111 a).
``c_N_ref`` holds the drawn reactor cost per draw. The five classes are
made over all the draws; a class without draws is None.
"""
if len(c_N_ref) != len(trekninger):
msg = "the surface needs the reactor cost of every draw"
raise ValueError(msg)
klasse = sobol.klasser(c_N_ref, terskler.KLASSER_FLATE)
punkter: list[Prisflatepunkt | None] = []
for q in range(terskler.KLASSER_FLATE):
med = [j for j, m in enumerate(klasse) if m == q]
if not med:
punkter.append(None)
continue
punkter.append(
Prisflatepunkt(
antall=len(med),
c_N_ref=persentil([c_N_ref[j] for j in med], 0.5),
terskel=pristerskel_for_losning(
[trekninger[j] for j in med], losning, trinn, scenario, prosesser=prosesser
),
)
)
return tuple(punkter)
# ---------------------------------------------- the surfaces read from the outcomes
def flate_over_trekningene(
kjoring: Kjoring,
x: Sequence[float],
y: Sequence[float],
losning: Losning,
trinn: int,
) -> tuple[tuple[Rute, ...], ...]:
"""Net present value over classes of two drawn quantities (clarification 111 c).
``x`` and ``y`` hold the drawn values per draw (the required return and
the reactor cost). All the draws are in; one in which the path cannot be
built has no positive net present value and ranks below every value.
"""
utfall = kjoring.utfall(kjoring.hovedscenario, losning, trinn)
return terskler.flate(x, y, [None if u is None else u.NNV for u in utfall])
def kraftprisflate(
kjoring: Kjoring, p_v: Sequence[float], losning: Losning, trinn: int
) -> tuple[int, tuple[tuple[Rute, ...], ...]]:
"""The competitor's power price against the cost of Norwegian power (clarification 111 b).
``p_v`` holds the drawn power price of the competitor per draw. The cost
of Norwegian power exists only where the path can be built, so the classes
of both axes are made among those draws; their number is returned first.
``flate[i][j]`` has class i of the competitor's price and class j of the
Norwegian cost.
"""
utfall = kjoring.utfall(kjoring.hovedscenario, losning, trinn)
if len(p_v) != len(utfall):
msg = "the surface needs the competitor's power price of every draw"
raise ValueError(msg)
med = [(p, u) for p, u in zip(p_v, utfall, strict=True) if u is not None]
kost = [u.c_snitt for _, u in med]
if any(c is None for c in kost):
msg = "the outcomes do not hold the cost of Norwegian power"
raise ValueError(msg)
return len(med), terskler.flate(
[p for p, _ in med], [c for c in kost if c is not None], [u.NNV for _, u in med]
)
# ------------------------------------------------- the timeline over the draws
@dataclass(frozen=True)

View file

@ -323,7 +323,8 @@ class Programresultat:
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).
mu_d: the factor of S51 per vintage (exactly one on the main path), times the price
factor of clarification 105 when that is set; ``mu_d.andel`` is S51 alone.
full_fortrengning: True in the sensitivity "full displacement in the first stage"
(chapter 17.8): delta_V is one for the modules of the first stage.
"""
@ -958,22 +959,34 @@ class Etterspoersel:
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.
k: the factor the price of compute is multiplied by for every vintage, for the
price threshold of chapter 3.2 (clarification 105); one in every other run.
"""
eps_d: float
d: Callable[[int], float] | None = None
k: float = 1.0
@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:
def andel(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 __call__(self, t_v: int) -> float:
"""The factor on the revenue per MW sold: mu_d, times the price factor when it is set.
The price factor stands everywhere mu stands together with the price
(clarification 105), and those are the places mu_d stands. With the
factor at one this is exactly mu_d.
"""
return self.andel(t_v) if self.k == 1.0 else self.k * self.andel(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."""
@ -1557,6 +1570,7 @@ def regn_program(
tilleggsregel: bool = True,
bortfall: Callable[[int], float] | None = None,
full_fortrengning_i_forste_trinn: bool = False,
prisfaktor: float = 1.0,
) -> Programresultat:
"""S26 for one path: the yearly cash flows and the net present value for Norway.
@ -1575,7 +1589,15 @@ def regn_program(
for solution T: delta_V is one for the modules that started within the
grid that exists, in S23, S24, the grid investment and V, through all
their operating years (clarification 80).
``prisfaktor`` multiplies the price of compute for every vintage, wherever
the share of capacity sold stands together with the price (the price
threshold of chapter 3.2, clarification 105). The scarcity markup of S43,
the build-out and the costs are as without it.
"""
if prisfaktor < 0:
msg = f"the price factor cannot be negative, got {prisfaktor}"
raise ValueError(msg)
if losning.trinnvis != isinstance(plan, ub.Trinnvisplan):
msg = "solution T, and only solution T, takes a plan built in modules"
raise TypeError(msg)
@ -1594,7 +1616,7 @@ def regn_program(
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),
mu_d=Etterspoersel(eps_d=inn["eps_d"], d=bortfall, k=prisfaktor),
T_0=plan.T_0,
T_s=plan.T_s,
full_fortrengning=full_fortrengning_i_forste_trinn,

View file

@ -149,7 +149,7 @@ def unngaatt_utslipp(inn: Inndata, res: Programresultat, *, anslag: str = "hoved
lg.s53_unngaatt_utslipp(
u_alt=inn.u_alt_i(anslag, t),
mu=inn["mu_rel"],
mu_d=res.mu_d(t_v),
mu_d=res.mu_d.andel(t_v),
Gamma=res.dim.Gamma,
lam=inn["lambda"],
PUE_v=inn["PUE_v"],

View file

@ -0,0 +1,90 @@
"""First-order Sobol indices from the stored draws (chapter 11; clarification 110).
The index of a drawn quantity X for an outcome Y is Var(E[Y | X]) / Var(Y).
It is estimated from the draws the verdicts are read from, without new runs:
the draws are put in classes by the value of X, and the variance between the
class averages is held against the variance over all the draws.
The estimate is biased upwards: without any effect its expectation is about
(M - 1) / (N - 1) with M classes and N draws (``forventning_uten_virkning``).
Nothing is corrected for it. Total indices cannot be estimated from given
draws without a surrogate model and are not given.
The sums are exactly rounded, so the figures are the same to the last digit
from run to run.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
def antall_klasser(N: int) -> int:
"""The number of classes for N draws: max(2, floor(sqrt(N) / 2)); 50 with 10 000."""
return max(2, math.isqrt(N) // 2)
def klasser(x: Sequence[float], M: int) -> list[int]:
"""The class of every draw: floor(M r / N), r the number of draws with a lower value.
Draws with the same value share a class, so a quantity with few distinct
values gets one class per value.
"""
N = len(x)
sortert = sorted(x)
lavere: dict[float, int] = {}
for r, v in enumerate(sortert):
lavere.setdefault(v, r)
return [M * lavere[v] // N for v in x]
def forventning_uten_virkning(N: int, M: int | None = None) -> float:
"""What the estimate is expected to be for a quantity without any effect."""
M = antall_klasser(N) if M is None else M
return (M - 1) / (N - 1)
def indeks(x: Sequence[float], y: Sequence[float], *, M: int | None = None) -> float | None:
"""The first-order index of one quantity for one outcome, from N draws.
``x`` holds the drawn value and ``y`` the outcome per draw. Returns None
when every draw has the same outcome: the variance is then zero and the
index has no value.
"""
if len(x) != len(y) or not x:
msg = "an index needs one value and one outcome per draw, and at least one draw"
raise ValueError(msg)
if min(y) == max(y):
return None
N = len(x)
M = antall_klasser(N) if M is None else M
snitt = math.fsum(y) / N
i_klasse: dict[int, list[float]] = {}
for m, verdi in zip(klasser(x, M), y, strict=True):
i_klasse.setdefault(m, []).append(verdi)
mellom = math.fsum(
len(verdier) * (math.fsum(verdier) / len(verdier) - snitt) ** 2
for verdier in i_klasse.values()
)
return mellom / math.fsum((verdi - snitt) ** 2 for verdi in y)
def indekser(
storrelser: Mapping[str, Sequence[float]],
y: Sequence[float | None],
) -> dict[str, float | None]:
"""The index of every drawn quantity for one outcome, over the draws that have it.
``y`` holds the outcome per draw; None leaves the draw out (the net present
value of a path that cannot be built). The number of classes follows the
number of draws that are in. Without any such draw every index is None.
"""
med = [j for j, verdi in enumerate(y) if verdi is not None]
verdier = [float(verdi) for verdi in y if verdi is not None]
if not med:
return dict.fromkeys(storrelser)
return {navn: indeks([x[j] for j in med], verdier) for navn, x in storrelser.items()}

View file

@ -0,0 +1,304 @@
"""Thresholds (chapters 3.2 and 11; chapter 16, clarifications 105 to 109 and 111).
Three kinds of threshold are read from the draws the verdicts are read from;
no new draws are made.
The price threshold is the factor the price of compute must be multiplied by,
for every vintage, for the median net present value to be zero. The median
does not fall when the factor rises, so the threshold is the lowest factor
with a median that is not negative; it is found to within ``K_TOLERANSE``.
A threshold in one drawn quantity is the least strict condition on that
quantity, between its 10th and 90th percentile, under which a target that
holds under conditions holds. It counts as a condition only for a quantity
with the status «kilde» (pre-registration, clarification 5).
A threshold surface is the net present value over classes of two quantities.
Nothing here runs the model: the functions take outcomes per draw, or a
function that gives the median for a factor.
"""
from __future__ import annotations
import bisect
import enum
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, Final
from tokenfabrikker import dommer, sobol
from tokenfabrikker import ligninger as lg
if TYPE_CHECKING:
from collections.abc import Callable, Mapping, Sequence
K_MAKS: Final = 100.0
"""The price threshold is searched for up to this factor (clarification 105)."""
K_TOLERANSE: Final = 1e-6
"""The price threshold is given to within this much (clarification 105)."""
SPENN: Final = (0.1, 0.9)
"""A threshold counts only between these percentiles of the draws (clarification 5)."""
STATUS_KILDE: Final = "kilde"
"""The status in the parameter file a quantity must have for its threshold to count."""
KLASSER_FLATE: Final = 5
"""The classes per axis of a threshold surface (clarification 111)."""
# ------------------------------------------------------------ the price threshold
@dataclass(frozen=True)
class Pristerskel:
"""The price threshold k of chapter 3.2 for one solution in one scenario.
Attributes:
k: the factor, with a median that is not negative at ``k`` and a negative one at
``k - K_TOLERANSE``; None when it has no value.
over_maks: True when the median is negative also at ``K_MAKS``.
uten_median: True when the median has no value: the path cannot be built in at
least half of the draws, whatever the price (clarification 103 a).
"""
k: float | None
over_maks: bool = False
uten_median: bool = False
def _omslutt(
f: Callable[[float], float], k_maks: float
) -> Pristerskel | tuple[float, float, float, float]:
"""A bracket (low, f(low), high, f(high)) with f(low) < 0 <= f(high), or the answer.
The search starts at one, the main run, and brackets the threshold by
trying zero or by doubling up to ``k_maks``.
"""
f_1 = f(1.0)
if f_1 == -math.inf:
return Pristerskel(k=None, uten_median=True)
if f_1 >= 0:
f_0 = f(0.0)
return Pristerskel(k=0.0) if f_0 >= 0 else (0.0, f_0, 1.0, f_1)
lav, f_lav, hoy = 1.0, f_1, 1.0
while hoy < k_maks:
hoy = min(2.0 * hoy, k_maks)
f_hoy = f(hoy)
if f_hoy >= 0:
return lav, f_lav, hoy, f_hoy
lav, f_lav = hoy, f_hoy
return Pristerskel(k=None, over_maks=True)
def pristerskel(
f: Callable[[float], float], *, toleranse: float = K_TOLERANSE, k_maks: float = K_MAKS
) -> Pristerskel:
"""The lowest factor k >= 0 with f(k) >= 0, for a function that does not fall with k.
``f(k)`` is the median net present value with the price multiplied by k;
minus infinity when the median has no value. The bracket around the
threshold is narrowed with the straight line between its ends, checked by
halving, until it is no wider than the tolerance.
"""
funnet = _omslutt(f, k_maks)
if isinstance(funnet, Pristerskel):
return funnet
lav, f_lav, hoy, f_hoy = funnet
while hoy - lav > toleranse:
bredde = hoy - lav
# The root of the straight line between the ends. A point just above it most often
# has a median that is not negative; when the upper end already is such a point, a
# point just below closes the bracket. The midpoint is tried when that did not at
# least halve the bracket, so the search always ends.
linje = lav - f_lav * bredde / (f_hoy - f_lav)
if hoy - linje <= toleranse:
proves = (hoy - 0.9 * toleranse, lav + 0.5 * bredde)
else:
proves = (linje + 0.45 * toleranse, lav + 0.5 * bredde)
for k in proves:
if not lav < k < hoy:
continue
f_k = f(k)
if f_k >= 0:
hoy, f_hoy = k, f_k
else:
lav, f_lav = k, f_k
if hoy - lav <= max(toleranse, 0.5 * bredde):
break
return Pristerskel(k=hoy)
def innenfor_kontraktsprisene(
k: float, lcoc_v_2025: Sequence[float], y_obs_maks: float
) -> tuple[bool, float]:
"""The check of the price threshold against the contract prices (clarification 106).
``lcoc_v_2025`` holds the competitor's cost of compute in 2025 per draw,
``y_obs_maks`` the upper end of the contract prices in the parameter file.
Returns whether k is at most y_obs_maks over the median cost, and the
share of the draws in which k times the cost is at most y_obs_maks.
"""
median = dommer.persentil(lcoc_v_2025, 0.5)
return k <= y_obs_maks / median, lg.s37_andel([k * c <= y_obs_maks for c in lcoc_v_2025])
# ----------------------------------------------------- a threshold in one quantity
class Retning(enum.StrEnum):
"""The direction of a condition on a quantity X: «X at most c» or «X at least c»."""
HOYST = "høyst"
MINST = "minst"
@dataclass(frozen=True)
class Terskel:
"""The least strict condition on one quantity under which a target holds.
Attributes:
storrelse: the id of the quantity in the parameter file.
retning: at most, or at least.
verdi: the threshold, in the unit the draws are passed in.
sannsynlighet: the share of all the draws the condition covers.
andel_oppfylt: the share that meets the condition for «holder» among them.
teller: True when the quantity has the status «kilde», so that the threshold counts
as a condition; otherwise it «depends on an assumption without a source».
"""
storrelse: str
retning: Retning
verdi: float
sannsynlighet: float
andel_oppfylt: float
teller: bool
def terskel(
x: Sequence[float],
oppfylt: Sequence[bool | None],
retning: Retning,
*,
grense: float = dommer.ANDEL_HOLDER,
) -> tuple[float, float, float] | None:
"""The threshold in one quantity and one direction (clarification 108).
``x`` holds the drawn value per draw and ``oppfylt`` whether the condition
for «holder» is met in the draw; None, a path that cannot be built, does
not meet it. The candidates are the distinct drawn values between the
10th and the 90th percentile of ``x``. Returns the largest candidate c
(at most) or the smallest (at least) for which the condition is met in at
least ``grense`` of the draws with x <= c (x >= c), with the share of all
the draws that condition covers and the share met among them; None when
no candidate does.
"""
if len(x) != len(oppfylt) or not x:
msg = "a threshold needs one value and one outcome per draw, and at least one draw"
raise ValueError(msg)
N = len(x)
par = sorted(zip(x, (o is True for o in oppfylt), strict=True))
xs = [v for v, _ in par]
oppsamlet = [0]
for _, o in par:
oppsamlet.append(oppsamlet[-1] + int(o))
lav, hoy = (dommer.persentil(xs, p) for p in SPENN)
kandidater = sorted({v for v in xs if lav <= v <= hoy}, reverse=retning is Retning.HOYST)
for c in kandidater:
if retning is Retning.HOYST:
n = bisect.bisect_right(xs, c)
med = oppsamlet[n]
else:
forste = bisect.bisect_left(xs, c)
n = N - forste
med = oppsamlet[N] - oppsamlet[forste]
if med / n >= grense:
return c, n / N, med / n
return None
def terskler_for_maal(
storrelser: Mapping[str, Sequence[float]],
status: Mapping[str, str],
oppfylt: Sequence[bool | None],
*,
grense: float = dommer.ANDEL_HOLDER,
) -> tuple[Terskel, ...]:
"""Every threshold for one target of one solution, over the drawn quantities.
``storrelser`` holds the drawn values per quantity and ``status`` its
status in the parameter file. The thresholds come in the order of the
quantities, at most before at least.
"""
ut = []
for navn, x in storrelser.items():
for retning in Retning:
funnet = terskel(x, oppfylt, retning, grense=grense)
if funnet is not None:
verdi, sannsynlighet, andel_oppfylt = funnet
ut.append(
Terskel(
storrelse=navn,
retning=retning,
verdi=verdi,
sannsynlighet=sannsynlighet,
andel_oppfylt=andel_oppfylt,
teller=status[navn] == STATUS_KILDE,
)
)
return tuple(ut)
# ------------------------------------------------------------ the threshold surfaces
@dataclass(frozen=True)
class Rute:
"""One cell of a threshold surface: the draws in one class of each of two quantities.
Attributes:
antall: the draws in the cell.
andel_positiv: the share of them with a positive net present value; a draw in
which the path cannot be built has none. None for an empty cell.
median: the median net present value, with a draw in which the path cannot be
built ranked below every value; None for an empty cell.
"""
antall: int
andel_positiv: float | None
median: float | None
def flate(
x: Sequence[float],
y: Sequence[float],
nnv: Sequence[float | None],
*,
Q: int = KLASSER_FLATE,
) -> tuple[tuple[Rute, ...], ...]:
"""The net present value over Q x Q classes of two quantities (clarification 111 b, c).
The classes of each quantity are made over the draws passed in, as for the
Sobol indices: draws with the same value share a class. ``flate[i][j]`` is
the cell with class i of ``x`` and class j of ``y``.
"""
if not len(x) == len(y) == len(nnv):
msg = "a surface needs the two quantities and the net present value for the same draws"
raise ValueError(msg)
kx, ky = sobol.klasser(x, Q), sobol.klasser(y, Q)
ruter: list[list[list[float | None]]] = [[[] for _ in range(Q)] for _ in range(Q)]
for i, j, v in zip(kx, ky, nnv, strict=True):
ruter[i][j].append(v)
return tuple(
tuple(
Rute(
antall=len(verdier),
andel_positiv=dommer.andel_positiv(verdier) if verdier else None,
median=dommer.median(verdier) if verdier else None,
)
for verdier in rad
)
for rad in ruter
)

View file

@ -288,8 +288,21 @@ def test_del_I_holder_ikke_naar_hver_losning_er_felt() -> None:
assert dommer.del_I(per_losning, median, valg) is Dom.HOLDER_IKKE
per_losning[Losning.C] = _dommer(M6=Dom.HOLDER_IKKE)
assert dommer.del_I(per_losning, median, valg) is Dom.BETINGELSER
# C has none of M1 to M5 under conditions: what is missing is the scale, and no
# threshold is needed (clarifications 103 g and 109)
assert dommer.del_I(per_losning, median, valg, har_terskel={}) is Dom.BETINGELSER
# without conditions that can be named within the range of the sources it does not hold
assert dommer.del_I(per_losning, median, valg, betingelser_kan_navngis=False) is Dom.HOLDER_IKKE
per_losning[Losning.C] = _dommer(M2=Dom.BETINGELSER, M6=Dom.HOLDER_IKKE)
assert dommer.del_I(per_losning, median, valg) is Dom.BETINGELSER
assert dommer.del_I(per_losning, median, valg, har_terskel={}) is Dom.HOLDER_IKKE
uten = {Losning.C: {"M1": True, "M2": False}}
assert dommer.del_I(per_losning, median, valg, har_terskel=uten) is Dom.HOLDER_IKKE
med = {Losning.C: {"M2": True}}
assert dommer.del_I(per_losning, median, valg, har_terskel=med) is Dom.BETINGELSER
# a threshold for a solution that is felled does not help
feil = {Losning.A: {"M2": True}, Losning.B: {"M1": True}}
assert dommer.del_I(per_losning, median, valg, har_terskel=feil) is Dom.HOLDER_IKKE
per_losning[Losning.C] = _dommer(M6=Dom.HOLDER_IKKE)
# the pre-registration says a negative median; a median of exactly zero does not fell
median[Losning.B] = 0.0
per_losning[Losning.C] = _dommer(M4=Dom.HOLDER_IKKE)
@ -317,3 +330,22 @@ def test_hvor_mye_av_dommen_som_skyldes_baner_som_ikke_lar_seg_bygge() -> None:
assert dommer.ved_siden_av_dommen(oppfylt) == pytest.approx((0.25, 0.5))
assert dommer.ved_siden_av_dommen([None, None]) == (1.0, None)
assert dommer.ved_siden_av_dommen([True, True]) == (0.0, 1.0)
def test_betingelsene_kan_navngis_naar_hvert_maal_har_en_terskel_som_teller() -> None:
"""Clarifications 93 and 109: every one of M1 to M5 under conditions; M5 by definition."""
d = _dommer(M1=Dom.BETINGELSER, M3=Dom.BETINGELSER, M5=Dom.BETINGELSER, M6=Dom.BETINGELSER)
assert dommer.maal_under_betingelser(d) == ("M1", "M3", "M5")
assert dommer.kan_navngis(d, {"M1": True, "M3": True})
assert not dommer.kan_navngis(d, {"M1": True, "M3": False})
assert not dommer.kan_navngis(d, {"M1": True})
# M5 alone is named by definition, and M6 needs no threshold
assert dommer.kan_navngis(_dommer(M5=Dom.BETINGELSER), {})
assert dommer.kan_navngis(_dommer(M6=Dom.BETINGELSER), {})
assert dommer.kan_navngis(_dommer(), {})
def test_felt_er_ett_av_M1_til_M5_som_ikke_holder_eller_negativ_median() -> None:
assert dommer.er_felt(_dommer(M5=Dom.HOLDER_IKKE), 1.0)
assert dommer.er_felt(_dommer(), -1.0)
assert not dommer.er_felt(_dommer(M6=Dom.HOLDER_IKKE), 0.0)

View file

@ -1,4 +1,4 @@
"""The run over the draws (chapter 11; clarifications 95 to 103).
"""The run over the draws (chapter 11; clarifications 95 to 111).
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.
@ -10,19 +10,21 @@ does not start within the final year 2060.
from __future__ import annotations
import dataclasses
import math
import statistics
from typing import TYPE_CHECKING
import pytest
from tokenfabrikker import dommer, eierskap, nivaaisert, skala
from tokenfabrikker import dommer, eierskap, nivaaisert, skala, terskler
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.terskler import Pristerskel, Retning, Rute, Terskel
from tokenfabrikker.utbygging import Kraft, Losning
if TYPE_CHECKING:
@ -409,17 +411,17 @@ def test_dommene_paa_oppdiktede_trekninger_henger_sammen_med_utfallene(
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)
assert dommer.persentil(x, 0.1) == pytest.approx(1.3)
assert dommer.persentil(x, 0.9) == pytest.approx(3.7)
assert dommer.persentil(x, 0.5) == statistics.median(x) == 2.5
assert (dommer.persentil(x, 0.0), dommer.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
assert dommer.persentil([10.0, 20.0, 30.0, 40.0, 50.0], 0.25) == 20.0
assert dommer.persentil([7.0], 0.1) == dommer.persentil([7.0], 0.9) == 7.0
with pytest.raises(ValueError, match="at least one value"):
kj.persentil([], 0.5)
dommer.persentil([], 0.5)
with pytest.raises(ValueError, match="between 0 and 1"):
kj.persentil([1.0], 10.0)
dommer.persentil([1.0], 10.0)
def test_tidslinjen_over_trekningene_har_med_baner_som_ikke_lar_seg_bygge() -> None:
@ -529,3 +531,326 @@ def test_de_seks_scenarioene_og_stigen_er_de_forhaandsregistrerte() -> None:
]
assert [s.teller for s in kj.SCENARIOER] == [False, True, False, False, False, False]
assert len({s.navn for s in kj.SCENARIOER}) == 6
# ------------------------------ thresholds, conditions and indices over the draws
X10 = [float(v) for v in range(1, 11)]
"""An invented quantity over ten draws: its 10th percentile is 1.9 and its 90th 9.1."""
def _ti_trekninger_der_A_er_positiv_til_og_med(grense: int) -> Kjoring:
"""Ten draws of A on step 5: net present value positive in the first ``grense`` of them."""
return _kjoring([{(Losning.A, 5): _alle(_u(1.0 if j < grense else -1.0))} for j in range(10)])
def test_del_I_avgjores_med_tersklene() -> None:
"""M1 is positive in 7 of 10 draws: at most 8 of the quantity gives 7 of 8."""
kjoring = _ti_trekninger_der_A_er_positiv_til_og_med(7)
M5 = {Losning.A: Dom.HOLDER}
uten = kj.sett_dommer(kjoring, M5)
assert uten.del_I is Dom.BETINGELSER
assert uten.scenarioer[NORM.navn].betingelser is None
assert not uten.scenarioer[NORM.navn].del_I_avgjort
storrelser = {"x": X10, "z": [11.0 - v for v in X10]}
d = kj.sett_dommer(
kjoring, M5, storrelser=storrelser, status={"x": "kilde", "z": "åpen forutsetning"}
)
norm = d.scenarioer[NORM.navn]
assert (d.valg.trinn, d.valg.grunnlag) == (5, Grunnlag.TRINN_25)
assert (d.del_I, norm.del_I_avgjort) == (Dom.BETINGELSER, True)
assert norm.betingelser is not None
b = norm.betingelser[Losning.A]
assert (b.felt, b.maal, b.kan_navngis, b.bare_skalaen_mangler) == (False, ("M1",), True, False)
assert b.terskler == {
"M1": (
Terskel("x", Retning.HOYST, 8.0, 0.8, 0.875, teller=True),
Terskel("z", Retning.MINST, 3.0, 0.8, 0.875, teller=False),
)
}
# the same threshold in a quantity without a source does not count: part I does not hold
d = kj.sett_dommer(
kjoring,
M5,
storrelser=storrelser,
status={"x": "modellvalg", "z": "åpen forutsetning"},
)
norm = d.scenarioer[NORM.navn]
assert d.del_I is Dom.HOLDER_IKKE
assert norm.betingelser is not None
assert not norm.betingelser[Losning.A].kan_navngis
assert [t.teller for t in norm.betingelser[Losning.A].terskler["M1"]] == [False, False]
# and with a quantity that says nothing there is no threshold at all
d = kj.sett_dommer(kjoring, M5, storrelser={"c": [1.0] * 10}, status={"c": "kilde"})
assert d.del_I is Dom.HOLDER_IKKE
norm = d.scenarioer[NORM.navn]
assert norm.betingelser is not None
assert norm.betingelser[Losning.A].terskler == {"M1": ()}
def test_M5_under_betingelser_er_navngitt_og_M6_trenger_ingen_terskel() -> None:
"""Clarifications 93 and 109: A has M5 and M6 under conditions and no threshold anywhere."""
kjoring = _kjoring([{(Losning.A, 5): _alle(_u(M6=0.1))} for _ in range(10)])
d = kj.sett_dommer(
kjoring, {Losning.A: Dom.BETINGELSER}, storrelser={"x": X10}, status={"x": "kilde"}
)
norm = d.scenarioer[NORM.navn]
assert (d.valg.trinn, d.valg.grunnlag) == (5, Grunnlag.TRINN_5)
assert norm.per_trinn[5][Losning.A].maal["M6"].dom is Dom.BETINGELSER
assert d.del_I is Dom.BETINGELSER
assert norm.betingelser is not None
b = norm.betingelser[Losning.A]
assert (b.maal, b.kan_navngis, b.terskler) == (("M5",), True, {"M6": ()})
# with M5 holding only the scale is missing (clarification 103 g)
d = kj.sett_dommer(
kjoring, {Losning.A: Dom.HOLDER}, storrelser={"x": X10}, status={"x": "kilde"}
)
norm = d.scenarioer[NORM.navn]
assert d.del_I is Dom.BETINGELSER
assert norm.betingelser is not None
assert norm.betingelser[Losning.A].bare_skalaen_mangler
def test_tersklene_for_M7_vises_og_endrer_ingenting() -> None:
"""A is best in the first 4 of 10 draws: at most 8 of the quantity gives 4 of 8."""
def trekning(j: int) -> dict[tuple[Losning, int], dict[str, Utfall] | None]:
return {
(Losning.A, 5): _alle(_u(1.0 if j < 4 else 0.2)),
(Losning.C, 5): _alle(_u(0.5)),
}
kjoring = _kjoring([trekning(j) for j in range(10)])
M5 = dict.fromkeys((Losning.A, Losning.C), Dom.HOLDER)
d = kj.sett_dommer(kjoring, M5, storrelser={"x": X10}, status={"x": "åpen forutsetning"})
norm = d.scenarioer[NORM.navn]
assert norm.M7[5].dom is Dom.BETINGELSER
assert norm.terskler_M7 == (Terskel("x", Retning.HOYST, 8.0, 0.8, 0.5, teller=False),)
assert (d.del_I, d.del_II) == (Dom.HOLDER, Dom.BETINGELSER)
assert kj.sett_dommer(kjoring, M5).scenarioer[NORM.navn].terskler_M7 == ()
def test_tersklene_trenger_verdier_og_status_for_hver_trekning() -> None:
kjoring = _ti_trekninger_der_A_er_positiv_til_og_med(7)
M5 = {Losning.A: Dom.HOLDER}
with pytest.raises(ValueError, match="both the drawn values and the status"):
kj.sett_dommer(kjoring, M5, storrelser={"x": X10})
with pytest.raises(ValueError, match="one value per draw"):
kj.sett_dommer(kjoring, M5, storrelser={"x": [1.0]}, status={"x": "kilde"})
def test_tallene_ved_siden_av_M6_over_trekningene_som_har_verdi() -> None:
"""Clarification 103 c. One draw cannot be built, one has no year of stable operation."""
utfall: list[Utfall | None] = [
None,
_u(M6=None),
dataclasses.replace(_u(M6=0.1), M6_2050=0.2),
dataclasses.replace(_u(M6=0.3), M6_2050=0.4),
]
side = kj.ved_siden_av_m6(utfall)
assert side["snitt"] == side["median av ti aar"]
assert side["snitt"].antall == 2
assert side["snitt"].median == pytest.approx(0.2)
assert side["snitt"].persentiler == pytest.approx((0.12, 0.28))
assert side["2050"].antall == 2
assert side["2050"].median == pytest.approx(0.3)
assert side["2050"].persentiler == pytest.approx((0.22, 0.38))
# the peak year has a value for every path that can be built: 0, 0.1 and 0.3
assert (side["toppaar"].antall, side["toppaar"].median) == (3, 0.1)
assert side["toppaar"].persentiler == pytest.approx((0.02, 0.26))
ingen = kj.ved_siden_av_m6([None, None])
assert all(x == kj.Sidetall(antall=0, median=None, persentiler=None) for x in ingen.values())
def test_utfallene_indeksene_gis_for() -> None:
"""Four draws of A and C on step 5; A cannot be built in the last."""
a: list[Utfall | None] = [_u(2.0), _u(1.0, M3=0.2, M6=0.01), _u(-1.0, S42=-1.0, M4=False), None]
kjoring = _kjoring(
[
{(Losning.A, 5): None if u is None else _alle(u), (Losning.C, 5): _alle(_u(1.5))}
for u in a
]
)
y = kj.utfall_for_indeksene(kjoring, Losning.A, 5)
assert y == {
"NNV": [2.0, 1.0, -1.0, None],
"byggbar": [1.0, 1.0, 1.0, 0.0],
"M1 holder": [1.0, 1.0, 0.0, 0.0],
"M2 holder": [1.0, 1.0, 0.0, 0.0],
"M3 holder": [1.0, 0.0, 1.0, 0.0],
"M4 holder": [1.0, 1.0, 0.0, 0.0],
"M6 holder": [1.0, 0.0, 1.0, 0.0],
"M3 holder ikke": [0.0, 1.0, 0.0, 0.0],
"M4 holder ikke": [0.0, 0.0, 1.0, 0.0],
# a path that cannot be built counts as under 5 % in M6
"M6 holder ikke": [0.0, 1.0, 0.0, 1.0],
"M7": [1.0, 0.0, 0.0, 0.0],
}
assert "M7" not in kj.utfall_for_indeksene(kjoring, Losning.C, 5)
indekser = kj.sobol_indekser(kjoring, {"x": [1.0, 2.0, 3.0, 4.0]}, Losning.A, 5)
assert set(indekser) == set(y)
# two classes of two draws: M1 follows the class exactly, M3 not at all
assert indekser["M1 holder"] == {"x": 1.0}
assert indekser["M3 holder"] == {"x": 0.0}
# the net present value among the three draws that can be built. With three draws and
# two classes the class is floor(2 r / 3): {2, 1} with the average 1.5, and {-1}
snitt = 2.0 / 3.0
mellom = 2 * (1.5 - snitt) ** 2 + (-1.0 - snitt) ** 2
total = (2.0 - snitt) ** 2 + (1.0 - snitt) ** 2 + (-1.0 - snitt) ** 2
assert indekser["NNV"]["x"] == pytest.approx(mellom / total)
assert kj.sobol_indekser(kjoring, {"x": [1.0, 2.0, 3.0, 4.0]}, Losning.C, 5)["M1 holder"] == {
"x": None
}
def test_flatene_leses_av_utfallene() -> None:
"""Four draws; A cannot be built in the second. Two of the 25 cells are filled per pair."""
a: list[Utfall | None] = [
dataclasses.replace(_u(2.0), c_snitt=300.0),
None,
dataclasses.replace(_u(-1.0), c_snitt=500.0),
dataclasses.replace(_u(4.0), c_snitt=400.0),
]
kjoring = _kjoring([{(Losning.A, 5): None if u is None else _alle(u)} for u in a])
rho = [0.05, 0.05, 0.09, 0.09]
kost = [100.0, 100.0, 200.0, 200.0]
flate = kj.flate_over_trekningene(kjoring, rho, kost, Losning.A, 5)
assert flate[0][0] == Rute(antall=2, andel_positiv=0.5, median=-math.inf)
assert flate[2][2] == Rute(antall=2, andel_positiv=0.5, median=1.5)
assert sum(rute.antall for rad in flate for rute in rad) == 4
# the competitor's price against the Norwegian cost, among the three that can be built:
# classes 0, 1 and 3 of five for both, since class is floor(5 r / 3)
antall, flate = kj.kraftprisflate(kjoring, [800.0, 850.0, 900.0, 950.0], Losning.A, 5)
assert antall == 3
assert flate[0][0] == Rute(antall=1, andel_positiv=1.0, median=2.0)
assert flate[1][3] == Rute(antall=1, andel_positiv=0.0, median=-1.0)
assert flate[3][1] == Rute(antall=1, andel_positiv=1.0, median=4.0)
uten_kost = _kjoring([{(Losning.A, 5): _alle(_u())}])
with pytest.raises(ValueError, match="cost of Norwegian power"):
kj.kraftprisflate(uten_kost, [800.0], Losning.A, 5)
# ------------------------------------------------ the price threshold, through the model
def test_prisfaktoren_en_gir_de_samme_tallene_til_siste_siffer(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
for losning in Losning:
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=2)
uten = ks.regn_program(inn, losning, plan, Knapphet.VARER, dim=dim)
med = ks.regn_program(inn, losning, plan, Knapphet.VARER, dim=dim, prisfaktor=1.0)
assert med.NNV == uten.NNV
assert kj.nnv_med_prisfaktor(
inn, losning=losning, trinn=2, knapphet=Knapphet.VARER, k=1.0
) == (uten.NNV)
with pytest.raises(ValueError, match="cannot be negative"):
ks.regn_program(inn, losning, plan, Knapphet.VARER, dim=dim, prisfaktor=-0.1)
def test_netto_naaverdi_avtar_ikke_med_prisen_og_faktoren_er_som_et_bortfall(
oppdiktet: LagInndata,
) -> None:
"""17.3: a loss d for every vintage is the price times 1 - eps_d d. Here eps_d is one."""
inn = oppdiktet()
for losning in Losning:
dim = ks.dimensjoner(inn, losning)
plan = ks.lag_plan(inn, losning, dim, N_anlegg=2)
def nnv(k: float, losning: Losning = losning) -> float:
verdi = kj.nnv_med_prisfaktor(
inn, losning=losning, trinn=2, knapphet=Knapphet.NORMALISERING, k=k
)
assert verdi is not None
return verdi
rekke = [nnv(k) for k in (0.0, 0.5, 0.8, 1.0, 1.3, 2.0, 5.0)]
assert rekke == sorted(rekke)
assert rekke[0] < rekke[-1]
med_bortfall = ks.regn_program(
inn, losning, plan, Knapphet.NORMALISERING, dim=dim, bortfall=ks.fast_bortfall(0.2)
)
assert nnv(0.8) == pytest.approx(med_bortfall.NNV, rel=1e-12)
# the avoided emissions follow the capacity sold, not the price
dobbel = ks.regn_program(
inn, losning, plan, Knapphet.NORMALISERING, dim=dim, prisfaktor=2.0
)
assert dobbel.mu_d.andel(2040) == 1.0
assert dobbel.mu_d(2040) == 2.0
def test_pristerskelen_gjennom_modellen(oppdiktet: LagInndata) -> None:
"""Four made-up draws; the median at the threshold is not negative, and negative just below."""
trekninger = _trekninger(oppdiktet)
for losning in (Losning.A, Losning.C, Losning.T_F):
funnet = kj.pristerskel_for_losning(trekninger, losning, 1, NORM)
assert funnet.k is not None
def median(k: float, losning: Losning = losning) -> float:
return dommer.median(
[
kj.nnv_med_prisfaktor(
inn, losning=losning, trinn=1, knapphet=Knapphet.NORMALISERING, k=k
)
for inn in trekninger
]
)
assert median(funnet.k) >= 0
assert funnet.k == 0.0 or median(funnet.k - terskler.K_TOLERANSE) < 0
# shared out over processes the same factors are tried, and the answer is the same
en = kj.pristerskel_for_losning(trekninger, Losning.C, 1, NORM)
assert kj.pristerskel_for_losning(trekninger, Losning.C, 1, NORM, prosesser=2) == en
with pytest.raises(ValueError, match="price scenarios on the main path"):
kj.pristerskel_for_losning(trekninger, Losning.C, 1, LAVT)
with pytest.raises(ValueError, match="at least one draw"):
kj.pristerskel_for_losning([], Losning.C, 1, NORM)
def test_pristerskelen_finnes_ikke_naar_halvparten_ikke_lar_seg_bygge(
oppdiktet: LagInndata,
) -> None:
"""Step 3 of the slow nuclear path cannot be built; with two of four such draws: no median."""
trekninger = [oppdiktet(), oppdiktet(p_v=3000.0), *[oppdiktet(n_reaktor=100.0)] * 2]
assert kj.pristerskel_for_losning(trekninger, Losning.A, 3, NORM) == Pristerskel(
k=None, uten_median=True
)
def test_prisflaten_gir_terskelen_per_klasse_av_reaktorkostnaden(oppdiktet: LagInndata) -> None:
"""Ten made-up draws in five classes of two; each class has the threshold of its own draws."""
kost = [80e6, 90e6, 100e6, 110e6, 120e6, 130e6, 140e6, 150e6, 160e6, 170e6]
trekninger = [oppdiktet(c_N_ref=c) for c in kost]
flate = kj.prisflate(trekninger, kost, Losning.A, 1, NORM)
assert [None if p is None else (p.antall, p.c_N_ref) for p in flate] == [
(2, 85e6),
(2, 105e6),
(2, 125e6),
(2, 145e6),
(2, 165e6),
]
forste = kj.pristerskel_for_losning(trekninger[:2], Losning.A, 1, NORM)
assert flate[0] is not None
assert flate[0].terskel == forste
terskel = [p.terskel.k for p in flate if p is not None]
assert all(k is not None for k in terskel)
# a dearer reactor needs a higher price
assert terskel == sorted(terskel) # type: ignore[type-var]
with pytest.raises(ValueError, match="reactor cost of every draw"):
kj.prisflate(trekninger, kost[:3], Losning.A, 1, NORM)
def test_kraftkostnaden_i_utfallet_er_snittet_over_aargangsleddene(oppdiktet: LagInndata) -> None:
inn = oppdiktet()
bane = kj.regn_bane(inn, Losning.C, 2, (NORM,))
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, dim=dim)
ledd = nivaaisert.kraftkostnad(inn, res, bedrift=True).aarganger
vekter = [(1.0 + inn["rho_D"]) ** -(a.t_v - plan.T_0) for a in ledd]
snitt = sum(w * a.c_a for w, a in zip(vekter, ledd, strict=True)) / sum(vekter)
assert bane.utfall[NORM.navn].c_snitt == pytest.approx(snitt, rel=1e-12)
assert min(a.c_a for a in ledd) <= snitt <= max(a.c_a for a in ledd)
assert kj.lcoc_v_2025(inn) == ks.regnekraftpris(inn, Knapphet.VARER, 2040).lcoc_v(2025)

254
tests/test_terskler.py Normal file
View file

@ -0,0 +1,254 @@
"""Thresholds and Sobol indices (chapter 16, clarifications 105 to 111).
Invented values and outcomes only, with the answers computed by hand. Nothing here says
anything about the hypothesis.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
import numpy as np
import pytest
from tokenfabrikker import sobol, terskler
from tokenfabrikker.terskler import Pristerskel, Retning, Rute, Terskel
if TYPE_CHECKING:
from collections.abc import Callable
X10 = [float(v) for v in range(1, 11)]
"""Ten draws of one quantity: the 10th percentile is 1.9 and the 90th 9.1."""
# ------------------------------------------------------------ the price threshold
def _teller(f: Callable[[float], float]) -> tuple[Callable[[float], float], list[float]]:
kall: list[float] = []
def g(k: float) -> float:
kall.append(k)
return float(f(k))
return g, kall
@pytest.mark.parametrize(
("f", "rot"),
[
(lambda k: 10.0 * k - 25.0, 2.5),
(lambda k: 3.0 * k - 0.9, 0.3),
(lambda k: min(k - 0.3, 0.1 * (k - 0.3)), 0.3),
(lambda k: -1.0 if k < 3.7 else 1.0, 3.7),
(lambda k: k**3 - 50.0, 50.0 ** (1 / 3)),
(lambda k: k - 99.5, 99.5),
],
)
def test_pristerskelen_er_laveste_faktor_med_median_som_ikke_er_negativ(
f: Callable[[float], float], rot: float
) -> None:
g, kall = _teller(f)
funnet = terskler.pristerskel(g)
assert funnet.k is not None
assert not funnet.over_maks
assert not funnet.uten_median
assert rot <= funnet.k <= rot + terskler.K_TOLERANSE
assert f(funnet.k) >= 0
assert f(funnet.k - terskler.K_TOLERANSE) < 0
# never more than two runs per halving of the bracket
assert len(kall) <= 60
def test_pristerskelen_finner_en_rett_linje_paa_faa_kjoringer() -> None:
g, kall = _teller(lambda k: 10.0 * k - 25.0)
terskler.pristerskel(g)
# 1, 2 and 4 bracket it; the line and the point just below close the bracket
assert kall[:3] == [1.0, 2.0, 4.0]
assert len(kall) == 5
def test_pristerskelen_ved_flat_median_er_det_laveste_punktet() -> None:
"""The median is zero from 2 and up: the threshold is the lowest such factor."""
funnet = terskler.pristerskel(lambda k: min(0.0, k - 2.0))
assert funnet.k is not None
assert 2.0 <= funnet.k <= 2.0 + terskler.K_TOLERANSE
def test_pristerskelen_er_null_naar_medianen_ikke_er_negativ_uten_inntekt() -> None:
assert terskler.pristerskel(lambda k: k) == Pristerskel(k=0.0)
assert terskler.pristerskel(lambda _k: 5.0) == Pristerskel(k=0.0)
def test_pristerskelen_har_ingen_verdi_over_hundre_eller_uten_median() -> None:
assert terskler.pristerskel(lambda k: k - 100.5) == Pristerskel(k=None, over_maks=True)
assert terskler.pristerskel(lambda _k: -math.inf) == Pristerskel(k=None, uten_median=True)
# exactly at the upper end it is found
funnet = terskler.pristerskel(lambda k: -1.0 if k < 100.0 else 0.0)
assert funnet.k == 100.0
def test_kontrollen_mot_kontraktsprisene_bruker_medianen() -> None:
"""The median cost is 20 and the highest contract price 50: k may be at most 2.5."""
lcoc = [10.0, 30.0, 20.0]
assert terskler.innenfor_kontraktsprisene(2.5, lcoc, 50.0) == (True, 2 / 3)
assert terskler.innenfor_kontraktsprisene(2.6, lcoc, 50.0) == (False, 1 / 3)
assert terskler.innenfor_kontraktsprisene(0.0, lcoc, 50.0) == (True, 1.0)
# ----------------------------------------------------- a threshold in one quantity
def test_terskelen_er_den_minst_strenge_betingelsen_innenfor_spennet() -> None:
"""The target is met where x <= 6. At most 9: 6 of 9. At most 8: 6 of 8. At most 7: 6 of 7."""
oppfylt: list[bool | None] = [v <= 6 for v in X10]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) == (7.0, 0.7, 6 / 7)
# at least 2 covers 5 of 9, and it only gets worse
assert terskler.terskel(X10, oppfylt, Retning.MINST) is None
def test_terskelen_naar_andelen_svinger() -> None:
"""Met everywhere but at 1 and 6. At most 5 gives exactly 4 of 5; at least 2 gives 8 of 9."""
oppfylt: list[bool | None] = [v not in (1.0, 6.0) for v in X10]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) == (5.0, 0.5, 0.8)
assert terskler.terskel(X10, oppfylt, Retning.MINST) == (2.0, 0.9, 8 / 9)
def test_terskelen_ligger_aldri_utenfor_10_og_90_persentilen() -> None:
"""Met only at 1: «at most 1» would hold, but 1 is below the 10th percentile, 1.9."""
oppfylt: list[bool | None] = [v == 1.0 for v in X10]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) is None
# met everywhere but at 10: «at most 9» is the least strict candidate, not «at most 10»
oppfylt = [v != 10.0 for v in X10]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) == (9.0, 0.9, 1.0)
def test_en_bane_som_ikke_lar_seg_bygge_oppfyller_ikke_vilkaaret() -> None:
"""Not buildable at 7: at most 7 is then 6 of 7 with the draw in the denominator."""
oppfylt: list[bool | None] = [True, True, True, True, True, True, None, False, False, False]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) == (7.0, 0.7, 6 / 7)
oppfylt = [True, True, True, True, True, None, None, False, False, False]
# at most 7: 5 of 7; at most 6: 5 of 6
assert terskler.terskel(X10, oppfylt, Retning.HOYST) == (6.0, 0.6, 5 / 6)
def test_like_verdier_er_en_kandidat() -> None:
"""Three draws at 1, three at 2 and four at 3: the percentiles are 1 and 3."""
x = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0]
oppfylt: list[bool | None] = [True, True, True, True, True, False, False, False, False, False]
assert terskler.terskel(x, oppfylt, Retning.HOYST) == (2.0, 0.6, 5 / 6)
assert terskler.terskel(x, oppfylt, Retning.MINST) is None
# a quantity with the same value in every draw has one candidate, which covers all
assert terskler.terskel([5.0] * 10, oppfylt, Retning.HOYST) is None
assert terskler.terskel([5.0] * 10, [True] * 8 + [False] * 2, Retning.MINST) == (5.0, 1.0, 0.8)
def test_grensen_i_M7_er_halvparten() -> None:
"""Met at 2, 4, 6 and 8: never 80 % of the draws up to a candidate; half of them up to 8."""
oppfylt: list[bool | None] = [v in (2.0, 4.0, 6.0, 8.0) for v in X10]
assert terskler.terskel(X10, oppfylt, Retning.HOYST) is None
assert terskler.terskel(X10, oppfylt, Retning.HOYST, grense=0.5) == (8.0, 0.8, 0.5)
def test_terskelen_trenger_en_verdi_per_trekning() -> None:
with pytest.raises(ValueError, match="one value and one outcome per draw"):
terskler.terskel([1.0, 2.0], [True], Retning.HOYST)
with pytest.raises(ValueError, match="at least one draw"):
terskler.terskel([], [], Retning.HOYST)
def test_terskler_for_et_maal_teller_bare_for_storrelser_med_kilde() -> None:
oppfylt: list[bool | None] = [v <= 6 for v in X10]
storrelser = {"a": X10, "b": [11.0 - v for v in X10], "c": [1.0] * 10}
status = {"a": "kilde", "b": "åpen forutsetning", "c": "kilde"}
assert terskler.terskler_for_maal(storrelser, status, oppfylt) == (
Terskel("a", Retning.HOYST, 7.0, 0.7, 6 / 7, teller=True),
Terskel("b", Retning.MINST, 4.0, 0.7, 6 / 7, teller=False),
)
# ------------------------------------------------------------ the threshold surfaces
def test_flaten_gir_antall_andel_og_median_per_rute() -> None:
"""Two classes per axis: draws 1 and 2 in the first cell, 3 and 4 in the last."""
x = [1.0, 2.0, 3.0, 4.0]
y = [10.0, 10.0, 20.0, 20.0]
flate = terskler.flate(x, y, [5.0, None, -1.0, 3.0], Q=2)
tom = Rute(antall=0, andel_positiv=None, median=None)
assert flate == (
(Rute(antall=2, andel_positiv=0.5, median=-math.inf), tom),
(tom, Rute(antall=2, andel_positiv=0.5, median=1.0)),
)
with pytest.raises(ValueError, match="the same draws"):
terskler.flate(x, y, [1.0])
def test_flaten_har_fem_klasser_per_akse() -> None:
x = [float(j % 5) for j in range(25)]
y = [float(j // 5) for j in range(25)]
flate = terskler.flate(x, y, [1.0] * 25)
assert len(flate) == 5
assert all(
rute == Rute(antall=1, andel_positiv=1.0, median=1.0) for rad in flate for rute in rad
)
# ----------------------------------------------------------------- the Sobol indices
def test_antall_klasser_er_halve_kvadratroten() -> None:
assert [sobol.antall_klasser(N) for N in (1, 16, 35, 36, 100, 9999, 10000)] == [
2,
2,
2,
3,
5,
49,
50,
]
def test_klassen_folger_antall_trekninger_med_lavere_verdi() -> None:
assert sobol.klasser([5.0, 1.0, 3.0, 1.0], 2) == [1, 0, 1, 0]
assert sobol.klasser([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 3) == [0, 0, 1, 1, 2, 2]
# equal values share a class; 30 % zeros and 70 % ones get a class each with ten classes
x = [0.0] * 3 + [1.0] * 7
assert sobol.klasser(x, 10) == [0] * 3 + [3] * 7
assert sobol.klasser([7.0] * 4, 2) == [0] * 4
def test_indeksen_er_variansen_mellom_klassene_over_variansen() -> None:
x = [1.0, 2.0, 3.0, 4.0]
assert sobol.indeks(x, [0.0, 0.0, 1.0, 1.0]) == 1.0
assert sobol.indeks(x, [0.0, 1.0, 0.0, 1.0]) == 0.0
# averages 1.5 and 4.5 around 3: 2 * 2.25 + 2 * 2.25 = 9, over 4 + 1 + 0 + 9 = 14
assert sobol.indeks(x, [1.0, 2.0, 3.0, 6.0]) == pytest.approx(9 / 14)
# the order of the draws does not matter
assert sobol.indeks([4.0, 1.0, 3.0, 2.0], [6.0, 1.0, 3.0, 2.0]) == pytest.approx(9 / 14)
def test_indeksen_har_ingen_verdi_naar_utfallet_er_likt_i_alle_trekningene() -> None:
assert sobol.indeks([1.0, 2.0, 3.0], [0.1, 0.1, 0.1]) is None
with pytest.raises(ValueError, match="one value and one outcome per draw"):
sobol.indeks([1.0], [])
def test_indeksene_gis_blant_trekningene_som_har_utfallet() -> None:
"""The third draw has no outcome: the index is that of the other four."""
storrelser = {"a": [1.0, 2.0, 9.0, 3.0, 4.0], "b": [1.0, 1.0, 1.0, 1.0, 1.0]}
y = [1.0, 2.0, None, 3.0, 6.0]
assert sobol.indekser(storrelser, y) == {"a": pytest.approx(9 / 14), "b": 0.0}
assert sobol.indekser(storrelser, [None] * 5) == {"a": None, "b": None}
def test_forventningen_uten_virkning_er_om_lag_M_minus_1_over_N_minus_1() -> None:
"""300 invented quantities without any effect on an invented outcome, 400 draws each."""
assert sobol.forventning_uten_virkning(10_000) == 49 / 9999
rng = np.random.default_rng(7)
N = 400
y = rng.normal(size=N).tolist()
indekser = [sobol.indeks(rng.normal(size=N).tolist(), y) for _ in range(300)]
snitt = math.fsum(i for i in indekser if i is not None) / 300
assert sobol.forventning_uten_virkning(N) == 9 / 399
assert snitt == pytest.approx(9 / 399, abs=0.002)

View file

@ -236,9 +236,7 @@ def test_del_I_holder_ikke_forst_naar_alle_fem_er_felt() -> None:
}
median = dict.fromkeys(per_losning, 5.0)
assert dommer.del_I(per_losning, median, _PAA_25) is Dom.BETINGELSER
assert (
dommer.del_I(per_losning, median, _PAA_25, betingelser_kan_navngis=False) is Dom.HOLDER_IKKE
)
assert dommer.del_I(per_losning, median, _PAA_25, har_terskel={}) is Dom.HOLDER_IKKE
median[Losning.T_K] = -1.0
assert dommer.del_I(per_losning, median, _PAA_25) is Dom.HOLDER_IKKE
# the order the solutions stand in does not matter