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,309 @@
1
+ """index.py: the tariff index, and reading a definition through it.
2
+
3
+ The index is a separate JSON file that lists the tariffs on offer, grouped by country and then
4
+ provider, so a client can browse, choose or ask for the latest without downloading a definition.
5
+ It holds no prices. Each revision of a tariff has its dates, the path of its file and a checksum of
6
+ that file. The checksum is computed here over the file's canonical form (keys sorted, no spaces),
7
+ never written by hand, and it is kept out of the definition because a file cannot hold its own.
8
+
9
+ `build_index` makes the index from a set of definition files and refuses a set that disagrees with
10
+ itself: a file in the wrong place, revisions of one tariff that overlap, or a `supersedes` that
11
+ names no earlier revision. `parse_index` reads one back. A `TariffSource` hands over the index and
12
+ the files, whether they come from a folder, a store or the options of this install, and
13
+ `load_revision` checks a file against its entry before it is trusted. A local definition has no
14
+ checksum until a store exists, so an entry without one is not checked.
15
+
16
+ Nothing here reads a disk or a network. The source does that.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import re
24
+ from collections.abc import Mapping
25
+ from dataclasses import dataclass
26
+ from datetime import date
27
+ from typing import Any, Protocol
28
+
29
+ from .definition import DefinitionError, TariffDefinition
30
+ from .definition_parse import COUNTRY, SLUG, Fields, load_json, parse_definition
31
+
32
+ INDEX_SCHEMA_VERSION = 1
33
+
34
+ _CHECKSUM = re.compile(r"^sha256:[0-9a-f]{64}$")
35
+ _REVISION_KEY = re.compile(r"^[1-9][0-9]{0,5}$")
36
+
37
+
38
+ class ChecksumMismatch(ValueError):
39
+ """A file does not match the checksum its index entry holds."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class RevisionEntry:
44
+ revision: int
45
+ effective_from: date # included
46
+ effective_to: date | None # excluded, None while open ended
47
+ path: str
48
+ checksum: str | None # "sha256:<hex>", None for a local definition
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class TariffEntry:
53
+ id: str
54
+ name: str
55
+ region: str | None
56
+ currency: str
57
+ complete: bool
58
+ latest: int | None # the revision in force on the day the index was generated
59
+ revisions: Mapping[int, RevisionEntry]
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class ProviderEntry:
64
+ id: str
65
+ name: str
66
+ tariffs: Mapping[str, TariffEntry]
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class TariffIndex:
71
+ generated: date
72
+ countries: Mapping[str, Mapping[str, ProviderEntry]] # country -> provider id -> entry
73
+
74
+
75
+ class TariffSource(Protocol):
76
+ """Where an index and its definition files come from."""
77
+
78
+ def read_index(self) -> str: ...
79
+
80
+ def read_file(self, path: str) -> str: ...
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class StaticSource:
85
+ """A source held in memory, for tests and for definitions made in this install."""
86
+
87
+ index_text: str
88
+ files: Mapping[str, str]
89
+
90
+ def read_index(self) -> str:
91
+ return self.index_text
92
+
93
+ def read_file(self, path: str) -> str:
94
+ try:
95
+ return self.files[path]
96
+ except KeyError:
97
+ raise DefinitionError(path, "is not in the source") from None
98
+
99
+
100
+ def canonical_json(text: str) -> str:
101
+ """The document with keys sorted and no spaces, the form a checksum is computed over."""
102
+ return json.dumps(load_json(text), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
103
+
104
+
105
+ def checksum_of(text: str) -> str:
106
+ """The checksum of a definition file, such as `sha256:ab12...`."""
107
+ return "sha256:" + hashlib.sha256(canonical_json(text).encode()).hexdigest()
108
+
109
+
110
+ def expected_path(definition: TariffDefinition) -> str:
111
+ """Where the file for *definition* sits: country/provider/tariff/revision.json."""
112
+ parts = (definition.country.lower(), definition.provider.id, definition.id)
113
+ return "/".join((*parts, f"{definition.revision}.json"))
114
+
115
+
116
+ # Building
117
+
118
+
119
+ def build_index(files: Mapping[str, str], generated: date) -> dict[str, Any]:
120
+ """The index for *files*, a mapping of path to definition text, as a JSON-ready dictionary.
121
+
122
+ Raises DefinitionError naming the path of the file that disagrees.
123
+ """
124
+ groups: dict[tuple[str, str, str], dict[int, tuple[str, str, TariffDefinition]]] = {}
125
+ for path, text in sorted(files.items()):
126
+ try:
127
+ definition = parse_definition(load_json(text))
128
+ except DefinitionError as err:
129
+ raise DefinitionError(path, str(err)) from err
130
+ if path != expected_path(definition):
131
+ raise DefinitionError(path, f"belongs at {expected_path(definition)}")
132
+ key = (definition.country, definition.provider.id, definition.id)
133
+ groups.setdefault(key, {})[definition.revision] = (path, text, definition)
134
+ countries: dict[str, Any] = {}
135
+ for (country, provider_id, tariff_id), revisions in sorted(groups.items()):
136
+ _check_revisions(revisions)
137
+ top = revisions[max(revisions)][2]
138
+ provider = countries.setdefault(country, {"providers": {}})["providers"].setdefault(
139
+ provider_id, {"name": top.provider.name, "tariffs": {}}
140
+ )
141
+ provider["tariffs"][tariff_id] = _tariff_entry(revisions, top, generated)
142
+ return {
143
+ "schema": INDEX_SCHEMA_VERSION,
144
+ "generated": generated.isoformat(),
145
+ "countries": countries,
146
+ }
147
+
148
+
149
+ def _check_revisions(revisions: Mapping[int, tuple[str, str, TariffDefinition]]) -> None:
150
+ ordered = sorted((d.effective_from, d.effective_to, path) for path, _, d in revisions.values())
151
+ for (_, end, path), (start, _, later) in zip(ordered, ordered[1:], strict=False):
152
+ if end is None or end > start:
153
+ raise DefinitionError(later, f"overlaps the dates of {path}")
154
+ for path, _, definition in revisions.values():
155
+ earlier = definition.supersedes
156
+ if earlier is not None and earlier not in revisions:
157
+ raise DefinitionError(path, f"supersedes revision {earlier}, which is not here")
158
+
159
+
160
+ def _tariff_entry(
161
+ revisions: Mapping[int, tuple[str, str, TariffDefinition]],
162
+ top: TariffDefinition,
163
+ generated: date,
164
+ ) -> dict[str, Any]:
165
+ in_force = [
166
+ number
167
+ for number, (_, _, d) in revisions.items()
168
+ if _in_force(d.effective_from, d.effective_to, generated)
169
+ ]
170
+ return {
171
+ "name": top.name,
172
+ "region": top.region,
173
+ "currency": top.currency,
174
+ "completeness": "complete" if top.complete else "partial",
175
+ "latest": max(in_force) if in_force else None,
176
+ "revisions": {
177
+ str(number): {
178
+ "effective_from": definition.effective_from.isoformat(),
179
+ "effective_to": _iso(definition.effective_to),
180
+ "path": path,
181
+ "checksum": checksum_of(text),
182
+ }
183
+ for number, (path, text, definition) in sorted(revisions.items(), reverse=True)
184
+ },
185
+ }
186
+
187
+
188
+ def _iso(day: date | None) -> str | None:
189
+ return None if day is None else day.isoformat()
190
+
191
+
192
+ def _in_force(start: date, end: date | None, on: date) -> bool:
193
+ return start <= on and (end is None or on < end)
194
+
195
+
196
+ # Reading
197
+
198
+
199
+ def parse_index(text: str) -> TariffIndex:
200
+ """Read index text. Raises DefinitionError for anything not valid."""
201
+ doc = Fields(load_json(text), "")
202
+ doc.only(required=("schema", "generated", "countries"))
203
+ doc.whole("schema", INDEX_SCHEMA_VERSION, INDEX_SCHEMA_VERSION)
204
+ countries = doc.child("countries")
205
+ parsed: dict[str, Mapping[str, ProviderEntry]] = {}
206
+ for code, _ in countries.items():
207
+ if not COUNTRY.match(code):
208
+ raise DefinitionError(countries.at(code), "must be a two letter country code")
209
+ parsed[code] = _providers(countries.child(code))
210
+ return TariffIndex(doc.day("generated"), parsed)
211
+
212
+
213
+ def _providers(country: Fields) -> dict[str, ProviderEntry]:
214
+ country.only(required=("providers",))
215
+ providers = country.child("providers")
216
+ found: dict[str, ProviderEntry] = {}
217
+ for provider_id, _ in providers.items():
218
+ _slug(providers, provider_id)
219
+ fields = providers.child(provider_id)
220
+ fields.only(required=("name", "tariffs"))
221
+ tariffs = fields.child("tariffs")
222
+ found[provider_id] = ProviderEntry(
223
+ provider_id,
224
+ fields.text("name"),
225
+ {name: _tariff(tariffs, name) for name, _ in tariffs.items()},
226
+ )
227
+ return found
228
+
229
+
230
+ def _tariff(parent: Fields, tariff_id: str) -> TariffEntry:
231
+ _slug(parent, tariff_id)
232
+ fields = parent.child(tariff_id)
233
+ fields.only(
234
+ required=("name", "region", "currency", "completeness", "latest", "revisions")
235
+ )
236
+ revisions = fields.child("revisions")
237
+ parsed = [_revision(revisions, key) for key, _ in revisions.items()]
238
+ entries = {entry.revision: entry for entry in parsed}
239
+ if not entries:
240
+ raise DefinitionError(revisions.path, "needs at least one revision")
241
+ latest = None if fields.raw("latest") is None else fields.whole("latest", 1, 1_000_000)
242
+ if latest is not None and latest not in entries:
243
+ raise DefinitionError(fields.at("latest"), "is not one of the revisions")
244
+ return TariffEntry(
245
+ tariff_id,
246
+ fields.text("name"),
247
+ fields.optional_text("region"),
248
+ fields.text("currency"),
249
+ fields.choice("completeness", ("complete", "partial")) == "complete",
250
+ latest,
251
+ entries,
252
+ )
253
+
254
+
255
+ def _revision(parent: Fields, key: str) -> RevisionEntry:
256
+ if not _REVISION_KEY.match(key):
257
+ raise DefinitionError(parent.at(key), "must be a revision number")
258
+ fields = parent.child(key)
259
+ fields.only(required=("effective_from", "effective_to", "path", "checksum"))
260
+ start, end = fields.day("effective_from"), fields.optional_day("effective_to")
261
+ if end is not None and end <= start:
262
+ raise DefinitionError(fields.at("effective_to"), "must be after effective_from")
263
+ checksum = fields.optional_text("checksum")
264
+ if checksum is not None and not _CHECKSUM.match(checksum):
265
+ raise DefinitionError(fields.at("checksum"), "must be sha256: and 64 hex digits")
266
+ return RevisionEntry(int(key), start, end, fields.text("path"), checksum)
267
+
268
+
269
+ def _slug(parent: Fields, name: str) -> None:
270
+ if not SLUG.match(name):
271
+ raise DefinitionError(parent.at(name), "must be lowercase letters, digits and hyphens")
272
+
273
+
274
+ # Choosing
275
+
276
+
277
+ def find_tariff(index: TariffIndex, country: str, provider_id: str, tariff_id: str) -> TariffEntry:
278
+ """The tariff at that place in the index. Raises LookupError when there is none."""
279
+ try:
280
+ return index.countries[country][provider_id].tariffs[tariff_id]
281
+ except KeyError:
282
+ raise LookupError(f"no tariff {country}/{provider_id}/{tariff_id} in the index") from None
283
+
284
+
285
+ def revision_in_force(tariff: TariffEntry, on: date) -> RevisionEntry | None:
286
+ """The revision that prices *on*, or None. The dates never overlap, so there is at most one."""
287
+ for entry in tariff.revisions.values():
288
+ if _in_force(entry.effective_from, entry.effective_to, on):
289
+ return entry
290
+ return None
291
+
292
+
293
+ def load_revision(source: TariffSource, entry: RevisionEntry) -> TariffDefinition:
294
+ """Read the file for *entry*, check it, and return the definition.
295
+
296
+ Raises ChecksumMismatch when the file is not the one the index describes, and DefinitionError
297
+ when it is not a valid definition or disagrees with the entry's revision or dates.
298
+ """
299
+ text = source.read_file(entry.path)
300
+ if entry.checksum is not None and checksum_of(text) != entry.checksum:
301
+ raise ChecksumMismatch(f"{entry.path} does not match its checksum")
302
+ definition = parse_definition(load_json(text))
303
+ if (definition.revision, definition.effective_from, definition.effective_to) != (
304
+ entry.revision,
305
+ entry.effective_from,
306
+ entry.effective_to,
307
+ ):
308
+ raise DefinitionError(entry.path, "does not agree with its index entry")
309
+ return definition
@@ -0,0 +1,136 @@
1
+ """period_bill.py: the bill so far for the current bill period, priced from the slot history.
2
+
3
+ slots -> bands.import_by_band, export_by_band -> engine.price_bill -> bill
4
+
5
+ The history holds energy and no price, so any tariff definition can be priced over the same days
6
+ with the same engine and the same rounding. The bill period comes from the definition's own start
7
+ day, length in months and start month, or from the ones the caller passes, so a re-priced bill
8
+ can follow the active tariff's dates. The bill covers the days from the period start to the day
9
+ given, that day included.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import calendar
15
+ from collections.abc import Callable, Mapping
16
+ from dataclasses import dataclass
17
+ from datetime import date
18
+ from decimal import Decimal
19
+
20
+ from .bands import export_by_band, import_by_band, no_holidays
21
+ from .definition import TariffDefinition
22
+ from .engine import BillInputs, PricedBill, price_bill
23
+ from .slot_history import SlotHistory
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class PeriodRules:
28
+ """What the caller decides about the period, beyond the definition itself."""
29
+
30
+ # Follow another tariff's bill dates. None uses the definition's own.
31
+ start_day: int | None = None
32
+ months: int | None = None # calendar months in one bill period
33
+ start_month: int | None = None # a month a period starts in
34
+ is_holiday: Callable[[date], bool] = no_holidays
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class PeriodBill:
39
+ """A bill period priced from the history."""
40
+
41
+ first_day: date # first day of the bill period
42
+ next_first_day: date # first day of the next period
43
+ through: date # last day priced, included
44
+ days: int # days priced, from first_day to through
45
+ period_days: int # days in the whole bill period
46
+ data_from: date | None # first day in the history inside the period, None when none
47
+ days_recorded: int # days inside the period the history holds
48
+ import_kwh_by_band: Mapping[str, Decimal] # the import the bill priced, by band name
49
+ coverage: float # share of the priced days' time that was observed, 0 to 1
50
+ priced: PricedBill
51
+
52
+
53
+ def start_day_of(definition: TariffDefinition) -> int:
54
+ """The day of the month the definition's bill period starts."""
55
+ return definition.period_value(definition.period.start_day)
56
+
57
+
58
+ def months_of(definition: TariffDefinition) -> int:
59
+ """The calendar months in one of the definition's bill periods."""
60
+ return definition.period_value(definition.period.months)
61
+
62
+
63
+ def start_month_of(definition: TariffDefinition) -> int:
64
+ """A month, 1 to 12, in which one of the definition's bill periods starts."""
65
+ return definition.period_value(definition.period.start_month)
66
+
67
+
68
+ def bill_period_bounds(
69
+ start_day: int, on: date, months: int = 1, start_month: int = 1
70
+ ) -> tuple[date, date]:
71
+ """The first day of the bill period holding *on*, and the first day of the next period.
72
+
73
+ A period is *months* calendar months long, and one starts in *start_month*. A start day past
74
+ the end of a short month falls on that month's last day.
75
+ """
76
+ if months < 1 or 12 % months:
77
+ raise ValueError("months must divide a year: 1, 2, 3, 4, 6 or 12")
78
+ index = on.year * 12 + on.month - 1 # months counted from year 0
79
+ first = index - (index - (start_month - 1)) % months
80
+ if on < _start_in_month(start_day, first):
81
+ first -= months
82
+ return _start_in_month(start_day, first), _start_in_month(start_day, first + months)
83
+
84
+
85
+ def price_period(
86
+ history: SlotHistory,
87
+ definition: TariffDefinition,
88
+ through: date,
89
+ rules: PeriodRules | None = None,
90
+ ) -> PeriodBill:
91
+ """The bill so far for the period holding *through*, priced under *definition*.
92
+
93
+ *rules* overrides the definition's own start day, length in months and start month. Days with
94
+ no history count as days of the bill with no import, so *coverage* tells a quiet day from a
95
+ missing one.
96
+ """
97
+ rules = rules or PeriodRules()
98
+ months = rules.months or months_of(definition)
99
+ first, following = bill_period_bounds(
100
+ rules.start_day or start_day_of(definition),
101
+ through,
102
+ months,
103
+ rules.start_month or start_month_of(definition),
104
+ )
105
+ days = history.between(first, through)
106
+ bands = import_by_band(days, definition, rules.is_holiday)
107
+ # A flat export stays one total, so its credit is unchanged to the last decimal place.
108
+ export: Decimal | dict[str, Decimal]
109
+ if definition.export_prices.zones:
110
+ export = export_by_band(days, definition, rules.is_holiday)
111
+ else:
112
+ export = _decimal(sum(day.total("export") for day in days))
113
+ length = (through - first).days + 1
114
+ inputs = BillInputs(length, (following - first).days, bands, export, months)
115
+ return PeriodBill(
116
+ first_day=first,
117
+ next_first_day=following,
118
+ through=through,
119
+ days=length,
120
+ period_days=(following - first).days,
121
+ data_from=days[0].day if days else None,
122
+ days_recorded=len(days),
123
+ import_kwh_by_band=bands,
124
+ coverage=sum(day.coverage for day in days) / length,
125
+ priced=price_bill(definition, inputs),
126
+ )
127
+
128
+
129
+ def _start_in_month(start_day: int, index: int) -> date:
130
+ year, month = index // 12, index % 12 + 1
131
+ last = calendar.monthrange(year, month)[1]
132
+ return date(year, month, max(1, min(start_day, last)))
133
+
134
+
135
+ def _decimal(value: float) -> Decimal:
136
+ return Decimal(repr(round(value, 6)))
@@ -0,0 +1,34 @@
1
+ """periods.py: a single named rate window."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, time
7
+
8
+
9
+ @dataclass
10
+ class RatePeriod:
11
+ """
12
+ A single timed tariff rate period.
13
+
14
+ Has explicit start and end times; is_active() returns True within that window.
15
+ Handles overnight spans where end < start (e.g. Night 23:00–08:00).
16
+
17
+ The base / daytime rate is NOT a RatePeriod — it is a separate scalar field
18
+ on TariffConfig (base_rate / base_rate_name). This keeps RatePeriod simple
19
+ and the config form clear: one field for the default rate, a list for overrides.
20
+ """
21
+
22
+ name: str
23
+ rate: float # €/kWh
24
+ start: time
25
+ end: time
26
+
27
+ def is_active(self, dt: datetime) -> bool:
28
+ """Return True if this period is active at the given datetime."""
29
+ current = dt.time().replace(second=0, microsecond=0)
30
+ if self.start <= self.end:
31
+ # Normal period e.g. 08:00 – 23:00
32
+ return self.start <= current < self.end
33
+ # Overnight period e.g. 23:00 – 08:00
34
+ return current >= self.start or current < self.end
@@ -0,0 +1,142 @@
1
+ """price_curve.py: what one more kWh costs in each band, and the price series over a time range.
2
+
3
+ The price of a band is not read from the document. It is the bill engine's own answer: the bill
4
+ with a large extra amount in that band, less the bill without it, divided by that amount. So a
5
+ levy, a discount, VAT before or after the discount, and any later charge shape the engine learns
6
+ are in the price without a second copy of the rules here. A charge that does not depend on the
7
+ energy (a standing charge, a monthly levy) cancels out.
8
+
9
+ The series is cut at the engine's slot length. A slot takes the band in force at its start, on the
10
+ clock of the definition's time zone, as `bands.py` does. Slots are real elapsed time, so a clock
11
+ change gives the right number of them. Neighbouring slots with the same band and prices are
12
+ joined, so a fixed-band tariff gives a few long slots.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable, Mapping
18
+ from dataclasses import dataclass
19
+ from datetime import date, datetime, timedelta, timezone
20
+ from decimal import Decimal
21
+
22
+ from .bands import band_at, export_band_at, no_holidays
23
+ from .defaults import SLOT_SECONDS
24
+ from .definition import ExportPrices, ImportPrices, TariffDefinition
25
+ from .engine import BillInputs, price_bill
26
+ from .price_series import series_names
27
+
28
+ # Large, so the cent rounding of a line moves the price by less than a millionth.
29
+ _STEP = Decimal(1_000_000)
30
+ _DAYS = 30
31
+ _SLOT = timedelta(seconds=SLOT_SECONDS)
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class MarginalPrices:
36
+ """What one more kWh costs, or earns, in each band, with every tax and discount applied."""
37
+
38
+ import_prices: Mapping[str, Decimal]
39
+ export_prices: Mapping[str, Decimal]
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class PriceSlot:
44
+ """A stretch of time with one import price and one export price, per kWh."""
45
+
46
+ start: datetime
47
+ end: datetime
48
+ import_band: str
49
+ export_band: str
50
+ import_price: Decimal
51
+ export_price: Decimal
52
+ # "fixed" for a band price in the document, "published" for a price read from a feed
53
+ source: str = "fixed"
54
+
55
+
56
+ def marginal_prices(definition: TariffDefinition) -> MarginalPrices:
57
+ """The price of one more kWh in every import band and every export band."""
58
+ none = _bill(definition, {}, Decimal(0))
59
+ imports = {
60
+ name: (_bill(definition, {name: _STEP}, Decimal(0)) - none) / _STEP
61
+ for name in _band_names(definition.import_prices)
62
+ }
63
+ exports = {
64
+ name: (none - _bill(definition, {}, _export(definition, name))) / _STEP
65
+ for name in _band_names(definition.export_prices)
66
+ }
67
+ return MarginalPrices(imports, exports)
68
+
69
+
70
+ def price_curve(
71
+ definition: TariffDefinition,
72
+ start: datetime,
73
+ end: datetime,
74
+ is_holiday: Callable[[date], bool] = no_holidays,
75
+ ) -> tuple[PriceSlot, ...]:
76
+ """The prices from *start* to *end* (aware times), joined where they do not change.
77
+
78
+ The first slot begins at *start* and the last ends at *end*. Between them slots begin on the
79
+ engine's slot grid, counted from the Unix epoch.
80
+ """
81
+ if start.tzinfo is None or end.tzinfo is None:
82
+ raise ValueError("start and end must have a time zone")
83
+ if end <= start:
84
+ raise ValueError("end must be after start")
85
+ marginal = marginal_prices(definition)
86
+ slots: list[PriceSlot] = []
87
+ cursor = start
88
+ while cursor < end:
89
+ following = min(_next_edge(cursor), end)
90
+ bands = (
91
+ band_at(definition, cursor, is_holiday),
92
+ export_band_at(definition, cursor, is_holiday),
93
+ )
94
+ slot = _slot(cursor, following, bands, marginal)
95
+ if slots and _same(slots[-1], slot):
96
+ slot = _joined(slots.pop(), slot)
97
+ slots.append(slot)
98
+ cursor = following
99
+ return tuple(slots)
100
+
101
+
102
+ def _bill(
103
+ definition: TariffDefinition,
104
+ imported: Mapping[str, Decimal],
105
+ exported: Decimal | Mapping[str, Decimal],
106
+ ) -> Decimal:
107
+ zero = {name: Decimal(0) for name in series_names(definition)}
108
+ inputs = BillInputs(_DAYS, _DAYS, imported, exported, import_cost_by_series=zero)
109
+ return price_bill(definition, inputs).total
110
+
111
+
112
+ def _export(definition: TariffDefinition, name: str) -> Decimal | Mapping[str, Decimal]:
113
+ return {name: _STEP} if definition.export_prices.zones else _STEP
114
+
115
+
116
+ def _band_names(prices: ImportPrices | ExportPrices) -> list[str]:
117
+ return [prices.base.name, *dict.fromkeys(zone.name for zone in prices.zones)]
118
+
119
+
120
+ def _next_edge(moment: datetime) -> datetime:
121
+ seconds = int(moment.timestamp()) // SLOT_SECONDS * SLOT_SECONDS + SLOT_SECONDS
122
+ return datetime.fromtimestamp(seconds, tz=timezone.utc).astimezone(moment.tzinfo)
123
+
124
+
125
+ def _slot(
126
+ start: datetime, end: datetime, bands: tuple[str, str], marginal: MarginalPrices
127
+ ) -> PriceSlot:
128
+ in_band, out_band = bands
129
+ return PriceSlot(
130
+ start, end, in_band, out_band,
131
+ marginal.import_prices[in_band], marginal.export_prices[out_band],
132
+ )
133
+
134
+
135
+ def _same(left: PriceSlot, right: PriceSlot) -> bool:
136
+ return (left.end == right.start and left.import_band == right.import_band
137
+ and left.export_band == right.export_band)
138
+
139
+
140
+ def _joined(left: PriceSlot, right: PriceSlot) -> PriceSlot:
141
+ return PriceSlot(left.start, right.end, left.import_band, left.export_band,
142
+ left.import_price, left.export_price, left.source)