utility-tariffs-lib 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- utility_tariffs_lib/README.md +41 -0
- utility_tariffs_lib/__init__.py +0 -0
- utility_tariffs_lib/py.typed +0 -0
- utility_tariffs_lib/tariff/__init__.py +164 -0
- utility_tariffs_lib/tariff/accumulator.py +195 -0
- utility_tariffs_lib/tariff/bands.py +124 -0
- utility_tariffs_lib/tariff/bill_days.py +73 -0
- utility_tariffs_lib/tariff/billing.py +28 -0
- utility_tariffs_lib/tariff/compile.py +124 -0
- utility_tariffs_lib/tariff/config.py +208 -0
- utility_tariffs_lib/tariff/defaults.py +16 -0
- utility_tariffs_lib/tariff/definition.py +321 -0
- utility_tariffs_lib/tariff/definition_parse.py +765 -0
- utility_tariffs_lib/tariff/definition_savings.py +116 -0
- utility_tariffs_lib/tariff/demand.py +44 -0
- utility_tariffs_lib/tariff/engine.py +284 -0
- utility_tariffs_lib/tariff/index.py +309 -0
- utility_tariffs_lib/tariff/period_bill.py +136 -0
- utility_tariffs_lib/tariff/periods.py +34 -0
- utility_tariffs_lib/tariff/price_curve.py +142 -0
- utility_tariffs_lib/tariff/price_series.py +137 -0
- utility_tariffs_lib/tariff/price_stats.py +194 -0
- utility_tariffs_lib/tariff/price_timeline.py +139 -0
- utility_tariffs_lib/tariff/reprice.py +106 -0
- utility_tariffs_lib/tariff/savings.py +118 -0
- utility_tariffs_lib/tariff/slot_history.py +128 -0
- utility_tariffs_lib/tariff/slots.py +266 -0
- utility_tariffs_lib/tariff/stored_energy.py +64 -0
- utility_tariffs_lib/tariff/windows.py +119 -0
- utility_tariffs_lib/tariffranking/__init__.py +39 -0
- utility_tariffs_lib/tariffranking/search.py +189 -0
- utility_tariffs_lib/tariffstore/__init__.py +13 -0
- utility_tariffs_lib/tariffstore/client.py +406 -0
- utility_tariffs_lib/tariffstore/compile.py +157 -0
- utility_tariffs_lib/tariffstore/index.py +188 -0
- utility_tariffs_lib/tariffstore/layout.py +39 -0
- utility_tariffs_lib/tariffstore/price_client.py +87 -0
- utility_tariffs_lib/tariffstore/prices.py +127 -0
- utility_tariffs_lib/tariffstore/schema.py +550 -0
- utility_tariffs_lib/timeutil/__init__.py +5 -0
- utility_tariffs_lib/timeutil/real_time.py +52 -0
- utility_tariffs_lib-0.1.0.dist-info/METADATA +61 -0
- utility_tariffs_lib-0.1.0.dist-info/RECORD +46 -0
- utility_tariffs_lib-0.1.0.dist-info/WHEEL +5 -0
- utility_tariffs_lib-0.1.0.dist-info/licenses/LICENSE +21 -0
- utility_tariffs_lib-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""definition_savings.py: what solar and a battery saved in a bill period, under a definition.
|
|
2
|
+
|
|
3
|
+
The same sum as `savings`, for a tariff held as a `TariffDefinition`: the house load bought from
|
|
4
|
+
the grid, less what was paid, priced as two bills over the same days. The standing charge and
|
|
5
|
+
levies cancel. Export credit is on the paid side only. The change in stored energy is valued
|
|
6
|
+
at what the grid energy put into the battery cost, else the cheapest import band, and battery
|
|
7
|
+
wear is taken off. A house load reading is required.
|
|
8
|
+
|
|
9
|
+
Pure Python, no Home Assistant imports.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from datetime import date, timedelta
|
|
17
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
18
|
+
|
|
19
|
+
from ..timeutil import shift_real
|
|
20
|
+
from .bands import band_at
|
|
21
|
+
from .defaults import SLOT_SECONDS
|
|
22
|
+
from .definition import TariffDefinition
|
|
23
|
+
from .period_bill import PeriodBill, PeriodRules, price_period
|
|
24
|
+
from .price_curve import marginal_prices
|
|
25
|
+
from .savings import Battery, all_from_grid
|
|
26
|
+
from .slot_history import SlotHistory
|
|
27
|
+
from .slots import SlotDay
|
|
28
|
+
|
|
29
|
+
_CENT = Decimal("0.01")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class SavingsOptions:
|
|
34
|
+
"""What the caller adds to the sum: the battery, and the bill rules of the period."""
|
|
35
|
+
|
|
36
|
+
battery: Battery | None = None
|
|
37
|
+
rules: PeriodRules = field(default_factory=PeriodRules)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class DefinitionSavings:
|
|
42
|
+
"""The saving over a bill period so far, with the two bills it is the difference of."""
|
|
43
|
+
|
|
44
|
+
without_system: PeriodBill # the whole house load bought from the grid
|
|
45
|
+
actual: PeriodBill
|
|
46
|
+
bill_difference: Decimal # without_system total less actual total
|
|
47
|
+
stored_energy_value: Decimal # value of the change in stored energy, negative for a fall
|
|
48
|
+
battery_wear: Decimal
|
|
49
|
+
total: Decimal # bill_difference + stored_energy_value - battery_wear
|
|
50
|
+
coverage: float # share of the priced days' time that was observed, 0 to 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def definition_savings(
|
|
54
|
+
history: SlotHistory,
|
|
55
|
+
definition: TariffDefinition,
|
|
56
|
+
through: date,
|
|
57
|
+
options: SavingsOptions | None = None,
|
|
58
|
+
) -> DefinitionSavings:
|
|
59
|
+
"""The saving from the start of the bill period holding *through* to *through* included.
|
|
60
|
+
|
|
61
|
+
Raises ValueError when those days hold no house load.
|
|
62
|
+
"""
|
|
63
|
+
battery, rules = (options.battery, options.rules) if options else (None, PeriodRules())
|
|
64
|
+
actual = price_period(history, definition, through, rules)
|
|
65
|
+
days = history.between(actual.first_day, through)
|
|
66
|
+
if not any(day.total("house") for day in days):
|
|
67
|
+
raise ValueError("no house load was recorded, so there is nothing to compare")
|
|
68
|
+
baseline_history = SlotHistory.from_days(history.tz, [all_from_grid(day) for day in days])
|
|
69
|
+
without = price_period(baseline_history, definition, through, rules)
|
|
70
|
+
difference = _cents(without.priced.total - actual.priced.total)
|
|
71
|
+
stored = _stored_value(days, definition, battery, rules.is_holiday)
|
|
72
|
+
wear = _cents(Decimal(repr(sum(d.total("battery_discharge") for d in days))) * _wear(battery))
|
|
73
|
+
return DefinitionSavings(
|
|
74
|
+
without, actual, difference, stored, wear, difference + stored - wear, actual.coverage
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _cents(value: Decimal) -> Decimal:
|
|
79
|
+
return value.quantize(_CENT, rounding=ROUND_HALF_UP)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _wear(battery: Battery | None) -> Decimal:
|
|
83
|
+
return Decimal(repr(battery.wear_per_kwh)) if battery else Decimal(0)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _stored_value(
|
|
87
|
+
days: list[SlotDay],
|
|
88
|
+
definition: TariffDefinition,
|
|
89
|
+
battery: Battery | None,
|
|
90
|
+
is_holiday: Callable[[date], bool],
|
|
91
|
+
) -> Decimal:
|
|
92
|
+
if battery is None or battery.capacity_kwh <= 0 or battery.soc_before_pct is None:
|
|
93
|
+
return Decimal(0)
|
|
94
|
+
closing = next(
|
|
95
|
+
(v for day in reversed(days) for v in reversed(day.soc_pct) if v is not None), None
|
|
96
|
+
)
|
|
97
|
+
if closing is None:
|
|
98
|
+
return Decimal(0)
|
|
99
|
+
change_kwh = Decimal(repr((closing - battery.soc_before_pct) / 100 * battery.capacity_kwh))
|
|
100
|
+
return _cents(change_kwh * _stored_rate(days, definition, is_holiday))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _stored_rate(
|
|
104
|
+
days: list[SlotDay], definition: TariffDefinition, is_holiday: Callable[[date], bool]
|
|
105
|
+
) -> Decimal:
|
|
106
|
+
"""Average cost of the grid energy that went into the battery, else the cheapest band."""
|
|
107
|
+
prices = marginal_prices(definition).import_prices
|
|
108
|
+
kwh = cost = Decimal(0)
|
|
109
|
+
for day in days:
|
|
110
|
+
for index, charged in enumerate(day.flows["grid_to_battery"]):
|
|
111
|
+
if charged:
|
|
112
|
+
start = shift_real(day.start, timedelta(seconds=index * SLOT_SECONDS))
|
|
113
|
+
amount = Decimal(repr(charged))
|
|
114
|
+
kwh += amount
|
|
115
|
+
cost += amount * prices[band_at(definition, start, is_holiday)]
|
|
116
|
+
return cost / kwh if kwh > 0 else min(prices.values())
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""demand.py: the highest half-hour power in each demand window, read from the slot history.
|
|
2
|
+
|
|
3
|
+
A demand charge is priced on the peak kW, not on kWh. A slot's kW is its import kWh over the slot's
|
|
4
|
+
length, so the peak is a half-hour average. A tariff that measures a shorter interval cannot be
|
|
5
|
+
read from half-hourly slots, and its peak is understated. A slot belongs to a window by the clock
|
|
6
|
+
at its start, as for a band.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from datetime import date, timedelta
|
|
13
|
+
from decimal import Decimal
|
|
14
|
+
|
|
15
|
+
from ..timeutil import shift_real
|
|
16
|
+
from .bands import no_holidays, zone_applies
|
|
17
|
+
from .defaults import SLOT_SECONDS
|
|
18
|
+
from .definition import TariffDefinition
|
|
19
|
+
from .definition_parse import demand_windows
|
|
20
|
+
from .slots import SlotDay
|
|
21
|
+
|
|
22
|
+
_KW_PER_KWH_SLOT = Decimal(3600) / Decimal(SLOT_SECONDS)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def peak_kw_by_window(
|
|
26
|
+
days: Sequence[SlotDay],
|
|
27
|
+
definition: TariffDefinition,
|
|
28
|
+
is_holiday: Callable[[date], bool] = no_holidays,
|
|
29
|
+
) -> dict[str, Decimal]:
|
|
30
|
+
"""The peak import kW in each demand window the definition uses, over *days*.
|
|
31
|
+
|
|
32
|
+
A window with no import in it has a peak of 0, because the slots say the power was zero."""
|
|
33
|
+
windows = demand_windows(definition.total)
|
|
34
|
+
peaks = dict.fromkeys(windows, 0.0)
|
|
35
|
+
for day in days:
|
|
36
|
+
for index, kwh in enumerate(day.flows["import"]):
|
|
37
|
+
if not kwh:
|
|
38
|
+
continue
|
|
39
|
+
local = shift_real(day.start, timedelta(seconds=index * SLOT_SECONDS))
|
|
40
|
+
local = local.astimezone(definition.timezone)
|
|
41
|
+
for name, zone in windows.items():
|
|
42
|
+
if zone_applies(zone, local, is_holiday):
|
|
43
|
+
peaks[name] = max(peaks[name], kwh)
|
|
44
|
+
return {name: Decimal(repr(round(kwh, 6))) * _KW_PER_KWH_SLOT for name, kwh in peaks.items()}
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""engine.py: price a bill from a tariff definition, with an amount on every node of the tree.
|
|
2
|
+
|
|
3
|
+
The engine reads only totals: the kWh in each import band, the export kWh (one figure, or the
|
|
4
|
+
kWh in each export band) and the days of the bill. Turning slots into band totals is a separate
|
|
5
|
+
step, so the same arithmetic prices a worked check, a re-priced history or a live month. It does
|
|
6
|
+
all sums in `Decimal`.
|
|
7
|
+
|
|
8
|
+
Each node is worked out after everything inside it, so the tree sets the order and the tax base.
|
|
9
|
+
A node is rounded to the currency's smallest unit, halves upward, unless it says `round: none`.
|
|
10
|
+
A credit is a negative amount, so the total is plain addition.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from dataclasses import dataclass, field, replace
|
|
17
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
18
|
+
|
|
19
|
+
from .definition import (
|
|
20
|
+
Adjust,
|
|
21
|
+
Block,
|
|
22
|
+
Bound,
|
|
23
|
+
Demand,
|
|
24
|
+
EnergyByBand,
|
|
25
|
+
ExportCredit,
|
|
26
|
+
Node,
|
|
27
|
+
NodeRounding,
|
|
28
|
+
PerDay,
|
|
29
|
+
PerKwh,
|
|
30
|
+
PerPeriod,
|
|
31
|
+
SeriesEnergy,
|
|
32
|
+
Sum,
|
|
33
|
+
TariffDefinition,
|
|
34
|
+
Tax,
|
|
35
|
+
TaxMode,
|
|
36
|
+
TieredEnergy,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
_HUNDRED = Decimal(100)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class CheckFailed(ValueError):
|
|
43
|
+
"""A worked bill in a definition did not give the total the definition expects."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class MissingPeak(ValueError):
|
|
47
|
+
"""A bill has a demand charge and no peak kW was given for its window."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class MissingSeries(ValueError):
|
|
51
|
+
"""A bill has a series energy node and no cost was given for its series."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class BillInputs:
|
|
56
|
+
"""What a bill is priced from."""
|
|
57
|
+
|
|
58
|
+
days: int # days the bill covers
|
|
59
|
+
period_days: int # days in the whole bill period, which sets the share of a period charge
|
|
60
|
+
import_kwh_by_band: Mapping[str, Decimal]
|
|
61
|
+
# One total, paid at the base export price, or the kWh in each export band.
|
|
62
|
+
export_kwh: Decimal | Mapping[str, Decimal]
|
|
63
|
+
# Months in the whole bill period, for a charge made once a month. None uses the definition's.
|
|
64
|
+
period_months: int | None = None
|
|
65
|
+
# The highest half-hour kW in each demand window of the bill. A window the tree uses and this
|
|
66
|
+
# leaves out is refused, never priced as zero.
|
|
67
|
+
peak_kw: Mapping[str, Decimal] = field(default_factory=dict)
|
|
68
|
+
# The cost of the import kWh under each price series the tree names, from `series_cost`. A
|
|
69
|
+
# series the tree uses and this leaves out is refused, never priced as zero.
|
|
70
|
+
import_cost_by_series: Mapping[str, Decimal] = field(default_factory=dict)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Line:
|
|
75
|
+
"""One node of the bill with its amount. *children* holds the lines inside it, by name."""
|
|
76
|
+
|
|
77
|
+
kind: str
|
|
78
|
+
amount: Decimal
|
|
79
|
+
name: str | None = None # the name an adjust or tax node gives itself
|
|
80
|
+
tax: Decimal | None = None # the tax reported by a tax node, added or already included
|
|
81
|
+
children: Mapping[str, Line] = field(default_factory=dict)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class PricedBill:
|
|
86
|
+
"""A priced bill: the tree with its amounts, and the total."""
|
|
87
|
+
|
|
88
|
+
total: Decimal
|
|
89
|
+
root: Line
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def price_bill(definition: TariffDefinition, inputs: BillInputs) -> PricedBill:
|
|
93
|
+
"""The bill for *inputs* under *definition*."""
|
|
94
|
+
if inputs.days < 1 or inputs.period_days < 1:
|
|
95
|
+
raise ValueError("days and period_days must be at least 1")
|
|
96
|
+
root = _Pricer(definition, inputs).line(definition.total)
|
|
97
|
+
return PricedBill(root.amount, root)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def verify_checks(definition: TariffDefinition) -> None:
|
|
101
|
+
"""Price each worked bill in *definition*. Raises CheckFailed for the first that differs."""
|
|
102
|
+
for name, check in definition.checks.items():
|
|
103
|
+
inputs = BillInputs(
|
|
104
|
+
check.period_days, check.period_days, check.import_kwh_by_band, check.export_kwh,
|
|
105
|
+
peak_kw=check.peak_kw,
|
|
106
|
+
)
|
|
107
|
+
total = price_bill(definition, inputs).total
|
|
108
|
+
if total != check.expected_total:
|
|
109
|
+
raise CheckFailed(f"check {name!r} gives {total}, expected {check.expected_total}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _kwh_in(block: Block, scale: Decimal, total: Decimal) -> Decimal:
|
|
113
|
+
"""The kWh of *total* that fall inside *block*, with its limits multiplied by *scale*."""
|
|
114
|
+
top = total if block.end is None else min(total, block.end * scale)
|
|
115
|
+
return max(top - block.start * scale, Decimal(0))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _netted(definition: TariffDefinition, inputs: BillInputs) -> BillInputs:
|
|
119
|
+
"""Inputs with export offset against import in the band of the same name, when the tariff nets.
|
|
120
|
+
|
|
121
|
+
Only the kWh left over are priced: import that remains in each band, and the export that no
|
|
122
|
+
import absorbed. There is no banking, so a surplus is paid, never carried to the next bill."""
|
|
123
|
+
if definition.netting != "band":
|
|
124
|
+
return inputs
|
|
125
|
+
exported = inputs.export_kwh
|
|
126
|
+
if not isinstance(exported, Mapping):
|
|
127
|
+
exported = {definition.export_prices.base.name: exported}
|
|
128
|
+
imported = dict(inputs.import_kwh_by_band)
|
|
129
|
+
leftover: dict[str, Decimal] = {}
|
|
130
|
+
for band, kwh in exported.items():
|
|
131
|
+
offset = min(imported.get(band, Decimal(0)), kwh)
|
|
132
|
+
if band in imported:
|
|
133
|
+
imported[band] -= offset
|
|
134
|
+
leftover[band] = kwh - offset
|
|
135
|
+
return replace(inputs, import_kwh_by_band=imported, export_kwh=leftover)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _Pricer:
|
|
139
|
+
def __init__(self, definition: TariffDefinition, inputs: BillInputs) -> None:
|
|
140
|
+
self._unit = Decimal(1).scaleb(-definition.rounding_places)
|
|
141
|
+
self._prices = {definition.import_prices.base.name: definition.import_prices.base.price}
|
|
142
|
+
self._prices.update({zone.name: zone.price for zone in definition.import_prices.zones})
|
|
143
|
+
exported = definition.export_prices
|
|
144
|
+
self._export_base = exported.base.name
|
|
145
|
+
self._export_prices = {exported.base.name: exported.base.price}
|
|
146
|
+
self._export_prices.update({zone.name: zone.price for zone in exported.zones})
|
|
147
|
+
self._inputs = _netted(definition, inputs)
|
|
148
|
+
self._months = inputs.period_months or definition.period_value(definition.period.months)
|
|
149
|
+
|
|
150
|
+
def _round(self, value: Decimal, rounding: NodeRounding) -> Decimal:
|
|
151
|
+
if rounding is NodeRounding.NONE:
|
|
152
|
+
return value
|
|
153
|
+
return value.quantize(self._unit, ROUND_HALF_UP)
|
|
154
|
+
|
|
155
|
+
def line(self, node: Node) -> Line:
|
|
156
|
+
leaf = self._leaf(node)
|
|
157
|
+
if leaf is not None:
|
|
158
|
+
return leaf
|
|
159
|
+
if isinstance(node, Adjust):
|
|
160
|
+
return self._adjust(node)
|
|
161
|
+
if isinstance(node, Tax):
|
|
162
|
+
return self._tax(node)
|
|
163
|
+
if isinstance(node, Bound):
|
|
164
|
+
return self._bound(node)
|
|
165
|
+
assert isinstance(node, Sum) # every other kind was handled by _leaf
|
|
166
|
+
return self._sum(node)
|
|
167
|
+
|
|
168
|
+
def _leaf(self, node: Node) -> Line | None:
|
|
169
|
+
"""The line for a node that holds no other node, or None for one that does."""
|
|
170
|
+
if isinstance(node, EnergyByBand | SeriesEnergy | TieredEnergy):
|
|
171
|
+
return self._import_energy(node)
|
|
172
|
+
if isinstance(node, ExportCredit):
|
|
173
|
+
return self._export(node)
|
|
174
|
+
if isinstance(node, PerDay):
|
|
175
|
+
return Line("per_day", self._round(node.amount * self._inputs.days, node.rounding))
|
|
176
|
+
if isinstance(node, PerKwh):
|
|
177
|
+
return self._per_kwh(node)
|
|
178
|
+
if isinstance(node, Demand):
|
|
179
|
+
return self._demand(node)
|
|
180
|
+
if isinstance(node, PerPeriod):
|
|
181
|
+
return self._per_period(node)
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
def _import_energy(self, node: EnergyByBand | SeriesEnergy | TieredEnergy) -> Line:
|
|
185
|
+
if isinstance(node, SeriesEnergy):
|
|
186
|
+
return self._series(node)
|
|
187
|
+
return self._tiered(node) if isinstance(node, TieredEnergy) else self._energy(node)
|
|
188
|
+
|
|
189
|
+
def _energy(self, node: EnergyByBand) -> Line:
|
|
190
|
+
costs = {}
|
|
191
|
+
for band, kwh in self._inputs.import_kwh_by_band.items():
|
|
192
|
+
cost = kwh * self._prices[band]
|
|
193
|
+
costs[band] = self._round(cost, node.rounding) if node.round_bands else cost
|
|
194
|
+
children = {band: Line("band", cost) for band, cost in costs.items()}
|
|
195
|
+
amount = self._round(sum(costs.values(), Decimal(0)), node.rounding)
|
|
196
|
+
return Line("energy_by_band", amount, children=children)
|
|
197
|
+
|
|
198
|
+
def _series(self, node: SeriesEnergy) -> Line:
|
|
199
|
+
if node.series not in self._inputs.import_cost_by_series:
|
|
200
|
+
raise MissingSeries(f"no cost was given for the price series {node.series!r}")
|
|
201
|
+
cost = self._inputs.import_cost_by_series[node.series]
|
|
202
|
+
return Line("series_energy", self._round(cost, node.rounding))
|
|
203
|
+
|
|
204
|
+
def _tiered(self, node: TieredEnergy) -> Line:
|
|
205
|
+
in_scope = (
|
|
206
|
+
kwh for band, kwh in self._inputs.import_kwh_by_band.items()
|
|
207
|
+
if not node.bands or band in node.bands
|
|
208
|
+
)
|
|
209
|
+
total = sum(in_scope, Decimal(0))
|
|
210
|
+
scale = self._limit_scale(node.limits)
|
|
211
|
+
costs = {
|
|
212
|
+
name: _kwh_in(block, scale, total) * block.price
|
|
213
|
+
for name, block in node.blocks.items()
|
|
214
|
+
}
|
|
215
|
+
children = {name: Line("block", cost) for name, cost in costs.items()}
|
|
216
|
+
amount = self._round(sum(costs.values(), Decimal(0)), node.rounding)
|
|
217
|
+
return Line("tiered_energy", amount, children=children)
|
|
218
|
+
|
|
219
|
+
def _bound(self, node: Bound) -> Line:
|
|
220
|
+
inner = self.line(node.child)
|
|
221
|
+
limit = self._round(node.amount * self._limit_scale(node.per), node.rounding)
|
|
222
|
+
pick = max if node.kind == "minimum" else min
|
|
223
|
+
return Line(node.kind, pick(inner.amount, limit), children={"of": inner})
|
|
224
|
+
|
|
225
|
+
def _limit_scale(self, limits: str) -> Decimal:
|
|
226
|
+
"""How many times the written block limits fit in this bill."""
|
|
227
|
+
if limits == "day":
|
|
228
|
+
return Decimal(self._inputs.days)
|
|
229
|
+
return Decimal(self._months) if limits == "month" else Decimal(1)
|
|
230
|
+
|
|
231
|
+
def _export(self, node: ExportCredit) -> Line:
|
|
232
|
+
exported = self._inputs.export_kwh
|
|
233
|
+
if not isinstance(exported, Mapping):
|
|
234
|
+
exported = {self._export_base: exported}
|
|
235
|
+
credits = {band: -kwh * self._export_prices[band] for band, kwh in exported.items()}
|
|
236
|
+
amount = self._round(sum(credits.values(), Decimal(0)), node.rounding)
|
|
237
|
+
# A flat export keeps the line it always had. Bands are listed only when there are some.
|
|
238
|
+
if len(self._export_prices) == 1:
|
|
239
|
+
return Line("export_credit", amount)
|
|
240
|
+
children = {band: Line("band", credit) for band, credit in credits.items()}
|
|
241
|
+
return Line("export_credit", amount, children=children)
|
|
242
|
+
|
|
243
|
+
def _per_kwh(self, node: PerKwh) -> Line:
|
|
244
|
+
if node.on == "import":
|
|
245
|
+
kwh = sum(self._inputs.import_kwh_by_band.values(), Decimal(0))
|
|
246
|
+
else:
|
|
247
|
+
exported = self._inputs.export_kwh
|
|
248
|
+
kwh = sum(exported.values(), Decimal(0)) if isinstance(exported, Mapping) else exported
|
|
249
|
+
return Line("per_kwh", self._round(kwh * node.amount, node.rounding))
|
|
250
|
+
|
|
251
|
+
def _demand(self, node: Demand) -> Line:
|
|
252
|
+
if node.window not in self._inputs.peak_kw:
|
|
253
|
+
raise MissingPeak(f"no peak kW was given for the demand window {node.window!r}")
|
|
254
|
+
months = Decimal(self._months) if node.per == "month" else Decimal(1)
|
|
255
|
+
amount = node.price * self._inputs.peak_kw[node.window] * months
|
|
256
|
+
return Line("demand", self._round(amount, node.rounding))
|
|
257
|
+
|
|
258
|
+
def _per_period(self, node: PerPeriod) -> Line:
|
|
259
|
+
amount = node.amount * self._months if node.per == "month" else node.amount
|
|
260
|
+
if node.share == "days_in_period":
|
|
261
|
+
amount = amount * self._inputs.days / self._inputs.period_days
|
|
262
|
+
return Line("per_period", self._round(amount, node.rounding))
|
|
263
|
+
|
|
264
|
+
def _adjust(self, node: Adjust) -> Line:
|
|
265
|
+
inner = self.line(node.child)
|
|
266
|
+
change = self._round(inner.amount * node.percent / _HUNDRED, node.rounding)
|
|
267
|
+
amount = self._round(inner.amount + change, node.rounding)
|
|
268
|
+
return Line("adjust", amount, node.name, change, {"of": inner})
|
|
269
|
+
|
|
270
|
+
def _tax(self, node: Tax) -> Line:
|
|
271
|
+
inner = self.line(node.child)
|
|
272
|
+
if node.mode is TaxMode.ADDED:
|
|
273
|
+
tax = self._round(inner.amount * node.percent / _HUNDRED, node.rounding)
|
|
274
|
+
amount = self._round(inner.amount + tax, node.rounding)
|
|
275
|
+
else:
|
|
276
|
+
share = inner.amount * node.percent / (_HUNDRED + node.percent)
|
|
277
|
+
tax = self._round(share, node.rounding)
|
|
278
|
+
amount = inner.amount
|
|
279
|
+
return Line("tax", amount, node.name, tax, {"of": inner})
|
|
280
|
+
|
|
281
|
+
def _sum(self, node: Sum) -> Line:
|
|
282
|
+
children = {name: self.line(child) for name, child in node.children.items()}
|
|
283
|
+
amount = self._round(sum((c.amount for c in children.values()), Decimal(0)), node.rounding)
|
|
284
|
+
return Line("sum", amount, children=children)
|