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.
Files changed (46) hide show
  1. utility_tariffs_lib/README.md +41 -0
  2. utility_tariffs_lib/__init__.py +0 -0
  3. utility_tariffs_lib/py.typed +0 -0
  4. utility_tariffs_lib/tariff/__init__.py +164 -0
  5. utility_tariffs_lib/tariff/accumulator.py +195 -0
  6. utility_tariffs_lib/tariff/bands.py +124 -0
  7. utility_tariffs_lib/tariff/bill_days.py +73 -0
  8. utility_tariffs_lib/tariff/billing.py +28 -0
  9. utility_tariffs_lib/tariff/compile.py +124 -0
  10. utility_tariffs_lib/tariff/config.py +208 -0
  11. utility_tariffs_lib/tariff/defaults.py +16 -0
  12. utility_tariffs_lib/tariff/definition.py +321 -0
  13. utility_tariffs_lib/tariff/definition_parse.py +765 -0
  14. utility_tariffs_lib/tariff/definition_savings.py +116 -0
  15. utility_tariffs_lib/tariff/demand.py +44 -0
  16. utility_tariffs_lib/tariff/engine.py +284 -0
  17. utility_tariffs_lib/tariff/index.py +309 -0
  18. utility_tariffs_lib/tariff/period_bill.py +136 -0
  19. utility_tariffs_lib/tariff/periods.py +34 -0
  20. utility_tariffs_lib/tariff/price_curve.py +142 -0
  21. utility_tariffs_lib/tariff/price_series.py +137 -0
  22. utility_tariffs_lib/tariff/price_stats.py +194 -0
  23. utility_tariffs_lib/tariff/price_timeline.py +139 -0
  24. utility_tariffs_lib/tariff/reprice.py +106 -0
  25. utility_tariffs_lib/tariff/savings.py +118 -0
  26. utility_tariffs_lib/tariff/slot_history.py +128 -0
  27. utility_tariffs_lib/tariff/slots.py +266 -0
  28. utility_tariffs_lib/tariff/stored_energy.py +64 -0
  29. utility_tariffs_lib/tariff/windows.py +119 -0
  30. utility_tariffs_lib/tariffranking/__init__.py +39 -0
  31. utility_tariffs_lib/tariffranking/search.py +189 -0
  32. utility_tariffs_lib/tariffstore/__init__.py +13 -0
  33. utility_tariffs_lib/tariffstore/client.py +406 -0
  34. utility_tariffs_lib/tariffstore/compile.py +157 -0
  35. utility_tariffs_lib/tariffstore/index.py +188 -0
  36. utility_tariffs_lib/tariffstore/layout.py +39 -0
  37. utility_tariffs_lib/tariffstore/price_client.py +87 -0
  38. utility_tariffs_lib/tariffstore/prices.py +127 -0
  39. utility_tariffs_lib/tariffstore/schema.py +550 -0
  40. utility_tariffs_lib/timeutil/__init__.py +5 -0
  41. utility_tariffs_lib/timeutil/real_time.py +52 -0
  42. utility_tariffs_lib-0.1.0.dist-info/METADATA +61 -0
  43. utility_tariffs_lib-0.1.0.dist-info/RECORD +46 -0
  44. utility_tariffs_lib-0.1.0.dist-info/WHEEL +5 -0
  45. utility_tariffs_lib-0.1.0.dist-info/licenses/LICENSE +21 -0
  46. utility_tariffs_lib-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,124 @@
