feat(kart): the map from equation to function, generated from the code (clarification 131)

Every S-number of the specification points to the functions named after it
and, where it is put together over the years or the draws, to the functions
that do so. A test holds the stored map against the code.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-13 20:53:31 +01:00
commit aff6624c5e
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
3 changed files with 538 additions and 0 deletions

64
modell/kart.md Normal file
View file

@ -0,0 +1,64 @@
# Kart fra ligning til funksjon
Kartet viser, for hvert S-nummer i spesifikasjonen (`modell/spesifikasjon.md`), funksjonene i koden som regner ligningen: først funksjonene som har nummeret i navnet (`s9_…`), så funksjonene som setter nummeret sammen over årene eller over trekningene, etter lista `SAMMENSATT` i `src/tokenfabrikker/kart.py` (avklaring 131).
Fila er laget av koden og rettes ikke for hånd. `PYTHONPATH=src .venv/bin/python -m tokenfabrikker.kart lag` skriver den, og `PYTHONPATH=src .venv/bin/python -m tokenfabrikker.kart kontroll` sier om den er lik den koden lager. Beskrivelsen er første linje av funksjonens egen dokumentasjon, på engelsk som i koden.
54 ligninger, 98 funksjoner med nummeret i navnet og 47 oppføringer for funksjoner som setter sammen.
| Ligning | Funksjon | Slag | Første linje av beskrivelsen |
|---|---|---|---|
| S1 | `ligninger.s1_crf` | ligning | S1: capital recovery factor, per year. CRF(0, L) = 1/L. |
| S2 | `ligninger.s2_laeringseksponent`<br>`ligninger.s2_investering_per_mw` | ligning<br>ligning | S2: b = -log2(1 - ell). ``ell`` is the learning rate per doubling and may be negative.<br>S2: overnight investment per MW for unit number ``n`` of the Norwegian series, kr/MW. |
| S3 | `ligninger.s3_byggetidsfaktor`<br>`ligninger.s3_investering_med_renter` | ligning<br>ligning | S3: interest during construction as a factor on the overnight cost.<br>S3: levelised-form investment for one unit, with interest during construction, kr. |
| S4 | `ligninger.s4_kapasitetsfaktor`<br>`ligninger.s4_kapasitetsfaktor_smaa_enheter`<br>`ligninger.s4_energi_kjernekraft` | ligning<br>ligning<br>ligning | S4 (text): the drawn capacity factor, capped at (1 - o_p)(1 - o_f).<br>S4 (text): capacity factor for small units on the grid (B'), KF (1 - o_f^A)/(1 - o_f).<br>S4: yearly production of a plant with ``N_u`` units of ``P_u`` MW, MWh per year. |
| S5 | `ligninger.s5_fast_drift`<br>`ligninger.s5_lcoe_kjernekraft` | ligning<br>ligning | S5: fixed operation per MW for a unit of ``P_u`` MW, f_N (P_u/P_ref)^nu_f, kr/MW per year.<br>S5: cost per MWh for a grid-connected plant with identical units, kr/MWh. |
| S6 | `ligninger.s6_ulykkeskostnad_per_hendelse`<br>`ligninger.s6_ulykkeskostnad` | ligning<br>ligning | S6: K_U(P_u) = K_U min(1, P_u/P_ref), kr per event. ``K_U`` in kr (the file's mrd. kr).<br>S6: expected accident cost not covered by insurance, kr/MWh. |
| S7 | `ligninger.s7_enhetsstorrelse`<br>`ligninger.s7_enheter_som_maa_gaa` | ligning<br>ligning | S7: unit size and number of units that must run in solution A.<br>S7: m = ceil(PUE * P_IT / P_u), the units that must run for a given unit size. |
| S8 | `ligninger.s8_planlagt_ute`<br>`ligninger.s8_uavhengig_utfallsrate`<br>`ligninger.s8_tilgjengelighet`<br>`ligninger.s8_reserveenheter`<br>`ligninger.s8_antall_enheter` | ligning<br>ligning<br>ligning<br>ligning<br>ligning | S8: n_p, the smallest whole x (zero allowed) with x >= (m + r + x) o_p.<br>S8: o' = (1 - beta_F) o_f^A, the part of forced outage that hits units one by one.<br>S8: A_uavh(m, r), the probability that at least ``m`` of ``m + r`` units run.<br>S8: r, the smallest number of reserve units with A_uavh(m, r) >= A_krav.<br>S8: N_u = m + r + n_p, all units in the plant. |
| S9 | `ligninger.s9_kraftkostnad_dedikert` | ligning | S9: cost per MWh delivered to the data centre in solution A, kr/MWh. |
| S10 | `ligninger.s10_energi_datasenter` | ligning | S10: E_D = 8760 * lam * PUE * P_IT, yearly energy to the data centre, MWh per year. |
| S11 | `ligninger.s11_nettkostnad`<br>`ligninger.s11_kraftkostnad_nett` | ligning<br>ligning | S11: H_a, yearly cost of new grid capacity for one facility, kr/year.<br>S11: cost per MWh to the data centre in a grid solution (B, B', C, R), kr/MWh. |
| S12 | `ligninger.s33_tidligste_tidspunkt_nett`<br>`ligninger.s39_portefolje_C`<br>`ligninger.s39_torraarsenergi_av_takt`<br>`utbygging.kraftrom_fornybar`<br>`kontantstrom.lag_plan` | setter sammen<br>setter sammen<br>setter sammen<br>setter sammen<br>setter sammen | S33 and S12 (C, R): T_0 + tau_nett, a point in time, not yet a year.<br>S39 and S12 (C): the portfolio that gives ``E_torr`` MWh in a dry year.<br>S12, S22 and S39 (C): dry-year production of ``E_normal`` MWh built in the fixed order.<br>S22, second term accumulated from T_0 (C): facilities the renewable power has room for.<br>The build-out of a path with ``N_anlegg`` facilities (S22, S33; chapter 17.1 for T). |
| S13 | `ligninger.s13_it_kostnad` | ligning | S13: c_H(t_v) = c_H0 (1 + gamma_H)^(min(t_v, 2035) - 2025), kr per MW IT. |
| S14 | `ligninger.s14_snittlast` | ligning | S14: lam = lam_0 + (1 - lam_0) mu_u. Used only in the token control (chapter 3.3). |
| S15 | `ligninger.s15_lcoc`<br>`nivaaisert.kraftkostnad` | ligning<br>setter sammen | S15: yearly cost of compute per MW IT, kr per MW IT per year.<br>The levelised cost of power and compute for the path in ``res``. |
| S16 | `ligninger.s16_inntekt` | ligning | S16: yearly revenue of one vintage, mu * Gamma * y * P_IT, kr/year. |
| S17 | `ligninger.s17_kontraktspris_fra_spot` | ligning | S17: fixed yearly price equivalent to a spot path over the equipment's life. |
| S18 | `ligninger.s18_pris` | ligning | S18: price of compute, y = LCOC^v (1 + pi_g), kr per MW IT per year. |
| S19 | `ligninger.s19_margin`<br>`nivaaisert.kraftkostnad` | ligning<br>setter sammen | S19: the right-hand side of the accounting identity M_a = mu Gamma y - LCOC_a.<br>The levelised cost of power and compute for the path in ``res``. |
| S20 | `ligninger.s20_tokeninntekt` | ligning | S20: yearly revenue from selling tokens (control only), kr/year. |
| S21 | `ligninger.s21_kostnad_per_token` | ligning | S21: cost per million tokens (control only), kr per million tokens. |
| S22 | `ligninger.s22_reaktoreffekt_B`<br>`ligninger.s22_grense_reaktor`<br>`ligninger.s22_grense_fornybar`<br>`ligninger.s22_grense_brikker`<br>`utbygging.kraftrom_reaktor`<br>`utbygging.kraftrom_fornybar`<br>`utbygging.utbyggingsplan`<br>`utbygging.utbyggingsplan_trinnvis`<br>`kontantstrom.lag_plan` | ligning<br>ligning<br>ligning<br>ligning<br>setter sammen<br>setter sammen<br>setter sammen<br>setter sammen<br>setter sammen | S22 (text): P_G^N in B, the reactor capacity one facility needs, lam PUE P_IT / KF, MW.<br>S22, first term (A, B, B'): n_reaktor P_IT / P_G^N, MW IT per year.<br>S22, second term (C): g w_tort / (8760 lam PUE), MW IT per year.<br>S22, third term: s_brikker G_server - utskifting(t), MW IT per year.<br>S22, first term accumulated from T_0: how many facilities the reactors built have room for.<br>S22, second term accumulated from T_0 (C): facilities the renewable power has room for.<br>S22: the year each facility starts and the vintages it gets.<br>Chapter 17.1: the year each module of a path in solution T starts, and its vintages.<br>The build-out of a path with ``N_anlegg`` facilities (S22, S33; chapter 17.1 for T). |
| S23 | `ligninger.s23_netto_uttak`<br>`ligninger.s23_prisvirkning`<br>`kraftsystem.kraftaar`<br>`kraftsystem.relativ_prisvirkning`<br>`kontantstrom.regn_program` | ligning<br>ligning<br>setter sammen<br>setter sammen<br>setter sammen | S23: Delta Q = (1 - delta_V) Q_D - Q_G, new use from the grid minus new production, MWh.<br>S23: Delta p_z = m_v s_v [P_z(S_0 - Delta Q) - P_z(S_0)], kr/MWh.<br>S23, S24 and S38 for one year.<br>S23: Delta p_z / p_z^0 per price area, in a normal year or in the dry year.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S24 | `ligninger.s24_effektbalanse`<br>`kraftsystem.kraftaar`<br>`kontantstrom.regn_program` | ligning<br>setter sammen<br>setter sammen | S24: (Delta R, Delta R^-1), the capacity balance in the scarcest hour, MW.<br>S23, S24 and S38 for one year.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S25 | `ligninger.s25_velferd`<br>`kontantstrom.regn_program` | ligning<br>setter sammen | S25: Delta W = Delta p S_0, kr per year. ``Delta_p`` for all of Norway, ``S_0`` in MWh.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S26 | `ligninger.s26_diskontering_rundskriv`<br>`ligninger.s26_subsidieelement`<br>`ligninger.s26_netto_naaverdi`<br>`kontantstrom.regn_program` | ligning<br>ligning<br>ligning<br>setter sammen | Clarification 118 b: D_R(j), the circular's stepwise discount factor, j = t - T_0.<br>S26: SE = max(0, -present value of the project's net cash flow), kr.<br>S26: net present value for Norway against the zero alternative, kr.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S27 | `ligninger.s27_nettariff`<br>`ligninger.s27_kraftkostnad_bedrift_nett`<br>`ligninger.s27_kraftkostnad_bedrift_dedikert`<br>`ligninger.s27_margin_bedrift`<br>`nivaaisert.kraftkostnad` | ligning<br>ligning<br>ligning<br>ligning<br>setter sammen | Chapter 7: the grid tariff of one facility, kr per year.<br>Chapter 7: S11 as a business pays it, kr/MWh.<br>Chapter 7: S9 as a business pays it, kr/MWh: the electricity tax also applies off-grid.<br>S27: mu Gamma y - LCOC^bed per MW IT and year, kr. S27 holds when this is not negative.<br>The levelised cost of power and compute for the path in ``res``. |
| S28 | `ligninger.s28_avskrivning`<br>`ligninger.s28_realverdi`<br>`ligninger.s28_etter_framforing`<br>`ligninger.s28_naaverdi`<br>`ligninger.s28_restverdi`<br>`eierskap.naaverdi_etter_skatt` | ligning<br>ligning<br>ligning<br>ligning<br>ligning<br>setter sammen | Chapter 7: straight-line depreciation of one asset in year ``t``, kr.<br>Chapter 7: what a nominal amount fixed ``aar`` years ago is worth in constant kroner.<br>Chapter 7: the taxable amount per year when negative amounts are carried forward.<br>S28: the present value at T_0 of yearly amounts with index t - T_0, kr.<br>Clarification 62: what one facility is worth at the final year, kr at T_s.<br>S28: NV_e, the project's present value after tax with the cost of capital r_e, kr. |
| S29 | `ligninger.s29_kapitalkostnad`<br>`ligninger.s29_krav_for_skatt`<br>`eierskap.kapitalkostnad`<br>`eierskap.krav_for_skatt` | ligning<br>ligning<br>setter sammen<br>setter sammen | S29: the cost of capital of an ownership form, real, after tax.<br>Clarification 66: the real required return before tax, r_e / (1 - tau_s).<br>S29: r_e, real. With direct ownership it is the state's borrowing rate as drawn.<br>Clarification 66: the required return before tax the cost of compute is computed with. |
| S30 | `ligninger.s30_skatt`<br>`ligninger.s30_statens_kontantstrom`<br>`ligninger.s30_private_eiere`<br>`eierskap.eierresultat`<br>`kjoring.regn_eierformer`<br>`kjoring.eierformer_paa_trinnet` | ligning<br>ligning<br>ligning<br>setter sammen<br>setter sammen<br>setter sammen | S30: corporate tax and special tax per year, kr, for the project as one taxpayer.<br>S30: the state's net cash flow in a year with ownership form e, kr.<br>Clarification 64: the private owners' cash flow in a year, kr.<br>S29 and S30 for one ownership form.<br>S30 and the cost of compute per ownership form for one path in one draw.<br>The ownership forms for each solution on the step the verdicts are read on. |
| S31 | `ligninger.s31_nettobidrag`<br>`skala.overskudd_utover_avkastning`<br>`skala.skala` | ligning<br>setter sammen<br>setter sammen | S31: the yearly net contribution to Norway's income above normal return on capital, kr.<br>S31, the sum over the facilities of Y_k - K_k^drift - ann_k per year, kr.<br>S31 per year and M6 for the path in ``res``. |
| S32 | `ligninger.s32_utslipp`<br>`miljo.utslipp_livslop` | ligning<br>setter sammen | S32: life-cycle emissions in one year, tonnes CO2 equivalents.<br>S32: life-cycle emissions per year, tonnes CO2 equivalents (index t - T_0). |
| S33 | `ligninger.s33_tidligste_tidspunkt_kjernekraft`<br>`ligninger.s33_tidligste_tidspunkt_nett` | ligning<br>ligning | S33 (A, B, B'): T_0 + max(tau_F, tau_reg_min + tau_N), a point in time, not yet a year.<br>S33 and S12 (C, R): T_0 + tau_nett, a point in time, not yet a year. |
| S34 | `ligninger.s34_kontantstrom_datasenter`<br>`kontantstrom.regn_program` | ligning<br>setter sammen | S34: the data centre's cash flow in a year, kr.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S35 | `ligninger.s35_kontantstrom_kraft`<br>`kontantstrom.regn_program` | ligning<br>setter sammen | S35: the cash flow of power plant, grid and capacity in a year, kr.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S36 | `ligninger.s36_buffer`<br>`ligninger.s36_ekstern_forsyning` | ligning<br>ligning | S36: P_buf = delta_L * PUE * P_IT, the buffer that covers the largest load step, MW.<br>S36: yearly cost of external supply to the plant itself (two lines and gensets), kr/year. |
| S37 | `ligninger.s37_andel`<br>`dommer.andel`<br>`kjoring.losningsdommer` | ligning<br>setter sammen<br>setter sammen | S37: the share of the draws in which the condition of a category is met.<br>S37 for a threshold: the share of all draws with a value at least / below ``vilkaar``.<br>The verdicts for one solution from its outcome in every draw (S37, clarification 100). |
| S38 | `ligninger.s38_tilpass_linje`<br>`ligninger.s38_pris`<br>`inndata.tilpass_prislinjer`<br>`kraftsystem.kraftaar` | ligning<br>ligning<br>setter sammen<br>setter sammen | S38: the least-squares line P = alpha + b S through the points. Returns (alpha, b).<br>S38: the price at power balance ``S``, kr/MWh.<br>S38: one least-squares line per price area through NVE's scenarios.<br>S23, S24 and S38 for one year. |
| S39 | `ligninger.s39_enheter_B`<br>`ligninger.s39_portefolje_C`<br>`ligninger.s39_torraarsenergi_av_takt` | ligning<br>ligning<br>ligning | S39 (B): N_u = ceil(sum of E_D / (8760 KF P_ref)), units of P_ref for the programme.<br>S39 and S12 (C): the portfolio that gives ``E_torr`` MWh in a dry year.<br>S12, S22 and S39 (C): dry-year production of ``E_normal`` MWh built in the fixed order. |
| S40 | `ligninger.s40_restverdi`<br>`ligninger.s40_restverdi_rundskriv`<br>`kontantstrom.regn_program` | ligning<br>ligning<br>setter sammen | S40: residual value of one facility after the final year, kr in present value at T_0.<br>Clarification 118 b: S40 with the circular's rate, kr in present value at T_0.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S41 | `ligninger.s41_programkostnad` | ligning | S41: K_prog per year for T_0 < t <= t_1, kr per year (A, B and B', once per programme). |
| S42 | `ligninger.s42_naaverdivektet_margin`<br>`nivaaisert.kraftkostnad` | ligning<br>setter sammen | S42: the margins of S27 for every vintage of the path, weighted by D_D(t_v), kr.<br>The levelised cost of power and compute for the path in ``res``. |
| S43 | `ligninger.s43_knapphetspaaslag`<br>`ligninger.s43_avtakende_paaslag` | ligning<br>ligning | S43: pi_0 = y_obs / LCOC^v(2025) - 1, set to zero when negative.<br>Clarification 120, line 13: pi(t_v) = pi_0 exp(-(t_v - 2026) / tau_pi), for every vintage. |
| S44 | `ligninger.s44_inntektsfaktor`<br>`ligninger.s44_tilgjengelighet`<br>`ligninger.s44_inntektsfaktor_trinn` | ligning<br>ligning<br>ligning | S44: revenue factor Gamma = (1 - beta_F o_f^A) E[min(X, m)] / m.<br>Clarification 119 c: the probability that at least ``m`` units run, A.<br>Clarification 119 c: Gamma as the step of the table Gamma_trinn for the availability A. |
| S45 | `ligninger.s45_tilleggsfaktor`<br>`ligninger.s45_los_tilleggsfaktor`<br>`kontantstrom.regn_program` | ligning<br>ligning<br>setter sammen | S45: varsigma_i = min(1, present value of costs / present value of sales revenue).<br>S45 by iteration (clarifications 12 and 22): varsigma_i for one technology.<br>S26 for one path: the yearly cash flows and the net present value for Norway. |
| S46 | `ligninger.s46_overskridelsesfaktor` | ligning | S46: xi_N = 1 + o_xi when u_xi < w_xi (the budget reading), otherwise 1. |
| S47 | `ligninger.s47_effektkostnad`<br>`ligninger.s47_utkobling`<br>`ligninger.s47_utfall_ut_over_dimensjonerende_feil` | ligning<br>ligning<br>ligning | S47: F_a, yearly cost of the capacity a grid solution lacks, kr/year, whole programme.<br>S47, second arm: the revenue lost when the data centres disconnect in the scarce hours.<br>Clarification 121, line 21: Delta R^-1' = Delta R - max(0, max_i kappa_i P_u,i - P_dim,0). |
| S48 | `ligninger.s48_tidligste_tidspunkt_trinnvis`<br>`ligninger.s48_nettsaldo` | ligning<br>ligning | S48 (T): T_0 + max(min(tau_1, tau_nett), 1 + tau_D), a point in time, not yet a year.<br>Text under S48: the grid balance at the start of a year in the first stage, MW of draw. |
| S49 | `ligninger.s49_kjernekraft_bygges` | ligning | S49 (T-K): True when what is left of the path needs at least one whole unit. |
| S50 | `ligninger.s50_regnekraft_i_drift`<br>`utbygging.tidslinje`<br>`kjoring.tidslinje_over_trekningene` | ligning<br>setter sammen<br>setter sammen | S50: MW IT in operation in one year on power of type ``x``.<br>S50 for one path: MW IT in operation per type of power, for each year T_0 + 1 .. T_s.<br>S50 over the draws for one solution on one step (chapter 17.2, clarification 99). |
| S51 | `ligninger.s51_bortfall`<br>`ligninger.s51_bortfall_egne_maskiner`<br>`ligninger.s51_etterspoerselsfaktor` | ligning<br>ligning<br>ligning | 17.3: the loss of demand for vintage ``t_v`` in a scenario.<br>17.3, the scenario "80 % on the users' own machines": s_flytt (1 - s_trening).<br>S51: mu_d = max(0, 1 - eps_d d), the factor on the share of capacity sold. |
| S52 | `ligninger.s52_bortfallsterskel`<br>`kjoring.pristerskel_for_losning`<br>`terskler.pristerskel` | ligning<br>setter sammen<br>setter sammen | S52: d* = min(1, max(0, (1 - k_a) / eps_d)), the loss that gives median NPV zero.<br>The price threshold k of chapter 3.2 for one solution on one step (clarification 105).<br>The lowest factor k >= 0 with f(k) >= 0, for a function that does not fall with k. |
| S53 | `ligninger.s53_unngaatt_utslipp`<br>`ligninger.s53_utslipp_med_fradrag`<br>`miljo.unngaatt_utslipp`<br>`miljo.utslipp_med_fradrag` | ligning<br>ligning<br>setter sammen<br>setter sammen | S53, one facility or module with a vintage in operation: avoided emissions, tonnes per year.<br>S53: U_med = U_liv - U_unngaatt, tonnes; shown next to the main figure, never judged.<br>S53: the emissions the same compute would have had elsewhere, tonnes per year.<br>S53: U_med = U_liv - U_unngaatt per year, tonnes; never part of M5 or any verdict. |
| S54 | `ligninger.s54_it_energi`<br>`ligninger.s54_kjolevann`<br>`miljo.it_energi`<br>`miljo.vannmengde`<br>`miljo.kjolevann` | ligning<br>ligning<br>setter sammen<br>setter sammen<br>setter sammen | S54: 8760 lam P, the IT energy of facilities and modules with a vintage in operation, MWh.<br>S54: w_D E_IT + w_N E_N, cubic metres of cooling water in one year.<br>S54: E_IT per year, 8760 lam P_k over facilities and modules with a vintage in operation.<br>S54 with the factors given: w_D E_IT + w_N E_N per year, cubic metres.<br>S54 with the main figures: sea water in once-through cooling for nuclear power. |

368
src/tokenfabrikker/kart.py Normal file
View file

@ -0,0 +1,368 @@
r"""The map from equation to function (chapter 16 of the specification, clarification 131).
For every S-number tagged in the specification (``\tag{S9}``) the map lists
the functions that carry the number in their name (``s9_...``), with module and
the first line of the docstring. A number that is not one function, but is put
together over the years or over the draws, points to the functions that put it
together, by the table ``SAMMENSATT`` below. The functions are found by
importing the package's modules and inspecting them, not by reading the source.
``python -m tokenfabrikker.kart lag`` writes ``modell/kart.md``, and
``kontroll`` says whether the stored file is the one the code makes.
Nothing here runs the model, reads the parameter file or reads the draws.
"""
from __future__ import annotations
import argparse
import importlib
import inspect
import pkgutil
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Final
import tokenfabrikker
if TYPE_CHECKING:
from collections.abc import Callable
from types import ModuleType
ROT: Final = Path(__file__).resolve().parents[2]
SPESIFIKASJON: Final = ROT / "modell" / "spesifikasjon.md"
KARTFIL: Final = ROT / "modell" / "kart.md"
PAKKE: Final = tokenfabrikker.__name__
_MERKE: Final = re.compile(r"\\tag\{S(\d+)\}")
_I_TEKSTEN: Final = re.compile(r"\(S(\d+)\)")
_NAVN: Final = re.compile(r"s(\d+)_")
SAMMENSATT: Final[dict[int, tuple[tuple[str, str], ...]]] = {
# The constraints of S12 are not one function. The potentials and the pace g
# are applied where the renewable power is built (the fixed order of S39,
# dry-year production of what the pace allows), and t_1 >= T_0 + tau_nett
# where the first operating year is set (lag_plan through _tidligste_aar).
12: (
("ligninger", "s33_tidligste_tidspunkt_nett"),
("ligninger", "s39_portefolje_C"),
("ligninger", "s39_torraarsenergi_av_takt"),
("utbygging", "kraftrom_fornybar"),
("kontantstrom", "lag_plan"),
),
# S15 per vintage with the power cost weighted over its years.
15: (("nivaaisert", "kraftkostnad"),),
# S19 per vintage, in the version that is not the business one.
19: (("nivaaisert", "kraftkostnad"),),
# S22: the power terms accumulated from T_0, the chips as a stock, year by year.
22: (
("utbygging", "kraftrom_reaktor"),
("utbygging", "kraftrom_fornybar"),
("utbygging", "utbyggingsplan"),
("utbygging", "utbyggingsplan_trinnvis"),
("kontantstrom", "lag_plan"),
),
# S23 for one year, per price area, and for every year of a path.
23: (
("kraftsystem", "kraftaar"),
("kraftsystem", "relativ_prisvirkning"),
("kontantstrom", "regn_program"),
),
# S24 for one year, and for every year of a path.
24: (
("kraftsystem", "kraftaar"),
("kontantstrom", "regn_program"),
),
# S25: Delta W per year of a path (Kraftaar.velferd in the years on the grid).
25: (("kontantstrom", "regn_program"),),
# S26: the present values of S34, S35 and the other effects, S40 and SE.
26: (("kontantstrom", "regn_program"),),
# S27 per vintage in the business version, inside S42.
27: (("nivaaisert", "kraftkostnad"),),
# S28: the present value after tax of the business cash flow of a path.
28: (("eierskap", "naaverdi_etter_skatt"),),
# S29 for an ownership form as drawn, and the requirement before tax.
29: (
("eierskap", "kapitalkostnad"),
("eierskap", "krav_for_skatt"),
),
# S30 per year for one ownership form, for one path in one draw, and on the step.
30: (
("eierskap", "eierresultat"),
("kjoring", "regn_eierformer"),
("kjoring", "eierformer_paa_trinnet"),
),
# S31 per year over the facilities, and M6 from it.
31: (
("skala", "overskudd_utover_avkastning"),
("skala", "skala"),
),
# S32 per year of a path.
32: (("miljo", "utslipp_livslop"),),
# S34: the data centres' cash flow summed over the facilities, per year.
34: (("kontantstrom", "regn_program"),),
# S35: the cash flow of power plants, grid and capacity, per year.
35: (("kontantstrom", "regn_program"),),
# S37: the shares over the draws, and the verdicts of one solution from them.
37: (
("dommer", "andel"),
("kjoring", "losningsdommer"),
),
# S38: the lines fitted per price area, and the price after the effect in a year.
38: (
("inndata", "tilpass_prislinjer"),
("kraftsystem", "kraftaar"),
),
# S40 per facility and for the programme's units, inside S26.
40: (("kontantstrom", "regn_program"),),
# S42 over the vintages of a path.
42: (("nivaaisert", "kraftkostnad"),),
# S45 per technology, summed over the power plants.
45: (("kontantstrom", "regn_program"),),
# S50 for one path, and over the draws.
50: (
("utbygging", "tidslinje"),
("kjoring", "tidslinje_over_trekningene"),
),
# S52 is read from the price threshold k_a over the draws (clarification 107).
52: (
("kjoring", "pristerskel_for_losning"),
("terskler", "pristerskel"),
),
# S53 per year over the facilities and modules with a vintage in operation.
53: (
("miljo", "unngaatt_utslipp"),
("miljo", "utslipp_med_fradrag"),
),
# S54 per year of a path.
54: (
("miljo", "it_energi"),
("miljo", "vannmengde"),
("miljo", "kjolevann"),
),
}
"""The numbers put together over the years or over the draws: module and function, in order."""
INNLEDNING: Final = (
(
"Kartet viser, for hvert S-nummer i spesifikasjonen (`modell/spesifikasjon.md`), "
"funksjonene i koden som regner ligningen: først funksjonene som har nummeret i navnet "
"(`s9_…`), så funksjonene som setter nummeret sammen over årene eller over trekningene, "
"etter lista `SAMMENSATT` i `src/tokenfabrikker/kart.py` (avklaring 131)."
),
"",
(
"Fila er laget av koden og rettes ikke for hånd. "
"`PYTHONPATH=src .venv/bin/python -m tokenfabrikker.kart lag` skriver den, og "
"`PYTHONPATH=src .venv/bin/python -m tokenfabrikker.kart kontroll` sier om den er lik "
"den koden lager. Beskrivelsen er første linje av funksjonens egen dokumentasjon, på "
"engelsk som i koden."
),
)
"""The paragraphs under the heading of the map, in Norwegian."""
class KartError(ValueError):
"""The table in the code does not match the code or the specification."""
@dataclass(frozen=True)
class Funksjon:
"""One function in the map.
Attributes:
modul: the module's name inside the package.
navn: the function's name.
beskrivelse: the first line of its docstring.
sammensatt: True when it comes from ``SAMMENSATT``, False for an ``sNN_`` function.
"""
modul: str
navn: str
beskrivelse: str
sammensatt: bool
@property
def fullt_navn(self) -> str:
"""``modul.navn``."""
return f"{self.modul}.{self.navn}"
def merkede_numre(tekst: str | None = None) -> tuple[int, ...]:
"""The S-numbers tagged as equations in the specification, ascending, each once."""
tekst = SPESIFIKASJON.read_text(encoding="utf-8") if tekst is None else tekst
return tuple(sorted({int(n) for n in _MERKE.findall(tekst)}))
def numre_i_teksten(tekst: str | None = None) -> tuple[int, ...]:
"""The S-numbers referred to as ``(S9)`` in the running text, ascending, each once."""
tekst = SPESIFIKASJON.read_text(encoding="utf-8") if tekst is None else tekst
return tuple(sorted({int(n) for n in _I_TEKSTEN.findall(tekst)}))
def moduler() -> tuple[ModuleType, ...]:
"""Every module of the package, imported, in the order of their names."""
navn = sorted(m.name for m in pkgutil.iter_modules(tokenfabrikker.__path__))
return tuple(importlib.import_module(f"{PAKKE}.{n}") for n in navn)
def _kortnavn(modul: ModuleType) -> str:
return modul.__name__.removeprefix(f"{PAKKE}.")
def _forste_linje(objekt: object) -> str:
dok = inspect.getdoc(objekt)
return dok.splitlines()[0].strip() if dok else ""
def _egne_funksjoner(modul: ModuleType) -> list[tuple[str, Callable[..., object]]]:
"""The public functions defined in ``modul`` (not imported), in the order they stand."""
funksjoner = [
(navn, objekt)
for navn, objekt in vars(modul).items()
if inspect.isfunction(objekt)
and objekt.__module__ == modul.__name__
and not navn.startswith("_")
]
return sorted(funksjoner, key=lambda par: par[1].__code__.co_firstlineno)
def nummererte_funksjoner() -> dict[int, tuple[Funksjon, ...]]:
"""Every public ``sNN_`` function of the package, per number.
Within a number: the modules in the order of their names, and the
functions in the order they stand in their module.
"""
funnet: dict[int, list[Funksjon]] = {}
for modul in moduler():
for navn, objekt in _egne_funksjoner(modul):
treff = _NAVN.match(navn)
if treff is None:
continue
funnet.setdefault(int(treff.group(1)), []).append(
Funksjon(_kortnavn(modul), navn, _forste_linje(objekt), sammensatt=False)
)
return {n: tuple(f) for n, f in sorted(funnet.items())}
def sammensatte_funksjoner(
merket: tuple[int, ...] | None = None,
) -> dict[int, tuple[Funksjon, ...]]:
"""The entries of ``SAMMENSATT``, checked against the code and the specification.
Raises:
KartError: a number the specification does not tag, a module or function
that does not exist, is not public, is not callable or is not
defined in that module, or a function listed twice for one number.
"""
merket = merkede_numre() if merket is None else merket
ut: dict[int, tuple[Funksjon, ...]] = {}
for nummer, oppforinger in SAMMENSATT.items():
if nummer not in merket:
msg = f"SAMMENSATT has S{nummer}, which the specification does not tag"
raise KartError(msg)
if len(set(oppforinger)) != len(oppforinger):
msg = f"SAMMENSATT lists a function twice for S{nummer}"
raise KartError(msg)
funksjoner = []
for modulnavn, navn in oppforinger:
try:
modul = importlib.import_module(f"{PAKKE}.{modulnavn}")
except ModuleNotFoundError as feil:
msg = f"S{nummer}: no module {modulnavn}"
raise KartError(msg) from feil
objekt = getattr(modul, navn, None)
if (
navn.startswith("_")
or not inspect.isfunction(objekt)
or objekt.__module__ != modul.__name__
):
msg = f"S{nummer}: {modulnavn}.{navn} is not a public function defined there"
raise KartError(msg)
funksjoner.append(Funksjon(modulnavn, navn, _forste_linje(objekt), sammensatt=True))
ut[nummer] = tuple(funksjoner)
return ut
def kart(merket: tuple[int, ...] | None = None) -> dict[int, tuple[Funksjon, ...]]:
"""Every tagged S-number with its functions: ``sNN_`` first, then the composed ones.
A number without any function maps to an empty tuple; ``sNN_`` functions
whose number is not tagged are left out (``uten_merke`` gives them).
"""
merket = merkede_numre() if merket is None else merket
nummererte = nummererte_funksjoner()
sammensatte = sammensatte_funksjoner(merket)
return {n: nummererte.get(n, ()) + sammensatte.get(n, ()) for n in merket}
def uten_funksjon(merket: tuple[int, ...] | None = None) -> tuple[int, ...]:
"""The tagged numbers with no function at all."""
return tuple(n for n, f in kart(merket).items() if not f)
def uten_merke(merket: tuple[int, ...] | None = None) -> tuple[Funksjon, ...]:
"""The ``sNN_`` functions whose number the specification does not tag."""
merket = merkede_numre() if merket is None else merket
return tuple(f for n, fs in nummererte_funksjoner().items() if n not in merket for f in fs)
def _celle(tekst: str) -> str:
"""Text safe inside one cell of a Markdown table."""
return tekst.replace("|", "\\|")
def lag() -> str:
"""The text of ``modell/kart.md``: LF line ends, one newline at the end."""
innhold = kart()
antall_nummererte = sum(1 for fs in innhold.values() for f in fs if not f.sammensatt)
antall_sammensatte = sum(1 for fs in innhold.values() for f in fs if f.sammensatt)
linjer = [
"# Kart fra ligning til funksjon",
"",
*INNLEDNING,
"",
(
f"{len(innhold)} ligninger, {antall_nummererte} funksjoner med nummeret i navnet og "
f"{antall_sammensatte} oppføringer for funksjoner som setter sammen."
),
"",
"| Ligning | Funksjon | Slag | Første linje av beskrivelsen |",
"|---|---|---|---|",
]
for nummer, funksjoner in innhold.items():
navn = "<br>".join(f"`{f.fullt_navn}`" for f in funksjoner) or "(ingen)"
slag = "<br>".join("setter sammen" if f.sammensatt else "ligning" for f in funksjoner)
beskrivelse = "<br>".join(_celle(f.beskrivelse) for f in funksjoner)
linjer.append(f"| S{nummer} | {navn} | {slag} | {beskrivelse} |")
return "\n".join(linjer) + "\n"
def kontroller(fil: Path = KARTFIL) -> str:
"""``identisk`` when the stored file has the bytes ``lag`` gives, otherwise ``endret``."""
if not fil.is_file():
return "endret"
return "identisk" if fil.read_bytes() == lag().encode("utf-8") else "endret"
def main(argumenter: list[str] | None = None) -> int:
"""Command line: ``lag`` writes the map, ``kontroll`` checks the stored one."""
tolker = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
tolker.add_argument("kommando", choices=("lag", "kontroll"))
valg = tolker.parse_args(argumenter)
if valg.kommando == "lag":
tekst = lag()
KARTFIL.write_bytes(tekst.encode("utf-8"))
sys.stdout.write(f"{KARTFIL.relative_to(ROT)} skrevet.\n")
return 0
dom = kontroller()
sys.stdout.write(f"{dom}\n")
return 0 if dom == "identisk" else 1
if __name__ == "__main__":
raise SystemExit(main())

106
tests/test_kart.py Normal file
View file

@ -0,0 +1,106 @@
"""The map from equation to function covers the specification and is stored as the code makes it.
Clarification 131: every S-number tagged in the specification has at least one
function, no function carries a number the specification does not have, and
the stored ``modell/kart.md`` equals the one the code makes. Nothing is run.
"""
from __future__ import annotations
import importlib
import re
from typing import TYPE_CHECKING
import pytest
from tokenfabrikker import kart
if TYPE_CHECKING:
from pathlib import Path
MERKET = kart.merkede_numre()
def test_the_specification_tags_s1_to_s54() -> None:
assert MERKET == tuple(range(1, 55))
@pytest.mark.parametrize("nummer", MERKET, ids=[f"S{n}" for n in MERKET])
def test_every_tagged_number_has_a_function(nummer: int) -> None:
assert kart.kart(MERKET)[nummer], f"S{nummer} has no function in the map"
def test_no_numbered_function_without_a_tag() -> None:
assert kart.uten_merke(MERKET) == ()
def test_numbers_in_the_running_text_are_tagged() -> None:
assert set(kart.numre_i_teksten()) <= set(MERKET)
def test_numbered_functions_carry_their_number() -> None:
for nummer, funksjoner in kart.nummererte_funksjoner().items():
for f in funksjoner:
assert re.match(rf"s{nummer}_", f.navn)
assert not f.sammensatt
def test_every_composed_entry_exists_and_is_callable() -> None:
for nummer, oppforinger in kart.SAMMENSATT.items():
assert nummer in MERKET
for modulnavn, navn in oppforinger:
modul = importlib.import_module(f"tokenfabrikker.{modulnavn}")
objekt = getattr(modul, navn)
assert callable(objekt)
assert objekt.__module__ == modul.__name__
assert kart.sammensatte_funksjoner(MERKET).keys() == kart.SAMMENSATT.keys()
def test_a_composed_entry_that_does_not_exist_is_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
feil = {**kart.SAMMENSATT, 26: (("kontantstrom", "finnes_ikke"),)}
monkeypatch.setattr(kart, "SAMMENSATT", feil)
with pytest.raises(kart.KartError, match="finnes_ikke"):
kart.sammensatte_funksjoner(MERKET)
def test_a_composed_entry_for_an_untagged_number_is_an_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
kart, "SAMMENSATT", {**kart.SAMMENSATT, 99: (("kontantstrom", "lag_plan"),)}
)
with pytest.raises(kart.KartError, match="S99"):
kart.sammensatte_funksjoner(MERKET)
def test_numbered_functions_come_before_composed_ones() -> None:
for funksjoner in kart.kart(MERKET).values():
slag = [f.sammensatt for f in funksjoner]
assert slag == sorted(slag)
def test_rows_are_in_numeric_order_and_each_number_once() -> None:
rader = re.findall(r"^\| S(\d+) \|", kart.lag(), flags=re.MULTILINE)
assert [int(n) for n in rader] == list(MERKET)
def test_the_text_is_deterministic_with_lf_and_one_trailing_newline() -> None:
tekst = kart.lag()
assert tekst == kart.lag()
assert "\r" not in tekst
assert tekst.endswith("\n")
assert not tekst.endswith("\n\n")
def test_the_stored_map_equals_the_one_the_code_makes() -> None:
assert kart.KARTFIL.read_bytes() == kart.lag().encode("utf-8")
assert kart.kontroller() == "identisk"
def test_a_missing_or_different_file_is_changed(tmp_path: Path) -> None:
fil = tmp_path / "kart.md"
assert kart.kontroller(fil) == "endret"
fil.write_bytes(kart.lag().encode("utf-8") + b"\n")
assert kart.kontroller(fil) == "endret"
fil.write_bytes(kart.lag().encode("utf-8"))
assert kart.kontroller(fil) == "identisk"