feat(kode): add the build-out, the power system and the cash flow
- utbygging.py: when each facility starts and which vintages of IT hardware it gets (S22, S33), with chips as a stock, replacement before new facilities and the export rule. - kraftsystem.py: the fitted price lines and the power and capacity balances year by year (S23, S24, S25, S38). - kontantstrom.py: the yearly cash flows per facility, the additionality rule by iteration, the residual value and the net present value for Norway (S26, S34, S35, S40, S45), for the solutions A, B, B', C and R. - hendelser.py and data/aarshendelser.npy: the stream of random numbers for the export rule, one uniform number per draw and year 2028-2100, from its own seed. - inndata.py: one set of values in the units of the equations. - ligninger.py: one function per equation for chapters 4 to 6. Tested on a made-up set of values only (tests/conftest.py); no result for the hypothesis has been computed. 271 tests pass. Seven are documented misses against a source: the five from before, and the price lines for NO3 and NO4, which miss one of NVE's twelve scenarios by 6.0 and 7.7 per cent. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
fd0db8b3d3
commit
5c91cadf4c
15 changed files with 3807 additions and 10 deletions
85
data/aarshendelser.json
Normal file
85
data/aarshendelser.json
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
{
|
||||
"beskrivelse": "Egen strøm av tilfeldige tall for hendelser som trekkes per år (eksportregelen, kapittel 4 i spesifikasjonen). Én rad per trekning, én kolonne per kalenderår. Tallene er jevnt fordelt mellom 0 og 1; en eksportregel innføres i et år når tallet er lavere enn den trukne phi_X.",
|
||||
"tabell": "aarshendelser.npy",
|
||||
"sha256_tabell": "b2a8c282629fea229e5a114506727dcd592c0b2deef95057f276f32fb0dde5f5",
|
||||
"sha256_parametere": "45828355036bb7fc57974bcb4d886ce13dd67a441b4c548836cc184ac3b3f6cc",
|
||||
"antall_trekninger": 10000,
|
||||
"froe": 20261112,
|
||||
"generator": "PCG64 (numpy.random.Generator)",
|
||||
"numpy": "2.5.4",
|
||||
"aar": [
|
||||
2028,
|
||||
2029,
|
||||
2030,
|
||||
2031,
|
||||
2032,
|
||||
2033,
|
||||
2034,
|
||||
2035,
|
||||
2036,
|
||||
2037,
|
||||
2038,
|
||||
2039,
|
||||
2040,
|
||||
2041,
|
||||
2042,
|
||||
2043,
|
||||
2044,
|
||||
2045,
|
||||
2046,
|
||||
2047,
|
||||
2048,
|
||||
2049,
|
||||
2050,
|
||||
2051,
|
||||
2052,
|
||||
2053,
|
||||
2054,
|
||||
2055,
|
||||
2056,
|
||||
2057,
|
||||
2058,
|
||||
2059,
|
||||
2060,
|
||||
2061,
|
||||
2062,
|
||||
2063,
|
||||
2064,
|
||||
2065,
|
||||
2066,
|
||||
2067,
|
||||
2068,
|
||||
2069,
|
||||
2070,
|
||||
2071,
|
||||
2072,
|
||||
2073,
|
||||
2074,
|
||||
2075,
|
||||
2076,
|
||||
2077,
|
||||
2078,
|
||||
2079,
|
||||
2080,
|
||||
2081,
|
||||
2082,
|
||||
2083,
|
||||
2084,
|
||||
2085,
|
||||
2086,
|
||||
2087,
|
||||
2088,
|
||||
2089,
|
||||
2090,
|
||||
2091,
|
||||
2092,
|
||||
2093,
|
||||
2094,
|
||||
2095,
|
||||
2096,
|
||||
2097,
|
||||
2098,
|
||||
2099,
|
||||
2100
|
||||
]
|
||||
}
|
||||
BIN
data/aarshendelser.npy
Normal file
BIN
data/aarshendelser.npy
Normal file
Binary file not shown.
|
|
@ -38,6 +38,7 @@ ignore = [
|
|||
"N802",
|
||||
"N803",
|
||||
"N806",
|
||||
"N815",
|
||||
# One function per equation: an equation with twelve symbols has twelve arguments.
|
||||
"PLR0913",
|
||||
# The licence is stated once, in LICENSE; files carry no copyright header.
|
||||
|
|
@ -56,4 +57,5 @@ convention = "google"
|
|||
"INP001", # tests are not a package
|
||||
"D103", # the name of a test says what it tests
|
||||
"PLR0917", # helpers that mirror a source's table take its columns in order
|
||||
"SIM300", # result fields named after symbols (RV, NNV, SE) are not constants
|
||||
]
|
||||
|
|
|
|||
161
src/tokenfabrikker/hendelser.py
Normal file
161
src/tokenfabrikker/hendelser.py
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
"""The stream of random numbers for events that are drawn per year (chapters 4 and 11).
|
||||
|
||||
The export rule is introduced with probability phi_X per year. Each draw of the
|
||||
parameters gets one uniform number per calendar year after the decision year;
|
||||
the rule is introduced in a year when the number is below the drawn phi_X
|
||||
(``tokenfabrikker.utbygging.eksportstopp``). The numbers come from their own
|
||||
stream, with the seed the parameter file gives, so that the 10 000 draws of the
|
||||
parameters are untouched and the same numbers serve every solution, path and
|
||||
sensitivity.
|
||||
|
||||
- ``data/aarshendelser.npy``: float64 table, one row per draw, one column per year.
|
||||
- ``data/aarshendelser.json``: the years, the set-up and the checksums.
|
||||
|
||||
Run ``python -m tokenfabrikker.hendelser lag`` to write the files and
|
||||
``python -m tokenfabrikker.hendelser kontroll`` to check that they can be
|
||||
reproduced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
import numpy as np
|
||||
|
||||
from tokenfabrikker.parametere import (
|
||||
FROSSEN_SHA256,
|
||||
STANDARDSTI,
|
||||
ParameterError,
|
||||
Parametersett,
|
||||
les_parametere,
|
||||
)
|
||||
from tokenfabrikker.trekninger import DATAMAPPE, GENERATOR, TOLERANSE, tabellbytes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import numpy.typing as npt
|
||||
|
||||
TABELLFIL: Final = "aarshendelser.npy"
|
||||
BESKRIVELSESFIL: Final = "aarshendelser.json"
|
||||
|
||||
_FROE: Final = re.compile(r"frø (\d+)")
|
||||
"""The parameter file states the seed of this stream in a sentence."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hendelser:
|
||||
"""The stream: ``tabell[i, j]`` is the uniform number of draw ``i`` for year ``aar[j]``."""
|
||||
|
||||
aar: tuple[int, ...]
|
||||
tabell: npt.NDArray[np.float64]
|
||||
|
||||
def rad(self, omega: int) -> tuple[float, ...]:
|
||||
"""The numbers of draw ``omega``, one per year T_0 + 1 .. T_s."""
|
||||
return tuple(float(u) for u in self.tabell[omega])
|
||||
|
||||
|
||||
def froe(sett: Parametersett) -> int:
|
||||
"""The seed of the stream, read from the parameter file's ``aarlige_hendelser``."""
|
||||
treff = _FROE.search(sett.monte_carlo.aarlige_hendelser)
|
||||
if treff is None:
|
||||
msg = "monte_carlo.aarlige_hendelser does not state a seed"
|
||||
raise ParameterError(msg)
|
||||
return int(treff.group(1))
|
||||
|
||||
|
||||
def trekk(sett: Parametersett) -> Hendelser:
|
||||
"""One uniform number per draw and per year after the decision year, from the stream's seed."""
|
||||
if sett.monte_carlo.generator != GENERATOR:
|
||||
msg = f"generator {sett.monte_carlo.generator!r} is not implemented"
|
||||
raise ParameterError(msg)
|
||||
aar = tuple(range(round(sett.fast("T0")) + 1, round(sett.fast("T_slutt")) + 1))
|
||||
rng = np.random.Generator(np.random.PCG64(froe(sett)))
|
||||
return Hendelser(aar, rng.random((sett.monte_carlo.antall_trekninger, len(aar))))
|
||||
|
||||
|
||||
def beskrivelse(hendelser: Hendelser, sett: Parametersett, sha256_tabell: str) -> str:
|
||||
"""The text of ``aarshendelser.json`` for this stream."""
|
||||
innhold = {
|
||||
"beskrivelse": (
|
||||
"Egen strøm av tilfeldige tall for hendelser som trekkes per år (eksportregelen, "
|
||||
"kapittel 4 i spesifikasjonen). Én rad per trekning, én kolonne per kalenderår. "
|
||||
"Tallene er jevnt fordelt mellom 0 og 1; en eksportregel innføres i et år når "
|
||||
"tallet er lavere enn den trukne phi_X."
|
||||
),
|
||||
"tabell": TABELLFIL,
|
||||
"sha256_tabell": sha256_tabell,
|
||||
"sha256_parametere": FROSSEN_SHA256,
|
||||
"antall_trekninger": sett.monte_carlo.antall_trekninger,
|
||||
"froe": froe(sett),
|
||||
"generator": sett.monte_carlo.generator,
|
||||
"numpy": np.__version__,
|
||||
"aar": list(hendelser.aar),
|
||||
}
|
||||
return json.dumps(innhold, ensure_ascii=False, indent=2) + "\n"
|
||||
|
||||
|
||||
def skriv(hendelser: Hendelser, sett: Parametersett, mappe: Path = DATAMAPPE) -> str:
|
||||
"""Write both files and return the checksum of the table."""
|
||||
mappe.mkdir(parents=True, exist_ok=True)
|
||||
raa = tabellbytes(hendelser.tabell)
|
||||
sha256 = hashlib.sha256(raa).hexdigest()
|
||||
(mappe / TABELLFIL).write_bytes(raa)
|
||||
(mappe / BESKRIVELSESFIL).write_text(beskrivelse(hendelser, sett, sha256), encoding="utf-8")
|
||||
return sha256
|
||||
|
||||
|
||||
def les(mappe: Path = DATAMAPPE) -> Hendelser:
|
||||
"""Read the stored stream. The table must match the checksum in the description file."""
|
||||
innhold = json.loads((mappe / BESKRIVELSESFIL).read_text(encoding="utf-8"))
|
||||
raa = (mappe / TABELLFIL).read_bytes()
|
||||
if hashlib.sha256(raa).hexdigest() != innhold["sha256_tabell"]:
|
||||
msg = f"{mappe / TABELLFIL} does not match the checksum in {BESKRIVELSESFIL}"
|
||||
raise ParameterError(msg)
|
||||
tabell = np.load(mappe / TABELLFIL, allow_pickle=False)
|
||||
return Hendelser(tuple(int(a) for a in innhold["aar"]), tabell)
|
||||
|
||||
|
||||
def kontroller(sett: Parametersett, mappe: Path = DATAMAPPE) -> tuple[str, float]:
|
||||
"""Make the stream again and compare with the stored table.
|
||||
|
||||
Returns the verdict and the largest absolute deviation: ``identisk`` (bit
|
||||
for bit), ``innenfor toleranse`` or ``endret``.
|
||||
"""
|
||||
lagret = les(mappe)
|
||||
ny = trekk(sett)
|
||||
if ny.aar != lagret.aar or ny.tabell.shape != lagret.tabell.shape:
|
||||
return "endret", math.inf
|
||||
if tabellbytes(ny.tabell) == (mappe / TABELLFIL).read_bytes():
|
||||
return "identisk", 0.0
|
||||
avvik = float(np.max(np.abs(ny.tabell - lagret.tabell)))
|
||||
return ("innenfor toleranse" if avvik <= TOLERANSE else "endret"), avvik
|
||||
|
||||
|
||||
def main(argumenter: list[str] | None = None) -> int:
|
||||
"""Command line: ``lag`` writes the stream, ``kontroll`` checks that it can be reproduced."""
|
||||
tolker = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else None)
|
||||
tolker.add_argument("kommando", choices=("lag", "kontroll"))
|
||||
tolker.add_argument("--parametere", type=Path, default=STANDARDSTI)
|
||||
tolker.add_argument("--mappe", type=Path, default=DATAMAPPE)
|
||||
valg = tolker.parse_args(argumenter)
|
||||
sett = les_parametere(valg.parametere)
|
||||
if valg.kommando == "lag":
|
||||
hendelser = trekk(sett)
|
||||
sha256 = skriv(hendelser, sett, valg.mappe)
|
||||
rader, kolonner = hendelser.tabell.shape
|
||||
sys.stdout.write(f"{rader} trekninger for {kolonner} år skrevet. SHA-256: {sha256}\n")
|
||||
return 0
|
||||
dom, avvik = kontroller(sett, valg.mappe)
|
||||
sys.stdout.write(f"{dom} (største avvik {avvik:.3g})\n")
|
||||
return 0 if dom != "endret" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
150
src/tokenfabrikker/inndata.py
Normal file
150
src/tokenfabrikker/inndata.py
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
"""One set of parameter values in the units of the equations.
|
||||
|
||||
The model is computed for one set of values at a time: one Monte Carlo draw,
|
||||
or a made-up set in a test. ``Inndata`` holds such a set. Scalars are looked up
|
||||
by the id of the parameter file (``inn["c_N_ref"]``, ``inn["vind.investering"]``),
|
||||
already converted to kroner, MW, MWh, kr/MWh and years.
|
||||
|
||||
``fra_trekning`` builds the set for one draw from the frozen file, the stored
|
||||
draws and the stored stream for yearly events. It only prepares the numbers;
|
||||
nothing is computed with them here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Final, cast
|
||||
|
||||
from tokenfabrikker import ligninger as lg
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
from tokenfabrikker.parametere import Parametersett, Prisscenario
|
||||
from tokenfabrikker.trekninger import Trekninger
|
||||
|
||||
DESIGNVERDIER: Final = ("o_f_liten", "o_f_stor", "o_p", "beta_F")
|
||||
"""Quantities whose mode value dimensions the reserve units (S8, clarification 4)."""
|
||||
|
||||
FORNYBARE: Final = ("vann", "vind", "havvind")
|
||||
"""The renewable technologies of solution C, in the order the portfolio is filled (S39)."""
|
||||
|
||||
SENTRAL_KARBONBANE: Final = "sentral"
|
||||
"""The carbon price path of the main run (the parameter file's note on p_CO2)."""
|
||||
|
||||
HELE_NORGE: Final = "Norge"
|
||||
"""The column of NVE's table with the price for Norway as a whole."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Prislinje:
|
||||
"""S38: the fitted line P_z(S) = alpha + b S for one price area.
|
||||
|
||||
Attributes:
|
||||
alpha: kr/MWh at balance zero.
|
||||
b: kr/MWh per MWh of power balance.
|
||||
"""
|
||||
|
||||
alpha: float
|
||||
b: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Inndata:
|
||||
"""One set of parameter values, in the units of the equations.
|
||||
|
||||
Attributes:
|
||||
v: every scalar quantity by its id in the parameter file.
|
||||
design: the mode values of the quantities in ``DESIGNVERDIER``.
|
||||
P_u_sett: the unit sizes that can be chosen in S7, MW.
|
||||
psi: value factor per renewable technology.
|
||||
kappa: capacity contribution in the scarcest hour for hydropower and offshore wind.
|
||||
linjer: the fitted price line per price area and for Norway (S38).
|
||||
karbonpris: the carbon price at the years of the table, kr per tonne.
|
||||
u_eksport: one uniform number per year T_0 + 1 .. T_s for the export rule.
|
||||
"""
|
||||
|
||||
v: Mapping[str, float]
|
||||
design: Mapping[str, float]
|
||||
P_u_sett: tuple[float, ...]
|
||||
psi: Mapping[str, float]
|
||||
kappa: Mapping[str, float]
|
||||
linjer: Mapping[str, Prislinje]
|
||||
karbonpris: Mapping[int, float]
|
||||
u_eksport: tuple[float, ...]
|
||||
|
||||
def __getitem__(self, navn: str) -> float:
|
||||
"""The scalar quantity with this id, in the units of the equations."""
|
||||
return self.v[navn]
|
||||
|
||||
def heltall(self, navn: str) -> int:
|
||||
"""A quantity that is a whole number (calendar years, L_H, n_0)."""
|
||||
verdi = self.v[navn]
|
||||
if verdi != round(verdi):
|
||||
msg = f"{navn} should be a whole number, got {verdi}"
|
||||
raise ValueError(msg)
|
||||
return round(verdi)
|
||||
|
||||
def karbonpris_i(self, t: int) -> float:
|
||||
"""The carbon price in year ``t``: linear between the years of the table."""
|
||||
aar = sorted(self.karbonpris)
|
||||
if t <= aar[0]:
|
||||
return self.karbonpris[aar[0]]
|
||||
if t >= aar[-1]:
|
||||
return self.karbonpris[aar[-1]]
|
||||
ovre = next(a for a in aar if a >= t)
|
||||
nedre = aar[aar.index(ovre) - 1]
|
||||
andel = (t - nedre) / (ovre - nedre)
|
||||
return self.karbonpris[nedre] + andel * (self.karbonpris[ovre] - self.karbonpris[nedre])
|
||||
|
||||
|
||||
def tilpass_prislinjer(scenarioer: Sequence[Prisscenario]) -> dict[str, Prislinje]:
|
||||
"""S38: one least-squares line per price area through NVE's scenarios."""
|
||||
balanse = [s.balanse for s in scenarioer]
|
||||
linjer = {}
|
||||
for omraade in scenarioer[0].pris:
|
||||
alpha, b = lg.s38_tilpass_linje(S=balanse, P=[s.pris[omraade] for s in scenarioer])
|
||||
linjer[omraade] = Prislinje(alpha=alpha, b=b)
|
||||
return linjer
|
||||
|
||||
|
||||
def _ordbok_av_tall(verdi: object) -> dict[str, float]:
|
||||
return {str(n): float(x) for n, x in cast("dict[str, float]", verdi).items()}
|
||||
|
||||
|
||||
def fra_trekning(
|
||||
sett: Parametersett,
|
||||
trekninger: Trekninger,
|
||||
u_eksport: Sequence[float],
|
||||
omega: int,
|
||||
) -> Inndata:
|
||||
"""The values of draw number ``omega``, converted to the units of the equations.
|
||||
|
||||
``u_eksport`` is the row of the stored event stream that belongs to the
|
||||
draw. Fixed scalars come from the file, drawn ones from the stored draws.
|
||||
"""
|
||||
verdier: dict[str, float] = {}
|
||||
for storrelse in sett.storrelser():
|
||||
fordeling = storrelse.fordeling
|
||||
if fordeling.tabell is not None:
|
||||
continue
|
||||
if fordeling.er_fast:
|
||||
verdier[storrelse.navn] = fordeling.tall["verdi"] * storrelse.faktor
|
||||
else:
|
||||
verdier[storrelse.navn] = (
|
||||
float(trekninger.kolonne(storrelse.navn)[omega]) * storrelse.faktor
|
||||
)
|
||||
design = {
|
||||
navn: sett.storrelse(navn).fordeling.tall["modus"] * sett.storrelse(navn).faktor
|
||||
for navn in DESIGNVERDIER
|
||||
}
|
||||
return Inndata(
|
||||
v=verdier,
|
||||
design=design,
|
||||
P_u_sett=sett.liste("P_u_sett"),
|
||||
psi=_ordbok_av_tall(sett.tabell("psi")),
|
||||
kappa=_ordbok_av_tall(sett.tabell("kappa")),
|
||||
linjer=tilpass_prislinjer(sett.pris_balanse()),
|
||||
karbonpris=sett.karbonpris()[SENTRAL_KARBONBANE],
|
||||
u_eksport=tuple(float(u) for u in u_eksport),
|
||||
)
|
||||
1083
src/tokenfabrikker/kontantstrom.py
Normal file
1083
src/tokenfabrikker/kontantstrom.py
Normal file
File diff suppressed because it is too large
Load diff
116
src/tokenfabrikker/kraftsystem.py
Normal file
116
src/tokenfabrikker/kraftsystem.py
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
"""The power system in one year (chapter 5 of the specification): S23, S24, S25 and S38.
|
||||
|
||||
The power market is in reduced form: one fitted line between Norway's power
|
||||
balance and the price per price area, a normal year and a dry year, and one
|
||||
scarce hour. The cash flow uses the price for Norway as a whole in a normal
|
||||
year, because the model does not place the facilities in a price area
|
||||
(specification, chapter 16).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from tokenfabrikker import ligninger as lg
|
||||
from tokenfabrikker.inndata import HELE_NORGE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from tokenfabrikker.inndata import Inndata
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Kraftaar:
|
||||
"""What a solution does to the power system in one year.
|
||||
|
||||
Attributes:
|
||||
Delta_Q: new use from the grid minus new production in a normal year, MWh (S23).
|
||||
Delta_Q_tort: the same in the dry year, MWh.
|
||||
pris: the price for Norway in a normal year after the price effect, kr/MWh.
|
||||
Delta_p: the price change for Norway in a normal year, kr/MWh.
|
||||
Delta_R: the capacity balance in the scarcest hour against the zero alternative, MW (S24).
|
||||
Delta_R_utfall: the same with the largest new unit out, MW.
|
||||
"""
|
||||
|
||||
Delta_Q: float
|
||||
Delta_Q_tort: float
|
||||
pris: float
|
||||
Delta_p: float
|
||||
Delta_R: float
|
||||
Delta_R_utfall: float
|
||||
|
||||
def velferd(self, *, S_0: float) -> float:
|
||||
"""S25: Delta W, the change in Norway's income from trade in power, kr per year."""
|
||||
return lg.s25_velferd(Delta_p=self.Delta_p, S_0=S_0)
|
||||
|
||||
|
||||
def kraftaar(
|
||||
inn: Inndata,
|
||||
*,
|
||||
Q_D_nett: float,
|
||||
Q_G_nett: float,
|
||||
Q_G_nett_tort: float,
|
||||
effektbidrag: Sequence[float],
|
||||
P_IT_sum: float,
|
||||
storste_enhet: float,
|
||||
) -> Kraftaar:
|
||||
"""S23, S24 and S38 for one year.
|
||||
|
||||
``Q_D_nett`` is what the facilities in operation take from the grid (MWh,
|
||||
zero in A), ``Q_G_nett`` and ``Q_G_nett_tort`` what the new power plants
|
||||
deliver in a normal and in the dry year, ``effektbidrag`` kappa_i P_G,i per
|
||||
plant, ``P_IT_sum`` the IT capacity on the grid and ``storste_enhet`` the
|
||||
largest new unit (kappa P_u), zero without nuclear power on the grid.
|
||||
"""
|
||||
linje = inn.linjer[HELE_NORGE]
|
||||
Delta_Q = lg.s23_netto_uttak(delta_V=inn["delta_V"], Q_D_nett=Q_D_nett, Q_G_nett=Q_G_nett)
|
||||
Delta_Q_tort = lg.s23_netto_uttak(
|
||||
delta_V=inn["delta_V"], Q_D_nett=Q_D_nett, Q_G_nett=Q_G_nett_tort
|
||||
)
|
||||
Delta_p = lg.s23_prisvirkning(
|
||||
alpha=linje.alpha, b=linje.b, b_ut=inn["b_ut"], S_0=inn["S0"], Delta_Q=Delta_Q
|
||||
)
|
||||
pris = lg.s38_pris(alpha=linje.alpha, b=linje.b, b_ut=inn["b_ut"], S=inn["S0"] - Delta_Q)
|
||||
Delta_R, Delta_R_utfall = lg.s24_effektbalanse(
|
||||
effektbidrag=effektbidrag,
|
||||
delta_V=inn["delta_V"],
|
||||
PUE=inn["PUE"],
|
||||
P_IT_sum=P_IT_sum,
|
||||
storste_enhet=storste_enhet,
|
||||
)
|
||||
return Kraftaar(
|
||||
Delta_Q=Delta_Q,
|
||||
Delta_Q_tort=Delta_Q_tort,
|
||||
pris=pris,
|
||||
Delta_p=Delta_p,
|
||||
Delta_R=Delta_R,
|
||||
Delta_R_utfall=Delta_R_utfall,
|
||||
)
|
||||
|
||||
|
||||
def relativ_prisvirkning(inn: Inndata, *, Delta_Q: float, tort: bool) -> dict[str, float]:
|
||||
"""S23: Delta p_z / p_z^0 per price area, in a normal year or in the dry year.
|
||||
|
||||
p_z^0 = m_v P_z(S_0). In the dry year the effect is multiplied by s_tort;
|
||||
the price level m_tort is in both numerator and denominator.
|
||||
"""
|
||||
m_v = inn["m_tort"] if tort else 1.0
|
||||
s_v = inn["s_tort"] if tort else 1.0
|
||||
andel = {}
|
||||
for omraade, linje in inn.linjer.items():
|
||||
if omraade == HELE_NORGE:
|
||||
continue
|
||||
endring = lg.s23_prisvirkning(
|
||||
alpha=linje.alpha,
|
||||
b=linje.b,
|
||||
b_ut=inn["b_ut"],
|
||||
S_0=inn["S0"],
|
||||
Delta_Q=Delta_Q,
|
||||
m_v=m_v,
|
||||
s_v=s_v,
|
||||
)
|
||||
uten = m_v * lg.s38_pris(alpha=linje.alpha, b=linje.b, b_ut=inn["b_ut"], S=inn["S0"])
|
||||
andel[omraade] = endring / uten
|
||||
return andel
|
||||
|
|
@ -9,19 +9,29 @@ energy in MWh, power prices in kr/MWh, compute capacity in MW IT, time in years.
|
|||
The parameter file states costs in other units (kr/kW, mill. kr ...);
|
||||
``tokenfabrikker.parametere`` converts them before they reach these functions.
|
||||
|
||||
This file covers chapters 1 to 3 (power plant, data centre, revenue) and the
|
||||
two rules (S45, S47) that the levelised cost depends on. The cash flow, the
|
||||
build-out and the power system (S12, S22 to S42) are not implemented here.
|
||||
This file covers chapters 1 to 6: the power plant, the data centre, the revenue,
|
||||
the build-out (S22, S33, S39, S41), the power system (S23 to S25, S38, S47) and
|
||||
the cash flow (S26, S34, S35, S40, S45). The functions for the build-out and the
|
||||
cash flow work on one year or one facility at a time; ``utbygging``,
|
||||
``kraftsystem`` and ``kontantstrom`` put them together over the years.
|
||||
Business economics, ownership, scale, environment and the verdicts (S27 to S32,
|
||||
S37, S42) are not implemented yet.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
|
||||
Belop = TypeVar("Belop", float, "npt.NDArray[np.float64]")
|
||||
"""An amount for one year, or a table with one amount per year."""
|
||||
|
||||
TIMER_PER_AAR = 8760.0
|
||||
"""Hours per year used throughout the specification."""
|
||||
|
|
@ -41,6 +51,15 @@ BASISAAR_IT_PRIS = 2025
|
|||
SISTE_AAR_IT_PRISENDRING = 2035
|
||||
"""The real price change of IT hardware stops after this year (S13)."""
|
||||
|
||||
KNEKK_BALANSE_MWH = -3.6e6
|
||||
"""The weakest power balance NVE has computed, -3.6 TWh; below it the slope is b_ut b_z (S38)."""
|
||||
|
||||
HALVT_AAR = 0.5
|
||||
"""Lifetimes and durations are rounded to the nearest whole year, halves up (clarification 21)."""
|
||||
|
||||
HALVERINGSTOLERANSE = 1e-12
|
||||
"""The interval for varsigma is halved until it is this narrow (S45, clarification 22)."""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- S1
|
||||
|
||||
|
|
@ -672,3 +691,351 @@ def s47_effektkostnad(
|
|||
fast_effekt = c_fast * R_minus + c_res * (R_utfall_minus - R_minus)
|
||||
utkobling = h_knapp * mu * y / (TIMER_PER_AAR * PUE) * R_utfall_minus
|
||||
return min(fast_effekt, utkobling)
|
||||
|
||||
|
||||
# ------------------------------------------- whole calendar years (chapter 16, 21)
|
||||
|
||||
|
||||
def forste_driftsaar(*, tidspunkt: float) -> int:
|
||||
"""Clarification 21: the first whole calendar year at or after a point in time.
|
||||
|
||||
A facility that can be in operation x years after the decision at the
|
||||
earliest has first operating year ceil(T_0 + x). A rounding error in the
|
||||
last digit does not add a year.
|
||||
"""
|
||||
return _tak(tidspunkt)
|
||||
|
||||
|
||||
def avrundet_varighet(*, varighet: float) -> int:
|
||||
"""Clarification 21: a lifetime or duration in whole years for the cash flow.
|
||||
|
||||
Nearest whole year, halves up, at least one year.
|
||||
"""
|
||||
if varighet <= 0:
|
||||
msg = f"a lifetime or duration must be positive, got {varighet}"
|
||||
raise ValueError(msg)
|
||||
return max(1, math.floor(varighet + HALVT_AAR))
|
||||
|
||||
|
||||
def byggeaar_andeler(*, tau: float) -> tuple[float, ...]:
|
||||
"""Clarification 21: the share of an investment paid in each construction year.
|
||||
|
||||
Element j is the share paid in year t_s - 1 - j, where t_s is the first
|
||||
operating year: the floor(tau) years just before t_s get 1/tau each, and
|
||||
the year before them gets the rest, (tau - floor(tau))/tau. A construction
|
||||
time of at most one year puts the whole amount in the year before start.
|
||||
"""
|
||||
if tau <= 0:
|
||||
msg = f"construction time must be positive, got {tau}"
|
||||
raise ValueError(msg)
|
||||
hele = math.floor(tau)
|
||||
andeler = [1.0 / tau] * hele
|
||||
rest = (tau - hele) / tau
|
||||
if rest > 0:
|
||||
andeler.append(rest)
|
||||
return tuple(andeler)
|
||||
|
||||
|
||||
def diskonteringsfaktor(*, rho: float, t: int, T_0: int) -> float:
|
||||
"""Chapter 6: D(t) = (1 + rho)^-(t - T_0), for an amount paid at the end of year t."""
|
||||
return float((1.0 + rho) ** -(t - T_0))
|
||||
|
||||
|
||||
# -------------------------------------------- the build-out: S33, S22, S39 and S41
|
||||
|
||||
|
||||
def s33_tidligste_tidspunkt_kjernekraft(
|
||||
*, T_0: float, tau_F: float, tau_reg_min: float, tau_N: float
|
||||
) -> float:
|
||||
"""S33 (A, B, B'): T_0 + max(tau_F, tau_reg_min + tau_N), a point in time, not yet a year."""
|
||||
return T_0 + max(tau_F, tau_reg_min + tau_N)
|
||||
|
||||
|
||||
def s33_tidligste_tidspunkt_nett(*, T_0: float, tau_nett: float) -> float:
|
||||
"""S33 and S12 (C, R): T_0 + tau_nett, a point in time, not yet a year."""
|
||||
return T_0 + tau_nett
|
||||
|
||||
|
||||
def s22_reaktoreffekt_B(*, lam: float, PUE: float, P_IT: float, KF: float) -> float:
|
||||
"""S22 (text): P_G^N in B, the reactor capacity one facility needs, lam PUE P_IT / KF, MW."""
|
||||
return lam * PUE * P_IT / KF
|
||||
|
||||
|
||||
def s22_grense_reaktor(*, n_reaktor: float, P_IT: float, P_G_N: float) -> float:
|
||||
"""S22, first term (A, B, B'): n_reaktor P_IT / P_G^N, MW IT per year.
|
||||
|
||||
``n_reaktor`` in MW of reactor capacity per year, ``P_G_N`` the reactor
|
||||
capacity one facility needs (MW).
|
||||
"""
|
||||
return n_reaktor * P_IT / P_G_N
|
||||
|
||||
|
||||
def s22_grense_fornybar(*, g_fornybar: float, w_tort: float, lam: float, PUE: float) -> float:
|
||||
"""S22, second term (C): g w_tort / (8760 lam PUE), MW IT per year.
|
||||
|
||||
``g_fornybar`` in MWh of normal-year production per year (the file's TWh
|
||||
per year times 10^6), ``w_tort`` the dry-year production of what is built
|
||||
over its normal-year production.
|
||||
"""
|
||||
return g_fornybar * w_tort / (TIMER_PER_AAR * lam * PUE)
|
||||
|
||||
|
||||
def s22_grense_brikker(*, s_brikker: float, G_server: float, utskifting: float) -> float:
|
||||
"""S22, third term: s_brikker G_server - utskifting(t), MW IT per year.
|
||||
|
||||
``G_server`` in MW IT per year (the file's GW per year times 1000),
|
||||
``utskifting`` the MW IT of vintages replaced that year.
|
||||
"""
|
||||
return s_brikker * G_server - utskifting
|
||||
|
||||
|
||||
def s39_enheter_B(*, E_D_sum: float, KF: float, P_ref: float) -> int:
|
||||
"""S39 (B): N_u = ceil(sum of E_D / (8760 KF P_ref)), units of P_ref for the programme."""
|
||||
return _tak(E_D_sum / (TIMER_PER_AAR * KF * P_ref))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fornybarportefolje:
|
||||
"""S39 (C): the normal-year production of the renewable portfolio, MWh per year."""
|
||||
|
||||
vann: float
|
||||
vind: float
|
||||
havvind: float
|
||||
|
||||
@property
|
||||
def sum(self) -> float:
|
||||
"""E_G, the portfolio's production in a normal year."""
|
||||
return self.vann + self.vind + self.havvind
|
||||
|
||||
def torraar(self, *, w_tort_vann: float) -> float:
|
||||
"""Production in a dry year: w for hydropower, 1 for wind."""
|
||||
return w_tort_vann * self.vann + self.vind + self.havvind
|
||||
|
||||
|
||||
def s39_portefolje_C(
|
||||
*, E_torr: float, w_tort_vann: float, E_vann_rest: float, E_vind_rest: float
|
||||
) -> Fornybarportefolje:
|
||||
"""S39 and S12 (C): the portfolio that gives ``E_torr`` MWh in a dry year.
|
||||
|
||||
Filled in fixed order: hydropower up to its potential, then onshore wind up
|
||||
to its potential, then bottom-fixed offshore wind. The potentials are
|
||||
normal-year production (MWh).
|
||||
"""
|
||||
if E_torr < 0:
|
||||
msg = f"energy cannot be negative, got {E_torr}"
|
||||
raise ValueError(msg)
|
||||
vann = min(E_vann_rest, E_torr / w_tort_vann)
|
||||
rest = max(0.0, E_torr - w_tort_vann * vann)
|
||||
vind = min(E_vind_rest, rest)
|
||||
return Fornybarportefolje(vann=vann, vind=vind, havvind=rest - vind)
|
||||
|
||||
|
||||
def s39_torraarsenergi_av_takt(
|
||||
*, E_normal: float, w_tort_vann: float, E_vann_rest: float, E_vind_rest: float
|
||||
) -> float:
|
||||
"""S12, S22 and S39 (C): dry-year production of ``E_normal`` MWh built in the fixed order.
|
||||
|
||||
``E_normal`` is the normal-year production the pace g allows so far. The
|
||||
inverse of ``s39_portefolje_C``: hydropower first, then wind.
|
||||
"""
|
||||
vann = min(E_vann_rest, E_normal)
|
||||
vind = min(E_vind_rest, E_normal - vann)
|
||||
return w_tort_vann * vann + vind + (E_normal - vann - vind)
|
||||
|
||||
|
||||
def s41_programkostnad(
|
||||
*, andel_myndighet: float, aarsverk_prog: float, c_aarsverk: float, t_1: int, T_0: int
|
||||
) -> float:
|
||||
"""S41: K_prog per year for T_0 < t <= t_1, kr per year (A, B and B', once per programme)."""
|
||||
if t_1 <= T_0:
|
||||
msg = f"the first facility must start after the decision year, got {t_1} <= {T_0}"
|
||||
raise ValueError(msg)
|
||||
return andel_myndighet * aarsverk_prog * c_aarsverk / (t_1 - T_0)
|
||||
|
||||
|
||||
# ------------------------------------------ the power system: S38, S23, S24 and S25
|
||||
|
||||
|
||||
def s38_tilpass_linje(*, S: Sequence[float], P: Sequence[float]) -> tuple[float, float]:
|
||||
"""S38: the least-squares line P = alpha + b S through the points. Returns (alpha, b)."""
|
||||
if len(S) != len(P) or len(S) < 2: # noqa: PLR2004 (a line needs two points)
|
||||
msg = "a line needs at least two points, and as many prices as balances"
|
||||
raise ValueError(msg)
|
||||
snitt_S = math.fsum(S) / len(S)
|
||||
snitt_P = math.fsum(P) / len(P)
|
||||
kvadrat = math.fsum((s - snitt_S) ** 2 for s in S)
|
||||
if kvadrat == 0:
|
||||
msg = "all balances are equal; no line can be fitted"
|
||||
raise ValueError(msg)
|
||||
b = math.fsum((s - snitt_S) * (p - snitt_P) for s, p in zip(S, P, strict=True)) / kvadrat
|
||||
return snitt_P - b * snitt_S, b
|
||||
|
||||
|
||||
def s38_pris(
|
||||
*, alpha: float, b: float, b_ut: float, S: float, S_knekk: float = KNEKK_BALANSE_MWH
|
||||
) -> float:
|
||||
"""S38: the price at power balance ``S``, kr/MWh.
|
||||
|
||||
The fitted line down to ``S_knekk`` (-3.6 TWh, the weakest balance NVE has
|
||||
computed); below it the slope is b_ut b. ``S`` and ``S_knekk`` in MWh,
|
||||
``b`` in kr/MWh per MWh.
|
||||
"""
|
||||
under_knekk = min(0.0, S - S_knekk)
|
||||
return alpha + b * (S - under_knekk) + b_ut * b * under_knekk
|
||||
|
||||
|
||||
def s23_netto_uttak(*, delta_V: float, Q_D_nett: float, Q_G_nett: float) -> float:
|
||||
"""S23: Delta Q = (1 - delta_V) Q_D - Q_G, new use from the grid minus new production, MWh."""
|
||||
return (1.0 - delta_V) * Q_D_nett - Q_G_nett
|
||||
|
||||
|
||||
def s23_prisvirkning(
|
||||
*,
|
||||
alpha: float,
|
||||
b: float,
|
||||
b_ut: float,
|
||||
S_0: float,
|
||||
Delta_Q: float,
|
||||
m_v: float = 1.0,
|
||||
s_v: float = 1.0,
|
||||
) -> float:
|
||||
"""S23: Delta p_z = m_v s_v [P_z(S_0 - Delta Q) - P_z(S_0)], kr/MWh.
|
||||
|
||||
``m_v`` and ``s_v`` are 1 in a normal year; in the dry year they are the
|
||||
price level against the normal year and the factor on the effect.
|
||||
"""
|
||||
med = s38_pris(alpha=alpha, b=b, b_ut=b_ut, S=S_0 - Delta_Q)
|
||||
uten = s38_pris(alpha=alpha, b=b, b_ut=b_ut, S=S_0)
|
||||
return m_v * s_v * (med - uten)
|
||||
|
||||
|
||||
def s24_effektbalanse(
|
||||
*,
|
||||
effektbidrag: Sequence[float],
|
||||
delta_V: float,
|
||||
PUE: float,
|
||||
P_IT_sum: float,
|
||||
storste_enhet: float,
|
||||
) -> tuple[float, float]:
|
||||
"""S24: (Delta R, Delta R^-1), the capacity balance in the scarcest hour, MW.
|
||||
|
||||
``effektbidrag`` holds kappa_i P_G,i for each new power plant in operation,
|
||||
``P_IT_sum`` the IT capacity of the facilities in operation, and
|
||||
``storste_enhet`` is max kappa_i P_u,i, the largest new unit (zero in C and R).
|
||||
"""
|
||||
Delta_R = math.fsum(effektbidrag) - (1.0 - delta_V) * PUE * P_IT_sum
|
||||
return Delta_R, Delta_R - storste_enhet
|
||||
|
||||
|
||||
def s25_velferd(*, Delta_p: float, S_0: float) -> float:
|
||||
"""S25: Delta W = Delta p S_0, kr per year. ``Delta_p`` for all of Norway, ``S_0`` in MWh."""
|
||||
return Delta_p * S_0
|
||||
|
||||
|
||||
# ------------------------------------- the cash flow: S34, S35, S40, S26 and S45
|
||||
|
||||
|
||||
def s34_kontantstrom_datasenter(
|
||||
*, inntekt: Belop, drift: Belop, kraftkjop: Belop, I_bygg: Belop, I_H: Belop
|
||||
) -> Belop:
|
||||
"""S34: the data centre's cash flow in a year, kr.
|
||||
|
||||
Revenue mu Gamma y P_IT, minus operation (o_D + d_o_D) P_IT, minus power
|
||||
bought from the grid (1 + n_tap) p_z E_D (zero in A), minus the investments
|
||||
in building and IT hardware paid that year.
|
||||
"""
|
||||
return inntekt - drift - kraftkjop - I_bygg - I_H
|
||||
|
||||
|
||||
def s35_kontantstrom_kraft(
|
||||
*,
|
||||
salg: Belop,
|
||||
investering: Belop,
|
||||
drift: Belop,
|
||||
avvikling: Belop,
|
||||
ulykke: Belop,
|
||||
I_nett: Belop,
|
||||
buffer: Belop,
|
||||
I_g: Belop,
|
||||
F_a: Belop,
|
||||
) -> Belop:
|
||||
"""S35: the cash flow of power plant, grid and capacity in a year, kr.
|
||||
|
||||
``salg`` is varsigma_i psi_i p_z E_G,i summed over the technologies (zero
|
||||
in A), ``ulykke`` is q_N E, ``buffer`` is I_buf + f_buf P_buf and ``I_g``
|
||||
the external supply (both only in A), ``I_nett`` and ``F_a`` only on the grid.
|
||||
"""
|
||||
return salg - investering - drift - avvikling - ulykke - I_nett - buffer - I_g - F_a
|
||||
|
||||
|
||||
def s40_restverdi(
|
||||
*,
|
||||
NK_snitt: float,
|
||||
L_rest: int,
|
||||
rho_D: float,
|
||||
rho_avvikling: float,
|
||||
avvikling: float,
|
||||
T_s: int,
|
||||
T_0: int,
|
||||
) -> float:
|
||||
"""S40: residual value of one facility after the final year, kr in present value at T_0.
|
||||
|
||||
``NK_snitt`` is the average net cash flow of the facility over the last L_H
|
||||
years, ``L_rest`` the operating years left after ``T_s``, ``avvikling`` is
|
||||
D_avv N_u P_u (zero without nuclear power) and ``rho_avvikling`` is rho_N
|
||||
(rho_A in solution A). A facility that loses money gets no value, but the
|
||||
decommissioning is always deducted. With no years left the value is zero
|
||||
(clarification 21): the decommissioning then stands in S35.
|
||||
|
||||
The same form gives the power plant's own part (clarification 22) when
|
||||
``NK_snitt`` holds the plant's own cash flow.
|
||||
"""
|
||||
if L_rest <= 0:
|
||||
return 0.0
|
||||
verdi = max(0.0, NK_snitt / s1_crf(rho=rho_D, L=L_rest))
|
||||
etter = verdi - avvikling * (1.0 + rho_avvikling) ** -L_rest
|
||||
return float(etter * (1.0 + rho_D) ** -(T_s - T_0))
|
||||
|
||||
|
||||
def s26_subsidieelement(*, naaverdi_prosjekt: float) -> float:
|
||||
"""S26: SE = max(0, -present value of the project's net cash flow), kr."""
|
||||
return max(0.0, -naaverdi_prosjekt)
|
||||
|
||||
|
||||
def s26_netto_naaverdi(
|
||||
*,
|
||||
NV_datasenter: float,
|
||||
NV_kraft: float,
|
||||
NV_ovrige: float,
|
||||
varphi: float,
|
||||
SE: float,
|
||||
RV: float,
|
||||
) -> float:
|
||||
"""S26: net present value for Norway against the zero alternative, kr.
|
||||
|
||||
``NV_datasenter`` is the sum of D_D(t) KS_D(t), ``NV_kraft`` the sum of
|
||||
D_N(t) KS_N(t) (with rho_A in solution A) and ``NV_ovrige`` the sum of
|
||||
D_N(t) [Delta W - p_CO2 U^NO - K_prog - V].
|
||||
"""
|
||||
return NV_datasenter + NV_kraft + NV_ovrige - varphi * SE + RV
|
||||
|
||||
|
||||
def s45_los_tilleggsfaktor(*, naaverdi: Callable[[float], float]) -> float:
|
||||
"""S45 by iteration (clarifications 12 and 22): varsigma_i for one technology.
|
||||
|
||||
``naaverdi(varsigma)`` is NV_i, the present value of the power plants' own
|
||||
cash flow with the sales revenue multiplied by ``varsigma``, residual value
|
||||
included. It is continuous and does not fall with ``varsigma``. Returns 1
|
||||
when NV_i(1) <= 0, otherwise the factor that gives NV_i = 0, found by
|
||||
halving the interval.
|
||||
"""
|
||||
if naaverdi(1.0) <= 0:
|
||||
return 1.0
|
||||
lav, hoy = 0.0, 1.0
|
||||
while hoy - lav > HALVERINGSTOLERANSE:
|
||||
midt = (lav + hoy) / 2.0
|
||||
if naaverdi(midt) <= 0:
|
||||
lav = midt
|
||||
else:
|
||||
hoy = midt
|
||||
return lav
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@ How one draw is made:
|
|||
distribution function of each quantity.
|
||||
4. KF is set to (1 - o_p)(1 - o_f) when the drawn value is higher.
|
||||
|
||||
Events that are drawn per year (the export rule) use their own stream and are
|
||||
generated together with the build-out (S22), not here.
|
||||
Events that are drawn per year (the export rule) use their own stream, which
|
||||
``tokenfabrikker.hendelser`` makes and stores.
|
||||
|
||||
Run ``python -m tokenfabrikker.trekninger lag`` to write the files and
|
||||
``python -m tokenfabrikker.trekninger kontroll`` to check that they can be
|
||||
|
|
@ -150,7 +150,7 @@ def beskrivelse(trekninger: Trekninger, sett: Parametersett, sha256_tabell: str)
|
|||
return json.dumps(innhold, ensure_ascii=False, indent=2) + "\n"
|
||||
|
||||
|
||||
def _tabellbytes(tabell: npt.NDArray[np.float64]) -> bytes:
|
||||
def tabellbytes(tabell: npt.NDArray[np.float64]) -> bytes:
|
||||
"""The bytes ``numpy.save`` writes for the table (little-endian float64, C order)."""
|
||||
import io # noqa: PLC0415 (only needed here)
|
||||
|
||||
|
|
@ -162,7 +162,7 @@ def _tabellbytes(tabell: npt.NDArray[np.float64]) -> bytes:
|
|||
def skriv(trekninger: Trekninger, sett: Parametersett, mappe: Path = DATAMAPPE) -> str:
|
||||
"""Write both files and return the checksum of the table."""
|
||||
mappe.mkdir(parents=True, exist_ok=True)
|
||||
raa = _tabellbytes(trekninger.tabell)
|
||||
raa = tabellbytes(trekninger.tabell)
|
||||
sha256 = hashlib.sha256(raa).hexdigest()
|
||||
(mappe / TABELLFIL).write_bytes(raa)
|
||||
(mappe / BESKRIVELSESFIL).write_text(beskrivelse(trekninger, sett, sha256), encoding="utf-8")
|
||||
|
|
@ -193,7 +193,7 @@ def kontroller(sett: Parametersett, mappe: Path = DATAMAPPE) -> tuple[str, float
|
|||
ny = trekk(sett)
|
||||
if ny.kolonner != lagret.kolonner or ny.tabell.shape != lagret.tabell.shape:
|
||||
return "endret", math.inf
|
||||
if _tabellbytes(ny.tabell) == (mappe / TABELLFIL).read_bytes():
|
||||
if tabellbytes(ny.tabell) == (mappe / TABELLFIL).read_bytes():
|
||||
return "identisk", 0.0
|
||||
nevner = np.maximum(np.abs(lagret.tabell), np.finfo(np.float64).tiny)
|
||||
avvik = float(np.max(np.abs(ny.tabell - lagret.tabell) / nevner))
|
||||
|
|
|
|||
265
src/tokenfabrikker/utbygging.py
Normal file
265
src/tokenfabrikker/utbygging.py
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
"""The build-out of a programme (chapter 4 of the specification).
|
||||
|
||||
A path is a number of facilities built as fast as S22 allows. This module
|
||||
decides the year each facility starts, the vintages of IT hardware it gets, and
|
||||
the years in which an export rule stops the delivery of chips.
|
||||
|
||||
How the limit in S22 is read (specification, chapter 16):
|
||||
|
||||
- Each of the three terms is accumulated from the decision year T_0. Facility
|
||||
number k starts the first year, not before t_1^min, in which each accumulated
|
||||
term has room for k whole facilities.
|
||||
- Chips are a stock: what has been delivered since T_0, minus what new
|
||||
facilities and replaced vintages have used. Replacement comes before new
|
||||
facilities; the vintage that expired first is replaced first, and among
|
||||
those that expired the same year the lowest facility number.
|
||||
- A vintage that has reached its lifetime and cannot be replaced (no chips in
|
||||
stock, or an export rule in force) earns nothing until it is replaced. The
|
||||
facility then uses no power, but is still operated and still carries its
|
||||
fixed costs.
|
||||
- While an export rule is in force nothing is delivered, and neither a new
|
||||
facility nor a new vintage can start.
|
||||
|
||||
Nothing here reads the parameter file or draws random numbers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from tokenfabrikker import ligninger as lg
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
|
||||
class Losning(enum.StrEnum):
|
||||
"""The power solutions (chapter 0). B' is the plant of A connected to the grid."""
|
||||
|
||||
A = "A"
|
||||
B = "B"
|
||||
B_MERKET = "B'"
|
||||
C = "C"
|
||||
R = "R"
|
||||
|
||||
@property
|
||||
def paa_nett(self) -> bool:
|
||||
"""True for the solutions where the data centre buys from the grid."""
|
||||
return self is not Losning.A
|
||||
|
||||
@property
|
||||
def kjernekraft(self) -> bool:
|
||||
"""True for the solutions with nuclear power."""
|
||||
return self in {Losning.A, Losning.B, Losning.B_MERKET}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Anleggsplan:
|
||||
"""One facility in a path.
|
||||
|
||||
Attributes:
|
||||
start: first operating year.
|
||||
siste_driftsaar: start + L_N - 1, the last operating year; may lie after the final year.
|
||||
aarganger: first operating year of each vintage of IT hardware, in order.
|
||||
"""
|
||||
|
||||
start: int
|
||||
siste_driftsaar: int
|
||||
aarganger: tuple[int, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""The build-out of one path.
|
||||
|
||||
Attributes:
|
||||
N_anlegg: the number of facilities the path asks for.
|
||||
T_0: decision year.
|
||||
T_s: final year of the analysis.
|
||||
L_H: lifetime of IT hardware in whole years.
|
||||
anlegg: the facilities that start within the final year, in order.
|
||||
stopp: for each year T_0 + 1 .. T_s, True when an export rule stops deliveries.
|
||||
"""
|
||||
|
||||
N_anlegg: int
|
||||
T_0: int
|
||||
T_s: int
|
||||
L_H: int
|
||||
anlegg: tuple[Anleggsplan, ...]
|
||||
stopp: tuple[bool, ...]
|
||||
|
||||
@property
|
||||
def gjennomforbar(self) -> bool:
|
||||
"""True when every facility of the path is in operation within the final year."""
|
||||
return len(self.anlegg) == self.N_anlegg
|
||||
|
||||
@property
|
||||
def t_1(self) -> int:
|
||||
"""The year the first facility starts."""
|
||||
if not self.anlegg:
|
||||
msg = "no facility starts within the final year"
|
||||
raise ValueError(msg)
|
||||
return self.anlegg[0].start
|
||||
|
||||
def i_drift(self, k: int, t: int) -> bool:
|
||||
"""True when facility ``k`` (0 is the first) is operated in year ``t``."""
|
||||
anlegg = self.anlegg[k]
|
||||
return anlegg.start <= t <= min(anlegg.siste_driftsaar, self.T_s)
|
||||
|
||||
def antall_i_drift(self, t: int) -> int:
|
||||
"""The number of facilities operated in year ``t``."""
|
||||
return sum(self.i_drift(k, t) for k in range(len(self.anlegg)))
|
||||
|
||||
def aargang(self, k: int, t: int) -> int | None:
|
||||
"""The vintage of facility ``k`` that earns revenue in year ``t`` (S16), or None.
|
||||
|
||||
None when the facility is not operated that year, or when its latest
|
||||
vintage has reached its lifetime and has not been replaced.
|
||||
"""
|
||||
if not self.i_drift(k, t):
|
||||
return None
|
||||
siste = max(v for v in self.anlegg[k].aarganger if v <= t)
|
||||
return siste if t < siste + self.L_H else None
|
||||
|
||||
def har_last(self, k: int, t: int) -> bool:
|
||||
"""True when facility ``k`` has a vintage in operation in year ``t``, and so uses power."""
|
||||
return self.aargang(k, t) is not None
|
||||
|
||||
def antall_med_last(self, t: int) -> int:
|
||||
"""The number of facilities with a vintage in operation in year ``t``."""
|
||||
return sum(self.har_last(k, t) for k in range(len(self.anlegg)))
|
||||
|
||||
|
||||
def eksportstopp(*, u: Sequence[float], phi_X: float, D_X: float) -> tuple[bool, ...]:
|
||||
"""Chapter 4: the years in which an export rule stops the delivery of chips.
|
||||
|
||||
``u`` holds one uniform number per year from T_0 + 1. A rule is introduced
|
||||
in a year when the number is below ``phi_X``, and it lasts ``D_X`` years
|
||||
(rounded to whole years, clarification 21) from and including that year. A
|
||||
rule introduced while another is in force prolongs the stop.
|
||||
"""
|
||||
varighet = lg.avrundet_varighet(varighet=D_X)
|
||||
stopp = [False] * len(u)
|
||||
for j, tall in enumerate(u):
|
||||
if tall < phi_X:
|
||||
for i in range(j, min(j + varighet, len(u))):
|
||||
stopp[i] = True
|
||||
return tuple(stopp)
|
||||
|
||||
|
||||
def kraftrom_reaktor(*, n_reaktor: float, P_G_N: float, T_0: int) -> Callable[[int], float]:
|
||||
"""S22, first term accumulated from T_0: how many facilities the reactors built have room for.
|
||||
|
||||
``P_G_N`` is the reactor capacity one facility needs (N_u P_u in A and B',
|
||||
lam PUE P_IT / KF in B).
|
||||
"""
|
||||
per_aar = lg.s22_grense_reaktor(n_reaktor=n_reaktor, P_IT=1.0, P_G_N=P_G_N)
|
||||
return lambda t: per_aar * (t - T_0)
|
||||
|
||||
|
||||
def kraftrom_fornybar(
|
||||
*,
|
||||
g_fornybar: float,
|
||||
w_tort_vann: float,
|
||||
E_vann_rest: float,
|
||||
E_vind_rest: float,
|
||||
E_D: float,
|
||||
T_0: int,
|
||||
) -> Callable[[int], float]:
|
||||
"""S22, second term accumulated from T_0 (C): facilities the renewable power has room for.
|
||||
|
||||
The pace ``g_fornybar`` (MWh of normal-year production per year) is filled
|
||||
in the fixed order of S39, and what counts is the production in a dry year.
|
||||
"""
|
||||
|
||||
def rom(t: int) -> float:
|
||||
torr = lg.s39_torraarsenergi_av_takt(
|
||||
E_normal=g_fornybar * (t - T_0),
|
||||
w_tort_vann=w_tort_vann,
|
||||
E_vann_rest=E_vann_rest,
|
||||
E_vind_rest=E_vind_rest,
|
||||
)
|
||||
return torr / E_D
|
||||
|
||||
return rom
|
||||
|
||||
|
||||
def kraftrom_ubegrenset(_t: int) -> float:
|
||||
"""R: no new power is built, so the power side sets no limit."""
|
||||
return math.inf
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Anlegg:
|
||||
start: int
|
||||
siste_driftsaar: int
|
||||
aarganger: list[int]
|
||||
|
||||
|
||||
def _rommer(mengde: float, behov: float) -> bool:
|
||||
"""True when ``mengde`` covers ``behov``, allowing for rounding in the last digit."""
|
||||
return mengde >= behov * (1.0 - lg.AVRUNDINGSTOLERANSE)
|
||||
|
||||
|
||||
def utbyggingsplan(
|
||||
*,
|
||||
N_anlegg: int,
|
||||
T_0: int,
|
||||
T_s: int,
|
||||
t_min: int,
|
||||
P_IT: float,
|
||||
L_H: int,
|
||||
L_N: int,
|
||||
brikker_per_aar: float,
|
||||
kraftrom: Callable[[int], float],
|
||||
stopp: Sequence[bool],
|
||||
forste_brikkeaar: int | None = None,
|
||||
) -> Plan:
|
||||
"""S22: the year each facility starts and the vintages it gets.
|
||||
|
||||
``t_min`` is the first possible operating year (S33, rounded up),
|
||||
``brikker_per_aar`` the third term of S22 without replacement (MW IT per
|
||||
year), ``kraftrom(t)`` the number of facilities the accumulated power-side
|
||||
limit has room for in year t, and ``stopp`` the export stops from
|
||||
``eksportstopp``. ``L_H`` and ``L_N`` are whole years (clarification 21).
|
||||
|
||||
``forste_brikkeaar`` is the first year whose deliveries of chips count.
|
||||
The specification counts from T_0, so the default is T_0 + 1; ``t_min``
|
||||
gives the reading where chips cannot be saved up before a facility can
|
||||
start (specification, chapter 16).
|
||||
"""
|
||||
if len(stopp) != T_s - T_0:
|
||||
msg = f"expected one export flag per year after T_0 ({T_s - T_0}), got {len(stopp)}"
|
||||
raise ValueError(msg)
|
||||
forste_brikkeaar = T_0 + 1 if forste_brikkeaar is None else forste_brikkeaar
|
||||
lager = 0.0
|
||||
anlegg: list[_Anlegg] = []
|
||||
for t in range(T_0 + 1, T_s + 1):
|
||||
if stopp[t - T_0 - 1]:
|
||||
continue
|
||||
if t >= forste_brikkeaar:
|
||||
lager += brikker_per_aar
|
||||
venter = [a for a in anlegg if a.aarganger[-1] + L_H <= t <= a.siste_driftsaar]
|
||||
for a in sorted(venter, key=lambda a: a.aarganger[-1]):
|
||||
if _rommer(lager, P_IT):
|
||||
a.aarganger.append(t)
|
||||
lager -= P_IT
|
||||
while (
|
||||
t >= t_min
|
||||
and len(anlegg) < N_anlegg
|
||||
and _rommer(lager, P_IT)
|
||||
and _rommer(kraftrom(t), len(anlegg) + 1)
|
||||
):
|
||||
anlegg.append(_Anlegg(start=t, siste_driftsaar=t + L_N - 1, aarganger=[t]))
|
||||
lager -= P_IT
|
||||
return Plan(
|
||||
N_anlegg=N_anlegg,
|
||||
T_0=T_0,
|
||||
T_s=T_s,
|
||||
L_H=L_H,
|
||||
anlegg=tuple(Anleggsplan(a.start, a.siste_driftsaar, tuple(a.aarganger)) for a in anlegg),
|
||||
stopp=tuple(stopp),
|
||||
)
|
||||
174
tests/conftest.py
Normal file
174
tests/conftest.py
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
"""A made-up set of parameter values for the tests of build-out, power system and cash flow.
|
||||
|
||||
Every number is round and invented. Nothing here comes from the frozen
|
||||
parameter file, and no test that uses this set says anything about the
|
||||
hypothesis.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
import pytest
|
||||
|
||||
from tokenfabrikker.inndata import Inndata, Prislinje
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
OMRAADER = ("NO1", "NO2", "NO3", "NO4", "NO5", "Norge")
|
||||
|
||||
GRUNNVERDIER: Mapping[str, float] = {
|
||||
# time and size
|
||||
"T0": 2027,
|
||||
"T_slutt": 2060,
|
||||
"P_IT": 1000.0,
|
||||
# nuclear power: investment (kr/MW), construction and operation
|
||||
"c_N_ref": 100e6,
|
||||
"P_ref": 1000.0,
|
||||
"nu": 1.0,
|
||||
"ell": 0.0,
|
||||
"n_0": 5,
|
||||
"u_xi": 0.9,
|
||||
"w_xi": 0.5,
|
||||
"o_xi": 0.5,
|
||||
"tau_F": 8.0,
|
||||
"tau_reg_min": 2.0,
|
||||
"tau_N": 4.0,
|
||||
"KF": 0.8,
|
||||
"o_p": 0.05,
|
||||
"o_f_stor": 0.02,
|
||||
"o_f_liten": 0.04,
|
||||
"beta_F": 0.1,
|
||||
"chi": 0.1,
|
||||
"A_krav": 0.99,
|
||||
"L_N": 20.0,
|
||||
"f_N": 1e6,
|
||||
"nu_f": 0.0,
|
||||
"v_N": 50.0,
|
||||
"u_N": 70.0,
|
||||
"u_N_liten": 100.0,
|
||||
"d_N": 30.0,
|
||||
"D_avv": 5e6,
|
||||
"phi_U": 1e-5,
|
||||
"K_U": 1e12,
|
||||
"D_fors": 8e9,
|
||||
"aarsverk_prog": 1000.0,
|
||||
"andel_myndighet": 0.2,
|
||||
"c_aarsverk": 1e6,
|
||||
"n_reaktor": 1000.0,
|
||||
# the plant without a grid: buffer and external supply
|
||||
"delta_L": 0.5,
|
||||
"c_buf": 10e6,
|
||||
"f_buf": 0.4e6,
|
||||
"L_buf": 20,
|
||||
"s_g": 0.02,
|
||||
"c_gen": 10e6,
|
||||
"D_linje": 50.0,
|
||||
"c_linje": 10e6,
|
||||
# the data centre
|
||||
"c_H0": 200e6,
|
||||
"gamma_H": 0.0,
|
||||
"c_bygg": 100e6,
|
||||
"d_bygg": 0.1,
|
||||
"L_H": 5,
|
||||
"L_B": 15.0,
|
||||
"tau_D": 2.0,
|
||||
"PUE": 1.2,
|
||||
"PUE_v": 1.2,
|
||||
"lambda": 0.75,
|
||||
"o_D_v": 3e6,
|
||||
"o_D": 2e6,
|
||||
"d_o_D": 0.5e6,
|
||||
"mu_rel": 1.0,
|
||||
"h_knapp": 100.0,
|
||||
# the price of compute
|
||||
"p_v": 800.0,
|
||||
"y_obs": 150e6,
|
||||
"T_knapp": 10,
|
||||
"pi_neg": -0.3,
|
||||
# the power system
|
||||
"S0": 10e6,
|
||||
"b_ut": 2.0,
|
||||
"m_tort": 1.5,
|
||||
"s_tort": 1.2,
|
||||
"w_tort_vann": 0.8,
|
||||
"psi_N": 1.0,
|
||||
"kappa_vind": 0.05,
|
||||
"c_fast": 1.4e6,
|
||||
"c_res": 1.0e6,
|
||||
"I_nett": 5e6,
|
||||
"L_nett": 40,
|
||||
"tau_nett": 3.0,
|
||||
"n_tap": 0.05,
|
||||
"t_el": 70.0,
|
||||
"delta_V": 0.5,
|
||||
# renewable power
|
||||
"vind.investering": 14e6,
|
||||
"vind.drift": 120.0,
|
||||
"vind.fullasttimer": 3000.0,
|
||||
"vind.levetid": 30,
|
||||
"vind.byggetid": 2,
|
||||
"vann.investering": 20e6,
|
||||
"vann.drift": 70.0,
|
||||
"vann.fullasttimer": 3000.0,
|
||||
"vann.levetid": 40,
|
||||
"vann.byggetid": 3,
|
||||
"havvind.investering": 50e6,
|
||||
"havvind.drift": 0.9e6,
|
||||
"havvind.fullasttimer": 4500.0,
|
||||
"havvind.levetid": 30,
|
||||
"havvind.byggetid": 3,
|
||||
"E_vann_rest": 2e6,
|
||||
"E_vind_rest": 3e6,
|
||||
"g_fornybar": 4e6,
|
||||
# discounting, emissions, chips
|
||||
"rho_N": 0.06,
|
||||
"rho_D": 0.08,
|
||||
"varphi": 0.2,
|
||||
"s_B_NO": 0.5,
|
||||
"u_B": 2000.0,
|
||||
"phi_X": 0.0,
|
||||
"D_X": 2.0,
|
||||
"s_brikker": 0.04,
|
||||
"G_server": 25_000.0,
|
||||
}
|
||||
"""Round, invented values in the units of the equations (kr, MW, MWh, kr/MWh, years)."""
|
||||
|
||||
|
||||
class LagInndata(Protocol):
|
||||
"""Builds the made-up set, with the named values replaced."""
|
||||
|
||||
def __call__(
|
||||
self, *, u_eksport: tuple[float, ...] | None = None, **endringer: float
|
||||
) -> Inndata:
|
||||
"""Return the set; ``vind__levetid`` replaces ``vind.levetid`` and ``lam`` ``lambda``."""
|
||||
...
|
||||
|
||||
|
||||
def lag_inndata(*, u_eksport: tuple[float, ...] | None = None, **endringer: float) -> Inndata:
|
||||
"""The made-up set; ``vind__drift`` replaces ``vind.drift`` and ``lam`` replaces ``lambda``."""
|
||||
verdier = dict(GRUNNVERDIER)
|
||||
for navn, verdi in endringer.items():
|
||||
noekkel = "lambda" if navn == "lam" else navn.replace("__", ".")
|
||||
if noekkel not in verdier:
|
||||
msg = f"unknown made-up quantity {noekkel!r}"
|
||||
raise KeyError(msg)
|
||||
verdier[noekkel] = verdi
|
||||
antall_aar = round(verdier["T_slutt"] - verdier["T0"])
|
||||
return Inndata(
|
||||
v=verdier,
|
||||
design={"o_f_liten": 0.04, "o_f_stor": 0.02, "o_p": 0.05, "beta_F": 0.1},
|
||||
P_u_sett=(5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0, 1000.0),
|
||||
psi={"vind": 0.9, "vann": 1.2, "havvind": 1.0},
|
||||
kappa={"vann": 0.9, "havvind": 0.0},
|
||||
linjer={omraade: Prislinje(alpha=700.0, b=-10e-6) for omraade in OMRAADER},
|
||||
karbonpris={2026: 1000.0, 2100: 1000.0},
|
||||
u_eksport=(0.5,) * antall_aar if u_eksport is None else u_eksport,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oppdiktet() -> LagInndata:
|
||||
"""The builder of the made-up set of parameter values."""
|
||||
return lag_inndata
|
||||
161
tests/test_hendelser.py
Normal file
161
tests/test_hendelser.py
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
"""The stream for yearly events and the set of values for one draw.
|
||||
|
||||
These tests look at random numbers and parameter values only. No model result is computed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tokenfabrikker import hendelser, inndata, trekninger
|
||||
from tokenfabrikker import parametere as pm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def sett() -> pm.Parametersett:
|
||||
return pm.les_parametere()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def strom(sett: pm.Parametersett) -> hendelser.Hendelser:
|
||||
return hendelser.trekk(sett)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- the stream
|
||||
|
||||
|
||||
def test_froet_staar_i_parameterfila(sett: pm.Parametersett) -> None:
|
||||
assert hendelser.froe(sett) == 20261112
|
||||
assert hendelser.froe(sett) != sett.monte_carlo.froe
|
||||
|
||||
|
||||
def test_ett_tall_per_trekning_og_aar_etter_beslutningsaaret(strom: hendelser.Hendelser) -> None:
|
||||
assert strom.aar == tuple(range(2028, 2101))
|
||||
assert strom.tabell.shape == (10_000, 73)
|
||||
assert strom.tabell.dtype == np.float64
|
||||
assert ((strom.tabell >= 0.0) & (strom.tabell < 1.0)).all()
|
||||
assert len(strom.rad(0)) == 73
|
||||
|
||||
|
||||
def test_tallene_er_jevnt_fordelt(strom: hendelser.Hendelser) -> None:
|
||||
"""730 000 numbers: mean 0.5 and a tenth in each tenth, within four standard errors."""
|
||||
antall = strom.tabell.size
|
||||
assert abs(float(strom.tabell.mean()) - 0.5) < 4 * (1 / 12) ** 0.5 / antall**0.5
|
||||
andeler = np.histogram(strom.tabell, bins=10, range=(0.0, 1.0))[0] / antall
|
||||
assert float(np.abs(andeler - 0.1).max()) < 4 * (0.1 * 0.9 / antall) ** 0.5
|
||||
|
||||
|
||||
def test_aarene_er_ikke_korrelert_med_hverandre(strom: hendelser.Hendelser) -> None:
|
||||
korrelasjon = np.asarray(np.corrcoef(strom.tabell[:, :10], rowvar=False), dtype=np.float64)
|
||||
np.fill_diagonal(korrelasjon, 0.0)
|
||||
assert float(np.abs(korrelasjon).max()) < 4 / 10_000**0.5
|
||||
|
||||
|
||||
def test_strommen_er_en_annen_enn_parametertrekningene(
|
||||
sett: pm.Parametersett, strom: hendelser.Hendelser
|
||||
) -> None:
|
||||
trukket = trekninger.trekk(sett)
|
||||
assert abs(float(np.corrcoef(strom.tabell[:, 0], trukket.kolonne("phi_X"))[0, 1])) < 0.04
|
||||
|
||||
|
||||
def test_samme_fro_gir_samme_strom(sett: pm.Parametersett, strom: hendelser.Hendelser) -> None:
|
||||
assert np.array_equal(hendelser.trekk(sett).tabell, strom.tabell)
|
||||
|
||||
|
||||
def test_den_lagrede_strommen_kan_gjenskapes(sett: pm.Parametersett) -> None:
|
||||
assert hendelser.kontroller(sett) == ("identisk", 0.0)
|
||||
|
||||
|
||||
def test_skriv_og_les(sett: pm.Parametersett, strom: hendelser.Hendelser, tmp_path: Path) -> None:
|
||||
sha256 = hendelser.skriv(strom, sett, tmp_path)
|
||||
lest = hendelser.les(tmp_path)
|
||||
assert lest.aar == strom.aar
|
||||
assert np.array_equal(lest.tabell, strom.tabell)
|
||||
beskrivelse = json.loads((tmp_path / hendelser.BESKRIVELSESFIL).read_text(encoding="utf-8"))
|
||||
assert beskrivelse["sha256_tabell"] == sha256
|
||||
assert beskrivelse["froe"] == 20261112
|
||||
assert beskrivelse["sha256_parametere"] == pm.FROSSEN_SHA256
|
||||
assert hendelser.kontroller(sett, tmp_path) == ("identisk", 0.0)
|
||||
|
||||
|
||||
def test_endret_tabell_oppdages(
|
||||
sett: pm.Parametersett, strom: hendelser.Hendelser, tmp_path: Path
|
||||
) -> None:
|
||||
hendelser.skriv(strom, sett, tmp_path)
|
||||
endret = strom.tabell.copy()
|
||||
endret[0, 0] = 0.123
|
||||
(tmp_path / hendelser.TABELLFIL).write_bytes(trekninger.tabellbytes(endret))
|
||||
with pytest.raises(pm.ParameterError, match="does not match the checksum"):
|
||||
hendelser.les(tmp_path)
|
||||
|
||||
|
||||
def test_kommandolinja(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
assert hendelser.main(["lag", "--mappe", str(tmp_path)]) == 0
|
||||
assert "10000 trekninger for 73 år skrevet" in capsys.readouterr().out
|
||||
assert hendelser.main(["kontroll", "--mappe", str(tmp_path)]) == 0
|
||||
assert capsys.readouterr().out.startswith("identisk")
|
||||
|
||||
|
||||
# ---------------------------------------------------- the values of one draw
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def forste_trekning(sett: pm.Parametersett) -> inndata.Inndata:
|
||||
return inndata.fra_trekning(sett, trekninger.les(), hendelser.les().rad(0), 0)
|
||||
|
||||
|
||||
def test_verdiene_er_regnet_om_til_ligningenes_enheter(
|
||||
sett: pm.Parametersett, forste_trekning: inndata.Inndata
|
||||
) -> None:
|
||||
"""Units only: kr/kW to kr/MW, TWh to MWh, GW to MW, mill. and mrd. kr to kr."""
|
||||
inn = forste_trekning
|
||||
assert 109_000e3 <= inn["c_N_ref"] <= 171_500e3
|
||||
assert -15e6 <= inn["S0"] <= 19.6e6
|
||||
assert inn["G_server"] == 25_000.0
|
||||
assert inn["D_fors"] == 8202e6
|
||||
assert 1625e9 <= inn["K_U"] <= 6217e9
|
||||
assert 0.2e6 <= inn["g_fornybar"] <= 0.6e6
|
||||
assert 10_100e3 <= inn["vind.investering"] <= 21_933e3
|
||||
assert inn["havvind.drift"] == 900e3
|
||||
assert inn["vind.drift"] == 120.0
|
||||
assert (inn.heltall("T0"), inn.heltall("T_slutt")) == (2027, 2100)
|
||||
assert inn.heltall("L_H") in {3, 4, 5, 6, 7}
|
||||
assert inn.heltall("n_0") in range(1, 21)
|
||||
for storrelse in sett.storrelser():
|
||||
assert (storrelse.navn in inn.v) == (storrelse.fordeling.tabell is None)
|
||||
|
||||
|
||||
def test_tabellene_og_designverdiene_foelger_parameterfila(
|
||||
forste_trekning: inndata.Inndata,
|
||||
) -> None:
|
||||
inn = forste_trekning
|
||||
assert inn.design == {"o_f_liten": 0.0465, "o_f_stor": 0.025, "o_p": 0.05, "beta_F": 0.1}
|
||||
assert inn.P_u_sett == (5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0, 1000.0)
|
||||
assert inn.psi == {"vind": 0.88, "vann": 1.26, "havvind": 0.96}
|
||||
assert inn.kappa == {"vann": 0.88, "havvind": 0.0}
|
||||
assert set(inn.linjer) == {"NO1", "NO2", "NO3", "NO4", "NO5", "Norge"}
|
||||
assert inn.karbonpris[2026] == 1588.0
|
||||
assert len(inn.u_eksport) == 73
|
||||
|
||||
|
||||
def test_karbonprisen_er_lineaer_mellom_aarene_i_tabellen(
|
||||
forste_trekning: inndata.Inndata,
|
||||
) -> None:
|
||||
inn = forste_trekning
|
||||
assert inn.karbonpris_i(2030) == 2377.0
|
||||
assert inn.karbonpris_i(2028) == pytest.approx((1588.0 + 2377.0) / 2)
|
||||
assert inn.karbonpris_i(2045) == 3367.0
|
||||
assert inn.karbonpris_i(2100) == 10956.0
|
||||
assert inn.karbonpris_i(2025) == 1588.0
|
||||
|
||||
|
||||
def test_heltall_avviser_tall_som_ikke_er_hele(forste_trekning: inndata.Inndata) -> None:
|
||||
with pytest.raises(ValueError, match="should be a whole number"):
|
||||
forste_trekning.heltall("rho_N")
|
||||
794
tests/test_kontantstrom.py
Normal file
794
tests/test_kontantstrom.py
Normal file
|
|
@ -0,0 +1,794 @@
|
|||
"""The cash flow and the net present value (chapters 0 and 6): S26, S34, S35, S40 and S45.
|
||||
|
||||
Everything is computed on the made-up set in ``conftest.py``. The numbers say nothing
|
||||
about the hypothesis.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from tokenfabrikker import kontantstrom as ks
|
||||
from tokenfabrikker import ligninger as lg
|
||||
from tokenfabrikker.kontantstrom import Knapphet
|
||||
from tokenfabrikker.utbygging import Losning
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from conftest import LagInndata
|
||||
from tokenfabrikker.inndata import Inndata
|
||||
|
||||
E_D = 8760.0 * 0.75 * 1.2 * 1000.0
|
||||
"""Yearly energy to one made-up data centre: 7 884 000 MWh."""
|
||||
|
||||
|
||||
def _crf(rho: float, levetid: float) -> float:
|
||||
return float(rho / (1.0 - (1.0 + rho) ** -levetid))
|
||||
|
||||
|
||||
def _lcoc_v() -> float:
|
||||
"""S15 for the made-up competitor, per MW IT and year."""
|
||||
return 100e6 * _crf(0.08, 15) + 200e6 * _crf(0.08, 5) + 3e6 + 8760.0 * 0.75 * 1.2 * 800.0
|
||||
|
||||
|
||||
def _regn(
|
||||
inn: Inndata,
|
||||
losning: Losning,
|
||||
*,
|
||||
N_anlegg: int = 1,
|
||||
knapphet: Knapphet = Knapphet.NORMALISERING,
|
||||
tilleggsregel: bool = True,
|
||||
) -> ks.Programresultat:
|
||||
dim = ks.dimensjoner(inn, losning)
|
||||
plan = ks.lag_plan(inn, losning, dim, N_anlegg=N_anlegg)
|
||||
return ks.regn_program(inn, losning, plan, knapphet, dim=dim, tilleggsregel=tilleggsregel)
|
||||
|
||||
|
||||
# ----------------------------------------------------- the equations one at a time
|
||||
|
||||
|
||||
def test_s34_og_s35_er_summer_av_leddene() -> None:
|
||||
assert lg.s34_kontantstrom_datasenter(
|
||||
inntekt=100.0, drift=10.0, kraftkjop=20.0, I_bygg=5.0, I_H=30.0
|
||||
) == pytest.approx(35.0)
|
||||
assert lg.s35_kontantstrom_kraft(
|
||||
salg=50.0,
|
||||
investering=10.0,
|
||||
drift=5.0,
|
||||
avvikling=1.0,
|
||||
ulykke=2.0,
|
||||
I_nett=3.0,
|
||||
buffer=4.0,
|
||||
I_g=6.0,
|
||||
F_a=7.0,
|
||||
) == pytest.approx(12.0)
|
||||
|
||||
|
||||
def test_s40_haandregnet() -> None:
|
||||
"""100 a year for 3 years at 10 % is 248.685; less 50 / 1.05^3; discounted 10 years."""
|
||||
verdi = lg.s40_restverdi(
|
||||
NK_snitt=100.0,
|
||||
L_rest=3,
|
||||
rho_D=0.10,
|
||||
rho_avvikling=0.05,
|
||||
avvikling=50.0,
|
||||
T_s=2037,
|
||||
T_0=2027,
|
||||
)
|
||||
assert verdi == pytest.approx((248.6852 - 43.1919) / 1.1**10, rel=1e-6)
|
||||
|
||||
|
||||
def test_s40_tap_gir_ingen_verdi_men_avviklingen_trekkes_alltid() -> None:
|
||||
verdi = lg.s40_restverdi(
|
||||
NK_snitt=-100.0,
|
||||
L_rest=3,
|
||||
rho_D=0.10,
|
||||
rho_avvikling=0.05,
|
||||
avvikling=50.0,
|
||||
T_s=2027,
|
||||
T_0=2027,
|
||||
)
|
||||
assert verdi == pytest.approx(-50.0 / 1.05**3)
|
||||
|
||||
|
||||
def test_s40_ingen_restverdi_uten_driftstid_igjen() -> None:
|
||||
assert (
|
||||
lg.s40_restverdi(
|
||||
NK_snitt=100.0,
|
||||
L_rest=0,
|
||||
rho_D=0.10,
|
||||
rho_avvikling=0.05,
|
||||
avvikling=50.0,
|
||||
T_s=2037,
|
||||
T_0=2027,
|
||||
)
|
||||
== 0.0
|
||||
)
|
||||
|
||||
|
||||
def test_s26_subsidieelement_og_sum() -> None:
|
||||
assert lg.s26_subsidieelement(naaverdi_prosjekt=-40.0) == 40.0
|
||||
assert lg.s26_subsidieelement(naaverdi_prosjekt=40.0) == 0.0
|
||||
assert lg.s26_netto_naaverdi(
|
||||
NV_datasenter=100.0, NV_kraft=-150.0, NV_ovrige=5.0, varphi=0.2, SE=40.0, RV=10.0
|
||||
) == pytest.approx(-43.0)
|
||||
|
||||
|
||||
def test_s45_iterasjonen_finner_nullpunktet() -> None:
|
||||
assert lg.s45_los_tilleggsfaktor(naaverdi=lambda s: 200.0 * s - 150.0) == pytest.approx(0.75)
|
||||
assert lg.s45_los_tilleggsfaktor(naaverdi=lambda s: 200.0 * s - 250.0) == 1.0
|
||||
# with a kink, as the residual value gives
|
||||
assert lg.s45_los_tilleggsfaktor(
|
||||
naaverdi=lambda s: 100.0 * s - 60.0 + max(0.0, 100.0 * s - 50.0)
|
||||
) == pytest.approx(0.55)
|
||||
|
||||
|
||||
# --------------------------------------------- one facility in R, computed by hand
|
||||
|
||||
|
||||
def test_R_ett_anlegg_aar_for_aar(oppdiktet: LagInndata) -> None:
|
||||
"""One facility that buys from the grid, 2027-2040, every term computed here by hand.
|
||||
|
||||
Start 2030 (grid lead time 3 years). Vintages 2030, 2035 and 2040. Building and first
|
||||
vintage are paid in 2028 and 2029, later vintages the year before they start, the grid
|
||||
connection in 2029.
|
||||
"""
|
||||
inn = oppdiktet(T_slutt=2040)
|
||||
res = _regn(inn, Losning.R)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
y = _lcoc_v()
|
||||
|
||||
assert [(a.start, a.siste_driftsaar, a.aarganger) for a in res.plan.anlegg] == [
|
||||
(2030, 2049, (2030, 2035, 2040))
|
||||
]
|
||||
pris = 700.0 - 10e-6 * (10e6 - 0.5 * E_D)
|
||||
assert res.kraftaar[aar[2035]].pris == pytest.approx(pris)
|
||||
assert res.kraftaar[aar[2029]].pris == pytest.approx(600.0)
|
||||
|
||||
anlegg = res.anlegg[0]
|
||||
assert anlegg.inntekt[aar[2030]] == pytest.approx(1000.0 * y)
|
||||
assert anlegg.inntekt[aar[2029]] == 0.0
|
||||
assert anlegg.drift[aar[2040]] == pytest.approx(2.5e9)
|
||||
assert anlegg.kraftkjop[aar[2033]] == pytest.approx(1.05 * pris * E_D)
|
||||
assert anlegg.I_bygg[aar[2028]] == pytest.approx(55e9)
|
||||
assert anlegg.I_bygg[aar[2029]] == pytest.approx(55e9)
|
||||
assert float(anlegg.I_bygg.sum()) == pytest.approx(110e9)
|
||||
assert [float(anlegg.I_H[aar[t]]) for t in (2028, 2029, 2034, 2039)] == pytest.approx(
|
||||
[100e9, 100e9, 200e9, 200e9]
|
||||
)
|
||||
assert float(anlegg.I_H.sum()) == pytest.approx(600e9)
|
||||
assert anlegg.I_nett[aar[2029]] == pytest.approx(5e6 * 0.5 * 1.2 * 1000.0)
|
||||
assert float(anlegg.I_nett.sum()) == pytest.approx(3e9)
|
||||
|
||||
# S47: 600 MW is missing; disconnection (100 hours) is cheaper than new firm capacity
|
||||
F_a = min(1.4e6 * 600.0, 100.0 * y / (8760.0 * 1.2) * 600.0)
|
||||
assert res.F_a[aar[2031]] == pytest.approx(F_a)
|
||||
assert res.F_a[aar[2029]] == 0.0
|
||||
|
||||
assert res.Delta_W[aar[2031]] == pytest.approx((pris - 600.0) * 10e6)
|
||||
assert res.V[aar[2031]] == pytest.approx(0.5 * E_D * 70.0)
|
||||
assert res.utslipp[aar[2030]] == pytest.approx(1000.0 * 0.5 * 2000.0 * 1000.0)
|
||||
assert float(res.utslipp.sum()) == pytest.approx(1e9)
|
||||
assert not res.K_prog.any()
|
||||
|
||||
# the sums of S26, built up again from the yearly amounts above
|
||||
KS_D, KS_N, ovrige = {}, {}, {}
|
||||
for t in range(2027, 2041):
|
||||
i_drift = t >= 2030
|
||||
KS_D[t] = (1000.0 * y - 2.5e9 - 1.05 * pris * E_D) if i_drift else 0.0
|
||||
KS_D[t] -= {2028: 155e9, 2029: 155e9, 2034: 200e9, 2039: 200e9}.get(t, 0.0)
|
||||
KS_N[t] = -(F_a if i_drift else 0.0) - (3e9 if t == 2029 else 0.0)
|
||||
ovrige[t] = ((pris - 600.0) * 10e6 - 0.5 * E_D * 70.0) if i_drift else 0.0
|
||||
ovrige[t] -= 1e9 if t == 2030 else 0.0
|
||||
NV_D = math.fsum(v / 1.08 ** (t - 2027) for t, v in KS_D.items())
|
||||
NV_N = math.fsum(v / 1.06 ** (t - 2027) for t, v in KS_N.items())
|
||||
NV_ovrige = math.fsum(v / 1.06 ** (t - 2027) for t, v in ovrige.items())
|
||||
assert res.NV_datasenter == pytest.approx(NV_D)
|
||||
assert res.NV_kraft == pytest.approx(NV_N)
|
||||
assert res.NV_ovrige == pytest.approx(NV_ovrige)
|
||||
|
||||
# S40: nine operating years left; the average of 2036-2040 holds the vintage paid in 2039
|
||||
snitt = math.fsum(KS_D[t] + KS_N[t] for t in range(2036, 2041)) / 5.0
|
||||
RV = max(0.0, snitt * (1.0 - 1.08**-9) / 0.08) / 1.08**13
|
||||
assert res.RV == pytest.approx(RV)
|
||||
assert res.RV > 0
|
||||
SE = max(0.0, -(NV_D + NV_N + RV))
|
||||
assert res.SE == pytest.approx(SE)
|
||||
assert res.NNV == pytest.approx(NV_D + NV_N + NV_ovrige - 0.2 * SE + RV)
|
||||
|
||||
|
||||
def test_nnv_er_summen_av_delene_i_alle_losninger(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
for losning in Losning:
|
||||
for knapphet in Knapphet:
|
||||
res = _regn(inn, losning, N_anlegg=2, knapphet=knapphet)
|
||||
D_D = np.array([1.08 ** -(t - 2027) for t in res.aar])
|
||||
D_N = np.array([1.06 ** -(t - 2027) for t in res.aar])
|
||||
D_kraft = D_D if losning is Losning.A else D_N
|
||||
assert res.NV_datasenter == pytest.approx(float(D_D @ res.KS_D))
|
||||
assert res.NV_kraft == pytest.approx(float(D_kraft @ res.KS_N))
|
||||
assert res.NV_ovrige == pytest.approx(
|
||||
float(D_N @ (res.Delta_W - res.utslipp - res.K_prog - res.V))
|
||||
)
|
||||
assert res.SE == pytest.approx(max(0.0, -(res.NV_datasenter + res.NV_kraft + res.RV)))
|
||||
assert res.NNV == pytest.approx(
|
||||
res.NV_datasenter + res.NV_kraft + res.NV_ovrige - 0.2 * res.SE + res.RV
|
||||
)
|
||||
assert res.KS_D == pytest.approx(sum(a.datasenter() for a in res.anlegg))
|
||||
|
||||
|
||||
def test_prisscenarioene_skiller_seg_bare_i_knapphetens_ti_aar(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
y = _lcoc_v()
|
||||
paaslag = 150e6 / y - 1.0
|
||||
pris = {k: ks.regnekraftpris(inn, k, t_1=2030) for k in Knapphet}
|
||||
assert pris[Knapphet.NORMALISERING](2030) == pytest.approx(y)
|
||||
assert pris[Knapphet.VARER](2030) == pytest.approx(150e6)
|
||||
assert pris[Knapphet.VARER](2039) == pytest.approx(y * (1.0 + paaslag))
|
||||
assert pris[Knapphet.VARER](2040) == pytest.approx(y)
|
||||
assert pris[Knapphet.OVERKAPASITET](2035) == pytest.approx(0.7 * y)
|
||||
assert pris[Knapphet.OVERKAPASITET](2040) == pytest.approx(y)
|
||||
|
||||
|
||||
def test_negativt_paaslag_settes_til_null(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet(y_obs=10e6)
|
||||
assert ks.regnekraftpris(inn, Knapphet.VARER, t_1=2030)(2030) == pytest.approx(_lcoc_v())
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------ timing
|
||||
|
||||
|
||||
def test_byggetid_som_ikke_er_hele_aar_fordeles_etter_andel(oppdiktet: LagInndata) -> None:
|
||||
res = _regn(oppdiktet(tau_D=2.5, T_slutt=2040), Losning.R)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
bygg = res.anlegg[0].I_bygg
|
||||
assert [float(bygg[aar[t]]) for t in (2027, 2028, 2029)] == pytest.approx([22e9, 44e9, 44e9])
|
||||
|
||||
|
||||
def test_levetid_for_bygg_rundes_og_bygget_fornyes(oppdiktet: LagInndata) -> None:
|
||||
"""L_B = 4.4 is four years in the cash flow: buildings enter operation in 2030, 2034, 2038."""
|
||||
res = _regn(oppdiktet(L_B=4.4, T_slutt=2040), Losning.R)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
assert res.anlegg[0].bygg_i_drift == (2030, 2034, 2038)
|
||||
assert res.anlegg[0].I_bygg[aar[2033]] == pytest.approx(55e9)
|
||||
assert float(res.anlegg[0].I_bygg.sum()) == pytest.approx(330e9)
|
||||
# emissions from building in Norway each time a building enters operation
|
||||
assert [float(res.utslipp[aar[t]]) for t in (2030, 2034, 2038)] == pytest.approx([1e9] * 3)
|
||||
|
||||
|
||||
def test_betaling_for_beslutningsaaret_er_en_feil(oppdiktet: LagInndata) -> None:
|
||||
with pytest.raises(ValueError, match="before the decision year"):
|
||||
_regn(oppdiktet(tau_D=3.5, tau_nett=2.0), Losning.R)
|
||||
|
||||
|
||||
def test_bane_som_ikke_lar_seg_bygge_har_ingen_naaverdi(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet(s_brikker=0.001) # 25 MW of chips a year: 825 MW by 2060
|
||||
dim = ks.dimensjoner(inn, Losning.R)
|
||||
plan = ks.lag_plan(inn, Losning.R, dim, N_anlegg=1)
|
||||
assert not plan.gjennomforbar
|
||||
with pytest.raises(ValueError, match="cannot be built"):
|
||||
ks.regn_program(inn, Losning.R, plan, Knapphet.NORMALISERING)
|
||||
|
||||
|
||||
def test_anlegg_uten_brikker_har_verken_inntekt_eller_kraftbruk(oppdiktet: LagInndata) -> None:
|
||||
"""Chips for one vintage every five years, but a three-year export stop from 2035.
|
||||
|
||||
The vintage from 2030 has expired in 2035 and is replaced in 2038. In between the
|
||||
facility earns nothing and uses no power, but its fixed operation is still paid.
|
||||
"""
|
||||
u = tuple(0.0 if aar == 2035 else 0.5 for aar in range(2028, 2061))
|
||||
inn = oppdiktet(u_eksport=u, phi_X=0.1, D_X=3.0, s_brikker=0.02)
|
||||
res = _regn(inn, Losning.R)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
assert res.plan.stopp[2035 - 2028 : 2039 - 2028] == (True, True, True, False)
|
||||
assert res.plan.anlegg[0].aarganger[:2] == (2030, 2038)
|
||||
anlegg = res.anlegg[0]
|
||||
for t in (2035, 2036, 2037):
|
||||
assert anlegg.inntekt[aar[t]] == 0.0
|
||||
assert anlegg.kraftkjop[aar[t]] == 0.0
|
||||
assert anlegg.drift[aar[t]] == pytest.approx(2.5e9)
|
||||
assert res.kraftaar[aar[t]].Delta_Q == 0.0
|
||||
assert res.kraftaar[aar[t]].Delta_R == 0.0
|
||||
assert res.F_a[aar[t]] == 0.0
|
||||
assert res.V[aar[t]] == 0.0
|
||||
assert res.Delta_W[aar[t]] == 0.0
|
||||
assert anlegg.inntekt[aar[2038]] > 0
|
||||
assert anlegg.kraftkjop[aar[2038]] > 0
|
||||
assert res.V[aar[2038]] > 0
|
||||
|
||||
|
||||
def test_A_uten_brikker_betaler_fast_men_ikke_variabel_drift(oppdiktet: LagInndata) -> None:
|
||||
"""A stop from 2040 to 2042: the plant's fixed operation runs on, fuel and waste fee do not."""
|
||||
u = tuple(0.0 if aar == 2040 else 0.5 for aar in range(2028, 2061))
|
||||
inn = oppdiktet(u_eksport=u, phi_X=0.1, D_X=3.0)
|
||||
res = _regn(inn, Losning.A)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
assert res.plan.anlegg[0].aarganger[:2] == (2035, 2043)
|
||||
drift = res.anlegg[0].kraftdrift[ks.KJERNEKRAFT]
|
||||
fast = 1e6 * res.dim.N_u * 50.0
|
||||
assert drift[aar[2039]] == pytest.approx(fast + 180.0 * E_D)
|
||||
assert drift[aar[2041]] == pytest.approx(fast)
|
||||
assert res.anlegg[0].ulykke[aar[2041]] > 0
|
||||
|
||||
|
||||
def test_kraftverk_paa_nettet_selger_ogsaa_naar_anlegget_staar(oppdiktet: LagInndata) -> None:
|
||||
u = tuple(0.0 if aar == 2040 else 0.5 for aar in range(2028, 2061))
|
||||
inn = oppdiktet(u_eksport=u, phi_X=0.1, D_X=3.0)
|
||||
res = _regn(inn, Losning.B)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
anlegg = res.anlegg[0]
|
||||
assert anlegg.kraftkjop[aar[2041]] == 0.0
|
||||
assert res.felles[0].salg[aar[2041]] > 0
|
||||
# all the new production is surplus that year
|
||||
assert res.kraftaar[aar[2041]].Delta_Q == pytest.approx(-2 * 8760.0 * 0.8 * 1000.0)
|
||||
|
||||
|
||||
def test_brikker_kan_telles_fra_forste_mulige_aar(oppdiktet: LagInndata) -> None:
|
||||
"""1 000 MW of chips a year. Counted from 2027, three facilities start in 2030.
|
||||
|
||||
Counted from the first possible year (2030), they start in 2030, 2031 and 2032.
|
||||
"""
|
||||
inn = oppdiktet(L_H=7)
|
||||
dim = ks.dimensjoner(inn, Losning.R)
|
||||
fra_beslutning = ks.lag_plan(inn, Losning.R, dim, N_anlegg=3)
|
||||
assert [a.start for a in fra_beslutning.anlegg] == [2030, 2030, 2030]
|
||||
fra_start = ks.lag_plan(inn, Losning.R, dim, N_anlegg=3, brikker_fra_T0=False)
|
||||
assert [a.start for a in fra_start.anlegg] == [2030, 2031, 2032]
|
||||
|
||||
|
||||
def test_uten_eksportregel_brukes_ikke_strommen(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet(u_eksport=(0.0,) * 33, phi_X=0.2)
|
||||
dim = ks.dimensjoner(inn, Losning.R)
|
||||
assert all(ks.lag_plan(inn, Losning.R, dim, N_anlegg=1).stopp)
|
||||
assert not any(ks.lag_plan(inn, Losning.R, dim, N_anlegg=1, eksportregel=False).stopp)
|
||||
|
||||
|
||||
# ----------------------------------------------------- the dedicated plant (A)
|
||||
|
||||
|
||||
def test_A_dimensjonering_og_kraftverk(oppdiktet: LagInndata) -> None:
|
||||
"""Average load 900 MW and chi = 0.1 give 50 MW units; 1 200 MW peak needs 24 of them."""
|
||||
inn = oppdiktet()
|
||||
dim = ks.dimensjoner(inn, Losning.A)
|
||||
assert (dim.P_u, dim.m) == (50.0, 24)
|
||||
assert dim.N_u == dim.m + dim.r + dim.n_p
|
||||
assert 0.99 < dim.Gamma < 1.0
|
||||
assert dim.xi_N == 1.0
|
||||
assert dim.rho_A == 0.08
|
||||
(verk,) = ks.kraftverk_for_anlegg(inn, Losning.A, dim, 2)
|
||||
assert verk.effekt == dim.N_u * 50.0
|
||||
assert not verk.selges
|
||||
assert verk.energi == pytest.approx(E_D)
|
||||
# nu = 1 and no learning: every unit costs the reference 100 mill. kr per MW
|
||||
assert verk.investering == pytest.approx(100e6 * dim.N_u * 50.0)
|
||||
# fixed operation per MW, and variable operation, small-unit fuel and waste fee per MWh used
|
||||
assert verk.fast_drift == pytest.approx(1e6 * dim.N_u * 50.0)
|
||||
assert verk.variabel_drift == pytest.approx((50.0 + 100.0 + 30.0) * E_D)
|
||||
assert verk.avvikling == pytest.approx(5e6 * dim.N_u * 50.0)
|
||||
# K_U scaled to 50 MW is 50 mrd. kr; 8 mrd. kr of it is insured
|
||||
assert verk.ulykke == pytest.approx(dim.N_u * 1e-5 * (50e9 - 8e9))
|
||||
assert verk.effektbidrag == 0.0
|
||||
|
||||
|
||||
def test_A_har_ingen_kraftkjop_og_ingen_virkning_paa_kraftsystemet(
|
||||
oppdiktet: LagInndata,
|
||||
) -> None:
|
||||
res = _regn(oppdiktet(), Losning.A)
|
||||
assert not res.anlegg[0].kraftkjop.any()
|
||||
assert not res.anlegg[0].salg[ks.KJERNEKRAFT].any()
|
||||
assert not res.F_a.any()
|
||||
assert not res.Delta_W.any()
|
||||
assert not res.V.any()
|
||||
assert all(rad.Delta_Q == 0.0 and rad.Delta_R == 0.0 for rad in res.kraftaar)
|
||||
assert res.varsigma == {ks.KJERNEKRAFT: 1.0}
|
||||
|
||||
|
||||
def test_A_bygging_buffer_ekstern_forsyning_og_avvikling(oppdiktet: LagInndata) -> None:
|
||||
"""Start 2035 (2027 + max(8, 2 + 4)); four construction years; last operating year 2054."""
|
||||
inn = oppdiktet()
|
||||
res = _regn(inn, Losning.A)
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
anlegg, dim = res.anlegg[0], res.dim
|
||||
effekt = dim.N_u * 50.0
|
||||
investering = anlegg.investering[ks.KJERNEKRAFT]
|
||||
assert [float(investering[aar[t]]) for t in (2030, 2031, 2034, 2035)] == pytest.approx(
|
||||
[0.0, 25e6 * effekt, 25e6 * effekt, 0.0]
|
||||
)
|
||||
assert anlegg.avvikling[ks.KJERNEKRAFT][aar[2054]] == pytest.approx(5e6 * effekt)
|
||||
assert float(anlegg.avvikling[ks.KJERNEKRAFT].sum()) == pytest.approx(5e6 * effekt)
|
||||
assert not anlegg.inntekt[aar[2055] :].any()
|
||||
# buffer: 600 MW at 10 mill. kr per MW the year before start, 0.4 mill. kr per MW a year
|
||||
assert anlegg.buffer[aar[2034]] == pytest.approx(600.0 * 10e6)
|
||||
assert anlegg.buffer[aar[2040]] == pytest.approx(600.0 * 0.4e6)
|
||||
# two lines of 50 km at 10 mill. kr per km, and gensets for 2 % of the plant
|
||||
assert anlegg.I_g[aar[2034]] == pytest.approx(2 * 50 * 10e6 + 0.02 * effekt * 10e6)
|
||||
assert float(anlegg.I_g.sum()) == pytest.approx(2 * 50 * 10e6 + 0.02 * effekt * 10e6)
|
||||
assert not anlegg.I_nett.any()
|
||||
# S41: 200 mill. kr spread on the eight years to the first facility
|
||||
assert res.K_prog[aar[2028]] == pytest.approx(25e6)
|
||||
assert res.K_prog[aar[2035]] == pytest.approx(25e6)
|
||||
assert float(res.K_prog.sum()) == pytest.approx(200e6)
|
||||
# revenue is reduced by the availability of a plant without a grid
|
||||
assert anlegg.inntekt[aar[2035]] == pytest.approx(dim.Gamma * 1000.0 * _lcoc_v())
|
||||
|
||||
|
||||
def test_A_enhetsnumrene_loper_paa_tvers_av_anleggene(oppdiktet: LagInndata) -> None:
|
||||
"""With 10 % learning the second facility's units are cheaper than the first's."""
|
||||
inn = oppdiktet(ell=0.1)
|
||||
dim = ks.dimensjoner(inn, Losning.A)
|
||||
forste, andre = (ks.kraftverk_for_anlegg(inn, Losning.A, dim, k)[0] for k in (1, 2))
|
||||
assert andre.investering < forste.investering
|
||||
haand = math.fsum(
|
||||
100e6 * ((5 + n) / 6) ** math.log2(0.9) * 50.0 for n in range(dim.N_u + 1, 2 * dim.N_u + 1)
|
||||
)
|
||||
assert andre.investering == pytest.approx(haand)
|
||||
|
||||
|
||||
def test_overskridelsen_slaar_inn_i_budsjettlesningen(oppdiktet: LagInndata) -> None:
|
||||
"""u_xi below w_xi is the budget reading: the investment is multiplied by 1 + o_xi."""
|
||||
investering = {}
|
||||
for u_xi in (0.1, 0.9):
|
||||
inn = oppdiktet(u_xi=u_xi)
|
||||
dim = ks.dimensjoner(inn, Losning.A)
|
||||
investering[dim.xi_N] = ks.kraftverk_for_anlegg(inn, Losning.A, dim, 1)[0].investering
|
||||
assert set(investering) == {1.0, 1.5}
|
||||
assert investering[1.5] == pytest.approx(1.5 * investering[1.0])
|
||||
|
||||
|
||||
def test_rho_A_kan_settes_for_seg(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
dim = ks.dimensjoner(inn, Losning.A, rho_A=0.06)
|
||||
plan = ks.lag_plan(inn, Losning.A, dim, N_anlegg=1)
|
||||
lav = ks.regn_program(inn, Losning.A, plan, Knapphet.NORMALISERING, dim=dim)
|
||||
hoy = _regn(inn, Losning.A)
|
||||
assert lav.KS_N == pytest.approx(hoy.KS_N)
|
||||
assert lav.NV_kraft < hoy.NV_kraft # the costs weigh more at a lower rate
|
||||
|
||||
|
||||
# ------------------------------------------------ nuclear power on the grid (B, B')
|
||||
|
||||
|
||||
def _enheter(inn: Inndata, N_anlegg: int) -> tuple[ks.Enhetsgruppe, ...]:
|
||||
dim = ks.dimensjoner(inn, Losning.B)
|
||||
return ks.enheter_i_B(inn, dim, ks.lag_plan(inn, Losning.B, dim, N_anlegg=N_anlegg))
|
||||
|
||||
|
||||
def test_B_enhetene_hoerer_til_programmet(oppdiktet: LagInndata) -> None:
|
||||
"""Three facilities that start together and need 1.125 unit each: four units of 1 000 MW."""
|
||||
inn = oppdiktet()
|
||||
dim = ks.dimensjoner(inn, Losning.B)
|
||||
assert dim.P_G_N == pytest.approx(0.75 * 1.2 * 1000.0 / 0.8)
|
||||
assert all(ks.kraftverk_for_anlegg(inn, Losning.B, dim, k) == () for k in (1, 2, 3))
|
||||
(gruppe,) = _enheter(inn, 3)
|
||||
assert (gruppe.start, gruppe.siste_driftsaar, gruppe.numre) == (2035, 2054, (1, 2, 3, 4))
|
||||
verk = gruppe.verk
|
||||
assert verk.effekt == 4000.0
|
||||
assert verk.energi == pytest.approx(4 * 8760.0 * 0.8 * 1000.0)
|
||||
assert verk.effektbidrag == pytest.approx(0.98 * 4000.0)
|
||||
assert verk.storste_enhet == pytest.approx(980.0)
|
||||
# large units: fuel 70 kr/MWh
|
||||
assert verk.fast_drift == pytest.approx(1e6 * 4000.0)
|
||||
assert verk.variabel_drift == pytest.approx((50.0 + 70.0 + 30.0) * verk.energi)
|
||||
assert verk.avvikling == pytest.approx(5e6 * 4000.0)
|
||||
# one facility alone needs two units
|
||||
assert _enheter(inn, 1)[0].numre == (1, 2)
|
||||
|
||||
|
||||
def test_B_enheter_settes_i_drift_naar_S39_krever_flere(oppdiktet: LagInndata) -> None:
|
||||
"""Staggered starts, 0.8 unit per facility (lam 0.6, KF 0.9), plant life 20 years.
|
||||
|
||||
200 MW of reactors a year and 800 MW per facility give starts in 2035 (two), 2039, 2043,
|
||||
2047 and 2051. S39 requires 2, 3, 4, 4 and 5 units as the facilities come: units 1 and 2
|
||||
in 2035, unit 3 in 2039, unit 4 in 2043, none in 2047, unit 5 in 2051. Units 1 and 2 go
|
||||
out in 2054 together with the first two facilities; the four facilities left require
|
||||
four units, and three are in operation, so unit 6 enters operation in 2055. After that
|
||||
the units go out as fast as the facilities.
|
||||
"""
|
||||
inn = oppdiktet(lam=0.6, KF=0.9, n_reaktor=200.0, T_slutt=2075, L_H=7, s_brikker=1.0)
|
||||
dim = ks.dimensjoner(inn, Losning.B)
|
||||
plan = ks.lag_plan(inn, Losning.B, dim, N_anlegg=6)
|
||||
assert [a.start for a in plan.anlegg] == [2035, 2035, 2039, 2043, 2047, 2051]
|
||||
grupper = ks.enheter_i_B(inn, dim, plan)
|
||||
assert [(g.start, g.siste_driftsaar, g.numre) for g in grupper] == [
|
||||
(2035, 2054, (1, 2)),
|
||||
(2039, 2058, (3,)),
|
||||
(2043, 2062, (4,)),
|
||||
(2051, 2070, (5,)),
|
||||
(2055, 2074, (6,)),
|
||||
]
|
||||
|
||||
|
||||
def test_B_kraftbalansen_svekkes_ikke_naar_anlegg_gaar_ut(oppdiktet: LagInndata) -> None:
|
||||
"""The same programme year by year: never fewer units than S39 requires.
|
||||
|
||||
The capacity balance shows the units in operation: 0.98 * 1 000 MW per unit, less
|
||||
0.5 * 1.2 * 1 000 MW per facility. Units in operation: 2 (2035-38), 3 (2039-42),
|
||||
4 (2043-50), 5 (2051-54), 4 (2055-58), 3 (2059-62), 2 (2063-70) and 1 (2071-74). In
|
||||
2067-70 one facility is left and two units run, and in 2071-74 unit 6 runs alone: a
|
||||
unit that is no longer required runs and sells until its lifetime is out.
|
||||
"""
|
||||
inn = oppdiktet(lam=0.6, KF=0.9, n_reaktor=200.0, T_slutt=2075, L_H=7, s_brikker=1.0)
|
||||
res = _regn(inn, Losning.B, N_anlegg=6)
|
||||
enheter = {}
|
||||
for t in range(2035, 2076):
|
||||
anlegg = res.plan.antall_i_drift(t)
|
||||
rad = res.kraftaar[t - 2027]
|
||||
enheter[t] = round((rad.Delta_R + 0.5 * 1.2 * 1000.0 * anlegg) / 980.0)
|
||||
assert enheter[t] >= math.ceil(0.8 * anlegg - 1e-9), t
|
||||
assert rad.Delta_Q <= 0, t
|
||||
assert [enheter[t] for t in (2035, 2039, 2043, 2051, 2055, 2059, 2063, 2067, 2071, 2075)] == [
|
||||
2, 3, 4, 5, 4, 3, 2, 2, 1, 0,
|
||||
] # fmt: skip
|
||||
# six units are built, and all six are decommissioned within 2075
|
||||
assert sum(len(f.gruppe.numre) for f in res.felles) == 6
|
||||
assert sum(float(f.avvikling.sum()) for f in res.felles) == pytest.approx(6 * 5e6 * 1000.0)
|
||||
siste = res.felles[-1]
|
||||
assert siste.avvikling[2074 - 2027] == pytest.approx(5e6 * 1000.0)
|
||||
assert siste.salg[2072 - 2027] > 0 # it sells after the last facility has gone out
|
||||
assert siste.investering[2054 - 2027] > 0
|
||||
assert res.RV_felles == 0.0
|
||||
assert all(a.salg == {} for a in res.anlegg)
|
||||
|
||||
|
||||
def test_B_avvikling_etter_sluttaaret_regnes_per_enhet(oppdiktet: LagInndata) -> None:
|
||||
"""Final year 2060 in the same programme: units 3 to 6 go out after it, each in its own year.
|
||||
|
||||
The decommissioning of a unit is discounted with rho_N over its own years left (2, 10
|
||||
and 14 years for the units that go out in 2062, 2070 and 2074), then to 2027 with rho_D.
|
||||
Unit 3 goes out in 2058, within the final year.
|
||||
"""
|
||||
inn = oppdiktet(lam=0.6, KF=0.9, n_reaktor=200.0, T_slutt=2060, L_H=7, s_brikker=1.0)
|
||||
res = _regn(inn, Losning.B, N_anlegg=6)
|
||||
assert [f.L_rest for f in res.felles] == [0, 0, 2, 10, 14]
|
||||
avvikling = 5e6 * 1000.0
|
||||
haand = -avvikling * (1.06**-2 + 1.06**-10 + 1.06**-14) / 1.08**33
|
||||
assert res.RV_felles == pytest.approx(haand)
|
||||
assert res.RV == pytest.approx(math.fsum(res.RV_anlegg) + res.RV_felles)
|
||||
assert all(a.avvikling_etter == {} for a in res.anlegg)
|
||||
|
||||
|
||||
def test_B_anlegget_baerer_sin_del_av_programmets_kjernekraft_i_restverdien(
|
||||
oppdiktet: LagInndata,
|
||||
) -> None:
|
||||
"""One facility in B with final year 2045: the two units are all its own in S40."""
|
||||
inn = oppdiktet(T_slutt=2045)
|
||||
res = _regn(inn, Losning.B, knapphet=Knapphet.VARER)
|
||||
(felles,) = res.felles
|
||||
assert felles.L_rest == 9
|
||||
netto = res.anlegg[0].datasenter() + res.anlegg[0].kraft(res.varsigma, res.F_a)
|
||||
netto = netto + felles.netto(res.varsigma[ks.KJERNEKRAFT])
|
||||
verdi = max(0.0, float(netto[-5:].mean()) * (1 - 1.08**-9) / 0.08) / 1.08**18
|
||||
assert list(res.RV_anlegg) == pytest.approx([verdi])
|
||||
assert res.RV_felles == pytest.approx(-5e6 * 2000.0 / 1.06**9 / 1.08**18)
|
||||
|
||||
|
||||
def test_B_merket_selger_alt_og_bruker_smaa_enheters_tall(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
dim = ks.dimensjoner(inn, Losning.B_MERKET)
|
||||
assert dim.Gamma == 1.0
|
||||
(verk,) = ks.kraftverk_for_anlegg(inn, Losning.B_MERKET, dim, 1)
|
||||
effekt = dim.N_u * 50.0
|
||||
kapasitetsfaktor = 0.8 * (1 - 0.04) / (1 - 0.02)
|
||||
assert verk.energi == pytest.approx(8760.0 * kapasitetsfaktor * effekt)
|
||||
assert verk.selges
|
||||
assert verk.effektbidrag == pytest.approx(0.96 * effekt)
|
||||
assert verk.storste_enhet == pytest.approx(0.96 * 50.0)
|
||||
assert verk.fast_drift + verk.variabel_drift == pytest.approx(
|
||||
1e6 * effekt + (50.0 + 100.0 + 30.0) * verk.energi
|
||||
)
|
||||
assert dim.P_G_N == effekt
|
||||
|
||||
|
||||
def test_B_nettinvesteringen_bruker_behovet_ikke_hele_enheter(oppdiktet: LagInndata) -> None:
|
||||
res = _regn(oppdiktet(), Losning.B)
|
||||
assert float(res.anlegg[0].I_nett.sum()) == pytest.approx(5e6 * (0.5 * 1.2 * 1000.0 + 1125.0))
|
||||
|
||||
|
||||
def test_B_kraftsystemet_i_driftsaarene(oppdiktet: LagInndata) -> None:
|
||||
res = _regn(oppdiktet(), Losning.B)
|
||||
rad = res.kraftaar[2040 - 2027]
|
||||
E_N = 2 * 8760.0 * 0.8 * 1000.0
|
||||
assert rad.Delta_Q == pytest.approx(0.5 * E_D - E_N)
|
||||
assert rad.Delta_Q_tort == pytest.approx(rad.Delta_Q)
|
||||
assert rad.pris == pytest.approx(700.0 - 10e-6 * (10e6 - rad.Delta_Q))
|
||||
assert rad.Delta_R == pytest.approx(0.98 * 2000.0 - 0.5 * 1.2 * 1000.0)
|
||||
assert rad.Delta_R_utfall == pytest.approx(rad.Delta_R - 980.0)
|
||||
assert not res.F_a.any() # the balance holds also with the largest unit out
|
||||
|
||||
|
||||
# ------------------------------------------------------- the additionality rule (S45)
|
||||
|
||||
|
||||
def _naaverdi_kraftverk(res: ks.Programresultat, teknologi: str, rho_N: float) -> float:
|
||||
"""NV_i of S45, built up again from the yearly amounts (no residual value: L_rest = 0)."""
|
||||
D_N = np.array([(1.0 + rho_N) ** -(t - res.aar[0]) for t in res.aar])
|
||||
egne = math.fsum(
|
||||
float(
|
||||
D_N
|
||||
@ (
|
||||
res.varsigma[teknologi] * a.salg[teknologi]
|
||||
- a.investering[teknologi]
|
||||
- a.kraftdrift[teknologi]
|
||||
- a.avvikling[teknologi]
|
||||
)
|
||||
)
|
||||
for a in res.anlegg
|
||||
if teknologi in a.salg
|
||||
)
|
||||
if teknologi != ks.KJERNEKRAFT:
|
||||
return egne
|
||||
# in B the units belong to the programme; the accident cost is not part of NV_i
|
||||
return egne + math.fsum(
|
||||
float(D_N @ (f.netto(res.varsigma[teknologi]) + f.ulykke)) for f in res.felles
|
||||
)
|
||||
|
||||
|
||||
def test_s45_binder_ikke_for_et_kraftverk_som_taper(oppdiktet: LagInndata) -> None:
|
||||
res = _regn(oppdiktet(), Losning.B_MERKET)
|
||||
assert res.varsigma == {ks.KJERNEKRAFT: 1.0}
|
||||
assert _naaverdi_kraftverk(res, ks.KJERNEKRAFT, 0.06) < 0
|
||||
|
||||
|
||||
def test_s45_gir_naaverdi_null_naar_den_binder(oppdiktet: LagInndata) -> None:
|
||||
"""A cheap reactor that earns money on the grid is credited nothing."""
|
||||
inn = oppdiktet(c_N_ref=10e6, f_N=0.3e6)
|
||||
for losning in (Losning.B, Losning.B_MERKET):
|
||||
res = _regn(inn, losning, N_anlegg=2)
|
||||
assert 0.0 < res.varsigma[ks.KJERNEKRAFT] < 1.0
|
||||
kostnader = -_naaverdi_kraftverk(
|
||||
ks.regn_program(inn, losning, res.plan, Knapphet.NORMALISERING, tilleggsregel=False),
|
||||
ks.KJERNEKRAFT,
|
||||
0.06,
|
||||
)
|
||||
assert kostnader < 0 # without the rule the plant has a surplus
|
||||
assert _naaverdi_kraftverk(res, ks.KJERNEKRAFT, 0.06) == pytest.approx(
|
||||
0.0, abs=1e-3 * abs(kostnader)
|
||||
)
|
||||
|
||||
|
||||
def test_s45_regnes_for_hver_teknologi_i_C(oppdiktet: LagInndata) -> None:
|
||||
"""Hydropower (value factor 1.2) earns money, offshore wind does not."""
|
||||
res = _regn(oppdiktet(), Losning.C)
|
||||
assert set(res.varsigma) == {"vann", "vind", "havvind"}
|
||||
assert res.varsigma["vann"] < 1.0
|
||||
assert res.varsigma["havvind"] == 1.0
|
||||
assert _naaverdi_kraftverk(res, "vann", 0.06) == pytest.approx(0.0, abs=1.0)
|
||||
assert _naaverdi_kraftverk(res, "havvind", 0.06) < 0
|
||||
|
||||
|
||||
def test_uten_tilleggsregelen_krediteres_overskuddet(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet(c_N_ref=10e6, f_N=0.3e6)
|
||||
med = _regn(inn, Losning.B_MERKET)
|
||||
uten = _regn(inn, Losning.B_MERKET, tilleggsregel=False)
|
||||
assert uten.varsigma == {ks.KJERNEKRAFT: 1.0}
|
||||
assert uten.NV_kraft > med.NV_kraft
|
||||
|
||||
|
||||
def test_s45_med_restverdi_gir_naaverdi_null_med_kraftverkets_del(
|
||||
oppdiktet: LagInndata,
|
||||
) -> None:
|
||||
"""Final year 2045: nine operating years are left, so the plant's own residual value counts.
|
||||
|
||||
NV_i is built up again here: the cash flow to 2045, plus the plant's own part of the
|
||||
residual value (clarification 22) with the decommissioning that falls after 2045.
|
||||
"""
|
||||
inn = oppdiktet(c_N_ref=10e6, f_N=0.3e6, T_slutt=2045)
|
||||
res = _regn(inn, Losning.B_MERKET)
|
||||
anlegg, varsigma = res.anlegg[0], res.varsigma[ks.KJERNEKRAFT]
|
||||
assert anlegg.L_rest == 9
|
||||
assert 0.0 < varsigma < 1.0
|
||||
assert not anlegg.avvikling[ks.KJERNEKRAFT].any()
|
||||
netto = (
|
||||
varsigma * anlegg.salg[ks.KJERNEKRAFT]
|
||||
- anlegg.investering[ks.KJERNEKRAFT]
|
||||
- anlegg.kraftdrift[ks.KJERNEKRAFT]
|
||||
)
|
||||
D_N = np.array([1.06 ** -(t - 2027) for t in res.aar])
|
||||
snitt = float(netto[-5:].mean())
|
||||
egen_restverdi = (
|
||||
max(0.0, snitt * (1 - 1.08**-9) / 0.08) - anlegg.avvikling_etter[ks.KJERNEKRAFT] / 1.06**9
|
||||
) / 1.08**18
|
||||
assert float(D_N @ netto) + egen_restverdi == pytest.approx(0.0, abs=1e3)
|
||||
assert anlegg.avvikling_etter[ks.KJERNEKRAFT] == pytest.approx(5e6 * res.dim.N_u * 50.0)
|
||||
|
||||
|
||||
# ------------------------------------------------------------ renewable power (C)
|
||||
|
||||
|
||||
def test_C_portefoljen_per_anlegg_og_toerraaret(oppdiktet: LagInndata) -> None:
|
||||
"""Dry-year need 7.884 TWh per facility: hydropower 2 (1.6 dry), wind 3, offshore 3.284."""
|
||||
inn = oppdiktet()
|
||||
dim = ks.dimensjoner(inn, Losning.C)
|
||||
forste = {v.teknologi: v for v in ks.kraftverk_for_anlegg(inn, Losning.C, dim, 1)}
|
||||
assert forste["vann"].energi == pytest.approx(2e6)
|
||||
assert forste["vind"].energi == pytest.approx(3e6)
|
||||
assert forste["havvind"].energi == pytest.approx(E_D - 1.6e6 - 3e6)
|
||||
# the potentials are used up: the second facility gets offshore wind only
|
||||
andre = ks.kraftverk_for_anlegg(inn, Losning.C, dim, 2)
|
||||
assert [v.teknologi for v in andre] == ["havvind"]
|
||||
assert andre[0].energi == pytest.approx(E_D)
|
||||
|
||||
vann, havvind = forste["vann"], forste["havvind"]
|
||||
assert vann.effekt == pytest.approx(2e6 / 3000.0)
|
||||
assert vann.investering == pytest.approx(20e6 * 2e6 / 3000.0)
|
||||
assert vann.byggetid == 1.0 # NVE's figure holds the interest: booked the year before start
|
||||
assert [vann.fast_drift, vann.variabel_drift] == pytest.approx([0.0, 70.0 * 2e6])
|
||||
assert vann.effektbidrag == pytest.approx(0.9 * 2e6 / 3000.0)
|
||||
# offshore wind: per MW and year
|
||||
assert [havvind.fast_drift, havvind.variabel_drift] == pytest.approx(
|
||||
[0.9e6 * havvind.effekt, 0.0]
|
||||
)
|
||||
assert havvind.effektbidrag == 0.0
|
||||
assert forste["vind"].effektbidrag == pytest.approx(0.05 * 1000.0)
|
||||
|
||||
|
||||
def test_C_dekker_forbruket_i_toerraar_og_selger_overskudd_i_normalaar(
|
||||
oppdiktet: LagInndata,
|
||||
) -> None:
|
||||
res = _regn(oppdiktet(), Losning.C)
|
||||
rad = res.kraftaar[2035 - 2027]
|
||||
E_G = 2e6 + 3e6 + (E_D - 4.6e6)
|
||||
assert rad.Delta_Q == pytest.approx(0.5 * E_D - E_G)
|
||||
assert rad.Delta_Q_tort == pytest.approx(0.5 * E_D - E_D)
|
||||
assert rad.Delta_Q < rad.Delta_Q_tort <= 0
|
||||
assert rad.Delta_R == pytest.approx(0.9 * 2e6 / 3000.0 + 0.05 * 1000.0 - 600.0)
|
||||
assert rad.Delta_R_utfall == rad.Delta_R # no largest unit without nuclear power
|
||||
|
||||
|
||||
def test_C_fornybare_kraftverk_fornyes_naar_levetiden_er_ute(oppdiktet: LagInndata) -> None:
|
||||
"""Wind lasts 30 years: with 45 operating years it is built twice, hydropower (40) twice."""
|
||||
inn = oppdiktet(L_N=45.0, T_slutt=2080, vind__levetid=30, u_eksport=(0.5,) * 53)
|
||||
res = _regn(inn, Losning.C)
|
||||
anlegg = res.anlegg[0]
|
||||
aar = dict(zip(res.aar, range(len(res.aar)), strict=True))
|
||||
en_gang = 14e6 * 1000.0
|
||||
assert float(anlegg.investering["vind"].sum()) == pytest.approx(2 * en_gang)
|
||||
assert [float(anlegg.investering["vind"][aar[t]]) for t in (2028, 2029, 2058, 2059)] == (
|
||||
pytest.approx([en_gang / 2] * 4)
|
||||
)
|
||||
assert anlegg.investering["vann"][aar[2029]] == pytest.approx(20e6 * 2e6 / 3000.0)
|
||||
assert anlegg.investering["vann"][aar[2069]] == pytest.approx(20e6 * 2e6 / 3000.0)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- residual value
|
||||
|
||||
|
||||
def test_restverdi_per_anlegg_og_avvikling_etter_sluttaaret(oppdiktet: LagInndata) -> None:
|
||||
"""A with final year 2045: nine years left, and the decommissioning falls after 2045."""
|
||||
inn = oppdiktet(T_slutt=2045)
|
||||
res = _regn(inn, Losning.A, knapphet=Knapphet.VARER)
|
||||
anlegg = res.anlegg[0]
|
||||
assert anlegg.L_rest == 9
|
||||
assert not anlegg.avvikling[ks.KJERNEKRAFT].any()
|
||||
avvikling = 5e6 * res.dim.N_u * 50.0
|
||||
assert anlegg.avvikling_etter == {ks.KJERNEKRAFT: pytest.approx(avvikling)}
|
||||
netto = anlegg.datasenter() + anlegg.kraft(res.varsigma, np.zeros(len(res.aar)))
|
||||
snitt = float(netto[-5:].mean())
|
||||
# in A the decommissioning is discounted with rho_A = rho_D
|
||||
haand = (max(0.0, snitt * (1 - 1.08**-9) / 0.08) - avvikling / 1.08**9) / 1.08**18
|
||||
assert list(res.RV_anlegg) == pytest.approx([haand])
|
||||
assert res.RV == pytest.approx(haand)
|
||||
|
||||
|
||||
def test_anlegg_som_taper_faar_bare_avviklingen_i_restverdien(oppdiktet: LagInndata) -> None:
|
||||
"""A price 90 % below cost in every vintage to 2045: the facility loses money each year."""
|
||||
inn = oppdiktet(T_slutt=2045, pi_neg=-0.9, T_knapp=20)
|
||||
res = _regn(inn, Losning.B_MERKET, knapphet=Knapphet.OVERKAPASITET)
|
||||
netto = res.anlegg[0].datasenter() + res.anlegg[0].kraft(res.varsigma, res.F_a)
|
||||
assert float(netto[-5:].mean()) < 0
|
||||
avvikling = 5e6 * res.dim.N_u * 50.0
|
||||
assert res.RV == pytest.approx(-avvikling / 1.06**9 / 1.08**18)
|
||||
|
||||
|
||||
def test_effektkostnaden_deles_paa_anleggene_i_drift(oppdiktet: LagInndata) -> None:
|
||||
"""Three facilities in R that start the same year carry a third each of F_a."""
|
||||
inn = oppdiktet(T_slutt=2040)
|
||||
en = _regn(inn, Losning.R, N_anlegg=1)
|
||||
tre = _regn(inn, Losning.R, N_anlegg=3)
|
||||
assert [a.start for a in tre.plan.anlegg] == [2030, 2030, 2030]
|
||||
assert tre.F_a[-1] == pytest.approx(3 * en.F_a[-1])
|
||||
assert len(set(tre.RV_anlegg)) == 1
|
||||
assert tre.RV == pytest.approx(3 * tre.RV_anlegg[0])
|
||||
150
tests/test_kraftsystem.py
Normal file
150
tests/test_kraftsystem.py
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
"""The power system (chapter 5): S38, S23, S24 and S25.
|
||||
|
||||
Made-up round numbers, except the test that holds the fitted lines against NVE's own
|
||||
twelve scenarios (the table in the parameter file).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from tokenfabrikker import inndata, kraftsystem
|
||||
from tokenfabrikker import ligninger as lg
|
||||
from tokenfabrikker import parametere as pm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from conftest import LagInndata
|
||||
|
||||
# --------------------------------------------------------------------------- S38
|
||||
|
||||
|
||||
def test_s38_linja_gaar_gjennom_punkter_som_ligger_paa_linje() -> None:
|
||||
balanse = [-2.0, 0.0, 3.0, 10.0]
|
||||
alpha, b = lg.s38_tilpass_linje(S=balanse, P=[700.0 - 10.0 * s for s in balanse])
|
||||
assert (alpha, b) == pytest.approx((700.0, -10.0))
|
||||
|
||||
|
||||
def test_s38_minste_kvadrater_haandregnet() -> None:
|
||||
"""Points (0, 1), (1, 3), (2, 2): slope 0.5 and intercept 1.5."""
|
||||
alpha, b = lg.s38_tilpass_linje(S=[0.0, 1.0, 2.0], P=[1.0, 3.0, 2.0])
|
||||
assert (alpha, b) == pytest.approx((1.5, 0.5))
|
||||
|
||||
|
||||
def test_s38_avviser_for_faa_eller_like_punkter() -> None:
|
||||
with pytest.raises(ValueError, match="at least two points"):
|
||||
lg.s38_tilpass_linje(S=[1.0], P=[1.0])
|
||||
with pytest.raises(ValueError, match="all balances are equal"):
|
||||
lg.s38_tilpass_linje(S=[1.0, 1.0], P=[1.0, 2.0])
|
||||
|
||||
|
||||
def test_s38_brattere_under_knekken_og_sammenhengende_i_den() -> None:
|
||||
felles = {"alpha": 700.0, "b": -10e-6, "b_ut": 2.0}
|
||||
assert lg.s38_pris(**felles, S=10e6) == pytest.approx(600.0)
|
||||
assert lg.s38_pris(**felles, S=-3.6e6) == pytest.approx(736.0)
|
||||
# one TWh below the kink: twice the slope
|
||||
assert lg.s38_pris(**felles, S=-4.6e6) == pytest.approx(756.0)
|
||||
assert lg.s38_pris(**felles, S=-3.6e6 - 1e-3) == pytest.approx(736.0)
|
||||
|
||||
|
||||
@pytest.mark.fasit
|
||||
@pytest.mark.parametrize(
|
||||
"omraade",
|
||||
[
|
||||
"NO1",
|
||||
"NO2",
|
||||
pytest.param(
|
||||
"NO3",
|
||||
marks=pytest.mark.xfail(
|
||||
strict=True,
|
||||
reason="the line misses NVE's scenario N7 (no growth in offshore wind) by 6.0 %",
|
||||
),
|
||||
),
|
||||
pytest.param(
|
||||
"NO4",
|
||||
marks=pytest.mark.xfail(
|
||||
strict=True,
|
||||
reason="the line misses NVE's scenario N7 (no growth in offshore wind) by 7.7 %",
|
||||
),
|
||||
),
|
||||
"NO5",
|
||||
"Norge",
|
||||
],
|
||||
)
|
||||
def test_linjene_gjenskaper_nves_tolv_scenarioer_innenfor_fem_prosent(omraade: str) -> None:
|
||||
"""S38 against the source: the fitted line gives NVE's price in each of its twelve points."""
|
||||
scenarioer = pm.les_parametere().pris_balanse()
|
||||
linje = inndata.tilpass_prislinjer(scenarioer)[omraade]
|
||||
avvik = [
|
||||
abs(lg.s38_pris(alpha=linje.alpha, b=linje.b, b_ut=1.0, S=s.balanse) / s.pris[omraade] - 1)
|
||||
for s in scenarioer
|
||||
]
|
||||
assert max(avvik) < 0.05
|
||||
|
||||
|
||||
@pytest.mark.fasit
|
||||
def test_linja_for_norge_faller_med_bedre_kraftbalanse() -> None:
|
||||
linje = inndata.tilpass_prislinjer(pm.les_parametere().pris_balanse())["Norge"]
|
||||
assert linje.b < 0
|
||||
# about 10 kr/MWh per TWh, between NVE's weakest and strongest scenario
|
||||
assert -12.0 < linje.b * 1e6 < -9.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- S23, S24, S25
|
||||
|
||||
|
||||
def test_s23_netto_uttak_og_prisvirkning() -> None:
|
||||
Delta_Q = lg.s23_netto_uttak(delta_V=0.5, Q_D_nett=8e6, Q_G_nett=1e6)
|
||||
assert Delta_Q == pytest.approx(3e6)
|
||||
felles = {"alpha": 700.0, "b": -10e-6, "b_ut": 2.0, "S_0": 10e6, "Delta_Q": Delta_Q}
|
||||
assert lg.s23_prisvirkning(**felles) == pytest.approx(30.0)
|
||||
assert lg.s23_prisvirkning(**felles, m_v=1.5, s_v=1.2) == pytest.approx(54.0)
|
||||
|
||||
|
||||
def test_s23_overskudd_av_ny_kraft_senker_prisen() -> None:
|
||||
assert lg.s23_prisvirkning(
|
||||
alpha=700.0, b=-10e-6, b_ut=2.0, S_0=10e6, Delta_Q=-2e6
|
||||
) == pytest.approx(-20.0)
|
||||
|
||||
|
||||
def test_s24_effektbalanse_med_og_uten_storste_enhet() -> None:
|
||||
Delta_R, Delta_R_utfall = lg.s24_effektbalanse(
|
||||
effektbidrag=[980.0, 450.0], delta_V=0.5, PUE=1.2, P_IT_sum=2000.0, storste_enhet=980.0
|
||||
)
|
||||
assert Delta_R == pytest.approx(230.0)
|
||||
assert Delta_R_utfall == pytest.approx(-750.0)
|
||||
|
||||
|
||||
def test_s25_prisoppgang_er_gevinst_for_et_land_som_eksporterer() -> None:
|
||||
assert lg.s25_velferd(Delta_p=30.0, S_0=10e6) == pytest.approx(300e6)
|
||||
assert lg.s25_velferd(Delta_p=30.0, S_0=-5e6) == pytest.approx(-150e6)
|
||||
|
||||
|
||||
def test_kraftaar_setter_ligningene_sammen(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
aar = kraftsystem.kraftaar(
|
||||
inn,
|
||||
Q_D_nett=8e6,
|
||||
Q_G_nett=1e6,
|
||||
Q_G_nett_tort=0.8e6,
|
||||
effektbidrag=[100.0],
|
||||
P_IT_sum=1000.0,
|
||||
storste_enhet=40.0,
|
||||
)
|
||||
assert aar.Delta_Q == pytest.approx(3e6)
|
||||
assert aar.Delta_Q_tort == pytest.approx(3.2e6)
|
||||
assert aar.pris == pytest.approx(630.0)
|
||||
assert aar.Delta_p == pytest.approx(30.0)
|
||||
assert (aar.Delta_R, aar.Delta_R_utfall) == pytest.approx((-500.0, -540.0))
|
||||
assert aar.velferd(S_0=inn["S0"]) == pytest.approx(300e6)
|
||||
|
||||
|
||||
def test_relativ_prisvirkning_per_omraade(oppdiktet: LagInndata) -> None:
|
||||
inn = oppdiktet()
|
||||
normal = kraftsystem.relativ_prisvirkning(inn, Delta_Q=3e6, tort=False)
|
||||
assert set(normal) == {"NO1", "NO2", "NO3", "NO4", "NO5"}
|
||||
assert normal["NO1"] == pytest.approx(30.0 / 600.0)
|
||||
# the price level of the dry year cancels; the factor on the effect does not
|
||||
tort = kraftsystem.relativ_prisvirkning(inn, Delta_Q=3e6, tort=True)
|
||||
assert tort["NO1"] == pytest.approx(1.2 * 30.0 / 600.0)
|
||||
289
tests/test_utbygging.py
Normal file
289
tests/test_utbygging.py
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
"""The build-out (chapter 4): whole calendar years, the limits of S22, vintages and export stops.
|
||||
|
||||
Made-up round numbers only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from tokenfabrikker import ligninger as lg
|
||||
from tokenfabrikker import utbygging as ub
|
||||
|
||||
# ------------------------------------------------- whole years (clarification 21)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tidspunkt", "aar"),
|
||||
[(2047.0, 2047), (2047.0000000000005, 2047), (2047.3, 2048), (2046.999, 2047)],
|
||||
)
|
||||
def test_forste_driftsaar_rundes_opp(tidspunkt: float, aar: int) -> None:
|
||||
assert lg.forste_driftsaar(tidspunkt=tidspunkt) == aar
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("varighet", "hele"), [(14.4, 14), (14.5, 15), (14.6, 15), (0.2, 1), (60.0, 60), (1.49, 1)]
|
||||
)
|
||||
def test_levetid_rundes_til_naermeste_hele_aar(varighet: float, hele: int) -> None:
|
||||
assert lg.avrundet_varighet(varighet=varighet) == hele
|
||||
|
||||
|
||||
def test_avrundet_varighet_avviser_null() -> None:
|
||||
with pytest.raises(ValueError, match="must be positive"):
|
||||
lg.avrundet_varighet(varighet=0.0)
|
||||
|
||||
|
||||
def test_byggeaar_hele_aar_faar_like_andeler() -> None:
|
||||
assert lg.byggeaar_andeler(tau=4.0) == (0.25, 0.25, 0.25, 0.25)
|
||||
|
||||
|
||||
def test_byggeaar_brokdelen_ligger_tidligst() -> None:
|
||||
andeler = lg.byggeaar_andeler(tau=2.5)
|
||||
assert andeler == pytest.approx((0.4, 0.4, 0.2))
|
||||
assert math.fsum(andeler) == pytest.approx(1.0)
|
||||
|
||||
|
||||
def test_byggetid_under_ett_aar_betales_aaret_for_oppstart() -> None:
|
||||
assert lg.byggeaar_andeler(tau=0.4) == pytest.approx((1.0,))
|
||||
assert lg.byggeaar_andeler(tau=1.0) == (1.0,)
|
||||
|
||||
|
||||
def test_diskonteringsfaktor() -> None:
|
||||
assert lg.diskonteringsfaktor(rho=0.1, t=2029, T_0=2027) == pytest.approx(1 / 1.21)
|
||||
assert lg.diskonteringsfaktor(rho=0.1, t=2027, T_0=2027) == 1.0
|
||||
|
||||
|
||||
# ------------------------------------------------------------- S33, S22, S39, S41
|
||||
|
||||
|
||||
def test_s33_byggetiden_forsinker_forste_kraft() -> None:
|
||||
felles = {"T_0": 2027.0, "tau_reg_min": 5.0}
|
||||
assert lg.s33_tidligste_tidspunkt_kjernekraft(**felles, tau_F=20.0, tau_N=9.5) == 2047.0
|
||||
assert lg.s33_tidligste_tidspunkt_kjernekraft(**felles, tau_F=15.0, tau_N=17.1) == 2049.1
|
||||
assert lg.s33_tidligste_tidspunkt_nett(T_0=2027.0, tau_nett=7.5) == 2034.5
|
||||
|
||||
|
||||
def test_s22_de_tre_leddene() -> None:
|
||||
assert lg.s22_grense_reaktor(n_reaktor=1500.0, P_IT=1000.0, P_G_N=1500.0) == 1000.0
|
||||
# 4.38 TWh per year, all of it counted in a dry year, covers 500 MW at full load
|
||||
assert lg.s22_grense_fornybar(g_fornybar=4.38e6, w_tort=1.0, lam=1.0, PUE=1.0) == pytest.approx(
|
||||
500.0
|
||||
)
|
||||
assert lg.s22_grense_brikker(s_brikker=0.04, G_server=25_000.0, utskifting=400.0) == 600.0
|
||||
assert lg.s22_reaktoreffekt_B(lam=0.7, PUE=1.2, P_IT=1000.0, KF=0.84) == pytest.approx(1000.0)
|
||||
|
||||
|
||||
def test_s39_enheter_i_B_rundes_opp_for_programmet() -> None:
|
||||
per_enhet = 8760.0 * 0.8 * 1000.0
|
||||
assert lg.s39_enheter_B(E_D_sum=2.0 * per_enhet, KF=0.8, P_ref=1000.0) == 2
|
||||
assert lg.s39_enheter_B(E_D_sum=2.01 * per_enhet, KF=0.8, P_ref=1000.0) == 3
|
||||
assert lg.s39_enheter_B(E_D_sum=0.0, KF=0.8, P_ref=1000.0) == 0
|
||||
|
||||
|
||||
def test_s39_portefoljen_fylles_i_fast_rekkefolge() -> None:
|
||||
felles = {"w_tort_vann": 0.8, "E_vann_rest": 2e6, "E_vind_rest": 3e6}
|
||||
bare_vann = lg.s39_portefolje_C(E_torr=0.8e6, **felles)
|
||||
assert (bare_vann.vann, bare_vann.vind, bare_vann.havvind) == pytest.approx((1e6, 0.0, 0.0))
|
||||
alle = lg.s39_portefolje_C(E_torr=7e6, **felles)
|
||||
# hydropower gives 1.6 TWh in a dry year, wind 3, and offshore wind the remaining 2.4
|
||||
assert (alle.vann, alle.vind, alle.havvind) == pytest.approx((2e6, 3e6, 2.4e6))
|
||||
assert alle.torraar(w_tort_vann=0.8) == pytest.approx(7e6)
|
||||
assert alle.sum == pytest.approx(7.4e6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("E_normal", [0.5e6, 2e6, 4e6, 9e6])
|
||||
def test_s39_takt_og_portefolje_er_hverandres_inverse(E_normal: float) -> None:
|
||||
felles = {"w_tort_vann": 0.8, "E_vann_rest": 2e6, "E_vind_rest": 3e6}
|
||||
torr = lg.s39_torraarsenergi_av_takt(E_normal=E_normal, **felles)
|
||||
assert lg.s39_portefolje_C(E_torr=torr, **felles).sum == pytest.approx(E_normal)
|
||||
|
||||
|
||||
def test_s41_fordeles_paa_aarene_til_forste_anlegg() -> None:
|
||||
per_aar = lg.s41_programkostnad(
|
||||
andel_myndighet=0.2, aarsverk_prog=1000.0, c_aarsverk=1e6, t_1=2037, T_0=2027
|
||||
)
|
||||
assert per_aar == pytest.approx(20e6)
|
||||
with pytest.raises(ValueError, match="after the decision year"):
|
||||
lg.s41_programkostnad(
|
||||
andel_myndighet=0.2, aarsverk_prog=1000.0, c_aarsverk=1e6, t_1=2027, T_0=2027
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the export rule
|
||||
|
||||
|
||||
def test_eksportstopp_varer_avrundet_antall_aar() -> None:
|
||||
u = (0.9, 0.05, 0.9, 0.9, 0.9, 0.9)
|
||||
assert ub.eksportstopp(u=u, phi_X=0.1, D_X=2.4) == (False, True, True, False, False, False)
|
||||
assert ub.eksportstopp(u=u, phi_X=0.1, D_X=2.5) == (False, True, True, True, False, False)
|
||||
|
||||
|
||||
def test_eksportstopp_ny_regel_forlenger_stoppen() -> None:
|
||||
u = (0.05, 0.9, 0.05, 0.9, 0.9, 0.9)
|
||||
assert ub.eksportstopp(u=u, phi_X=0.1, D_X=3.0) == (True, True, True, True, True, False)
|
||||
|
||||
|
||||
def test_ingen_eksportregel_naar_sannsynligheten_er_null() -> None:
|
||||
assert ub.eksportstopp(u=(0.0, 0.5, 0.99), phi_X=0.0, D_X=4.0) == (False, False, False)
|
||||
|
||||
|
||||
def test_eksportstopp_stopper_ved_sluttaaret() -> None:
|
||||
assert ub.eksportstopp(u=(0.9, 0.9, 0.0), phi_X=0.1, D_X=4.0) == (False, False, True)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the schedule
|
||||
|
||||
|
||||
def _plan(**endringer: object) -> ub.Plan:
|
||||
argumenter: dict[str, object] = {
|
||||
"N_anlegg": 3,
|
||||
"T_0": 2027,
|
||||
"T_s": 2040,
|
||||
"t_min": 2030,
|
||||
"P_IT": 1000.0,
|
||||
"L_H": 3,
|
||||
"L_N": 20,
|
||||
"brikker_per_aar": 500.0,
|
||||
"kraftrom": ub.kraftrom_ubegrenset,
|
||||
"stopp": (False,) * 13,
|
||||
}
|
||||
argumenter.update(endringer)
|
||||
return ub.utbyggingsplan(**argumenter) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_brikker_samles_opp_fra_beslutningsaaret_og_utskifting_gaar_foran() -> None:
|
||||
"""Hand-computed: 500 MW of chips a year, facilities of 1 000 MW, vintages of three years.
|
||||
|
||||
Stock after deliveries: 2028 500, 2029 1 000, 2030 1 500 (facility 1 starts, 500 left),
|
||||
2031 1 000 (facility 2 starts, 0 left), 2032 500, 2033 1 000 (facility 1's vintage is
|
||||
replaced before facility 3 can start), 2034 500 (facility 2's vintage has expired and
|
||||
waits), 2035 1 000 (facility 2 replaced), 2036 500 (facility 1 waits), 2037 1 000
|
||||
(facility 1 replaced), 2038 500 (facility 2 waits), 2039 1 000 (facility 2 replaced),
|
||||
2040 500 (facility 1 waits). Facility 3 never gets chips.
|
||||
"""
|
||||
plan = _plan()
|
||||
assert [a.start for a in plan.anlegg] == [2030, 2031]
|
||||
assert plan.anlegg[0].aarganger == (2030, 2033, 2037)
|
||||
assert plan.anlegg[1].aarganger == (2031, 2035, 2039)
|
||||
assert not plan.gjennomforbar
|
||||
assert plan.t_1 == 2030
|
||||
|
||||
|
||||
def test_utlevd_aargang_staar_uten_inntekt_til_den_byttes() -> None:
|
||||
plan = _plan()
|
||||
assert plan.aargang(1, 2033) == 2031
|
||||
assert plan.aargang(1, 2034) is None # expired, no chips in stock
|
||||
assert plan.aargang(1, 2035) == 2035
|
||||
assert plan.aargang(0, 2036) is None
|
||||
assert plan.aargang(0, 2029) is None # not in operation yet
|
||||
assert plan.i_drift(1, 2034) # the facility is still operated
|
||||
|
||||
|
||||
def test_den_som_har_ventet_lengst_faar_brikker_forst() -> None:
|
||||
"""Chips for one facility a year from 2030, vintages of two years, a stop in 2033.
|
||||
|
||||
Facility 1 starts in 2030 and is replaced in 2032; facility 2 starts in 2031. Its vintage
|
||||
expires in 2033, during the stop, so it waits. In 2034 facility 1 expires too, and there
|
||||
are chips for one: facility 2, which expired first. Facility 1 follows in 2035. After
|
||||
that each is replaced the year it expires.
|
||||
"""
|
||||
stopp = [False] * 13
|
||||
stopp[2033 - 2028] = True
|
||||
plan = _plan(
|
||||
N_anlegg=2,
|
||||
L_H=2,
|
||||
brikker_per_aar=1000.0,
|
||||
t_min=2030,
|
||||
stopp=tuple(stopp),
|
||||
forste_brikkeaar=2030,
|
||||
)
|
||||
assert plan.anlegg[0].aarganger == (2030, 2032, 2035, 2037, 2039)
|
||||
assert plan.anlegg[1].aarganger == (2031, 2034, 2036, 2038, 2040)
|
||||
assert plan.antall_med_last(2033) == 1
|
||||
assert plan.antall_med_last(2034) == 1
|
||||
assert plan.antall_i_drift(2034) == 2
|
||||
assert not plan.har_last(0, 2034)
|
||||
assert plan.har_last(1, 2034)
|
||||
|
||||
|
||||
def test_reaktortakten_begrenser_antall_anlegg() -> None:
|
||||
"""1 000 MW of reactors a year and 2 500 MW per facility: room for k after 2.5 k years."""
|
||||
plan = _plan(
|
||||
brikker_per_aar=5000.0,
|
||||
L_H=20,
|
||||
kraftrom=ub.kraftrom_reaktor(n_reaktor=1000.0, P_G_N=2500.0, T_0=2027),
|
||||
)
|
||||
assert [a.start for a in plan.anlegg] == [2030, 2032, 2035]
|
||||
assert plan.gjennomforbar
|
||||
|
||||
|
||||
def test_flere_anlegg_kan_starte_samme_aar() -> None:
|
||||
plan = _plan(brikker_per_aar=5000.0, L_H=20, t_min=2035)
|
||||
assert [a.start for a in plan.anlegg] == [2035, 2035, 2035]
|
||||
assert plan.antall_i_drift(2034) == 0
|
||||
assert plan.antall_i_drift(2035) == 3
|
||||
|
||||
|
||||
def test_fornybar_takt_regnes_i_toerraarsenergi() -> None:
|
||||
"""2 TWh a year: hydropower first (2 TWh potential, 0.8 in a dry year), then wind.
|
||||
|
||||
Dry-year energy after x years is 1.6 + 2 (x - 1) TWh for x >= 1. One facility needs
|
||||
5 TWh: room for one after 2.7 years (first whole year 2030), for two after 5.2 (2033).
|
||||
"""
|
||||
rom = ub.kraftrom_fornybar(
|
||||
g_fornybar=2e6, w_tort_vann=0.8, E_vann_rest=2e6, E_vind_rest=1e6, E_D=5e6, T_0=2027
|
||||
)
|
||||
assert rom(2028) == pytest.approx(1.6 / 5)
|
||||
assert rom(2030) == pytest.approx(5.6 / 5)
|
||||
plan = _plan(N_anlegg=2, brikker_per_aar=5000.0, L_H=20, t_min=2028, kraftrom=rom)
|
||||
assert [a.start for a in plan.anlegg] == [2030, 2033]
|
||||
|
||||
|
||||
def test_eksportstopp_gir_verken_leveranser_nye_anlegg_eller_nye_aarganger() -> None:
|
||||
"""Chips for two facilities a year, but a stop in 2030-2031 and in 2033.
|
||||
|
||||
Facility 1 starts in 2032 instead of 2030; nothing is delivered during the stop, so the
|
||||
stock in 2032 is what 2028, 2029 and 2032 gave. Its vintage expires in 2033, inside the
|
||||
second stop, and is replaced in 2034.
|
||||
"""
|
||||
stopp = [False] * 13
|
||||
for aar in (2030, 2031, 2033):
|
||||
stopp[aar - 2028] = True
|
||||
plan = _plan(N_anlegg=1, L_H=1, brikker_per_aar=2000.0, stopp=tuple(stopp))
|
||||
assert plan.anlegg[0].start == 2032
|
||||
assert plan.anlegg[0].aarganger[:3] == (2032, 2034, 2035)
|
||||
assert plan.aargang(0, 2033) is None
|
||||
|
||||
|
||||
def test_anlegget_drives_L_N_aar_og_fornyes_ikke_etter_det() -> None:
|
||||
plan = _plan(N_anlegg=1, L_N=4, L_H=3, brikker_per_aar=5000.0)
|
||||
anlegg = plan.anlegg[0]
|
||||
assert (anlegg.start, anlegg.siste_driftsaar) == (2030, 2033)
|
||||
assert anlegg.aarganger == (2030, 2033)
|
||||
assert plan.i_drift(0, 2033)
|
||||
assert not plan.i_drift(0, 2034)
|
||||
assert plan.aargang(0, 2034) is None
|
||||
|
||||
|
||||
def test_plan_uten_anlegg_har_ikke_noe_forste_aar() -> None:
|
||||
plan = _plan(brikker_per_aar=10.0)
|
||||
assert plan.anlegg == ()
|
||||
with pytest.raises(ValueError, match="no facility"):
|
||||
_ = plan.t_1
|
||||
|
||||
|
||||
def test_feil_antall_aar_i_eksportstrommen_avvises() -> None:
|
||||
with pytest.raises(ValueError, match="one export flag per year"):
|
||||
_plan(stopp=(False,) * 5)
|
||||
|
||||
|
||||
def test_losningenes_egenskaper() -> None:
|
||||
assert not ub.Losning.A.paa_nett
|
||||
assert all(a.paa_nett for a in ub.Losning if a is not ub.Losning.A)
|
||||
assert [a for a in ub.Losning if a.kjernekraft] == [
|
||||
ub.Losning.A,
|
||||
ub.Losning.B,
|
||||
ub.Losning.B_MERKET,
|
||||
]
|
||||
Loading…
Add table
Add a link
Reference in a new issue