besslib 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.
besslib/soh/record.py ADDED
@@ -0,0 +1,556 @@
1
+ """The parameters of Annex VII of Regulation (EU) 2023/1542 for one battery at one date.
2
+
3
+ ``annex_vii`` computes, from operating data, the ten parameters that Annex VII lists for
4
+ stationary battery energy storage systems: five for the state of health (part A) and
5
+ five for the expected lifetime (part B). Each field carries the legal wording, besslib's
6
+ own label for what is actually computed, a value with a band, the number of events it
7
+ rests on, its method with the source, and a status: ``estimated`` or ``not possible
8
+ from this data`` with the reason. Nothing is filled in where the data do not allow it.
9
+
10
+ The record computes the Annex VII parameters; it does not certify them. It is not a
11
+ compliance certificate and not legal advice.
12
+
13
+ Estimates (A1-A5) leave the ``mask`` intervals out (for example capacity tests) and use
14
+ only data up to the record's date. Counts (B2-B5) are facts about the battery: they count
15
+ everything, masked intervals included, over the whole days of data up to the date, and
16
+ they start on the first day of data, not on the battery's first day.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import math
23
+ from dataclasses import dataclass, field
24
+ from datetime import date
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from besslib.frames import PackSpec
30
+ from besslib.soh import _core
31
+ from besslib.soh.capacity import estimate_capacity
32
+ from besslib.soh.charge_loss import charge_loss, charge_loss_trend
33
+ from besslib.soh.config import CapacityConfig, RecordConfig, config_hash
34
+ from besslib.soh.efficiency import estimate_efficiency
35
+ from besslib.soh.reduce import Reduced, reduce_frame
36
+ from besslib.soh.resistance import estimate_resistance, resistance_growth
37
+ from besslib.soh.rests import levels_from, operating_rests, rest_chain, rest_pairs
38
+ from besslib.soh.usage import Limits, count_usage
39
+
40
+ #: The version of the Regulation the wording below is taken from.
41
+ ANNEX_VII_VERSION = "Regulation (EU) 2023/1542, Annex VII, consolidated version of 31 July 2025"
42
+
43
+ #: The parameters of Annex VII for stationary battery energy storage systems, in the
44
+ #: Annex's order and wording (part A: state of health; part B: expected lifetime).
45
+ ANNEX_VII_FIELDS = (
46
+ ("A1", "the remaining capacity"),
47
+ ("A2", "where possible, the remaining power capability"),
48
+ ("A3", "where possible, the remaining round trip efficiency"),
49
+ ("A4", "the evolution of self-discharging rates"),
50
+ ("A5", "where possible, the ohmic resistance"),
51
+ ("B1", "the date of manufacture of the battery and, where appropriate, the date of putting into service"),
52
+ ("B2", "the energy throughput"),
53
+ ("B3", "the capacity throughput"),
54
+ (
55
+ "B4",
56
+ "the tracking of harmful events, such as the number of deep discharge events, time spent in extreme "
57
+ "temperatures, time spent charging in extreme temperatures",
58
+ ),
59
+ ("B5", "the number of full equivalent charge-discharge cycles"),
60
+ )
61
+ _LEGAL = dict(ANNEX_VII_FIELDS)
62
+
63
+ ESTIMATED = _core.STATUS_TEXT[_core.OK]
64
+ NOT_IN_DATASET = "not possible from this data: not in the dataset"
65
+ NO_LIMITS = "not possible from this data: no limits given"
66
+
67
+ _FIGGENER = "Figgener et al., Nature Energy 9, 1438 (2024), doi:10.1038/s41560-024-01620-9"
68
+ _SENSORS = (
69
+ "band: sensor accuracy (Figgener et al. 2024, Supplementary Table 2) as a rectangular half-width "
70
+ "(JCGM 100:2008, 4.3.7)"
71
+ )
72
+ _RESISTANCE = (
73
+ "dV/dI of current steps between consecutive samples (Barai et al., Sci. Rep. 8, 21 (2018), "
74
+ "doi:10.1038/s41598-017-18424-5; Schweiger et al., Sensors 10, 5604 (2010), doi:10.3390/s100605604)"
75
+ )
76
+ _METHODS = {
77
+ "A1": f"capacity between full and empty rests by coulomb counting, fitted with the offset current ({_FIGGENER})",
78
+ "A2": f"ratio of the resistance on the first day to the resistance at the date, from {_RESISTANCE}; no power test",
79
+ "A3": (
80
+ "energy out / energy in over closed loops between full rests (Regulation (EU) 2023/1542, Annex IV (6)); "
81
+ "band: the ratio over these loops had each closed exactly, from the error of the state of charge at their "
82
+ "end rests, estimated as the mean lag-2 product of the loop scores minus the mean lag-1 product"
83
+ ),
84
+ "A4": f"minus the offset current of the capacity fit ({_FIGGENER}); band with the current sensor's gain error",
85
+ "A5": _RESISTANCE,
86
+ "B1": "the pack's documents (PackSpec), passed through",
87
+ "B2": f"trapezoid sums of charging and discharging power over the measured time; {_SENSORS}",
88
+ "B3": f"trapezoid sums of charging and discharging current over the measured time; {_SENSORS}",
89
+ "B4": (
90
+ "measured hours per pack-temperature band and mode; discharges that reached the system's own "
91
+ "end-of-discharge level (empty rests); voltage extremes; counts against limits when limits are given"
92
+ ),
93
+ "B5": f"capacity throughput / (2 x reference capacity); {_SENSORS}",
94
+ }
95
+
96
+ #: Columns of ``AnnexVII.to_frame``.
97
+ FRAME_COLUMNS = ["code", "field", "value", "low", "high", "unit", "events", "status"]
98
+
99
+ #: Significant digits of the floats in ``AnnexVII.to_json``.
100
+ JSON_DIGITS = 8
101
+
102
+
103
+ @dataclass
104
+ class Field:
105
+ """One parameter of the record: the legal ``field`` name and besslib's own ``label``."""
106
+
107
+ code: str
108
+ field: str
109
+ label: str
110
+ value: float
111
+ low: float
112
+ high: float
113
+ unit: str
114
+ method: str
115
+ events: float
116
+ status: str
117
+ details: dict = field(default_factory=dict)
118
+
119
+
120
+ @dataclass
121
+ class AnnexVII:
122
+ """The Annex VII parameters of one battery at one date (module docstring).
123
+
124
+ It computes the parameters; it does not certify them and is not a compliance
125
+ certificate. ``fields`` holds the ten parameters in the order of the Annex.
126
+ """
127
+
128
+ date: pd.Timestamp
129
+ pack: dict
130
+ reference_capacity_ah: float
131
+ capacity_config_hash: str
132
+ record_config_hash: str
133
+ data_credit: str | None
134
+ sample_s: float
135
+ level: float
136
+ annex_vii_version: str
137
+ fields: list
138
+
139
+ def field(self, code: str) -> Field:
140
+ """The field with this code (``"A1"`` ... ``"B5"``)."""
141
+ for f in self.fields:
142
+ if f.code == code:
143
+ return f
144
+ raise KeyError(code)
145
+
146
+ def to_frame(self) -> pd.DataFrame:
147
+ """One row per field: code, field (legal name), value, low, high, unit, events, status."""
148
+ return pd.DataFrame(
149
+ [[getattr(f, c) for c in FRAME_COLUMNS] for f in self.fields], columns=FRAME_COLUMNS
150
+ )
151
+
152
+ def to_dict(self) -> dict:
153
+ """The whole record as plain values (dates as ISO text, NaN as None)."""
154
+ out = {
155
+ "date": self.date,
156
+ "pack": self.pack,
157
+ "reference_capacity_ah": self.reference_capacity_ah,
158
+ "capacity_config_hash": self.capacity_config_hash,
159
+ "record_config_hash": self.record_config_hash,
160
+ "data_credit": self.data_credit,
161
+ "sample_s": self.sample_s,
162
+ "level": self.level,
163
+ "annex_vii_version": self.annex_vii_version,
164
+ "not_a_certificate": "computes the Annex VII parameters; does not certify them",
165
+ "fields": [
166
+ {
167
+ "code": f.code, "field": f.field, "label": f.label, "value": f.value, "low": f.low,
168
+ "high": f.high, "unit": f.unit, "method": f.method, "events": f.events, "status": f.status,
169
+ "details": f.details,
170
+ }
171
+ for f in self.fields
172
+ ],
173
+ }
174
+ return _plain(out)
175
+
176
+ def to_json(self) -> str:
177
+ """Deterministic JSON: sorted keys, floats to ``JSON_DIGITS`` significant digits, NaN as null."""
178
+ return json.dumps(self.to_dict(), sort_keys=True, indent=1, allow_nan=False) + "\n"
179
+
180
+
181
+ def _plain(value):
182
+ """Plain JSON values: rounded floats, None for NaN, ISO text for times, lists for tables."""
183
+ if isinstance(value, dict):
184
+ return {str(k): _plain(v) for k, v in value.items()}
185
+ if isinstance(value, (list, tuple)):
186
+ return [_plain(v) for v in value]
187
+ if isinstance(value, pd.DataFrame):
188
+ return [_plain(r) for r in value.to_dict("records")]
189
+ if isinstance(value, (bool, np.bool_)):
190
+ return bool(value)
191
+ if isinstance(value, (int, np.integer)):
192
+ return int(value)
193
+ if isinstance(value, (float, np.floating)):
194
+ v = float(value)
195
+ return float(f"{v:.{JSON_DIGITS}g}") if math.isfinite(v) else None
196
+ if value is None or value is pd.NaT:
197
+ return None
198
+ if isinstance(value, pd.Timestamp):
199
+ return value.isoformat()
200
+ if isinstance(value, date):
201
+ return value.isoformat()
202
+ if isinstance(value, np.datetime64):
203
+ return pd.Timestamp(value).isoformat() if not np.isnat(value) else None
204
+ return value if isinstance(value, str) else str(value)
205
+
206
+
207
+ def _nan_field(code: str, label: str, unit: str, status: str, details: dict | None = None) -> Field:
208
+ return Field(code, _LEGAL[code], label, math.nan, math.nan, math.nan, unit, _METHODS[code], 0.0, status,
209
+ details or {})
210
+
211
+
212
+
213
+ def _row_value(row, name: str):
214
+ """``(value, low, high)`` of a quantity in a row, NaN unless the row is estimated."""
215
+ if row["status"] != ESTIMATED:
216
+ return math.nan, math.nan, math.nan
217
+ return float(row[name]), float(row[f"{name}_low"]), float(row[f"{name}_high"])
218
+
219
+
220
+ def _until(reduced: Reduced, at: pd.Timestamp) -> Reduced:
221
+ """The reduced tables up to ``at``: the days whose samples all lie at or before it, the rests that start
222
+ at or before it. Days are whole: a day that goes on after ``at`` is left out."""
223
+ d = reduced.daily
224
+ last = d["t_last"]
225
+ keep = (last <= at) | (last.isna() & (d["day"] < at.normalize()))
226
+ days = d[keep.to_numpy()]
227
+ # Days without samples after the last kept day add nothing; drop them, so the record ends at its data.
228
+ if len(days) and days["t_last"].notna().any():
229
+ days = days[days["day"] <= days.loc[days["t_last"].notna(), "day"].max()]
230
+ rests = reduced.rests[reduced.rests["start"] <= at]
231
+ steps = reduced.steps[reduced.steps["time"] <= at]
232
+ return Reduced(daily=days.reset_index(drop=True), steps=steps, rests=rests, sample_s=reduced.sample_s)
233
+
234
+
235
+ # --- A1 and A4: the capacity fit ---------------------------------------------------------
236
+
237
+
238
+ def _capacity_fields(reduced, spec, at, mask, level, config, capacity_config) -> list[Field]:
239
+ rests = operating_rests(reduced.rests, spec, capacity_config, mask=mask)
240
+ pairs = rest_pairs(rest_chain(rests, spec, capacity_config, mask=mask), capacity_config)
241
+ ready = levels_from(rests, capacity_config)
242
+ first = reduced.daily["day"].min()
243
+ times = pd.DatetimeIndex(pd.date_range(first, at, freq="ME").append(pd.DatetimeIndex([at])).unique()).sort_values()
244
+ cap = estimate_capacity(None, spec, config=capacity_config, pairs=pairs, levels_from=ready, at=times)
245
+ now = cap.loc[at]
246
+ value, low, high = _row_value(now, "capacity_ah")
247
+ ref = float(spec.reference_capacity_ah)
248
+ a1 = Field(
249
+ "A1", _LEGAL["A1"], "remaining capacity between the system's own end of charge and end of discharge",
250
+ value, low, high, "Ah", _METHODS["A1"], float(now["n_pairs"]), now["status"],
251
+ {
252
+ "share_of_reference": value / ref,
253
+ "share_of_reference_low": low / ref,
254
+ "share_of_reference_high": high / ref,
255
+ "reference_capacity_ah": ref,
256
+ "n_full_empty_pairs": float(now["n_full_empty"]),
257
+ "n_same_kind_pairs": float(now["n_same_kind"]),
258
+ "band_level": capacity_config.level,
259
+ "levels_from": ready,
260
+ },
261
+ )
262
+ loss = charge_loss(cap, spec, level=level, config=config)
263
+ trend = charge_loss_trend(loss, config=config, level=level)
264
+ row = loss.loc[at]
265
+ value, low, high = _row_value(row, "charge_loss_ma")
266
+ pv, pl, ph = _row_value(row, "charge_loss_percent_per_month")
267
+ a4 = Field(
268
+ "A4", _LEGAL["A4"], "apparent charge loss (an upper bound for self-discharge)", value, low, high, "mA",
269
+ _METHODS["A4"], float(row["n_pairs"]), row["status"],
270
+ {
271
+ "what_it_holds": (
272
+ "the charge the battery loses that its meter does not see: cell self-discharge, BMS supply, "
273
+ "balancing and the current sensor's zero offset; mostly not cell self-discharge"
274
+ ),
275
+ "percent_of_reference_per_month": pv,
276
+ "percent_of_reference_per_month_low": pl,
277
+ "percent_of_reference_per_month_high": ph,
278
+ "reference_capacity_ah": ref,
279
+ "evolution": {k: v for k, v in trend.items() if k != "year_end"},
280
+ "year_end_values": trend["year_end"],
281
+ },
282
+ )
283
+ return [a1, a4]
284
+
285
+
286
+ # --- A3: round-trip efficiency -------------------------------------------------------------
287
+
288
+
289
+ def _efficiency_field(reduced, spec, at, mask, level, config, capacity_config) -> Field:
290
+ common = dict(config=config, capacity_config=capacity_config, reduced=reduced, at=[at], mask=mask)
291
+ full = estimate_efficiency(None, spec, level=level, kind="full", **common).iloc[0]
292
+ empty = estimate_efficiency(None, spec, level=level, kind="empty", **common).iloc[0]
293
+ value, low, high = _row_value(full, "round_trip_efficiency")
294
+ ev, el, eh = _row_value(empty, "round_trip_efficiency")
295
+ return Field(
296
+ "A3", _LEGAL["A3"], "round-trip efficiency (DC, at the battery terminals) over full-to-full loops",
297
+ value, low, high, "share", _METHODS["A3"], float(full["n_loops"]), full["status"],
298
+ {
299
+ "coulombic_part": float(full["coulombic_efficiency"]),
300
+ "voltage_part": float(full["voltage_efficiency"]),
301
+ "rho": float(full["rho"]),
302
+ "dof": float(full["dof"]),
303
+ "rest_error_wh": float(full["rest_error_wh"]),
304
+ "empty_loops": {
305
+ "value": ev, "low": el, "high": eh, "n_loops": float(empty["n_loops"]), "status": empty["status"],
306
+ },
307
+ "limits": (
308
+ "DC at the battery terminals, not the AC efficiency of the plant; depends on the use "
309
+ "(Schimpe et al., Applied Energy 210, 211 (2018), doi:10.1016/j.apenergy.2017.10.129); the band "
310
+ "holds the ratio over these loops, not the efficiency under other use; a change of the loops' own "
311
+ "efficiency within two loops makes the band too narrow; below one degree of freedom there is no "
312
+ "band; the energy in "
313
+ "also restores the charge the meter does not see; the band holds no zero offset of the current "
314
+ "sensor"
315
+ ),
316
+ },
317
+ )
318
+
319
+
320
+ # --- A2 and A5: resistance -----------------------------------------------------------------
321
+
322
+
323
+ def _resistance_fields(reduced, spec, at, mask, level, config, capacity_config) -> list[Field]:
324
+ common = dict(config=config, capacity_config=capacity_config, reduced=reduced, mask=mask)
325
+ table = estimate_resistance(None, spec, level=level, at=[at], **common)
326
+ growth = resistance_growth(None, spec, level=level, at=at, **common)
327
+ seconds = f"{reduced.sample_s:g}-second resistance"
328
+ head = table[table["headline"].astype(bool)]
329
+ bands = table.sort_values("temp_band_c")[
330
+ ["temp_band_c", "resistance_ohm", "resistance_ohm_low", "resistance_ohm_high", "n_days", "n_steps", "status"]
331
+ ]
332
+ if len(head):
333
+ row = head.iloc[0]
334
+ value, low, high = _row_value(row, "resistance_ohm")
335
+ events, status, band_c = float(row["n_days"]), row["status"], float(row["temp_band_c"])
336
+ else:
337
+ value = low = high = math.nan
338
+ events, band_c = 0.0, math.nan
339
+ status = "not possible from this data: no temperature band at the reference temperature"
340
+ a5 = Field(
341
+ "A5", _LEGAL["A5"], f"{seconds}, pack temperature band at {band_c:g} degrees C", value, low, high, "ohm",
342
+ _METHODS["A5"], events, status,
343
+ {
344
+ "sample_s": reduced.sample_s,
345
+ "headline_band_c": band_c,
346
+ "n_steps": float(head.iloc[0]["n_steps"]) if len(head) else 0.0,
347
+ "bands": bands,
348
+ "growth_percent_per_year": growth["growth_percent_per_year"],
349
+ "growth_percent_per_year_low": growth["growth_percent_per_year_low"],
350
+ "growth_percent_per_year_high": growth["growth_percent_per_year_high"],
351
+ "growth_status": growth["status"],
352
+ "growth_n_days": growth["n_days"],
353
+ "growth_span_years": growth["span_years"],
354
+ "what_it_is": (
355
+ f"the voltage step over the current step between two samples {reduced.sample_s:g} s apart; it "
356
+ "depends on that timescale, the state of charge and the temperature, and is not the cell's "
357
+ "ohmic resistance alone"
358
+ ),
359
+ },
360
+ )
361
+ ok = growth["status"] == ESTIMATED
362
+ share = float(growth["power_capability_share"]) if ok else math.nan
363
+ a2 = Field(
364
+ "A2", _LEGAL["A2"], f"power capability share, derived from the {seconds}, not measured",
365
+ share, float(growth["power_capability_share_low"]) if ok else math.nan,
366
+ float(growth["power_capability_share_high"]) if ok else math.nan, "share of the first day", _METHODS["A2"],
367
+ float(growth["n_days"]), growth["status"],
368
+ {
369
+ "power_capability_w": growth["power_capability_w"],
370
+ "power_capability_w_low": growth["power_capability_w_low"],
371
+ "power_capability_w_high": growth["power_capability_w_high"],
372
+ "power_capability_w_status": growth["power_capability_w_status"],
373
+ "resistance_start_ohm": growth["resistance_start_ohm"],
374
+ "resistance_at_ohm": growth["resistance_at_ohm"],
375
+ "first_day": growth["first_day"],
376
+ "what_it_is": (
377
+ "the resistance on the first day divided by the resistance at the date: the share of the first "
378
+ "day's power that the same voltage limits allow now, if the resistance alone limits the power"
379
+ ),
380
+ },
381
+ )
382
+ return [a2, a5]
383
+
384
+
385
+ # --- B: the counts ---------------------------------------------------------------------------
386
+
387
+
388
+ def _date_field(spec: PackSpec) -> Field:
389
+ made = spec.date_of_manufacture
390
+ service = spec.date_put_into_service
391
+ status = "stated in the pack's documents" if made is not None else NOT_IN_DATASET
392
+ return _nan_field(
393
+ "B1", "date of manufacture; date of putting into service", "date", status,
394
+ {
395
+ "date_of_manufacture": made,
396
+ "date_of_manufacture_status": "stated in the pack's documents" if made is not None else NOT_IN_DATASET,
397
+ "date_put_into_service": service,
398
+ "date_put_into_service_status": (
399
+ "stated in the pack's documents" if service is not None else NOT_IN_DATASET
400
+ ),
401
+ },
402
+ )
403
+
404
+
405
+ def _usage_fields(reduced, spec, at, limits, level, config, capacity_config) -> list[Field]:
406
+ use = count_usage(None, spec, limits, config=config, capacity_config=capacity_config, reduced=_until(reduced, at),
407
+ level=level)
408
+ days = float(use.n_days_with_data)
409
+ ok = use.first_day is not None and math.isfinite(use.energy_throughput_kwh)
410
+ status = ESTIMATED if ok else use.status
411
+ coverage = {
412
+ "counted_from": use.first_day,
413
+ "counted_to": use.last_day,
414
+ "since": "the first day of data, not a lifetime total",
415
+ "hours_measured": use.hours_measured,
416
+ "hours_missing": use.hours_missing,
417
+ "share_interpolated": use.share_interpolated,
418
+ "n_days_with_data": use.n_days_with_data,
419
+ "note": use.status,
420
+ }
421
+ b2 = Field(
422
+ "B2", _LEGAL["B2"], "energy throughput (in + out) since the first day of data", use.energy_throughput_kwh,
423
+ use.energy_throughput_kwh_low, use.energy_throughput_kwh_high, "kWh", _METHODS["B2"], days, status,
424
+ {"energy_in_kwh": use.energy_in_kwh, "energy_out_kwh": use.energy_out_kwh, **coverage},
425
+ )
426
+ b3 = Field(
427
+ "B3", _LEGAL["B3"], "capacity throughput (in + out) since the first day of data", use.capacity_throughput_ah,
428
+ use.capacity_throughput_ah_low, use.capacity_throughput_ah_high, "Ah", _METHODS["B3"], days, status,
429
+ {"charge_in_ah": use.charge_in_ah, "charge_out_ah": use.charge_out_ah, **coverage},
430
+ )
431
+ b5 = Field(
432
+ "B5", _LEGAL["B5"], "full equivalent cycles since the first day of data", use.full_equivalent_cycles,
433
+ use.full_equivalent_cycles_low, use.full_equivalent_cycles_high, "cycles", _METHODS["B5"], days, status,
434
+ {"reference_capacity_ah": use.reference_capacity_ah, **coverage},
435
+ )
436
+ given = limits is not None and any(getattr(limits, n) is not None for n in limits.__dataclass_fields__)
437
+
438
+ def against(value, limit_name):
439
+ if not given:
440
+ return {"value": None, "status": NO_LIMITS}
441
+ if getattr(limits, limit_name) is None:
442
+ return {"value": None, "status": f"not possible from this data: no limit given for {limit_name}"}
443
+ if value is None:
444
+ return {"value": None, "status": f"not possible from this data: {limit_name} lies outside -19 to 69 degrees C"}
445
+ return {"value": value, "status": ESTIMATED, "limit": getattr(limits, limit_name)}
446
+
447
+ n_empty = float(use.n_empty_rests)
448
+ b4 = Field(
449
+ "B4", _LEGAL["B4"], "discharges to the system's own end-of-discharge level (observed; not a limit count)",
450
+ n_empty if ok else math.nan, n_empty if ok else math.nan, n_empty if ok else math.nan, "events",
451
+ _METHODS["B4"], n_empty if ok else 0.0, status,
452
+ {
453
+ "hours_per_temperature_band": use.temp_hours,
454
+ "hours_no_temperature": use.hours_no_temperature,
455
+ "temperature_measured": "pack temperature, not cell temperature",
456
+ "voltage_min_v": use.voltage_min_v,
457
+ "voltage_max_v": use.voltage_max_v,
458
+ "voltage_min_cell_v": use.voltage_min_cell_v,
459
+ "voltage_max_cell_v": use.voltage_max_cell_v,
460
+ "cell_voltage_note": "pack voltage / cells in series: an average, one cell can be lower or higher",
461
+ "deep_discharge_events": against(use.n_deep_discharge, "voltage_min_v"),
462
+ "hours_below_temp_low": against(use.hours_below_temp_low, "temp_low_c"),
463
+ "hours_above_temp_high": against(use.hours_above_temp_high, "temp_high_c"),
464
+ "hours_charging_below_temp_low": against(use.hours_charging_below_temp_low, "charge_temp_low_c"),
465
+ "hours_charging_above_temp_high": against(use.hours_charging_above_temp_high, "charge_temp_high_c"),
466
+ "limits_status": use.limits_status,
467
+ **coverage,
468
+ },
469
+ )
470
+ return [b2, b3, b4, b5]
471
+
472
+
473
+ # --- the record --------------------------------------------------------------------------------
474
+
475
+
476
+ def annex_vii(
477
+ frame: pd.DataFrame | None,
478
+ spec: PackSpec,
479
+ level: float = 0.90,
480
+ limits: Limits | None = None,
481
+ reduced: Reduced | None = None,
482
+ *,
483
+ at=None,
484
+ mask=None,
485
+ config: RecordConfig | None = None,
486
+ capacity_config: CapacityConfig | None = None,
487
+ ) -> AnnexVII:
488
+ """The Annex VII parameters of one battery at the date ``at`` (module docstring).
489
+
490
+ Parameters
491
+ ----------
492
+ frame
493
+ Operating data in the besslib frame format; reduced first (``reduce.reduce_frame``).
494
+ May be ``None`` when ``reduced`` is given.
495
+ spec
496
+ The pack: reference capacity, dates, data credit (``spec.extra["data_credit"]``).
497
+ level
498
+ Band level of A2-A5 and B2-B5. A1 uses the level of ``capacity_config``.
499
+ limits
500
+ Operating limits for the harmful events of B4. Without them, the counts against
501
+ limits are ``not possible from this data: no limits given``; the observed facts
502
+ (hours per temperature band, voltage extremes, discharges to the system's own
503
+ end-of-discharge level) are always given.
504
+ reduced
505
+ The reduced tables (``reduce.reduce_parts`` or ``reduce.reduce_frame``).
506
+ at
507
+ The date of the record. Default: the last sample.
508
+ mask
509
+ Intervals ``(start, end)`` left out of the estimates A1-A5 (for example capacity
510
+ tests). The counts B2-B5 count everything.
511
+ config, capacity_config
512
+ Settings; the defaults are the frozen ones. Both hashes are in the record.
513
+
514
+ Returns
515
+ -------
516
+ AnnexVII with the ten fields in the order of the Annex. It computes the parameters; it
517
+ does not certify them.
518
+ """
519
+ config = config or RecordConfig()
520
+ capacity_config = capacity_config or CapacityConfig()
521
+ if reduced is None:
522
+ if frame is None:
523
+ raise ValueError("give a frame or reduced tables")
524
+ reduced = reduce_frame(frame, spec, capacity_config)
525
+ if len(reduced.daily) == 0 or reduced.daily["t_last"].isna().all():
526
+ raise ValueError("the record has no samples")
527
+ at = pd.Timestamp(reduced.daily["t_last"].max() if at is None else at)
528
+ args = (reduced, spec, at, mask, level, config, capacity_config)
529
+ a1, a4 = _capacity_fields(*args)
530
+ a3 = _efficiency_field(*args)
531
+ a2, a5 = _resistance_fields(*args)
532
+ b2, b3, b4, b5 = _usage_fields(reduced, spec, at, limits, level, config, capacity_config)
533
+ fields = [a1, a2, a3, a4, a5, _date_field(spec), b2, b3, b4, b5]
534
+ assert [f.code for f in fields] == [c for c, _ in ANNEX_VII_FIELDS]
535
+ for f in fields:
536
+ if f.status == ESTIMATED and not (f.low <= f.value <= f.high):
537
+ raise RuntimeError(f"field {f.code}: an estimate outside its own band")
538
+ return AnnexVII(
539
+ date=at,
540
+ pack={
541
+ "name": spec.name,
542
+ "chemistry": spec.chemistry,
543
+ "nominal_capacity_ah": spec.nominal_capacity_ah,
544
+ "nominal_energy_kwh": spec.nominal_energy_kwh,
545
+ "cells_in_series": spec.cells_in_series,
546
+ "cells_in_parallel": spec.cells_in_parallel,
547
+ },
548
+ reference_capacity_ah=float(spec.reference_capacity_ah),
549
+ capacity_config_hash=config_hash(capacity_config),
550
+ record_config_hash=config_hash(config),
551
+ data_credit=spec.extra.get("data_credit"),
552
+ sample_s=float(reduced.sample_s),
553
+ level=level,
554
+ annex_vii_version=ANNEX_VII_VERSION,
555
+ fields=fields,
556
+ )