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,118 @@
1
+ """savings.py: what solar and a battery saved over some days, from the half-hourly history.
2
+
3
+ The saving is what the house load would have cost bought from the grid at the rate in force,
4
+ less what was paid. Both sides are priced as a bill under the same tariff, so the discount,
5
+ VAT and levies apply to each, and the standing charge cancels. Export credit is on the paid
6
+ side only: it is money the system earned.
7
+
8
+ Two corrections keep the figure fair, as in stored_energy.py. Energy bought to fill the
9
+ battery is paid for today but earns its keep when the battery gives it back, so the change
10
+ in stored energy is valued and added. Battery wear is a cost of the saving, so it is taken off.
11
+
12
+ With solar and no battery there is no stored energy, with a battery and no solar there is no
13
+ solar use. The same sum covers both. Without a house load reading nothing can be compared, so
14
+ the call is refused.
15
+
16
+ Pure Python, no Home Assistant imports.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Sequence
22
+ from dataclasses import dataclass
23
+
24
+ from .billing import BillBreakdown, money
25
+ from .config import TariffConfig
26
+ from .reprice import BillPeriod, Rounding, import_rates, reprice
27
+ from .slots import SlotDay
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Battery:
32
+ """What the battery costs and holds. Leave it out for a house with no battery."""
33
+
34
+ capacity_kwh: float
35
+ soc_before_pct: float | None = None # charge when the first day began, None if unknown
36
+ wear_per_kwh: float = 0.0 # cost of each kWh discharged
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Savings:
41
+ """The saving over the days, with the two bills it is the difference of."""
42
+
43
+ without_system: BillBreakdown # the whole house load bought from the grid
44
+ actual: BillBreakdown
45
+ bill_difference: float # without_system.total less actual.total
46
+ stored_energy_value: float # value of the change in stored energy, negative for a fall
47
+ battery_wear: float
48
+ total: float # bill_difference + stored_energy_value - battery_wear
49
+ coverage: float # share of the days' time that was observed, 0 to 1
50
+
51
+
52
+ def savings(
53
+ days: Sequence[SlotDay],
54
+ tariff: TariffConfig,
55
+ period: BillPeriod,
56
+ battery: Battery | None = None,
57
+ ) -> Savings:
58
+ """The saving over *days*, the days of one bill or any part of it, in any order.
59
+
60
+ Raises ValueError when the days hold no house load.
61
+ """
62
+ if not any(day.total("house") for day in days):
63
+ raise ValueError("no house load was recorded, so there is nothing to compare")
64
+ actual = reprice(days, tariff, period, Rounding.TOTAL)
65
+ baseline = reprice([all_from_grid(day) for day in days], tariff, period, Rounding.TOTAL)
66
+ difference = money(baseline.bill.total - actual.bill.total)
67
+ stored = _stored_value(days, tariff, battery)
68
+ wear = money(sum(day.total("battery_discharge") for day in days) * _wear(battery))
69
+ return Savings(
70
+ baseline.bill,
71
+ actual.bill,
72
+ difference,
73
+ stored,
74
+ wear,
75
+ money(difference + stored - wear),
76
+ actual.coverage,
77
+ )
78
+
79
+
80
+ def _wear(battery: Battery | None) -> float:
81
+ return battery.wear_per_kwh if battery else 0.0
82
+
83
+
84
+ def all_from_grid(day: SlotDay) -> SlotDay:
85
+ """The day as it would have been with no solar and no battery."""
86
+ return SlotDay(
87
+ day.day,
88
+ day.tz,
89
+ flows={"import": list(day.loads["house"])},
90
+ loads=dict(day.loads),
91
+ seconds=list(day.seconds),
92
+ )
93
+
94
+
95
+ def _stored_value(days: Sequence[SlotDay], tariff: TariffConfig, battery: Battery | None) -> float:
96
+ if battery is None or battery.capacity_kwh <= 0 or battery.soc_before_pct is None:
97
+ return 0.0
98
+ ordered = sorted(days, key=lambda d: d.day)
99
+ closing = next(
100
+ (v for day in reversed(ordered) for v in reversed(day.soc_pct) if v is not None), None
101
+ )
102
+ if closing is None:
103
+ return 0.0
104
+ change_kwh = (closing - battery.soc_before_pct) / 100 * battery.capacity_kwh
105
+ return money(change_kwh * _stored_rate(days, tariff))
106
+
107
+
108
+ def _stored_rate(days: Sequence[SlotDay], tariff: TariffConfig) -> float:
109
+ """Average cost of the grid energy that went into the battery, else the cheapest rate."""
110
+ kwh = cost = 0.0
111
+ for day in days:
112
+ charges = day.flows["grid_to_battery"]
113
+ for charged, rate in zip(charges, import_rates(day, tariff), strict=True):
114
+ kwh += charged
115
+ cost += charged * tariff.effective_import_rate(rate)
116
+ if kwh > 0:
117
+ return cost / kwh
118
+ return tariff.effective_import_rate(tariff.get_cheapest_rate().rate)
@@ -0,0 +1,128 @@
1
+ """slot_history.py: the slot days kept, with retention, midnight splitting and storage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from datetime import date, datetime, timedelta, timezone, tzinfo
7
+ from typing import Any
8
+
9
+ from ..timeutil import elapsed_seconds
10
+ from .defaults import SLOT_MAX_INTERVAL_SECONDS, SLOT_RETENTION_DAYS
11
+ from .slots import SlotDay, SlotEnergy, StoredSlotDay
12
+
13
+
14
+ class SlotHistory:
15
+ """Slot days by date, oldest dropped after the retention period."""
16
+
17
+ def __init__(self, tz: tzinfo, retention_days: int = SLOT_RETENTION_DAYS) -> None:
18
+ self._tz = tz
19
+ self._retention = retention_days
20
+ self._days: dict[date, SlotDay] = {}
21
+ # Stored days that could not be read the last time the history was restored.
22
+ self.skipped = 0
23
+
24
+ @property
25
+ def tz(self) -> tzinfo:
26
+ return self._tz
27
+
28
+ @classmethod
29
+ def from_days(
30
+ cls, tz: tzinfo, days: Iterable[SlotDay], retention_days: int = SLOT_RETENTION_DAYS
31
+ ) -> SlotHistory:
32
+ """A history holding exactly *days*, as they are, without rounding them to storage."""
33
+ history = cls(tz, retention_days)
34
+ history._days = {day.day: day for day in days}
35
+ return history
36
+
37
+ def record(self, energy: SlotEnergy, start: datetime, end: datetime) -> bool:
38
+ """Book *energy* used between start and end. False when the interval is a gap or empty.
39
+
40
+ An interval that crosses midnight is split between the two days by time. Nothing is
41
+ booked for a gap, and the slots it spans keep their old observed seconds, so coverage
42
+ shows the hole.
43
+ """
44
+ total = elapsed_seconds(start, end)
45
+ if not 0 < total <= SLOT_MAX_INTERVAL_SECONDS:
46
+ return False
47
+ # Two datetimes in one zone compare by their clock fields and ignore which side of a clock
48
+ # change they are on, so an interval in the repeated hour would look empty. UTC compares
49
+ # by real time.
50
+ if start.tzinfo is not None and end.tzinfo is not None:
51
+ start, end = start.astimezone(timezone.utc), end.astimezone(timezone.utc)
52
+ cursor = start
53
+ while cursor < end:
54
+ day = self._day_for(cursor.astimezone(self._tz).date())
55
+ piece_end = min(end, day.end)
56
+ share = elapsed_seconds(cursor, piece_end) / total
57
+ day.add(energy.scaled(share), cursor, piece_end)
58
+ cursor = piece_end
59
+ self._prune(end.astimezone(self._tz).date())
60
+ return True
61
+
62
+ def record_soc(self, moment: datetime, percent: float) -> None:
63
+ """Note the battery state of charge in the slot holding *moment*."""
64
+ self._day_for(moment.astimezone(self._tz).date()).set_soc(moment, percent)
65
+
66
+ def note_counters(self, day: date, readings: Mapping[str, float]) -> None:
67
+ """Keep the inverter's day totals for *day* as last read."""
68
+ self._day_for(day).note_counters(readings)
69
+
70
+ def get(self, day: date) -> SlotDay | None:
71
+ return self._days.get(day)
72
+
73
+ def between(self, first: date, last: date) -> list[SlotDay]:
74
+ """The days recorded from *first* to *last* inclusive, oldest first."""
75
+ return [self._days[d] for d in sorted(self._days) if first <= d <= last]
76
+
77
+ def summary(self, days: int = 7) -> list[dict[str, Any]]:
78
+ """The newest days, newest first, for diagnostics.
79
+
80
+ Each row has the day's coverage and, for each series that has data or an inverter
81
+ total, the slots' total, the inverter's own day total and the gap between them (kWh).
82
+ """
83
+ newest = sorted(self._days, reverse=True)[:days]
84
+ return [_day_summary(self._days[d]) for d in newest]
85
+
86
+ def to_storage(self) -> list[StoredSlotDay]:
87
+ return [self._days[d].to_storage() for d in sorted(self._days)]
88
+
89
+ def restore(self, stored: list[Any]) -> None:
90
+ """Load stored days, skipping and counting any that cannot be read."""
91
+ self._days = {}
92
+ self.skipped = 0
93
+ for item in stored:
94
+ try:
95
+ day = SlotDay.from_storage(item, self._tz)
96
+ except ValueError, TypeError, AttributeError:
97
+ self.skipped += 1
98
+ continue
99
+ self._days[day.day] = day
100
+
101
+ def _day_for(self, day: date) -> SlotDay:
102
+ if day not in self._days:
103
+ self._days[day] = SlotDay(day, self._tz)
104
+ return self._days[day]
105
+
106
+ def _prune(self, today: date) -> None:
107
+ oldest = today - timedelta(days=self._retention - 1)
108
+ for day in [d for d in self._days if d < oldest]:
109
+ del self._days[day]
110
+
111
+
112
+ def _series_summary(day: SlotDay, name: str) -> dict[str, float | None]:
113
+ counter = day.counters_kwh.get(name)
114
+ gap = day.gap_kwh(name)
115
+ return {
116
+ "slots_kwh": round(day.total(name), 3),
117
+ "inverter_kwh": None if counter is None else round(counter, 3),
118
+ "gap_kwh": None if gap is None else round(gap, 3),
119
+ }
120
+
121
+
122
+ def _day_summary(day: SlotDay) -> dict[str, Any]:
123
+ names = [n for n in (*day.flows, *day.loads) if day.total(n) or n in day.counters_kwh]
124
+ return {
125
+ "date": day.day.isoformat(),
126
+ "coverage": round(day.coverage, 3),
127
+ "series": {n: _series_summary(day, n) for n in names},
128
+ }
@@ -0,0 +1,266 @@
1
+ """slots.py: one local day of energy in half-hour slots.
2
+
3
+ A day starts at local midnight and runs to the next local midnight. Slots are counted in real
4
+ elapsed time, so a spring-forward day has 46 and a fall-back day has 50 (never assume 48).
5
+
6
+ Two kinds of energy are kept apart. Flows are the supply side at the grid and the inverter
7
+ (FLOWS). Loads are the consumers, by name: the house, the EV and the immersion are always
8
+ there and another can be added by name. Every figure is a reading, never derived from the
9
+ others, so a drift in one source shows up instead of being absorbed by another. The loads
10
+ overlap: "house" is the whole-house load as the inverter reports it, which includes the EV and
11
+ the immersion, and those are recorded on their own as well.
12
+
13
+ Each slot also keeps the seconds actually observed, so a slot with no data can be told from a
14
+ slot that used nothing, and the battery state of charge at the end of the slot.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ import re
21
+ from collections.abc import Mapping, Sequence
22
+ from dataclasses import dataclass, field
23
+ from datetime import date, datetime, time, timedelta, tzinfo
24
+ from typing import Any, NotRequired, TypedDict
25
+
26
+ from ..timeutil import elapsed_seconds
27
+ from .defaults import SLOT_SECONDS
28
+
29
+ FLOWS = ("import", "export", "solar", "battery_charge", "battery_discharge", "grid_to_battery")
30
+ DEFAULT_LOADS = ("house", "ev", "immersion")
31
+ STORAGE_VERSION = 1
32
+
33
+ _WH_PER_KWH = 1000
34
+ _LOAD_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class SlotEnergy:
39
+ """Energy in kWh over one interval, as it is handed to SlotDay.add.
40
+
41
+ flows: kWh by name, names from FLOWS only (a typo is refused, not stored).
42
+ loads: kWh by name. Any lowercase name is allowed, so a new consumer needs no schema change.
43
+ "house" is the whole-house load and includes the "ev" and "immersion" loads, so loads do not
44
+ add up to a total.
45
+ Both are readings from the inverter or the device, never worked out from each other.
46
+ """
47
+
48
+ flows: Mapping[str, float] = field(default_factory=dict)
49
+ loads: Mapping[str, float] = field(default_factory=dict)
50
+
51
+ def scaled(self, share: float) -> SlotEnergy:
52
+ return SlotEnergy(
53
+ {k: v * share for k, v in self.flows.items()},
54
+ {k: v * share for k, v in self.loads.items()},
55
+ )
56
+
57
+ def check(self) -> None:
58
+ """Refuse an unknown flow, a bad load name, or a negative or non-finite figure."""
59
+ for name in self.flows:
60
+ if name not in FLOWS:
61
+ raise ValueError(f"unknown flow {name!r}")
62
+ for name in self.loads:
63
+ if not _LOAD_NAME.match(name):
64
+ raise ValueError(f"load names are lowercase letters, digits and _, not {name!r}")
65
+ for name, value in (*self.flows.items(), *self.loads.items()):
66
+ if not math.isfinite(value) or value < 0:
67
+ raise ValueError(f"{name} must be a finite number of kWh, 0 or more")
68
+
69
+
70
+ def local_midnight(day: date, tz: tzinfo) -> datetime:
71
+ """Midnight at the start of *day* in *tz*."""
72
+ return datetime.combine(day, time(0), tzinfo=tz)
73
+
74
+
75
+ def _slots_in_day(day: date, tz: tzinfo) -> int:
76
+ start = local_midnight(day, tz)
77
+ end = local_midnight(day + timedelta(days=1), tz)
78
+ return round(elapsed_seconds(start, end) / SLOT_SECONDS)
79
+
80
+
81
+ class StoredSlotDay(TypedDict):
82
+ """The saved form of one SlotDay, as written to storage and read back.
83
+
84
+ The only definition of the stored shape. Change it only with a new `version`, and give
85
+ from_storage a way to read the old one. Watt-hours are whole numbers to keep a year small.
86
+ """
87
+
88
+ version: int # STORAGE_VERSION when written. An unknown version is skipped on load.
89
+ date: str # local calendar day, ISO 8601, e.g. "2026-06-01"
90
+ start: str # that day's local midnight with its UTC offset. A different offset is skipped.
91
+ slots: int # 48, or 46 and 50 on a clock-change day. Every list below has this length.
92
+ flows_wh: dict[str, list[int]] # name from FLOWS -> Wh in each slot
93
+ # load name -> Wh per slot. house is the whole-house load and includes ev and immersion.
94
+ loads_wh: dict[str, list[int]]
95
+ soc_pct: list[float | None] # battery state of charge at the end of each slot, null if unseen
96
+ seconds: list[int] # seconds of the slot actually observed, 0 to 1800
97
+ # The inverter's own total for the day, in Wh, by name, as last read. Compare it with the sum
98
+ # of the slots to see drift or missed time. Absent in a day saved before it was kept.
99
+ counters_wh: NotRequired[dict[str, int]]
100
+
101
+
102
+ @dataclass
103
+ class SlotDay:
104
+ """Energy in each slot of one local day, in memory.
105
+
106
+ Slot i is the i-th half hour of real elapsed time since local midnight. Every list below has
107
+ one entry per slot. StoredSlotDay is the saved form of this class.
108
+ """
109
+
110
+ day: date # the local calendar day
111
+ tz: tzinfo # the zone whose midnight starts and ends the day
112
+ flows: dict[str, list[float]] = field(default_factory=dict) # FLOWS name -> kWh per slot
113
+ loads: dict[str, list[float]] = field(default_factory=dict) # load name -> kWh per slot
114
+ seconds: list[float] = field(default_factory=list) # observed time per slot, 0 to 1800
115
+ soc_pct: list[float | None] = field(default_factory=list) # end-of-slot charge, None unseen
116
+ # The inverter's own total for the day by name, in kWh, as last read. Not part of the slots:
117
+ # it is what they should add up to, kept so a drift can be seen. See `gap_kwh`.
118
+ counters_kwh: dict[str, float] = field(default_factory=dict)
119
+
120
+ def __post_init__(self) -> None:
121
+ count = _slots_in_day(self.day, self.tz)
122
+ if not self.seconds:
123
+ self.seconds = [0.0] * count
124
+ if not self.soc_pct:
125
+ self.soc_pct = [None] * count
126
+ for name in FLOWS:
127
+ self.flows.setdefault(name, [0.0] * count)
128
+ for name in DEFAULT_LOADS:
129
+ self.loads.setdefault(name, [0.0] * count)
130
+ series: list[Sequence[object]] = [
131
+ *self.flows.values(),
132
+ *self.loads.values(),
133
+ self.seconds,
134
+ self.soc_pct,
135
+ ]
136
+ if any(len(s) != count for s in series):
137
+ raise ValueError(f"{self.day} has {count} slots here, the data does not match")
138
+
139
+ @property
140
+ def start(self) -> datetime:
141
+ return local_midnight(self.day, self.tz)
142
+
143
+ @property
144
+ def end(self) -> datetime:
145
+ return local_midnight(self.day + timedelta(days=1), self.tz)
146
+
147
+ @property
148
+ def slot_count(self) -> int:
149
+ return len(self.seconds)
150
+
151
+ @property
152
+ def coverage(self) -> float:
153
+ """Share of the day that was observed, 0 to 1."""
154
+ observed = sum(min(s, SLOT_SECONDS) for s in self.seconds)
155
+ return observed / (self.slot_count * SLOT_SECONDS)
156
+
157
+ def total(self, name: str) -> float:
158
+ """The day's total in kWh for a flow or a load."""
159
+ return sum(self.flows[name] if name in self.flows else self.loads[name])
160
+
161
+ def add(self, energy: SlotEnergy, start: datetime, end: datetime) -> None:
162
+ """Spread *energy* evenly over [start, end), in proportion to the time in each slot.
163
+
164
+ The interval must lie inside this day. Bad figures are refused before anything is booked.
165
+ """
166
+ energy.check()
167
+ first, last = self._offset(start), self._offset(end)
168
+ if not 0 <= first < last <= self.slot_count * SLOT_SECONDS:
169
+ raise ValueError("the interval must be non-empty and inside the day")
170
+ for load in energy.loads:
171
+ self.loads.setdefault(load, [0.0] * self.slot_count)
172
+ for index in range(int(first // SLOT_SECONDS), math.ceil(last / SLOT_SECONDS)):
173
+ share = _overlap(first, last, index) / (last - first)
174
+ self.seconds[index] += share * (last - first)
175
+ _book(self.flows, energy.flows, index, share)
176
+ _book(self.loads, energy.loads, index, share)
177
+
178
+ def note_counters(self, readings: Mapping[str, float]) -> None:
179
+ """Keep the inverter's day totals as last read. A later reading replaces an earlier one."""
180
+ for name, value in readings.items():
181
+ if name not in FLOWS and not _LOAD_NAME.match(name):
182
+ raise ValueError(f"unknown series {name!r}")
183
+ if not math.isfinite(value) or value < 0:
184
+ raise ValueError(f"{name} must be a finite number of kWh, 0 or more")
185
+ self.counters_kwh.update(readings)
186
+
187
+ def gap_kwh(self, name: str) -> float | None:
188
+ """The inverter's day total less what the slots hold, None without a counter.
189
+
190
+ Positive means the slots hold less than the inverter counted, for example time when
191
+ Home Assistant was not running. It is never adjusted away.
192
+ """
193
+ if name not in self.counters_kwh:
194
+ return None
195
+ return self.counters_kwh[name] - self.total(name)
196
+
197
+ def set_soc(self, moment: datetime, percent: float) -> None:
198
+ """Note the battery state of charge in the slot holding *moment*. The last one wins."""
199
+ offset = self._offset(moment)
200
+ if not 0 <= percent <= 100 or not 0 <= offset < self.slot_count * SLOT_SECONDS:
201
+ raise ValueError("a state of charge is 0 to 100 and must be inside the day")
202
+ self.soc_pct[int(offset // SLOT_SECONDS)] = round(percent, 1)
203
+
204
+ def _offset(self, moment: datetime) -> float:
205
+ return elapsed_seconds(self.start, moment)
206
+
207
+ def to_storage(self) -> StoredSlotDay:
208
+ """JSON-safe form: whole watt-hours and whole seconds, to keep a year small."""
209
+ return {
210
+ "version": STORAGE_VERSION,
211
+ "date": self.day.isoformat(),
212
+ "start": self.start.isoformat(),
213
+ "slots": self.slot_count,
214
+ "flows_wh": _to_wh(self.flows),
215
+ "loads_wh": _to_wh(self.loads),
216
+ "soc_pct": list(self.soc_pct),
217
+ "seconds": [round(s) for s in self.seconds],
218
+ "counters_wh": {n: round(v * _WH_PER_KWH) for n, v in self.counters_kwh.items()},
219
+ }
220
+
221
+ @classmethod
222
+ def from_storage(cls, data: Mapping[str, Any], tz: tzinfo) -> SlotDay: # data: untrusted
223
+ """Rebuild a day. Raises ValueError for anything that does not fit this day's slots.
224
+
225
+ A day saved under another time zone or format version is refused, not converted.
226
+ """
227
+ try:
228
+ if data["version"] != STORAGE_VERSION:
229
+ raise ValueError(f"format version {data['version']}")
230
+ day = date.fromisoformat(data["date"])
231
+ flows = _from_wh(data["flows_wh"])
232
+ loads = _from_wh(data["loads_wh"])
233
+ seconds = [float(s) for s in data["seconds"]]
234
+ soc = [None if v is None else float(v) for v in data["soc_pct"]]
235
+ counters = _from_wh_values(data.get("counters_wh", {}))
236
+ result = cls(day, tz, flows, loads, seconds, soc, counters)
237
+ if data["start"] != result.start.isoformat():
238
+ raise ValueError("saved under another time zone")
239
+ except (KeyError, TypeError, ValueError) as err:
240
+ raise ValueError(f"unreadable slot day: {err}") from err
241
+ return result
242
+
243
+
244
+ def _book(
245
+ target: dict[str, list[float]], kwh: Mapping[str, float], index: int, share: float
246
+ ) -> None:
247
+ for name, value in kwh.items():
248
+ target[name][index] += value * share
249
+
250
+
251
+ def _to_wh(series: Mapping[str, list[float]]) -> dict[str, list[int]]:
252
+ return {n: [round(v * _WH_PER_KWH) for v in vals] for n, vals in series.items()}
253
+
254
+
255
+ def _from_wh(stored: Mapping[str, list[Any]]) -> dict[str, list[float]]:
256
+ return {n: [float(v) / _WH_PER_KWH for v in vals] for n, vals in stored.items()}
257
+
258
+
259
+ def _from_wh_values(stored: Mapping[str, Any]) -> dict[str, float]:
260
+ return {n: float(v) / _WH_PER_KWH for n, v in stored.items()}
261
+
262
+
263
+ def _overlap(first: float, last: float, index: int) -> float:
264
+ """Seconds of [first, last) that fall in slot *index*."""
265
+ lo, hi = index * SLOT_SECONDS, (index + 1) * SLOT_SECONDS
266
+ return max(0.0, min(last, hi) - max(first, lo))
@@ -0,0 +1,64 @@
1
+ """The value of the energy the battery gained or lost since the day began.
2
+
3
+ The saving is the cost of the load at the rate in force, less what was paid. Energy bought
4
+ to fill the battery is paid for on the day it is bought but only earns its keep on the day
5
+ the battery gives it back. Without a correction the saving reads negative after a cheap
6
+ overnight charge and recovers through the day. The correction adds the value of the change
7
+ in stored energy, so the energy bought and the energy still held balance.
8
+
9
+ The change is (SoC now minus SoC at the start of the day) times the battery capacity. Each kWh
10
+ is valued at the average cost of the grid energy that went into the battery today, or at the
11
+ cheapest rate in the tariff when none did. A fall in stored energy is valued the same way, so
12
+ it is the negative of what the same rise would have been.
13
+
14
+ Why this rule: the grid energy stored today is the only energy the battery was bought with,
15
+ so its average cost is what a kWh of stored energy cost. Solar stored has no purchase price
16
+ and a rate of 0 would pull the average down, so it is left out. With no grid charge there is
17
+ no cost to average, and the cheapest rate is the lowest price the battery could have been
18
+ filled at, which keeps the figure steady from day to day.
19
+
20
+ Pure Python, no Home Assistant imports.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass
26
+
27
+ from .accumulator import EnergyAccumulator
28
+ from .config import TariffConfig
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class StoredEnergy:
33
+ """The kWh the battery gained (positive) or lost today and the value of each kWh."""
34
+
35
+ change_kwh: float = 0.0
36
+ value_per_kwh: float = 0.0
37
+
38
+ @property
39
+ def value(self) -> float:
40
+ return self.change_kwh * self.value_per_kwh
41
+
42
+
43
+ def value_per_stored_kwh(acc: EnergyAccumulator, tariff: TariffConfig) -> float:
44
+ """Average cost of the grid energy stored today, else the cheapest rate.
45
+
46
+ Both are after the supplier discount and VAT, like every cost the accumulators hold.
47
+ """
48
+ if acc.grid_to_battery_priced_kwh > 0:
49
+ return acc.grid_to_battery_cost / acc.grid_to_battery_priced_kwh
50
+ return tariff.effective_import_rate(tariff.get_cheapest_rate().rate)
51
+
52
+
53
+ def stored_energy_change(
54
+ acc: EnergyAccumulator, soc_pct: float | None, capacity_kwh: float, tariff: TariffConfig
55
+ ) -> StoredEnergy:
56
+ """The change in stored energy since acc began, nothing without a SoC or a capacity.
57
+
58
+ soc_pct is None while the SoC reading is unavailable. A capacity of 0 or less means it
59
+ is unknown. Without the SoC the period began at, there is no change to value yet.
60
+ """
61
+ if soc_pct is None or acc.soc_at_start_pct is None or capacity_kwh <= 0:
62
+ return StoredEnergy()
63
+ change_kwh = (soc_pct - acc.soc_at_start_pct) / 100 * capacity_kwh
64
+ return StoredEnergy(change_kwh, value_per_stored_kwh(acc, tariff))