1
+ """compile.py: write a TariffConfig, the tariff as the options hold it, as a definition document.
2
+
3
+ The options describe one household's tariff: a base rate, timed rates where the cheapest wins, a
4
+ saving on energy, a standing charge, a monthly levy and VAT. This builds the document that prices
5
+ the same bill, then reads it through `parse_definition`, so the document is checked the same way
6
+ as one from a store. The options do not hold a currency code, country or time zone, so the caller
7
+ passes them as a `Locale`.
8
+
9
+ The cheapest-wins rule becomes priorities: the dearest timed rate gets priority 1, so a cheaper
10
+ rate that is also active outranks it. Equal rates keep the order they were listed in.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from datetime import date
17
+ from decimal import Decimal
18
+ from typing import Any
19
+
20
+ from .config import TariffConfig
21
+ from .definition import DefinitionError, TariffDefinition
22
+ from .definition_parse import parse_definition
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Locale:
27
+ """What the options do not hold: where the tariff applies and from when."""
28
+
29
+ currency: str # ISO 4217
30
+ country: str # ISO 3166-1 alpha-2
31
+ timezone_name: str
32
+ effective_from: date
33
+
34
+
35
+ def definition_from_config(config: TariffConfig, locale: Locale) -> TariffDefinition:
36
+ """The definition that prices the same bill as *config*.
37
+
38
+ Raises DefinitionError when the options cannot be written as a document, for example a bill
39
+ start day after the 28th, which a monthly period cannot name.
40
+ """
41
+ return parse_definition(
42
+ {
43
+ "schema": 1,
44
+ "id": "household-options",
45
+ "revision": 1,
46
+ "supersedes": None,
47
+ "name": "Tariff from the saved options",
48
+ "service": "electricity",
49
+ "customer_class": "residential",
50
+ "provider": {"id": "household", "name": "Household"},
51
+ "country": locale.country,
52
+ "region": None,
53
+ "currency": locale.currency,
54
+ "timezone": locale.timezone_name,
55
+ "effective_from": locale.effective_from.isoformat(),
56
+ "effective_to": None,
57
+ "source_url": None,
58
+ "last_verified": None,
59
+ "completeness": "partial",
60
+ "inputs": {},
61
+ "import": {
62
+ "base": {"name": config.base_rate_name, "price": _text(config.base_rate)},
63
+ "zones": _zones(config),
64
+ },
65
+ "export": {"base": {"name": "Export", "price": _text(config.export_rate)}},
66
+ "bill": {"period": _period(config), "total": _total(config)},
67
+ }
68
+ )
69
+
70
+
71
+ def _text(value: float) -> str:
72
+ """A float written as the decimal string it prints as, so 0.1056 stays 0.1056."""
73
+ return str(Decimal(repr(value)))
74
+
75
+
76
+ def _zones(config: TariffConfig) -> list[dict[str, Any]]:
77
+ # sorted is stable, so equal rates keep their listed order and the later one wins a tie,
78
+ # as min() over the same list would pick the first. Reverse the tie order to match.
79
+ ordered = sorted(enumerate(config.rate_periods), key=lambda item: (-item[1].rate, -item[0]))
80
+ return [
81
+ {
82
+ "name": period.name,
83
+ "priority": priority,
84
+ "price": _text(period.rate),
85
+ "hours": f"{period.start:%H:%M}-{period.end:%H:%M}",
86
+ }
87
+ for priority, (_, period) in enumerate(ordered, start=1)
88
+ ]
89
+
90
+
91
+ def _period(config: TariffConfig) -> dict[str, Any]:
92
+ if not 1 <= config.bill_start_day <= 28:
93
+ raise DefinitionError(
94
+ "bill.period.start_day", "a monthly period can start on day 1 to 28 only"
95
+ )
96
+ return {"rule": "monthly", "start_day": config.bill_start_day}
97
+
98
+
99
+ def _total(config: TariffConfig) -> dict[str, Any]:
100
+ energy = {
101
+ "kind": "adjust",
102
+ "name": "Saving",
103
+ "percent": _text(-config.discount_rate) if config.discount_rate else "0",
104
+ "of": {"kind": "energy_by_band", "round_bands": True},
105
+ }
106
+ charges = {
107
+ "kind": "tax",
108
+ "name": "VAT",
109
+ "percent": _text(config.vat_rate),
110
+ "mode": "included" if config.vat_included else "added",
111
+ "of": {
112
+ "kind": "sum",
113
+ "of": {
114
+ "energy": energy,
115
+ "standing": {"kind": "per_day", "amount": _text(config.standing_charge)},
116
+ "levy": {
117
+ "kind": "per_period",
118
+ "amount": _text(config.pso_levy),
119
+ "share": "days_in_period",
120
+ },
121
+ },
122
+ },
123
+ }
124
+ return {"kind": "sum", "of": {"charges": charges, "credit": {"kind": "export_credit"}}}
@@ -0,0 +1,208 @@
1
+ """config.py: the full tariff, and the cost of energy under it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import calendar
6
+ from dataclasses import dataclass
7
+ from datetime import date, datetime, time, timedelta
8
+
9
+ from ..timeutil import elapsed_seconds, local_time_on
10
+ from .billing import BillBreakdown, money
11
+ from .periods import RatePeriod
12
+
13
+ _AVERAGE_DAYS_PER_MONTH = 30.44
14
+
15
+
16
+ @dataclass
17
+ class TariffConfig:
18
+ """
19
+ Full tariff configuration.
20
+
21
+ rate_periods — timed override slots only (Night, Nightboost, etc.).
22
+ Each overrides the base rate during its window.
23
+ base_rate — the default rate that applies whenever no timed period is active.
24
+ base_rate_name — display name for the base rate (e.g. "Day").
25
+ """
26
+
27
+ rate_periods: list[RatePeriod]
28
+ base_rate: float # €/kWh — standard daytime / catch-all rate
29
+ base_rate_name: str # display name for the base rate
30
+ export_rate: float # €/kWh CEG rate
31
+ standing_charge: float # €/day
32
+ pso_levy: float # €/month
33
+ vat_rate: float # % e.g. 9.0
34
+ discount_rate: float # % e.g. 5.5
35
+ bill_start_day: int # day of month billing period starts
36
+ vat_included: bool = False # True when the prices already include VAT (vat_rate is inside them)
37
+
38
+ @property
39
+ def _vat_factor(self) -> float:
40
+ """What VAT multiplies a price by: nothing when the prices already include it."""
41
+ return 1.0 if self.vat_included else 1 + self.vat_rate / 100
42
+
43
+ @property
44
+ def _base_rate_period(self) -> RatePeriod:
45
+ """Return the base rate as a RatePeriod for uniform handling."""
46
+ return RatePeriod(self.base_rate_name, self.base_rate, time(0, 0), time(0, 0))
47
+
48
+ def get_current_rate(self, dt: datetime) -> RatePeriod:
49
+ """
50
+ Return the rate period that applies at the given datetime.
51
+
52
+ Precedence rules:
53
+ 1. Among all timed periods that are currently active, the cheapest wins.
54
+ Nightboost (02:00–04:00 at €0.0965) overrides Night (23:00–08:00 at
55
+ €0.1644) automatically — no special-casing needed.
56
+ 2. If no timed period is active, the base rate applies.
57
+ """
58
+ active_timed = [p for p in self.rate_periods if p.is_active(dt)]
59
+ if active_timed:
60
+ return min(active_timed, key=lambda p: p.rate)
61
+ return self._base_rate_period
62
+
63
+ def get_cheapest_rate(self) -> RatePeriod:
64
+ """Return the cheapest rate across all periods including the base rate."""
65
+ candidates = list(self.rate_periods) + [self._base_rate_period]
66
+ return min(candidates, key=lambda p: p.rate)
67
+
68
+ def get_cheapest_rate_start(self) -> time:
69
+ """Return the start time of the cheapest *timed* rate period.
70
+
71
+ This is when the coordinator should write the overnight charge target
72
+ to the inverter, so it takes effect as soon as cheap electricity begins.
73
+
74
+ Only considers timed periods — the base rate has no meaningful start
75
+ time (its synthetic period uses time(0,0)). Callers should check
76
+ that rate_periods is non-empty before calling this.
77
+ """
78
+ if not self.rate_periods:
79
+ raise ValueError(
80
+ "get_cheapest_rate_start() called on a flat-rate tariff with no "
81
+ "timed periods. Check tariff.rate_periods before calling."
82
+ )
83
+ return min(self.rate_periods, key=lambda p: p.rate).start
84
+
85
+ def next_cheap_rate(self, dt: datetime) -> tuple[float, str | None] | None:
86
+ """Return (hours until a cheaper-than-base period starts, its HH:MM start).
87
+
88
+ Returns (0.0, None) when a cheaper-than-base period is active now, and None
89
+ when the tariff has no such period.
90
+ """
91
+ cheap = [p for p in self.rate_periods if p.rate < self.base_rate]
92
+ if not cheap:
93
+ return None
94
+ if any(p.is_active(dt) for p in cheap):
95
+ return 0.0, None
96
+ now = dt.replace(second=0, microsecond=0)
97
+ starts = []
98
+ for period in cheap:
99
+ start = local_time_on(now, period.start)
100
+ if elapsed_seconds(now, start) < 0:
101
+ start = local_time_on(now + timedelta(days=1), period.start)
102
+ starts.append((elapsed_seconds(now, start), period))
103
+ seconds, soonest = min(starts, key=lambda item: item[0])
104
+ return round(seconds / 3600, 2), soonest.start.strftime("%H:%M")
105
+
106
+ def calculate_import_cost(self, kwh: float, dt: datetime) -> float:
107
+ """Calculate cost of importing energy at the current rate."""
108
+ rate = self.get_current_rate(dt)
109
+ gross = kwh * rate.rate * (1 - self.discount_rate / 100)
110
+ return gross * self._vat_factor
111
+
112
+ def effective_import_rate(self, rate: float) -> float:
113
+ """What one kWh costs at this unit rate once the discount and VAT are applied.
114
+
115
+ Uses the same two factors as calculate_import_cost, so a price compared with it is
116
+ compared with what the cost sensors charge.
117
+ """
118
+ return rate * (1 - self.discount_rate / 100) * self._vat_factor
119
+
120
+ def calculate_export_earnings(self, kwh: float) -> float:
121
+ """Calculate earnings from exporting energy."""
122
+ return kwh * self.export_rate
123
+
124
+ def energy_cost_from_import_cost(self, import_cost: float) -> float:
125
+ """Reverse the discount and VAT applied to accumulated import cost."""
126
+ factor = (1 - self.discount_rate / 100) * self._vat_factor
127
+ return import_cost / factor if factor > 0 else 0.0
128
+
129
+ def calculate_bill(
130
+ self,
131
+ energy_cost: float,
132
+ days: int,
133
+ period_days: int | None = None,
134
+ export_credit: float = 0.0,
135
+ ) -> BillBreakdown:
136
+ """Build a bill from energy cost (kWh x rate, before discount and VAT).
137
+
138
+ The supplier saving applies to energy only. VAT applies to energy less the
139
+ saving, plus standing charge and PSO levy. The export credit carries no VAT
140
+ and comes off after VAT. When the prices include VAT, the VAT figure is the part
141
+ already inside the total and nothing is added.
142
+ """
143
+ energy = money(energy_cost)
144
+ saving = money(energy_cost * self.discount_rate / 100)
145
+ standing = money(self.standing_charge * days)
146
+ if period_days is not None and period_days > 0:
147
+ share = min(1.0, days / period_days)
148
+ else:
149
+ share = min(1.0, days / _AVERAGE_DAYS_PER_MONTH)
150
+ pso = money(self.pso_levy * share)
151
+ before_vat = money(energy - saving + standing + pso)
152
+ if self.vat_included:
153
+ vat = money(before_vat * self.vat_rate / (100 + self.vat_rate)) # already inside
154
+ payable = before_vat
155
+ else:
156
+ vat = money(before_vat * self.vat_rate / 100)
157
+ payable = money(before_vat + vat)
158
+ export = money(export_credit)
159
+ return BillBreakdown(
160
+ energy=energy,
161
+ supplier_saving=saving,
162
+ standing_charge=standing,
163
+ pso_levy=pso,
164
+ vat=vat,
165
+ export_credit=export,
166
+ total=money(payable - export),
167
+ )
168
+
169
+ def _bill_start_date(self, year: int, month: int) -> date:
170
+ last_day = calendar.monthrange(year, month)[1]
171
+ return date(year, month, max(1, min(self.bill_start_day, last_day)))
172
+
173
+ def _bill_period_bounds(self, dt: datetime) -> tuple[date, date]:
174
+ """Return (first day of the current period, first day of the next period)."""
175
+ today = dt.date()
176
+ this_start = self._bill_start_date(today.year, today.month)
177
+ if today >= this_start:
178
+ start = this_start
179
+ next_year, next_month = (
180
+ (today.year + 1, 1) if today.month == 12 else (today.year, today.month + 1)
181
+ )
182
+ return start, self._bill_start_date(next_year, next_month)
183
+ prev_year, prev_month = (
184
+ (today.year - 1, 12) if today.month == 1 else (today.year, today.month - 1)
185
+ )
186
+ return self._bill_start_date(prev_year, prev_month), this_start
187
+
188
+ def days_in_bill_period(self, dt: datetime) -> int:
189
+ """Return the total length in days of the billing period containing dt."""
190
+ start, end = self._bill_period_bounds(dt)
191
+ return (end - start).days
192
+
193
+ def days_in_current_bill_period(self, dt: datetime) -> int:
194
+ """Return the day number of dt within its billing period.
195
+
196
+ The bill start day is day 1, so the result is always at least 1.
197
+ """
198
+ start, _ = self._bill_period_bounds(dt)
199
+ return (dt.date() - start).days + 1
200
+
201
+ def days_remaining_in_bill_period(self, dt: datetime) -> int:
202
+ """Return the days left in the billing period after dt's day."""
203
+ return self.days_in_bill_period(dt) - self.days_in_current_bill_period(dt)
204
+
205
+
206
+ def cheapest_period(tariff: TariffConfig) -> RatePeriod:
207
+ """The timed rate period with the lowest rate."""
208
+ return min(tariff.rate_periods, key=lambda p: p.rate)
@@ -0,0 +1,16 @@
1
+ """defaults.py: the numbers the half-hourly store needs. Imports nothing."""
2
+
3
+ # Length of one slot. Every slot is exactly this many real seconds, so a clock change shows up as
4
+ # a day with fewer or more slots, never as a slot of another length.
5
+ SLOT_SECONDS = 1800
6
+
7
+ # How many days of slots are kept. A year plus a spare bill period, so any bill can be re-priced.
8
+ SLOT_RETENTION_DAYS = 400
9
+
10
+ # A reading interval longer than this is a gap (Home Assistant down, or a stalled update). Its
11
+ # energy is not spread over the slots it spans, because the shape inside the gap is unknown.
12
+ SLOT_MAX_INTERVAL_SECONDS = 1800
13
+
14
+ # How deeply a bill tree may nest. A real bill is about four levels, so this refuses a document
15
+ # built to exhaust the stack without limiting any honest tariff.
16
+ MAX_TARIFF_TREE_DEPTH = 8
@@ -0,0 +1,321 @@
1
+ """definition.py: a tariff and its bill written as data.
2
+
3
+ A definition is one document that holds everything needed to price energy and work out a bill:
4
+ the supplier, the dates it applies, the prices, the customer's own inputs and the bill as a tree
5
+ of nodes. It is data, not code. The only things a document can ask for are the node kinds listed
6
+ here, so a document from a shared store can do nothing but price.
7
+
8
+ The shape is described in `definition_parse.py`, which turns a JSON document into these types and
9
+ refuses anything it does not understand. Nothing here reads a price source or a slot. Money is
10
+ `Decimal` throughout, never a float.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Mapping
16
+ from dataclasses import dataclass, field
17
+ from datetime import date, time, tzinfo
18
+ from decimal import Decimal
19
+ from enum import Enum
20
+
21
+ SCHEMA_VERSION = 1
22
+
23
+
24
+ class DefinitionError(ValueError):
25
+ """A document that is not a valid definition. *path* names the field, such as `bill.total`."""
26
+
27
+ def __init__(self, path: str, message: str) -> None:
28
+ super().__init__(f"{path or 'definition'}: {message}")
29
+ self.path = path
30
+
31
+
32
+ class NodeRounding(Enum):
33
+ """How a node's amount is rounded before its parent uses it."""
34
+
35
+ MINOR_UNIT = "minor_unit" # to the currency's smallest unit, halves upward
36
+ NONE = "none" # keep full precision until the parent rounds
37
+
38
+
39
+ class TaxMode(Enum):
40
+ """Whether a tax is added to the wrapped amount or already inside it."""
41
+
42
+ ADDED = "added"
43
+ INCLUDED = "included"
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Provider:
48
+ id: str # stable slug, such as "example-energy"
49
+ name: str # for display, may change
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Band:
54
+ """The base price, charged when no zone applies."""
55
+
56
+ name: str
57
+ price: Decimal # per kWh, in the document's currency
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Zone:
62
+ """A price that applies in some hours. The applicable zone of highest priority wins."""
63
+
64
+ name: str
65
+ priority: int # unique across the tariff's zones
66
+ price: Decimal
67
+ start: time # local clock time the zone begins
68
+ end: time # local clock time it ends. Earlier than start means it runs past midnight
69
+ days: frozenset[int] # weekdays it applies on, Monday 0 to Sunday 6. Empty means every day
70
+ months: frozenset[int] # months it applies in, 1 to 12. Empty means every month
71
+ holidays_as_weekend: bool # whether a public holiday counts as a weekend day
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class ImportPrices:
76
+ base: Band
77
+ zones: tuple[Zone, ...]
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ExportPrices:
82
+ """What exported energy is paid. With no zones it is one flat price."""
83
+
84
+ base: Band
85
+ zones: tuple[Zone, ...] = ()
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class InputSpec:
90
+ """A value the customer supplies, with the range it must stay inside."""
91
+
92
+ minimum: int
93
+ maximum: int
94
+ default: int
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class PeriodValue:
99
+ """One whole number of the bill period: fixed by the tariff, or an input."""
100
+
101
+ fixed: int | None
102
+ input: str | None
103
+
104
+
105
+ StartDay = PeriodValue # the name the start day had before the period gained other values
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class PeriodRule:
110
+ """When a bill period starts and how long it runs.
111
+
112
+ A period is *months* calendar months long and starts on *start_day* of a month. *start_month*
113
+ names one month a period starts in, which places a period of two months or more in the year.
114
+ """
115
+
116
+ rule: str # "monthly": the period is a whole number of calendar months
117
+ start_day: PeriodValue
118
+ months: PeriodValue = PeriodValue(1, None)
119
+ start_month: PeriodValue = PeriodValue(1, None)
120
+
121
+
122
+ # The bill tree. Each node is worked out after everything inside it, so nesting sets the order.
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class EnergyByBand:
127
+ """Import kWh in each band times the band's price."""
128
+
129
+ round_bands: bool # round each band's cost before adding them, as a supplier bill lists it
130
+ rounding: NodeRounding
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class SeriesEnergy:
135
+ """Import kWh priced against a named price series, a price for each interval of the day.
136
+
137
+ The engine reads only totals, so the cost is worked out first from the slots and the series
138
+ (`price_series.series_cost`) and handed over under *series*."""
139
+
140
+ series: str # the name the bill inputs give the cost under
141
+ rounding: NodeRounding
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class Block:
146
+ """One block of a tiered price: the kWh from *start* up to *end* cost *price* each."""
147
+
148
+ start: Decimal # kWh where the block begins, as the limits are written
149
+ end: Decimal | None # kWh where it ends. None for the last block, which has no top
150
+ price: Decimal # per kWh, in the document's currency
151
+
152
+
153
+ @dataclass(frozen=True)
154
+ class TieredEnergy:
155
+ """All import kWh priced by block, the first kWh at the first block's price and so on.
156
+
157
+ The blocks replace the band prices, so the kWh in a band do not change the price. *limits* says
158
+ what the block limits are written for: the whole bill period, one month of it, or one day.
159
+ With *bands*, the node prices only the kWh in those bands, so each band, or group of bands,
160
+ can have a tier table of its own.
161
+ """
162
+
163
+ blocks: Mapping[str, Block] # by name, in order of start
164
+ limits: str # "period", "month" or "day"
165
+ rounding: NodeRounding
166
+ bands: frozenset[str] = frozenset() # the import bands it prices. Empty means every band
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class ExportCredit:
171
+ """Export kWh times the export price, or the kWh in each export band times its price. A
172
+ credit."""
173
+
174
+ rounding: NodeRounding
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class PerDay:
179
+ """An amount for each day of the bill."""
180
+
181
+ amount: Decimal
182
+ rounding: NodeRounding
183
+
184
+
185
+ @dataclass(frozen=True)
186
+ class PerPeriod:
187
+ """An amount for the bill period, of which a bill carries the share of its days.
188
+
189
+ With *per* "month" the amount is for one month, so a longer period charges it once a month.
190
+ """
191
+
192
+ amount: Decimal
193
+ share: str # "days_in_period" or "whole"
194
+ rounding: NodeRounding
195
+ per: str = "period" # "period" or "month"
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class PerKwh:
200
+ """An amount for each kWh imported or exported, for a levy, rider or fuel adjustment."""
201
+
202
+ amount: Decimal # per kWh, in the document's currency. Negative for a credit
203
+ on: str # "import" or "export"
204
+ rounding: NodeRounding
205
+
206
+
207
+ @dataclass(frozen=True)
208
+ class Demand:
209
+ """A charge on the highest power drawn, in kW, in a window of the day.
210
+
211
+ The peak is the highest half-hour average import in the window, over the bill period. The
212
+ engine does not read slots, so the caller gives the peak for *window* in `BillInputs`. Two
213
+ nodes that name the same window must describe the same hours, days and months.
214
+ """
215
+
216
+ window: str # the name the peak is given under, in `BillInputs` and in a check
217
+ price: Decimal # per kW, in the document's currency
218
+ per: str # "period": once for the bill, or "month": for each month of it
219
+ when: Zone # the hours, days and months it counts. Equal start and end mean the whole day
220
+ rounding: NodeRounding
221
+
222
+
223
+ @dataclass(frozen=True)
224
+ class Bound:
225
+ """Wraps one node and sets a floor (`minimum`) or a cap (`maximum`) on its amount.
226
+
227
+ *amount* is written for a whole *per* ("period", "month" or "day"), and the engine multiplies
228
+ it by the months or days of the bill.
229
+ """
230
+
231
+ kind: str # "minimum" or "maximum"
232
+ amount: Decimal
233
+ per: str
234
+ child: Node
235
+ rounding: NodeRounding
236
+
237
+
238
+ @dataclass(frozen=True)
239
+ class Adjust:
240
+ """Wraps one node and adds a percentage of it. A saving is a negative percentage."""
241
+
242
+ name: str
243
+ percent: Decimal
244
+ child: Node
245
+ rounding: NodeRounding
246
+
247
+
248
+ @dataclass(frozen=True)
249
+ class Tax:
250
+ """Wraps one node and adds, or reports, a percentage tax on everything inside it."""
251
+
252
+ name: str
253
+ percent: Decimal
254
+ mode: TaxMode
255
+ child: Node
256
+ rounding: NodeRounding
257
+
258
+
259
+ @dataclass(frozen=True)
260
+ class Sum:
261
+ """Adds its children. They are held by name, so their order never matters."""
262
+
263
+ children: Mapping[str, Node]
264
+ rounding: NodeRounding
265
+
266
+
267
+ Node = (
268
+ EnergyByBand | SeriesEnergy | TieredEnergy | ExportCredit | PerDay | PerPeriod | PerKwh
269
+ | Demand | Bound | Adjust | Tax | Sum
270
+ )
271
+
272
+
273
+ @dataclass(frozen=True)
274
+ class Check:
275
+ """A worked bill the definition must reproduce. Another implementation can run it too."""
276
+
277
+ period_days: int
278
+ import_kwh_by_band: Mapping[str, Decimal]
279
+ export_kwh: Decimal | Mapping[str, Decimal] # one total, or the kWh in each export band
280
+ expected_total: Decimal
281
+ peak_kw: Mapping[str, Decimal] = field(default_factory=dict) # kW by demand window
282
+
283
+
284
+ @dataclass(frozen=True)
285
+ class TariffDefinition:
286
+ """A validated tariff document. Build one with `parse_definition`."""
287
+
288
+ id: str
289
+ revision: int
290
+ supersedes: int | None # the earlier revision of this id this one replaces
291
+ name: str
292
+ service: str
293
+ customer_class: str
294
+ provider: Provider
295
+ country: str # ISO 3166-1 alpha-2
296
+ region: str | None # ISO 3166-2, or None for a national tariff
297
+ currency: str # ISO 4217
298
+ timezone: tzinfo
299
+ timezone_name: str
300
+ effective_from: date # included
301
+ effective_to: date | None # excluded, None while open ended
302
+ source_url: str | None
303
+ last_verified: date | None
304
+ complete: bool # False when the tree does not hold every charge on the supplier's bill
305
+ inputs: Mapping[str, InputSpec]
306
+ import_prices: ImportPrices
307
+ export_prices: ExportPrices
308
+ period: PeriodRule
309
+ rounding_places: int # decimal places of the currency's smallest unit
310
+ total: Node
311
+ checks: Mapping[str, Check]
312
+ # "none", or "band": export kWh offset the import kWh of the import band with the same name
313
+ # before any price is applied, and only what is left over is paid at the export price.
314
+ netting: str = "none"
315
+
316
+ def period_value(self, value: PeriodValue) -> int:
317
+ """The number *value* stands for: its fixed number, or the default of its input."""
318
+ if value.fixed is not None:
319
+ return value.fixed
320
+ assert value.input is not None # parse_definition accepts a fixed number or an input
321
+ return self.inputs[value.input].default