r"""What the modules behind chapter 6 share: numbers with their origin, and Norwegian number format. Every number chapter 6 shows (in the prose, in a table cell) is a ``Tall``: the string that is printed, and where in which result file the value stands. The driver ``rapport/lag_resultater.py`` writes them to ``rapport/generert/tall.tex`` (read in the prose with ``\tall{key}``) and to ``rapport/generert/tall.json`` (the list a reader checks against the files). Standard library only. """ from __future__ import annotations import json from dataclasses import dataclass from decimal import ROUND_HALF_UP, Decimal from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from pathlib import Path Steg = str | int | tuple[str, Any] """One step of a path into a result file: a key, a list index, or (field, value) picking the element of a list whose field has that value, e.g. ("navn", "normalisering") or ("trinn", 1).""" MINUS = r"\textminus{}" TUSEN = r"\," # Short names used in keys (ASCII, no spaces). The texts shown to the reader are written in the # chapter, not here. LOSNING = {"A": "A", "B": "B", "B'": "Bm", "C": "C", "R": "R", "T-F": "TF", "T-K": "TK"} SCENARIO = { "knapphet varer": "knapphet", "normalisering": "normalisering", "overkapasitet": "overkapasitet", "kildenes lave forlop": "lavt", "80 % paa egne maskiner, lav": "egne-lav", "80 % paa egne maskiner, hoy": "egne-hoy", } OMREGNINGER = ("tall", "pst", "mill", "mrd", "tekst", "avledet") @dataclass(frozen=True) class Tall: """One number as chapter 6 shows it, with where it comes from. ``omregning`` says how ``raa`` became ``vist``: "tall" (as it stands), "pst" (times 100), "mill" (divided by 1e6), "mrd" (divided by 1e9), "tekst" (a word from the file, ``vist`` written by the module), or "avledet" (computed from several values: ``sti`` is then empty, ``raa`` the computed value and ``forklaring`` says exactly from what and how). """ vist: str fil: str sti: tuple[Steg, ...] raa: float | int | str | bool | None omregning: str desimaler: int forklaring: str = "" def les(mappe: Path, fil: str) -> Any: # noqa: ANN401 """Read one result file.""" return json.loads((mappe / fil).read_text(encoding="utf-8")) def hent(data: Any, sti: tuple[Steg, ...]) -> Any: # noqa: ANN401 """Follow a path from the root of a result file. Stops with an error when it does not exist.""" her = data for steg in sti: if isinstance(steg, tuple): felt, verdi = steg treff = [x for x in her if x[felt] == verdi] if len(treff) != 1: melding = f"{sti}: {len(treff)} elementer med {felt} = {verdi!r}" raise KeyError(melding) her = treff[0] else: her = her[steg] return her def norsk(x: float, desimaler: int, faktor: str = "1") -> str: """Write a number the Norwegian way for LaTeX text: decimal comma, thin space, real minus. The number is rounded in decimal, from the shortest decimal that gives back the same float (``repr``), times ``faktor`` (a decimal written as a string, "100" or "1e-9"), and a tie goes away from zero. A share of 0.2515 is then 25,2 per cent, never 25,1 because 25.15 has no exact binary form. """ verdi = Decimal(repr(float(x))) * Decimal(faktor) avrundet = verdi.quantize(Decimal(1).scaleb(-desimaler), rounding=ROUND_HALF_UP) tekst = f"{abs(avrundet):,f}".replace(",", " ").replace(".", ",").replace(" ", TUSEN) return MINUS + tekst if avrundet < 0 else tekst def fra_fil( data: Any, # noqa: ANN401 fil: str, sti: tuple[Steg, ...], omregning: str = "tall", desimaler: int = 1, ) -> Tall: """Make the ``Tall`` for the value at a path. A value that is ``null`` in the file is shown as an en dash; a "tekst" is shown as it stands (the module may replace ``vist`` afterwards). """ raa = hent(data, sti) if omregning not in ("tall", "pst", "mill", "mrd", "tekst"): melding = f"ukjent omregning {omregning!r}" raise ValueError(melding) if raa is None: vist = "--" elif omregning == "tekst": vist = str(raa) else: faktor = {"tall": "1", "pst": "100", "mill": "1e-6", "mrd": "1e-9"}[omregning] vist = norsk(float(raa), desimaler, faktor) return Tall(vist, fil, sti, raa, omregning, desimaler) def avledet(verdi: float, desimaler: int, fil: str, forklaring: str) -> Tall: """Make the ``Tall`` for a value computed from several values of one file.""" if not forklaring: melding = "et avledet tall må ha en forklaring" raise ValueError(melding) return Tall(norsk(verdi, desimaler), fil, (), verdi, "avledet", desimaler, forklaring)