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,765 @@
1
+ """definition_parse.py: read a tariff document and refuse anything that is not understood.
2
+
3
+ The document is JSON. A bad document raises DefinitionError naming the field, and nothing is
4
+ repaired or guessed: an unknown key, an unknown node kind, a number where a decimal string is
5
+ required, a date that is not YYYY-MM-DD and a reference to something undeclared are all refused.
6
+
7
+ Shape, top level (every key is required unless marked optional):
8
+
9
+ schema, id, revision, supersedes (null or an earlier revision), name, service, customer_class,
10
+ provider {id, name}, country, region (null or ISO 3166-2), currency, timezone,
11
+ effective_from, effective_to (null), source_url (null), last_verified (null), completeness,
12
+ inputs {name: {type, min, max, default}}, import {base, zones}, export {base, zones?},
13
+ bill {period {rule, start_day, months?, start_month?}, total <node>},
14
+ checks {name: {...}} (optional)
15
+
16
+ The bill tree and the vocabulary of node kinds are described in definition.py. Prices, amounts,
17
+ percentages and kWh are strings such as "0.365", so no float ever stands for money. A JSON number
18
+ with a decimal point is refused for that reason.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import re
25
+ from collections.abc import Callable, Collection, Iterable, Mapping
26
+ from datetime import date, time
27
+ from decimal import Decimal
28
+ from typing import Any, NamedTuple
29
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
30
+
31
+ from .defaults import MAX_TARIFF_TREE_DEPTH
32
+ from .definition import (
33
+ SCHEMA_VERSION,
34
+ Adjust,
35
+ Band,
36
+ Block,
37
+ Bound,
38
+ Check,
39
+ DefinitionError,
40
+ Demand,
41
+ EnergyByBand,
42
+ ExportCredit,
43
+ ExportPrices,
44
+ ImportPrices,
45
+ InputSpec,
46
+ Node,
47
+ NodeRounding,
48
+ PerDay,
49
+ PeriodRule,
50
+ PeriodValue,
51
+ PerKwh,
52
+ PerPeriod,
53
+ Provider,
54
+ SeriesEnergy,
55
+ Sum,
56
+ TariffDefinition,
57
+ Tax,
58
+ TaxMode,
59
+ TieredEnergy,
60
+ Zone,
61
+ )
62
+
63
+ SLUG = re.compile(r"^[a-z0-9][a-z0-9-]*$")
64
+ _NODE_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
65
+ _DECIMAL = re.compile(r"^-?(0|[1-9][0-9]*)(\.[0-9]+)?$")
66
+ _DATE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
67
+ _HOURS = re.compile(r"^([01][0-9]|2[0-3]):([0-5][0-9])-([01][0-9]|2[0-3]):([0-5][0-9])$")
68
+ COUNTRY = re.compile(r"^[A-Z]{2}$")
69
+ _REGION = re.compile(r"^[A-Z]{2}-[A-Z0-9]{1,3}$")
70
+ _CURRENCY = re.compile(r"^[A-Z]{3}$")
71
+
72
+ _WEEKDAYS = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
73
+ _SERVICES = ("electricity",) # others (gas) are added with their own nodes
74
+ _CUSTOMER_CLASSES = ("residential", "commercial")
75
+ _PERIOD_RULES = ("monthly",)
76
+ _SHARES = ("days_in_period", "whole")
77
+ _PER = ("period", "month")
78
+ _LIMITS = ("period", "month", "day")
79
+ _FLOWS = ("import", "export")
80
+ _NETTING = ("none", "band")
81
+ _START_DAYS = (1, 28) # a month always has these days
82
+ _PERIOD_MONTHS = (1, 2, 3, 4, 6, 12) # lengths that start in the same months every year
83
+ _MONTHS = (1, 12)
84
+
85
+ # ISO 4217 minor units that are not two places. Any other currency is taken as two.
86
+ _MINOR_UNIT_PLACES = {
87
+ "JPY": 0, "KRW": 0, "ISK": 0, "CLP": 0, "BHD": 3, "KWD": 3, "OMR": 3, "TND": 3,
88
+ }
89
+
90
+
91
+ def load_json(text: str) -> Any:
92
+ """Decode JSON text, refusing a number with a decimal point, NaN and Infinity.
93
+
94
+ Raises DefinitionError. Shared by every reader of the tariff documents.
95
+ """
96
+ try:
97
+ return json.loads(text, parse_float=_refuse_float, parse_constant=_refuse_constant)
98
+ except json.JSONDecodeError as err:
99
+ raise DefinitionError("", f"not valid JSON ({err.msg} at position {err.pos})") from err
100
+
101
+
102
+ def load_definition(text: str) -> TariffDefinition:
103
+ """Parse JSON text into a definition. Raises DefinitionError for anything not valid."""
104
+ return parse_definition(load_json(text))
105
+
106
+
107
+ def parse_definition(data: object) -> TariffDefinition:
108
+ """Validate a decoded document and return it as a TariffDefinition."""
109
+ doc = Fields(data, "")
110
+ doc.only(
111
+ required=(
112
+ "schema", "id", "revision", "supersedes", "name", "service", "customer_class",
113
+ "provider", "country", "region", "currency", "timezone", "effective_from",
114
+ "effective_to", "source_url", "last_verified", "completeness", "inputs", "import",
115
+ "export", "bill",
116
+ ),
117
+ optional=("checks",),
118
+ )
119
+ doc.whole("schema", SCHEMA_VERSION, SCHEMA_VERSION) # refuses any other version
120
+ identity = _identity(doc)
121
+ inputs = _inputs(doc.child("inputs"))
122
+ import_prices, export_prices = _prices(doc)
123
+ period, total = _bill(doc.child("bill"), inputs)
124
+ _check_bands(total, _names(import_prices))
125
+ checks = _checks(doc, import_prices, export_prices, set(demand_windows(total)))
126
+ complete = doc.choice("completeness", ("complete", "partial")) == "complete"
127
+ if complete and not checks:
128
+ raise DefinitionError("completeness", "complete needs at least one entry in checks")
129
+ zone_name = doc.text("timezone")
130
+ return TariffDefinition(
131
+ **identity,
132
+ complete=complete,
133
+ inputs=inputs,
134
+ import_prices=import_prices,
135
+ export_prices=export_prices,
136
+ period=period,
137
+ rounding_places=_MINOR_UNIT_PLACES.get(identity["currency"], 2),
138
+ total=total,
139
+ checks=checks,
140
+ netting=_netting(doc.child("bill"), import_prices, export_prices),
141
+ timezone=_zone(zone_name, "timezone"),
142
+ timezone_name=zone_name,
143
+ )
144
+
145
+
146
+ def _refuse_float(text: str) -> Any:
147
+ raise DefinitionError("", f"the number {text} has a decimal point. Write money as a string")
148
+
149
+
150
+ def _refuse_constant(text: str) -> Any:
151
+ raise DefinitionError("", f"{text} is not allowed")
152
+
153
+
154
+ class Fields:
155
+ """One JSON object and the path to it, with typed reads that refuse the wrong type."""
156
+
157
+ def __init__(self, data: object, path: str) -> None:
158
+ if not isinstance(data, Mapping):
159
+ raise DefinitionError(path, "must be an object")
160
+ self._data: Mapping[str, Any] = data
161
+ self.path = path
162
+
163
+ def at(self, key: str) -> str:
164
+ return f"{self.path}.{key}" if self.path else key
165
+
166
+ def only(self, required: Iterable[str], optional: Iterable[str] = ()) -> None:
167
+ required, optional = tuple(required), tuple(optional)
168
+ for key in required:
169
+ if key not in self._data:
170
+ raise DefinitionError(self.at(key), "is missing")
171
+ for key in self._data:
172
+ if key not in (*required, *optional):
173
+ raise DefinitionError(self.at(str(key)), "is not a known field")
174
+
175
+ def raw(self, key: str) -> Any:
176
+ return self._data[key]
177
+
178
+ def has(self, key: str) -> bool:
179
+ return key in self._data
180
+
181
+ def child(self, key: str) -> Fields:
182
+ return Fields(self._data[key], self.at(key))
183
+
184
+ def items(self) -> Iterable[tuple[str, Any]]:
185
+ return self._data.items()
186
+
187
+ def text(self, key: str) -> str:
188
+ value = self._data[key]
189
+ if not isinstance(value, str) or not value.strip():
190
+ raise DefinitionError(self.at(key), "must be a non-empty string")
191
+ return value
192
+
193
+ def optional_text(self, key: str) -> str | None:
194
+ return None if self._data[key] is None else self.text(key)
195
+
196
+ def match(self, key: str, pattern: re.Pattern[str], what: str) -> str:
197
+ value = self.text(key)
198
+ if not pattern.match(value):
199
+ raise DefinitionError(self.at(key), f"must be {what}")
200
+ return value
201
+
202
+ def choice(self, key: str, options: Collection[str]) -> str:
203
+ value = self.text(key)
204
+ if value not in options:
205
+ raise DefinitionError(self.at(key), f"must be one of {', '.join(options)}")
206
+ return value
207
+
208
+ def whole(self, key: str, minimum: int, maximum: int) -> int:
209
+ return _whole(self._data[key], self.at(key), minimum, maximum)
210
+
211
+ def money(self, key: str) -> Decimal:
212
+ value = self.signed(key)
213
+ if value < 0:
214
+ raise DefinitionError(self.at(key), "must be 0 or more")
215
+ return value
216
+
217
+ def signed(self, key: str) -> Decimal:
218
+ return _decimal(self._data[key], self.at(key))
219
+
220
+ def day(self, key: str) -> date:
221
+ return _day(self._data[key], self.at(key))
222
+
223
+ def optional_day(self, key: str) -> date | None:
224
+ return None if self._data[key] is None else self.day(key)
225
+
226
+ def sequence(self, key: str) -> list[Any]:
227
+ value = self._data[key]
228
+ if not isinstance(value, list):
229
+ raise DefinitionError(self.at(key), "must be a list")
230
+ return value
231
+
232
+
233
+ def _whole(value: object, path: str, minimum: int, maximum: int) -> int:
234
+ if isinstance(value, bool) or not isinstance(value, int):
235
+ raise DefinitionError(path, "must be a whole number")
236
+ if not minimum <= value <= maximum:
237
+ raise DefinitionError(path, f"must be {minimum} to {maximum}")
238
+ return value
239
+
240
+
241
+ def _decimal(value: object, path: str) -> Decimal:
242
+ if not isinstance(value, str) or not _DECIMAL.match(value):
243
+ raise DefinitionError(path, 'must be a decimal string such as "0.365"')
244
+ return Decimal(value)
245
+
246
+
247
+ def _day(value: object, path: str) -> date:
248
+ if not isinstance(value, str) or not _DATE.match(value):
249
+ raise DefinitionError(path, "must be a date written YYYY-MM-DD")
250
+ try:
251
+ return date.fromisoformat(value)
252
+ except ValueError as err:
253
+ raise DefinitionError(path, "is not a real date") from err
254
+
255
+
256
+ def _zone(name: str, path: str) -> ZoneInfo:
257
+ try:
258
+ return ZoneInfo(name)
259
+ except (ZoneInfoNotFoundError, ValueError, OSError) as err:
260
+ raise DefinitionError(path, f"{name!r} is not a time zone") from err
261
+
262
+
263
+ def _identity(doc: Fields) -> dict[str, Any]:
264
+ """The fields that say what the tariff is, who sells it and when it applies."""
265
+ revision = doc.whole("revision", 1, 1_000_000)
266
+ effective_from, effective_to = doc.day("effective_from"), doc.optional_day("effective_to")
267
+ if effective_to is not None and effective_to <= effective_from:
268
+ raise DefinitionError("effective_to", "must be after effective_from")
269
+ country = doc.match("country", COUNTRY, "a two letter ISO 3166-1 code such as IE")
270
+ return {
271
+ "id": doc.match("id", SLUG, "lowercase letters, digits and hyphens"),
272
+ "revision": revision,
273
+ "supersedes": _supersedes(doc, revision),
274
+ "name": doc.text("name"),
275
+ "service": doc.choice("service", _SERVICES),
276
+ "customer_class": doc.choice("customer_class", _CUSTOMER_CLASSES),
277
+ "provider": _provider(doc.child("provider")),
278
+ "country": country,
279
+ "region": _region(doc, country),
280
+ "currency": doc.match("currency", _CURRENCY, "a three letter ISO 4217 code such as EUR"),
281
+ "effective_from": effective_from,
282
+ "effective_to": effective_to,
283
+ "source_url": _source_url(doc),
284
+ "last_verified": doc.optional_day("last_verified"),
285
+ }
286
+
287
+
288
+ def _supersedes(doc: Fields, revision: int) -> int | None:
289
+ if doc.raw("supersedes") is None:
290
+ return None
291
+ earlier = doc.whole("supersedes", 1, 1_000_000)
292
+ if earlier >= revision:
293
+ raise DefinitionError("supersedes", "must be an earlier revision than this one")
294
+ return earlier
295
+
296
+
297
+ def _provider(fields: Fields) -> Provider:
298
+ fields.only(required=("id", "name"))
299
+ return Provider(
300
+ fields.match("id", SLUG, "lowercase letters, digits and hyphens"), fields.text("name")
301
+ )
302
+
303
+
304
+ def _region(doc: Fields, country: str) -> str | None:
305
+ if doc.raw("region") is None:
306
+ return None
307
+ region = doc.match("region", _REGION, "an ISO 3166-2 code such as GB-SCT")
308
+ if not region.startswith(f"{country}-"):
309
+ raise DefinitionError("region", f"must belong to the country {country}")
310
+ return region
311
+
312
+
313
+ def _source_url(doc: Fields) -> str | None:
314
+ url = doc.optional_text("source_url")
315
+ if url is not None and not url.startswith(("https://", "http://")):
316
+ raise DefinitionError("source_url", "must start with https:// or http://")
317
+ return url
318
+
319
+
320
+ def _inputs(fields: Fields) -> dict[str, InputSpec]:
321
+ specs: dict[str, InputSpec] = {}
322
+ for name, _ in fields.items():
323
+ if not _NODE_NAME.match(name):
324
+ raise DefinitionError(fields.at(name), "is not a valid input name")
325
+ specs[name] = _input_spec(fields.child(name))
326
+ return specs
327
+
328
+
329
+ def _input_spec(fields: Fields) -> InputSpec:
330
+ fields.only(required=("type", "min", "max", "default"))
331
+ fields.choice("type", ("integer",))
332
+ low = fields.whole("min", -1_000_000, 1_000_000)
333
+ high = fields.whole("max", -1_000_000, 1_000_000)
334
+ if low > high:
335
+ raise DefinitionError(fields.at("min"), "must not be above max")
336
+ return InputSpec(low, high, fields.whole("default", low, high))
337
+
338
+
339
+ def _prices(doc: Fields) -> tuple[ImportPrices, ExportPrices]:
340
+ imported = doc.child("import")
341
+ imported.only(required=("base", "zones"))
342
+ zones = _zones(imported)
343
+ exported = doc.child("export")
344
+ exported.only(required=("base",), optional=("zones",))
345
+ export_zones = _zones(exported) if exported.has("zones") else ()
346
+ return (
347
+ ImportPrices(_base(imported, zones), zones),
348
+ ExportPrices(_base(exported, export_zones), export_zones),
349
+ )
350
+
351
+
352
+ def _zones(prices: Fields) -> tuple[Zone, ...]:
353
+ zones = tuple(_zone_of(item) for item in _zone_fields(prices))
354
+ _unique(zones, prices, "name")
355
+ _unique(zones, prices, "priority")
356
+ return zones
357
+
358
+
359
+ def _base(prices: Fields, zones: tuple[Zone, ...]) -> Band:
360
+ base = _band(prices.child("base"))
361
+ if any(zone.name == base.name for zone in zones):
362
+ raise DefinitionError(prices.at("zones"), f"a zone is named {base.name!r}, like the base")
363
+ return base
364
+
365
+
366
+ def _zone_fields(imported: Fields) -> list[Fields]:
367
+ return [
368
+ Fields(item, f"{imported.at('zones')}[{index}]")
369
+ for index, item in enumerate(imported.sequence("zones"))
370
+ ]
371
+
372
+
373
+ def _unique(zones: tuple[Zone, ...], imported: Fields, attribute: str) -> None:
374
+ seen = [getattr(zone, attribute) for zone in zones]
375
+ if len(set(seen)) != len(seen):
376
+ raise DefinitionError(imported.at("zones"), f"each zone needs its own {attribute}")
377
+
378
+
379
+ def _band(fields: Fields) -> Band:
380
+ fields.only(required=("name", "price"))
381
+ return Band(fields.text("name"), fields.money("price"))
382
+
383
+
384
+ def _zone_of(fields: Fields) -> Zone:
385
+ fields.only(
386
+ required=("name", "priority", "price", "hours"), optional=("days", "months", "holidays")
387
+ )
388
+ start, end = _hours(fields)
389
+ return Zone(
390
+ name=fields.text("name"),
391
+ priority=fields.whole("priority", 1, 1000),
392
+ price=fields.money("price"),
393
+ start=start,
394
+ end=end,
395
+ days=_days(fields),
396
+ months=_months(fields),
397
+ holidays_as_weekend=_holidays(fields),
398
+ )
399
+
400
+
401
+ def _days(fields: Fields) -> frozenset[int]:
402
+ if not fields.has("days"):
403
+ return frozenset()
404
+ names = fields.sequence("days")
405
+ bad = [n for n in names if n not in _WEEKDAYS]
406
+ if bad or len(set(names)) != len(names):
407
+ raise DefinitionError(fields.at("days"), f"must be distinct values from {_WEEKDAYS}")
408
+ return frozenset(_WEEKDAYS.index(n) for n in names)
409
+
410
+
411
+ def _months(fields: Fields) -> frozenset[int]:
412
+ if not fields.has("months"):
413
+ return frozenset()
414
+ path = fields.at("months")
415
+ months = [_whole(m, path, 1, 12) for m in fields.sequence("months")]
416
+ if len(set(months)) != len(months):
417
+ raise DefinitionError(path, "must not repeat a month")
418
+ return frozenset(months)
419
+
420
+
421
+ def _holidays(fields: Fields) -> bool:
422
+ return fields.has("holidays") and fields.choice("holidays", ("weekend", "normal")) == "weekend"
423
+
424
+
425
+ def _bill(fields: Fields, inputs: Mapping[str, InputSpec]) -> tuple[PeriodRule, Node]:
426
+ fields.only(required=("period", "total"), optional=("netting",))
427
+ period = _period(fields.child("period"), inputs)
428
+ return period, _node(fields.child("total"), 1)
429
+
430
+
431
+ def _netting(bill: Fields, import_prices: ImportPrices, export_prices: ExportPrices) -> str:
432
+ """`band` nets export against import by band name, so each export band needs an import band."""
433
+ netting = bill.choice("netting", _NETTING) if bill.has("netting") else "none"
434
+ stray = sorted(_names(export_prices) - _names(import_prices))
435
+ if netting == "band" and stray:
436
+ raise DefinitionError(bill.at("netting"), f"export band {stray[0]!r} has no import band")
437
+ return netting
438
+
439
+
440
+ def _period(fields: Fields, inputs: Mapping[str, InputSpec]) -> PeriodRule:
441
+ fields.only(required=("rule", "start_day"), optional=("months", "start_month"))
442
+ rule = fields.choice("rule", _PERIOD_RULES)
443
+ start_day = _period_value(fields, "start_day", inputs, _START_DAYS)
444
+ months = _period_value(fields, "months", inputs, _MONTHS)
445
+ _check_months(months, fields, inputs)
446
+ start_month = _period_value(fields, "start_month", inputs, _MONTHS)
447
+ return PeriodRule(rule, start_day, months, start_month)
448
+
449
+
450
+ def _period_value(
451
+ fields: Fields, key: str, inputs: Mapping[str, InputSpec], limits: tuple[int, int]
452
+ ) -> PeriodValue:
453
+ """A fixed whole number or `{"input": name}`. A value left out is 1."""
454
+ if not fields.has(key):
455
+ return PeriodValue(1, None)
456
+ value = fields.raw(key)
457
+ if isinstance(value, Mapping):
458
+ return _period_input(fields.child(key), inputs, limits)
459
+ return PeriodValue(_whole(value, fields.at(key), *limits), None)
460
+
461
+
462
+ def _period_input(
463
+ fields: Fields, inputs: Mapping[str, InputSpec], limits: tuple[int, int]
464
+ ) -> PeriodValue:
465
+ fields.only(required=("input",))
466
+ name = fields.text("input")
467
+ spec = inputs.get(name)
468
+ if spec is None:
469
+ raise DefinitionError(fields.at("input"), f"{name!r} is not declared in inputs")
470
+ low, high = limits
471
+ if spec.minimum < low or spec.maximum > high:
472
+ raise DefinitionError(fields.at("input"), f"{name!r} must stay within {low} to {high}")
473
+ return PeriodValue(None, name)
474
+
475
+
476
+ def _check_months(months: PeriodValue, fields: Fields, inputs: Mapping[str, InputSpec]) -> None:
477
+ length = months.fixed if months.input is None else inputs[months.input].default
478
+ if length not in _PERIOD_MONTHS:
479
+ allowed = ", ".join(str(n) for n in _PERIOD_MONTHS)
480
+ raise DefinitionError(fields.at("months"), f"must be one of {allowed}")
481
+
482
+
483
+ # The bill tree. Each parser reads one node kind and refuses any field it does not own.
484
+
485
+
486
+ def _rounding(fields: Fields) -> NodeRounding:
487
+ if not fields.has("round"):
488
+ return NodeRounding.MINOR_UNIT
489
+ return NodeRounding(fields.choice("round", [m.value for m in NodeRounding]))
490
+
491
+
492
+ def _node(fields: Fields, depth: int) -> Node:
493
+ if depth > MAX_TARIFF_TREE_DEPTH:
494
+ raise DefinitionError(fields.path, f"is nested deeper than {MAX_TARIFF_TREE_DEPTH}")
495
+ if not fields.has("kind"):
496
+ raise DefinitionError(fields.at("kind"), "is missing")
497
+ kind = fields.text("kind")
498
+ parser = _NODE_PARSERS.get(kind)
499
+ if parser is None:
500
+ raise DefinitionError(fields.at("kind"), f"{kind!r} is not a known kind")
501
+ return parser(fields, depth)
502
+
503
+
504
+ def _energy_by_band(fields: Fields, depth: int) -> Node:
505
+ fields.only(required=("kind",), optional=("round_bands", "round"))
506
+ round_bands = fields.raw("round_bands") if fields.has("round_bands") else False
507
+ if not isinstance(round_bands, bool):
508
+ raise DefinitionError(fields.at("round_bands"), "must be true or false")
509
+ return EnergyByBand(round_bands, _rounding(fields))
510
+
511
+
512
+ def _tiered_energy(fields: Fields, depth: int) -> Node:
513
+ fields.only(required=("kind", "blocks"), optional=("limits", "bands", "round"))
514
+ limits = fields.choice("limits", _LIMITS) if fields.has("limits") else "period"
515
+ bands = _band_list(fields) if fields.has("bands") else frozenset[str]()
516
+ return TieredEnergy(_blocks(fields.child("blocks")), limits, _rounding(fields), bands)
517
+
518
+
519
+ def _band_list(fields: Fields) -> frozenset[str]:
520
+ names = fields.sequence("bands")
521
+ if not names or any(not isinstance(n, str) or not n for n in names):
522
+ raise DefinitionError(fields.at("bands"), "must be a list of band names")
523
+ if len(set(names)) != len(names):
524
+ raise DefinitionError(fields.at("bands"), "names a band twice")
525
+ return frozenset(names)
526
+
527
+
528
+ def _children_of(node: Node, path: str) -> Iterable[tuple[Node, str]]:
529
+ """Every node under *node*, itself first, with the path to it."""
530
+ yield node, path
531
+ if isinstance(node, Sum):
532
+ for key, child in node.children.items():
533
+ yield from _children_of(child, f"{path}.of.{key}")
534
+ elif isinstance(node, (Adjust, Tax, Bound)):
535
+ yield from _children_of(node.child, f"{path}.of")
536
+
537
+
538
+ def _check_bands(total: Node, known: Collection[str]) -> None:
539
+ """A tier table may name only import bands the tariff has."""
540
+ for node, path in _children_of(total, "bill.total"):
541
+ if isinstance(node, TieredEnergy):
542
+ for name in sorted(node.bands - set(known)):
543
+ raise DefinitionError(f"{path}.bands", f"{name!r} is not an import band")
544
+
545
+
546
+ def demand_windows(total: Node) -> dict[str, Zone]:
547
+ """The demand windows a bill tree uses, by name. A name used twice must mean one window."""
548
+ windows: dict[str, Zone] = {}
549
+ for node, path in _children_of(total, "bill.total"):
550
+ if isinstance(node, Demand):
551
+ if windows.setdefault(node.window, node.when) != node.when:
552
+ raise DefinitionError(f"{path}.window", f"{node.window!r} is two different windows")
553
+ return windows
554
+
555
+
556
+ def _blocks(fields: Fields) -> dict[str, Block]:
557
+ blocks: list[tuple[str, Block]] = []
558
+ for name, _ in fields.items():
559
+ if not _NODE_NAME.match(name):
560
+ raise DefinitionError(fields.at(name), "is not a valid name")
561
+ blocks.append((name, _block(fields.child(name))))
562
+ if not blocks:
563
+ raise DefinitionError(fields.path, "needs at least one block")
564
+ blocks.sort(key=lambda item: item[1].start)
565
+ _check_contiguous(fields, blocks)
566
+ return dict(blocks)
567
+
568
+
569
+ def _block(fields: Fields) -> Block:
570
+ fields.only(required=("from_kwh", "price"), optional=("upto_kwh",))
571
+ start = fields.money("from_kwh")
572
+ end = fields.money("upto_kwh") if fields.has("upto_kwh") else None
573
+ if end is not None and end <= start:
574
+ raise DefinitionError(fields.at("upto_kwh"), "must be above from_kwh")
575
+ return Block(start, end, fields.money("price"))
576
+
577
+
578
+ def _check_contiguous(fields: Fields, blocks: list[tuple[str, Block]]) -> None:
579
+ """Blocks start at 0, each starts where the one before ended, and only the last is open."""
580
+ expected: Decimal | None = Decimal(0)
581
+ for name, block in blocks:
582
+ if expected is None:
583
+ raise DefinitionError(fields.at(name), "comes after a block with no upto_kwh")
584
+ if block.start != expected:
585
+ raise DefinitionError(fields.at(name), f"must start at {expected} kWh")
586
+ expected = block.end
587
+ if expected is not None:
588
+ raise DefinitionError(fields.path, "needs a last block with no upto_kwh")
589
+
590
+
591
+ def _export_credit(fields: Fields, depth: int) -> Node:
592
+ fields.only(required=("kind",), optional=("round",))
593
+ return ExportCredit(_rounding(fields))
594
+
595
+
596
+ def _per_day(fields: Fields, depth: int) -> Node:
597
+ fields.only(required=("kind", "amount"), optional=("round",))
598
+ return PerDay(fields.money("amount"), _rounding(fields))
599
+
600
+
601
+ def _series_energy(fields: Fields, depth: int) -> Node:
602
+ fields.only(required=("kind", "series"), optional=("round",))
603
+ name = fields.text("series")
604
+ if not _NODE_NAME.match(name):
605
+ raise DefinitionError(fields.at("series"), "must be a lower case name")
606
+ return SeriesEnergy(name, _rounding(fields))
607
+
608
+
609
+ def _per_kwh(fields: Fields, depth: int) -> Node:
610
+ fields.only(required=("kind", "amount"), optional=("on", "round"))
611
+ on = fields.choice("on", _FLOWS) if fields.has("on") else "import"
612
+ return PerKwh(fields.signed("amount"), on, _rounding(fields))
613
+
614
+
615
+ def _per_period(fields: Fields, depth: int) -> Node:
616
+ fields.only(required=("kind", "amount", "share"), optional=("per", "round"))
617
+ per = fields.choice("per", _PER) if fields.has("per") else "period"
618
+ return PerPeriod(
619
+ fields.money("amount"), fields.choice("share", _SHARES), _rounding(fields), per
620
+ )
621
+
622
+
623
+ def _demand(fields: Fields, depth: int) -> Node:
624
+ fields.only(
625
+ required=("kind", "window", "price"),
626
+ optional=("per", "hours", "days", "months", "holidays", "round"),
627
+ )
628
+ if not _NODE_NAME.match(fields.text("window")):
629
+ raise DefinitionError(fields.at("window"), "is not a valid name")
630
+ per = fields.choice("per", _PER) if fields.has("per") else "month"
631
+ start, end = _hours(fields) if fields.has("hours") else (time(0, 0), time(0, 0))
632
+ when = Zone(
633
+ fields.text("window"), 1, Decimal(0), start, end,
634
+ _days(fields), _months(fields), _holidays(fields),
635
+ )
636
+ return Demand(fields.text("window"), fields.money("price"), per, when, _rounding(fields))
637
+
638
+
639
+ def _hours(fields: Fields) -> tuple[time, time]:
640
+ match = _HOURS.match(fields.text("hours"))
641
+ if match is None:
642
+ raise DefinitionError(fields.at("hours"), 'must be HH:MM-HH:MM such as "23:00-08:00"')
643
+ start = time(int(match.group(1)), int(match.group(2)))
644
+ end = time(int(match.group(3)), int(match.group(4)))
645
+ if start == end:
646
+ raise DefinitionError(fields.at("hours"), "must not start and end at the same time")
647
+ return start, end
648
+
649
+
650
+ def _bound(kind: str) -> Callable[[Fields, int], Node]:
651
+ def parse(fields: Fields, depth: int) -> Node:
652
+ fields.only(required=("kind", "amount", "of"), optional=("per", "round"))
653
+ per = fields.choice("per", _LIMITS) if fields.has("per") else "period"
654
+ child = _node(fields.child("of"), depth + 1)
655
+ return Bound(kind, fields.money("amount"), per, child, _rounding(fields))
656
+
657
+ return parse
658
+
659
+
660
+ def _adjust(fields: Fields, depth: int) -> Node:
661
+ fields.only(required=("kind", "name", "percent", "of"), optional=("round",))
662
+ percent = fields.signed("percent")
663
+ if percent <= -100:
664
+ raise DefinitionError(fields.at("percent"), "must be above -100")
665
+ child = _node(fields.child("of"), depth + 1)
666
+ return Adjust(fields.text("name"), percent, child, _rounding(fields))
667
+
668
+
669
+ def _tax(fields: Fields, depth: int) -> Node:
670
+ fields.only(required=("kind", "name", "percent", "mode", "of"), optional=("round",))
671
+ percent = fields.money("percent")
672
+ mode = TaxMode(fields.choice("mode", [m.value for m in TaxMode]))
673
+ child = _node(fields.child("of"), depth + 1)
674
+ return Tax(fields.text("name"), percent, mode, child, _rounding(fields))
675
+
676
+
677
+ def _sum(fields: Fields, depth: int) -> Node:
678
+ fields.only(required=("kind", "of"), optional=("round",))
679
+ children = fields.child("of")
680
+ nodes: dict[str, Node] = {}
681
+ for name, _ in children.items():
682
+ if not _NODE_NAME.match(name):
683
+ raise DefinitionError(children.at(name), "is not a valid name")
684
+ nodes[name] = _node(children.child(name), depth + 1)
685
+ if not nodes:
686
+ raise DefinitionError(children.path, "needs at least one child")
687
+ return Sum(nodes, _rounding(fields))
688
+
689
+
690
+ _NODE_PARSERS: dict[str, Callable[[Fields, int], Node]] = {
691
+ "energy_by_band": _energy_by_band,
692
+ "series_energy": _series_energy,
693
+ "tiered_energy": _tiered_energy,
694
+ "export_credit": _export_credit,
695
+ "per_day": _per_day,
696
+ "per_kwh": _per_kwh,
697
+ "demand": _demand,
698
+ "per_period": _per_period,
699
+ "minimum": _bound("minimum"),
700
+ "maximum": _bound("maximum"),
701
+ "adjust": _adjust,
702
+ "tax": _tax,
703
+ "sum": _sum,
704
+ }
705
+
706
+
707
+ def _checks(
708
+ doc: Fields, import_prices: ImportPrices, export_prices: ExportPrices, windows: Collection[str]
709
+ ) -> dict[str, Check]:
710
+ if not doc.has("checks"):
711
+ return {}
712
+ bands = _Bands(_names(import_prices), _names(export_prices), windows)
713
+ fields = doc.child("checks")
714
+ checks: dict[str, Check] = {}
715
+ for name, _ in fields.items():
716
+ if not SLUG.match(name):
717
+ raise DefinitionError(fields.at(name), "is not a valid name")
718
+ checks[name] = _check(fields.child(name), bands)
719
+ return checks
720
+
721
+
722
+ class _Bands(NamedTuple):
723
+ imported: Collection[str]
724
+ exported: Collection[str]
725
+ windows: Collection[str]
726
+
727
+
728
+ def _names(prices: ImportPrices | ExportPrices) -> set[str]:
729
+ return {prices.base.name, *(zone.name for zone in prices.zones)}
730
+
731
+
732
+ def _check(fields: Fields, bands: _Bands) -> Check:
733
+ fields.only(
734
+ required=("period_days", "import_kwh_by_band", "export_kwh", "expected_total"),
735
+ optional=("peak_kw",),
736
+ )
737
+ # A plain export figure is paid at the base export price. An object names the bands.
738
+ export: Decimal | dict[str, Decimal]
739
+ if isinstance(fields.raw("export_kwh"), Mapping):
740
+ export = _kwh_by_band(fields.child("export_kwh"), bands.exported, "an export band")
741
+ else:
742
+ export = fields.money("export_kwh")
743
+ imported = _kwh_by_band(fields.child("import_kwh_by_band"), bands.imported, "a band")
744
+ return Check(
745
+ period_days=fields.whole("period_days", 1, 366),
746
+ import_kwh_by_band=imported,
747
+ export_kwh=export,
748
+ expected_total=fields.signed("expected_total"),
749
+ peak_kw=_peaks(fields, bands),
750
+ )
751
+
752
+
753
+ def _peaks(fields: Fields, bands: _Bands) -> dict[str, Decimal]:
754
+ if not fields.has("peak_kw"):
755
+ return {}
756
+ return _kwh_by_band(fields.child("peak_kw"), bands.windows, "a demand window")
757
+
758
+
759
+ def _kwh_by_band(by_band: Fields, bands: Collection[str], what: str) -> dict[str, Decimal]:
760
+ kwh: dict[str, Decimal] = {}
761
+ for band, _ in by_band.items():
762
+ if band not in bands:
763
+ raise DefinitionError(by_band.at(band), f"is not {what} of this tariff")
764
+ kwh[band] = by_band.money(band)
765
+ return kwh