r"""Emissions over the life cycle, «med fradrag», and cooling water (chapter 6, section «Utslipp»). Reads ``miljo.json`` (clarifications 141 and 142: S32, S53 per estimate of u_alt, and S54, per scenario, step and solution; median, p10 and p90 over the draws where the path can be built, per year and of the sum over the years), ``dommer.json`` (the step the verdicts are read on, the share of paths that cannot be built, and the verdict in M5) and ``modell/parametere.json`` (the four estimates of u_alt and the fixed fresh-water consumption of nuclear power with sea-water cooling, read as data). Before anything is written it checks the file against itself and against ``dommer.json``, and stops when a check fails: ``antall`` against the share «ikke byggbar»; that U_liv and the water do not differ between the scenarios, and that the deduction does not differ between the three price scenarios; that a solution without nuclear power withdraws only the data centres' water; that in A all nuclear power is the data centres' own use; that the withdrawal for own use is never above the withdrawal; that the nuclear plants' fresh-water consumption is zero when the parameter file fixes it at zero; and that p10 <= median <= p90 for every series. Writes the tables ``miljo-*.tex`` and the figure data ``miljo-vann.dat``, and returns every number ``kap6-miljo.tex`` shows, under keys that start with ``miljo.``. Standard library only. """ from __future__ import annotations import json import math from typing import TYPE_CHECKING, Any from resultater.felles import LOSNING, SCENARIO, Tall, fra_fil, hent, les, norsk if TYPE_CHECKING: from pathlib import Path from resultater.felles import Steg MILJO = "miljo.json" DOM = "dommer.json" PARAM = "modell/parametere.json" LOSNINGER = ("A", "B", "B'", "C", "R", "T-F", "T-K") UTEN_KJERNEKRAFT = ("C", "R", "T-F") TELLER = "normalisering" PRIS = ("knapphet varer", "normalisering", "overkapasitet") BORTFALL = ("kildenes lave forlop", "80 % paa egne maskiner, lav", "80 % paa egne maskiner, hoy") ANSLAG = ("hoved", "lav", "hoy_nedre", "hoy_ovre") VANN = ("uttak", "uttak_egen_bruk", "forbruk_kjernekraft", "forbruk_hoyst") LOSNING_TEX = {"A": "A", "B": "B", "B'": "$B'$", "C": "C", "R": "R", "T-F": "T-F", "T-K": "T-K"} ANSLAG_KEY = {"hoved": "hoved", "lav": "lav", "hoy_nedre": "hoy410", "hoy_ovre": "hoy626"} VANN_KEY = { "uttak": "uttak", "uttak_egen_bruk": "egen", "forbruk_kjernekraft": "forbruk-kjerne", "forbruk_hoyst": "forbruk-hoyst", } PERT_FORM = 4 # Relative tolerance when two medians that should be equal are compared after the file's rounding. TOLERANSE = 1e-9 # The body of a table ends with its bottom rule: \bottomrule cannot follow \input in a tabular. BUNN = "\\bottomrule\n" class Samler: """Collects the numbers under their keys and refuses one key with two values.""" def __init__(self) -> None: """Start empty.""" self.tall: dict[str, Tall] = {} def __call__(self, nokkel: str, tall: Tall) -> Tall: """Store one number and give it back.""" if nokkel in self.tall and self.tall[nokkel] != tall: melding = f"{nokkel} har to ulike verdier" raise ValueError(melding) self.tall[nokkel] = tall return tall def _sti(scenario: str, trinn: int, *rest: Steg) -> tuple[Steg, ...]: return ("per_scenario", ("navn", scenario), "trinn", ("trinn", trinn), *rest) def _mill(data: Any, fil: str, sti: tuple[Steg, ...], desimaler: int = 1) -> Tall: # noqa: ANN401 """A value in millions (tonnes or cubic metres).""" return fra_fil(data, fil, sti, "mill", desimaler) def _aar(aar: int, fil: str, sti: tuple[Steg, ...]) -> Tall: return Tall(str(aar), fil, sti, aar, "tekst", 0) # ------------------------------------------------------------------ the checks def _feil(melding: str) -> None: raise ValueError(melding) def _sjekk_rekkefolge(serie: Any, hvor: str) -> None: # noqa: ANN401 """p10 <= median <= p90 for the sum and for every year of one series.""" s = serie["sum"] if not s["p10"] <= s["median"] <= s["p90"]: _feil(f"{hvor}: sum har p10 > median eller median > p90") for j, (a, b, c) in enumerate(zip(serie["p10"], serie["median"], serie["p90"], strict=True)): if not a <= b <= c: _feil(f"{hvor}: år nr. {j} har p10 > median eller median > p90") def _sjekk_vann(k: Any, los: str, hvor: str, w_N_forbruk: float) -> None: # noqa: ANN401 """The water of one path. Zero fresh water from nuclear power when the parameter file fixes it at zero; only the data centres' water without nuclear power; all nuclear power own use in A; and the withdrawal for own use never above the withdrawal (it is so per draw, so also per percentile). """ if w_N_forbruk == 0.0 and any( x != 0.0 for f in ("median", "p10", "p90") for x in k["forbruk_kjernekraft"][f] ): _feil(f"{hvor}: forbruk_kjernekraft er ikke null") if los in UTEN_KJERNEKRAFT and not (k["uttak"] == k["forbruk_hoyst"] == k["uttak_egen_bruk"]): _feil(f"{hvor}: en løsning uten kjernekraft tar ut mer enn datasentrenes vann") if los == "A" and k["uttak"] != k["uttak_egen_bruk"]: _feil(f"{hvor}: i A er ikke all kjernekraft egen bruk") for f in ("median", "p10", "p90"): par = zip(k["uttak_egen_bruk"][f], k["uttak"][f], strict=True) if any(e > u * (1 + TOLERANSE) for e, u in par): _feil(f"{hvor}: uttak for egen bruk over uttaket ({f})") def _sjekk_bane(v: Any, *, ib: float, n: int, los: str, hvor: str, w_N_forbruk: float) -> None: # noqa: ANN401 """One scenario, step and solution: the count against «ikke byggbar», and its series.""" if v["antall"] != round(n * (1.0 - ib)): _feil(f"{hvor}: antall {v['antall']} mot ikke byggbar {ib}") if v["antall"] == 0: if v["U_liv"] is not None or v["med_fradrag"] is not None: _feil(f"{hvor}: antall null men verdier") return _sjekk_rekkefolge(v["U_liv"], hvor + ", U_liv") for a in ANSLAG: for felt in ("U_unngaatt", "U_med"): _sjekk_rekkefolge(v["med_fradrag"][a][felt], f"{hvor}, {a}, {felt}") for felt in VANN: _sjekk_rekkefolge(v["kjolevann"][felt], f"{hvor}, {felt}") _sjekk_vann(v["kjolevann"], los, hvor, w_N_forbruk) def _sjekk(m: Any, d: Any, p: Any) -> None: # noqa: ANN401 """The internal checks; stops at the first that fails.""" n = m["antall_trekninger"] for felt in ("antall_trekninger", "stige", "scenarioer"): if m[felt] != d[felt]: _feil(f"miljo.json og dommer.json hører ikke til samme kjøring ({felt})") w_N_forbruk = hent(p, ("parametere", ("id", "w_N_forbruk"), "fordeling", "verdi")) for sc in m["scenarioer"]: for trinn in m["stige"]: for los in LOSNINGER: hvor = f"{sc}, trinn {trinn}, {los}" v = hent(m, _sti(sc, trinn, "losninger", los)) ib = hent(d, _sti(sc, trinn, "losninger", los, "M1", "ikke_byggbar")) _sjekk_bane(v, ib=ib, n=n, los=los, hvor=hvor, w_N_forbruk=w_N_forbruk) # Not the price: U_liv and the water are the same in every scenario, and the # deduction in the three price scenarios (clarifications 95 and 99, S51). base = hent(m, _sti(TELLER, trinn, "losninger", los)) if v["U_liv"] != base["U_liv"] or v["kjolevann"] != base["kjolevann"]: _feil(f"{hvor}: U_liv eller vannet er ulikt «normalisering»") if sc in PRIS and v["med_fradrag"] != base["med_fradrag"]: _feil(f"{hvor}: fradraget er ulikt «normalisering»") # ------------------------------------------------------------------ the numbers and tables def _celle(t: Tall, lav: Tall, hoy: Tall) -> str: return ( r"\begin{tabular}[c]{@{}r@{}}" rf"{t.vist}\\{{\footnotesize ({lav.vist} til {hoy.vist})}}" r"\end{tabular}" ) def _serie_tall( m: Any, # noqa: ANN401 s: Samler, nokkel: str, sti: tuple[Steg, ...], desimaler: int = 1, ) -> tuple[Tall, Tall, Tall]: """The median, p10 and p90 of the sum over the years of one series, in millions.""" return ( s(f"{nokkel}.median", _mill(m, MILJO, (*sti, "sum", "median"), desimaler)), s(f"{nokkel}.p10", _mill(m, MILJO, (*sti, "sum", "p10"), desimaler)), s(f"{nokkel}.p90", _mill(m, MILJO, (*sti, "sum", "p90"), desimaler)), ) def _tabell_liv(m: Any, d: Any, s: Samler, trinn: int, neste: int) -> str: # noqa: ANN401 """S32 summed over the years, the number of draws, and the verdict in M5 (rule-based).""" linjer = [] for los in LOSNINGER: k = f"miljo.t{trinn}.{LOSNING[los]}" ant = s( f"{k}.antall", fra_fil(m, MILJO, _sti(TELLER, trinn, "losninger", los, "antall"), "tall", 0), ) ant5 = s( f"miljo.t{neste}.{LOSNING[los]}.antall", fra_fil(m, MILJO, _sti(TELLER, neste, "losninger", los, "antall"), "tall", 0), ) med, lav, hoy = _serie_tall( m, s, f"{k}.liv", _sti(TELLER, trinn, "losninger", los, "U_liv") ) m5 = s(f"{k}.m5", fra_fil(d, DOM, _sti(TELLER, trinn, "losninger", los, "M5"), "tekst")) linjer.append( f"{LOSNING_TEX[los]} & {ant.vist} & {med.vist} & {lav.vist} & {hoy.vist} & " f"{m5.vist} & {ant5.vist} \\\\" ) return "\n".join(linjer) + "\n" + BUNN def _tabell_fradrag(m: Any, s: Samler, trinn: int, felt: str) -> str: # noqa: ANN401 """S53 per estimate of u_alt, over the years: U_unngaatt (medians) or U_med (with range).""" linjer = [] navn = "unngaatt" if felt == "U_unngaatt" else "med" for los in LOSNINGER: celler = [] for a in ANSLAG: k = f"miljo.t{trinn}.{LOSNING[los]}.{navn}.{ANSLAG_KEY[a]}" med, lav, hoy = _serie_tall( m, s, k, _sti(TELLER, trinn, "losninger", los, "med_fradrag", a, felt) ) celler.append(med.vist if felt == "U_unngaatt" else _celle(med, lav, hoy)) linjer.append(LOSNING_TEX[los] + " & " + " & ".join(celler) + r" \\") return "\n".join(linjer) + "\n" + BUNN def _tabell_bortfall(m: Any, s: Samler, trinn: int) -> str: # noqa: ANN401 """U_unngaatt in the main estimate in «normalisering» and the three scenarios of lost demand.""" linjer = [] for los in LOSNINGER: celler = [] for sc in (TELLER, *BORTFALL): k = f"miljo.{SCENARIO[sc]}.t{trinn}.{LOSNING[los]}.unngaatt.hoved.median" sti = _sti(sc, trinn, "losninger", los, "med_fradrag", "hoved", "U_unngaatt") t = s(k, _mill(m, MILJO, (*sti, "sum", "median"))) celler.append(t.vist) linjer.append(LOSNING_TEX[los] + " & " + " & ".join(celler) + r" \\") return "\n".join(linjer) + "\n" + BUNN def _tabell_vann(m: Any, s: Samler, trinn: int) -> str: # noqa: ANN401 """S54 summed over the years, millions of cubic metres.""" linjer = [] for los in LOSNINGER: celler = [] for felt in VANN: k = f"miljo.t{trinn}.{LOSNING[los]}.vann.{VANN_KEY[felt]}" med, lav, hoy = _serie_tall( m, s, k, _sti(TELLER, trinn, "losninger", los, "kjolevann", felt) ) celler.append(med.vist if felt == "forbruk_kjernekraft" else _celle(med, lav, hoy)) linjer.append(LOSNING_TEX[los] + " & " + " & ".join(celler) + r" \\") return "\n".join(linjer) + "\n" + BUNN def _dat_vann(m: Any, trinn: int) -> str: # noqa: ANN401 """The water per year for the figure, every second year from the first. Withdrawal (median, p10, p90) for the nuclear solutions, and the data centres' own water (median) for all solutions. """ kjerne = ("A", "B", "B'") alle = ("A", "C", "R", "T-F", "T-K") hode = f"# kilde: {MILJO}, per_scenario[navn={TELLER}].trinn[trinn={trinn}].losninger." linjer = [ f"{hode}.kjolevann.uttak.median, .p10, .p90 [year] for L in {', '.join(kjerne)}; m3/year", ( f"{hode}.kjolevann.forbruk_hoyst.median [year] for L in {', '.join(alle)}; m3/year " "(the data centres' own withdrawal, since the nuclear plants' fresh-water use is zero)" ), "# every second year from the first; aar from miljo.json, aar", ] navn = [f"{LOSNING[x]}{f}" for x in kjerne for f in ("med", "p10", "p90")] navn += [f"{LOSNING[x]}dc" for x in alle] linjer.append("aar " + " ".join(navn)) aar = m["aar"] serier = {los: hent(m, _sti(TELLER, trinn, "losninger", los, "kjolevann")) for los in LOSNINGER} # The figure draws A's own water for A, B and B'; stop if they are not the same series. for los in ("B", "B'"): if serier[los]["forbruk_hoyst"] != serier["A"]["forbruk_hoyst"]: _feil(f"datasentrenes vann i {los} er ikke likt A på trinn {trinn}") for j in range(0, len(aar), 2): verdier = [ repr(float(serier[los]["uttak"][f][j])) for los in kjerne for f in ("median", "p10", "p90") ] verdier += [repr(float(serier[los]["forbruk_hoyst"]["median"][j])) for los in alle] linjer.append(f"{aar[j]} " + " ".join(verdier)) return "\n".join(linjer) + "\n" def _anslag(p: Any, s: Samler) -> None: # noqa: ANN401 """The four estimates of u_alt as the parameter file states them, g CO2 per kWh.""" base = ("parametere", ("id", "u_alt"), "fordeling", "verdi") for aar in ("2024", "2030", "2035", "2040", "2050"): s( f"miljo.ualt.hoved.{aar}", fra_fil(p, PARAM, (*base, "hoved", aar), "tall", 1 if aar in ("2040", "2050") else 0), ) for aar in ("2025", "2030"): s(f"miljo.ualt.lav.{aar}", fra_fil(p, PARAM, (*base, "lav", aar), "tall", 0)) s("miljo.ualt.hoy.lav", fra_fil(p, PARAM, (*base, "hoy", "lav"), "tall", 0)) s("miljo.ualt.hoy.hoy", fra_fil(p, PARAM, (*base, "hoy", "hoy"), "tall", 0)) s("miljo.ualt.null", fra_fil(p, PARAM, (*base, "null"), "tall", 0)) s( "miljo.wN-forbruk", fra_fil(p, PARAM, ("parametere", ("id", "w_N_forbruk"), "fordeling", "verdi"), "tall", 0), ) def _tekst(m: Any, s: Samler, trinn: int) -> None: # noqa: ANN401 """Single figures the prose reads: the years, the yearly medians against the sum, and step 5.""" s("miljo.forste-aar", _aar(m["aar"][0], MILJO, ("aar", 0))) s("miljo.siste-aar", _aar(m["aar"][-1], MILJO, ("aar", len(m["aar"]) - 1))) s("miljo.antall", fra_fil(m, MILJO, ("antall_trekninger",), "tall", 0)) s("miljo.enhet.utslipp", fra_fil(m, MILJO, ("enheter", "utslipp"), "tekst")) s("miljo.enhet.vann", fra_fil(m, MILJO, ("enheter", "kjolevann"), "tekst")) # The sum of the yearly medians, next to the median of the sums, for A: why the two differ. sti = _sti(TELLER, trinn, "losninger", "A", "U_liv", "median") verdi = math.fsum(hent(m, sti)) s( f"miljo.t{trinn}.A.liv.sum-av-medianer", Tall( norsk(verdi, 1, "1e-6"), MILJO, (), verdi, "avledet", 1, f"the sum (math.fsum) over the years of per_scenario[navn={TELLER}]" f".trinn[trinn={trinn}].losninger.A.U_liv.median, in tonnes; shown in millions", ), ) def _kraftutslipp(p: Any, s: Samler) -> None: # noqa: ANN401 """The drawn distributions of life-cycle emissions per kWh (S32), and their means. A PERT distribution with form 4 has the mean (low + 4 mode + high) / 6. """ for pid, navn in (("u_kjerne", "kjerne"), ("u_vind", "vind"), ("u_vann", "vann")): sti = ("parametere", ("id", pid), "fordeling") fordeling = hent(p, sti) if fordeling["type"] != "pert" or fordeling["form"] != PERT_FORM: _feil(f"{pid} er ikke en PERT-fordeling med form 4") for felt in ("lav", "modus", "hoy"): desimaler = 0 if float(fordeling[felt]).is_integer() else 2 if pid == "u_vann" else 1 s(f"miljo.u.{navn}.{felt}", fra_fil(p, PARAM, (*sti, felt), "tall", desimaler)) snitt = (fordeling["lav"] + PERT_FORM * fordeling["modus"] + fordeling["hoy"]) / ( PERT_FORM + 2 ) s( f"miljo.u.{navn}.snitt", Tall( norsk(snitt, 1), PARAM, (), snitt, "avledet", 1, f"the mean of the PERT distribution of {pid} in the parameter file: " "(lav + 4 modus + hoy) / 6, g CO2e per kWh", ), ) def lag(data: Path, ut: Path) -> dict[str, Tall]: """Check ``miljo.json``, write the tables and figure data, and return the numbers.""" m = les(data, MILJO) d = les(data, DOM) p = json.loads((data.parent.parent / PARAM).read_text(encoding="utf-8")) _sjekk(m, d, p) s = Samler() trinn = hent(d, ("trinn",)) stige = list(m["stige"]) neste = stige[stige.index(trinn) + 1] s("miljo.domstrinn", fra_fil(d, DOM, ("trinn",), "tall", 0)) s("miljo.nestetrinn", fra_fil(m, MILJO, ("stige", stige.index(neste)), "tall", 0)) _anslag(p, s) _kraftutslipp(p, s) _tekst(m, s, trinn) (ut / "miljo-liv.tex").write_text(_tabell_liv(m, d, s, trinn, neste), encoding="utf-8") (ut / "miljo-unngaatt.tex").write_text( _tabell_fradrag(m, s, trinn, "U_unngaatt"), encoding="utf-8" ) (ut / "miljo-med.tex").write_text(_tabell_fradrag(m, s, trinn, "U_med"), encoding="utf-8") (ut / "miljo-bortfall.tex").write_text(_tabell_bortfall(m, s, trinn), encoding="utf-8") (ut / "miljo-vann.tex").write_text(_tabell_vann(m, s, trinn), encoding="utf-8") (ut / "miljo-vann.dat").write_text(_dat_vann(m, trinn), encoding="utf-8") return s.tall