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/__init__.py +12 -0
- besslib/data/__init__.py +1 -0
- besslib/data/sample_05/NOTICE.md +39 -0
- besslib/data/sample_05/daily.parquet +0 -0
- besslib/data/sample_05/rests.parquet +0 -0
- besslib/data/sample_05/steps.parquet +0 -0
- besslib/frames.py +84 -0
- besslib/io/__init__.py +6 -0
- besslib/io/figgener.py +236 -0
- besslib/io/figgener_meta/README.md +12 -0
- besslib/io/figgener_meta/capacity_tests.csv +61 -0
- besslib/io/figgener_meta/systems.csv +22 -0
- besslib/soh/__init__.py +43 -0
- besslib/soh/_core.py +1081 -0
- besslib/soh/_ratio.py +277 -0
- besslib/soh/capacity.py +332 -0
- besslib/soh/capacity_test.py +205 -0
- besslib/soh/charge_loss.py +199 -0
- besslib/soh/config.py +153 -0
- besslib/soh/efficiency.py +270 -0
- besslib/soh/record.py +556 -0
- besslib/soh/reduce.py +352 -0
- besslib/soh/report.py +290 -0
- besslib/soh/resistance.py +570 -0
- besslib/soh/rests.py +488 -0
- besslib/soh/usage.py +322 -0
- besslib-0.1.0.dist-info/METADATA +210 -0
- besslib-0.1.0.dist-info/RECORD +31 -0
- besslib-0.1.0.dist-info/WHEEL +5 -0
- besslib-0.1.0.dist-info/licenses/LICENSE +28 -0
- besslib-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""The 1-second resistance of the pack from the current steps of normal operation, and its growth.
|
|
2
|
+
|
|
3
|
+
"1-second" names the field data's sampling interval: the value is the resistance over one
|
|
4
|
+
sampling interval of the record, whatever that interval is, and every output carries it.
|
|
5
|
+
|
|
6
|
+
Annex VII of Regulation (EU) 2023/1542 asks, "where possible", for the ohmic resistance
|
|
7
|
+
and its increase. besslib measures a DC resistance the way a current-step test does
|
|
8
|
+
(Barai et al., Sci. Rep. 8, 21 (2018), doi:10.1038/s41598-017-18424-5; Schweiger et al.,
|
|
9
|
+
Sensors 10, 5604 (2010), doi:10.3390/s100605604): the change of the terminal voltage
|
|
10
|
+
divided by the change of the current, over one sampling interval. Normal operation
|
|
11
|
+
holds many such steps (the inverter follows the load and the sun), so no test is needed.
|
|
12
|
+
|
|
13
|
+
A *current step* is a row of the step table (``besslib.soh.reduce``): two consecutive
|
|
14
|
+
samples whose current differs by at least ``min_step_c_rate`` x the nominal capacity,
|
|
15
|
+
after ``steady_s`` seconds in which the current stayed within ``steady_tolerance`` x the
|
|
16
|
+
step of its value before the step. ``dI`` and ``dV`` are the value after minus the value
|
|
17
|
+
before. Steps inside a ``mask`` interval (for example a capacity test) are left out.
|
|
18
|
+
|
|
19
|
+
Event: one calendar day in one pack-temperature band, ``a = sum dI^2``, ``b = sum dI dV``
|
|
20
|
+
over its steps, at the end of that day. Bands are ``temp_band_c`` wide and centred on
|
|
21
|
+
``temp_ref_c + n temp_band_c``; a step's band is that of its pack temperature (lower
|
|
22
|
+
edge included). Steps without a temperature reading are counted and left out.
|
|
23
|
+
|
|
24
|
+
Estimate in each band: ``R = sum lambda b / sum lambda a`` over the days in memory,
|
|
25
|
+
``lambda = exp(-age / tau_days)``: the least-squares slope of dV on dI through the
|
|
26
|
+
origin, over all steps of those days. Its statistical band is the sandwich of the
|
|
27
|
+
through-origin ratio fit (``besslib.soh._core``) on the day scores ``b - R a``; days are
|
|
28
|
+
not linked (no two days share a measurement), so it is the heteroskedasticity-consistent
|
|
29
|
+
form. The sensors' gain errors are added as a systematic term
|
|
30
|
+
(``RecordConfig.resistance_sigma``): a gain error moves every step of the record the same
|
|
31
|
+
way, so averaging does not reduce it. Half-width:
|
|
32
|
+
``sqrt((t sigma_stat)^2 + (z resistance_sigma R)^2)``. No model of temperature is
|
|
33
|
+
applied; each band stands for itself, and ``headline`` marks the band centred on
|
|
34
|
+
``temp_ref_c``.
|
|
35
|
+
|
|
36
|
+
Limits. At a sampling interval of about one second the value holds the ohmic part and
|
|
37
|
+
a part of the charge-transfer resistance: Barai et al. (2018) measured 1.35 mOhm at
|
|
38
|
+
0.1 s and 1.61 mOhm at 1 s on the same 20 Ah LFP cell. It is therefore not the ohmic
|
|
39
|
+
resistance of an impedance spectrum, and values from records with different sampling
|
|
40
|
+
intervals are not comparable; every output carries the interval (``sample_s``). It is
|
|
41
|
+
an average over the states of charge and the currents the system visits in its band
|
|
42
|
+
(the resistance depends on both, Schweiger et al. 2010), not a value at a fixed state
|
|
43
|
+
of charge. With memory time ``tau_days`` it lags a growing resistance by about
|
|
44
|
+
``tau_days``.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import math
|
|
50
|
+
from statistics import NormalDist
|
|
51
|
+
|
|
52
|
+
import numpy as np
|
|
53
|
+
import pandas as pd
|
|
54
|
+
|
|
55
|
+
from besslib.frames import PackSpec
|
|
56
|
+
from besslib.soh import _core, _ratio
|
|
57
|
+
from besslib.soh.capacity import days
|
|
58
|
+
from besslib.soh.config import CapacityConfig, RecordConfig, config_hash
|
|
59
|
+
from besslib.soh.reduce import LOOSEST_MIN_STEP_C_RATE, LOOSEST_STEADY_S, STEADY_CAP_S, STEADY_TOLERANCE, reduce_frame
|
|
60
|
+
from besslib.soh.rests import operating_rests
|
|
61
|
+
|
|
62
|
+
#: Columns of the day-band event table.
|
|
63
|
+
EVENT_COLUMNS = ["day", "temp_band_c", "t_days", "a", "b", "n_steps", "n_unrefreshed", "resistance_ohm"]
|
|
64
|
+
|
|
65
|
+
#: Columns of the estimate table.
|
|
66
|
+
RESISTANCE_COLUMNS = [
|
|
67
|
+
"time", "temp_band_c", "headline", "resistance_ohm", "resistance_ohm_low", "resistance_ohm_high",
|
|
68
|
+
"n_days", "n_steps", "status",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
def power_label(sample_s: float) -> str:
|
|
72
|
+
"""The label of every power capability value, with the record's sampling interval."""
|
|
73
|
+
return f"derived from the {sample_s:g}-second resistance, not measured"
|
|
74
|
+
|
|
75
|
+
_OK = _core.STATUS_TEXT[_core.OK]
|
|
76
|
+
_NOT = "not possible from this data: "
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _z(level: float) -> float:
|
|
80
|
+
return NormalDist().inv_cdf(0.5 + level / 2.0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _check_setting(config: RecordConfig) -> None:
|
|
84
|
+
"""The step table holds the steps of the loosest setting only, with a fixed steady tolerance."""
|
|
85
|
+
if config.min_step_c_rate < LOOSEST_MIN_STEP_C_RATE:
|
|
86
|
+
raise ValueError(f"min_step_c_rate below {LOOSEST_MIN_STEP_C_RATE}: the step table does not hold those steps")
|
|
87
|
+
if not LOOSEST_STEADY_S <= config.steady_s <= STEADY_CAP_S:
|
|
88
|
+
raise ValueError(f"steady_s must lie within {LOOSEST_STEADY_S} to {STEADY_CAP_S} s for the step table")
|
|
89
|
+
if config.steady_tolerance != STEADY_TOLERANCE:
|
|
90
|
+
raise ValueError(f"the step table was made with steady_tolerance {STEADY_TOLERANCE}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def qualifying_steps(
|
|
94
|
+
steps: pd.DataFrame, spec: PackSpec, config: RecordConfig | None = None, mask=None
|
|
95
|
+
) -> pd.DataFrame:
|
|
96
|
+
"""The rows of a step table that qualify for ``(config.min_step_c_rate, config.steady_s)``,
|
|
97
|
+
outside every ``mask`` interval, with ``d_current_a`` and ``d_voltage_v`` (after - before)."""
|
|
98
|
+
config = config or RecordConfig()
|
|
99
|
+
_check_setting(config)
|
|
100
|
+
d_i = (steps["current_after_a"] - steps["current_before_a"]).to_numpy(float)
|
|
101
|
+
d_v = (steps["voltage_after_v"] - steps["voltage_before_v"]).to_numpy(float)
|
|
102
|
+
keep = (
|
|
103
|
+
(np.abs(d_i) >= config.min_step_c_rate * spec.nominal_capacity_ah)
|
|
104
|
+
& (steps["steady_s"].to_numpy(float) >= config.steady_s)
|
|
105
|
+
& np.isfinite(d_i)
|
|
106
|
+
& np.isfinite(d_v)
|
|
107
|
+
)
|
|
108
|
+
time = pd.DatetimeIndex(steps["time"])
|
|
109
|
+
for begin, end in mask or []:
|
|
110
|
+
keep &= ~((time >= pd.Timestamp(begin)) & (time <= pd.Timestamp(end)))
|
|
111
|
+
out = steps.loc[keep].copy()
|
|
112
|
+
out["d_current_a"] = d_i[keep]
|
|
113
|
+
out["d_voltage_v"] = d_v[keep]
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def band_centre(temp_c, temp_ref_c: float = 25.0, width_c: float = 5.0) -> np.ndarray:
|
|
118
|
+
"""The centre of the temperature band of each temperature: ``temp_ref_c + n width_c``,
|
|
119
|
+
with the band ``[centre - width_c / 2, centre + width_c / 2)``. NaN stays NaN."""
|
|
120
|
+
t = np.asarray(temp_c, dtype=float)
|
|
121
|
+
return temp_ref_c + width_c * np.floor((t - temp_ref_c + 0.5 * width_c) / width_c)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def day_band_events(
|
|
125
|
+
steps: pd.DataFrame, spec: PackSpec, config: RecordConfig | None = None, temp_ref_c: float = 25.0, mask=None
|
|
126
|
+
) -> tuple[pd.DataFrame, dict]:
|
|
127
|
+
"""The events of the estimator: one row per calendar day and temperature band.
|
|
128
|
+
|
|
129
|
+
Columns ``day``, ``temp_band_c`` (band centre), ``t_days`` (the end of the day, days
|
|
130
|
+
since 2000-01-01), ``a = sum dI^2``, ``b = sum dI dV``, ``n_steps``,
|
|
131
|
+
``n_unrefreshed`` (steps whose voltage did not change at all) and the day's own
|
|
132
|
+
``resistance_ohm = b / a``.
|
|
133
|
+
|
|
134
|
+
A band-day is kept only when at most ``config.unrefreshed_max_share`` of its steps
|
|
135
|
+
show no voltage change: a current step of at least ``min_step_c_rate`` x C moves the
|
|
136
|
+
terminal voltage by far more than the sensor's resolution, so an exact zero means the
|
|
137
|
+
voltage was not refreshed together with the current, and the day's ratio would mix
|
|
138
|
+
real steps with steps that measure nothing.
|
|
139
|
+
|
|
140
|
+
Also returns a dict of counts: ``n_steps`` (qualifying, with a temperature),
|
|
141
|
+
``n_steps_no_temperature`` and ``n_steps_masked`` (left out), ``n_days_unrefreshed``
|
|
142
|
+
and ``n_steps_unrefreshed_days`` (band-days left out by the rule and their steps),
|
|
143
|
+
``unrefreshed_share_by_band`` (band centre -> share of its qualifying steps without
|
|
144
|
+
voltage change, over the record) and ``dropped`` (the band-days left out, same columns).
|
|
145
|
+
"""
|
|
146
|
+
config = config or RecordConfig()
|
|
147
|
+
every = qualifying_steps(steps, spec, config)
|
|
148
|
+
use = qualifying_steps(steps, spec, config, mask)
|
|
149
|
+
temp = use["temp_pack_c"].to_numpy(float)
|
|
150
|
+
has_temp = np.isfinite(temp)
|
|
151
|
+
counts = {
|
|
152
|
+
"n_steps": int(has_temp.sum()),
|
|
153
|
+
"n_steps_no_temperature": int((~has_temp).sum()),
|
|
154
|
+
"n_steps_masked": int(len(every) - len(use)),
|
|
155
|
+
}
|
|
156
|
+
use = use.loc[has_temp]
|
|
157
|
+
frame = pd.DataFrame(
|
|
158
|
+
{
|
|
159
|
+
"day": pd.DatetimeIndex(use["time"]).normalize(),
|
|
160
|
+
"temp_band_c": band_centre(use["temp_pack_c"].to_numpy(float), temp_ref_c, config.temp_band_c),
|
|
161
|
+
"a": use["d_current_a"].to_numpy(float) ** 2,
|
|
162
|
+
"b": (use["d_current_a"] * use["d_voltage_v"]).to_numpy(float),
|
|
163
|
+
"n_steps": 1,
|
|
164
|
+
"n_unrefreshed": (use["d_voltage_v"].to_numpy(float) == 0.0).astype(int),
|
|
165
|
+
}
|
|
166
|
+
)
|
|
167
|
+
events = frame.groupby(["day", "temp_band_c"], sort=True, as_index=False).sum()
|
|
168
|
+
events["t_days"] = days(events["day"]) + 1.0
|
|
169
|
+
events["resistance_ohm"] = events["b"] / events["a"]
|
|
170
|
+
events = events[EVENT_COLUMNS]
|
|
171
|
+
kept = (events["n_unrefreshed"] <= config.unrefreshed_max_share * events["n_steps"]).to_numpy()
|
|
172
|
+
by_band = events.groupby("temp_band_c")[["n_unrefreshed", "n_steps"]].sum()
|
|
173
|
+
counts.update(
|
|
174
|
+
n_days_unrefreshed=int((~kept).sum()),
|
|
175
|
+
n_steps_unrefreshed_days=int(events.loc[~kept, "n_steps"].sum()),
|
|
176
|
+
unrefreshed_share_by_band={float(c): float(r["n_unrefreshed"] / r["n_steps"]) for c, r in by_band.iterrows()},
|
|
177
|
+
dropped=events.loc[~kept].reset_index(drop=True),
|
|
178
|
+
)
|
|
179
|
+
return events.loc[kept].reset_index(drop=True), counts
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _refresh_status(kept: pd.DataFrame, dropped: pd.DataFrame, tq: float, tau_days: float, min_days: float):
|
|
183
|
+
"""The refresh status of a band whose kept days in memory are too few, or None.
|
|
184
|
+
|
|
185
|
+
The rule is the reason when the band-days it left out would have brought the band to
|
|
186
|
+
``min_days`` (decayed counts with memory ``tau_days``; no forgetting for 0). X is the
|
|
187
|
+
share of steps without voltage change among all qualifying steps of the band in
|
|
188
|
+
memory, with the same weights.
|
|
189
|
+
"""
|
|
190
|
+
def weighted(table):
|
|
191
|
+
t = table["t_days"].to_numpy(float)
|
|
192
|
+
use = t <= tq
|
|
193
|
+
lam = np.exp(-(tq - t[use]) / tau_days) if tau_days > 0 else np.ones(int(use.sum()))
|
|
194
|
+
return (float(lam.sum()), float((lam * table["n_steps"].to_numpy(float)[use]).sum()),
|
|
195
|
+
float((lam * table["n_unrefreshed"].to_numpy(float)[use]).sum()))
|
|
196
|
+
|
|
197
|
+
k_days, k_steps, k_unref = weighted(kept)
|
|
198
|
+
d_days, d_steps, d_unref = weighted(dropped)
|
|
199
|
+
if d_days <= 0.0 or k_days >= min_days or k_days + d_days < min_days:
|
|
200
|
+
return None
|
|
201
|
+
return unrefreshed_text((k_unref + d_unref) / (k_steps + d_steps))
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def unrefreshed_text(share: float) -> str:
|
|
205
|
+
"""The status of an estimate the voltage-refresh rule made impossible."""
|
|
206
|
+
share_text = f"{100.0 * share:.1f} % of steps show no voltage change"
|
|
207
|
+
return f"{_NOT}the voltage is not refreshed with the current ({share_text})"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _status(code: int, centre: float) -> str:
|
|
211
|
+
if code == _core.OK:
|
|
212
|
+
return _OK
|
|
213
|
+
if code == _core.TOO_FEW_EVENTS:
|
|
214
|
+
return f"{_NOT}too few current steps near {centre:g} °C"
|
|
215
|
+
if code == _core.OUT_OF_RANGE:
|
|
216
|
+
return f"{_NOT}the current steps near {centre:g} °C give a resistance at or below zero"
|
|
217
|
+
if code == _core.SHORT_SPAN:
|
|
218
|
+
return f"{_NOT}the days with current steps near {centre:g} °C span too short a time for a growth rate"
|
|
219
|
+
return _core.STATUS_TEXT.get(code, f"{_NOT}status {code}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _systematic_half(stat_half: float, value: float, level: float, config: RecordConfig) -> float:
|
|
223
|
+
"""``sqrt(stat_half^2 + (z resistance_sigma value)^2)``: the statistical half-width plus
|
|
224
|
+
the sensors' gain errors as a systematic term."""
|
|
225
|
+
return math.hypot(stat_half, _z(level) * config.resistance_sigma * value)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _reduced(frame, spec, reduced, capacity_config):
|
|
229
|
+
if reduced is not None:
|
|
230
|
+
return reduced
|
|
231
|
+
if frame is None:
|
|
232
|
+
raise ValueError("give a frame or reduced tables")
|
|
233
|
+
return reduce_frame(frame, spec, capacity_config)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def estimate_resistance(
|
|
237
|
+
frame: pd.DataFrame | None,
|
|
238
|
+
spec: PackSpec,
|
|
239
|
+
temp_ref_c: float = 25.0,
|
|
240
|
+
level: float = 0.90,
|
|
241
|
+
*,
|
|
242
|
+
config: RecordConfig | None = None,
|
|
243
|
+
capacity_config: CapacityConfig | None = None,
|
|
244
|
+
reduced=None,
|
|
245
|
+
at=None,
|
|
246
|
+
mask=None,
|
|
247
|
+
) -> pd.DataFrame:
|
|
248
|
+
"""The 1-second resistance with its band, per temperature band, at each time in ``at`` (module docstring).
|
|
249
|
+
|
|
250
|
+
Parameters
|
|
251
|
+
----------
|
|
252
|
+
frame
|
|
253
|
+
Operating data in the besslib frame format; may be ``None`` when ``reduced`` is given.
|
|
254
|
+
spec
|
|
255
|
+
The pack; its nominal capacity sets the smallest current step.
|
|
256
|
+
temp_ref_c
|
|
257
|
+
Centre of the headline band.
|
|
258
|
+
level
|
|
259
|
+
Band level.
|
|
260
|
+
config, capacity_config
|
|
261
|
+
Settings of the record and of the reduction; defaults are the frozen ones.
|
|
262
|
+
reduced
|
|
263
|
+
A ``reduce.Reduced`` of the record (its step table is used).
|
|
264
|
+
at
|
|
265
|
+
Times of the estimate. Default: the end of every calendar month in the data.
|
|
266
|
+
mask
|
|
267
|
+
Intervals ``(start, end)`` whose steps are left out.
|
|
268
|
+
|
|
269
|
+
Returns
|
|
270
|
+
-------
|
|
271
|
+
DataFrame, one row per time and temperature band (every band with at least one day,
|
|
272
|
+
and always the headline band): ``time``, ``temp_band_c`` (band centre), ``headline``,
|
|
273
|
+
``resistance_ohm`` with ``_low`` and ``_high`` (statistical and systematic part),
|
|
274
|
+
``n_days`` and ``n_steps`` (in memory, decayed), ``status``. A value is given only
|
|
275
|
+
when the status is ``estimated``. When a band has too few days in memory because the
|
|
276
|
+
voltage-refresh rule left band-days out (they would have brought it to
|
|
277
|
+
``resistance_min_days``), the status says so, with the share of steps without voltage
|
|
278
|
+
change among the band's qualifying steps in memory (decayed weights). ``attrs``:
|
|
279
|
+
``config_hash``, ``capacity_config_hash``, ``sample_s``, ``events`` (the kept
|
|
280
|
+
day-band table) and the counts of ``day_band_events`` (``dropped``,
|
|
281
|
+
``n_days_unrefreshed``, ``unrefreshed_share_by_band``, ...).
|
|
282
|
+
"""
|
|
283
|
+
config = config or RecordConfig()
|
|
284
|
+
capacity_config = capacity_config or CapacityConfig()
|
|
285
|
+
reduced = _reduced(frame, spec, reduced, capacity_config)
|
|
286
|
+
events, counts = day_band_events(reduced.steps, spec, config, temp_ref_c, mask)
|
|
287
|
+
if at is None:
|
|
288
|
+
known = pd.DatetimeIndex(reduced.daily["day"]) if len(reduced.daily) else pd.DatetimeIndex([])
|
|
289
|
+
if len(known) == 0:
|
|
290
|
+
raise ValueError("no data to estimate from")
|
|
291
|
+
at = pd.date_range(known.min(), known.max() + pd.Timedelta(days=1), freq="ME")
|
|
292
|
+
at = pd.DatetimeIndex(at)
|
|
293
|
+
at_days = days(at)
|
|
294
|
+
dropped = counts["dropped"]
|
|
295
|
+
bands = sorted(set(events["temp_band_c"].tolist()) | set(dropped["temp_band_c"].tolist()) | {float(temp_ref_c)})
|
|
296
|
+
rows = []
|
|
297
|
+
for centre in bands:
|
|
298
|
+
sel = events[events["temp_band_c"] == centre]
|
|
299
|
+
sel_dropped = dropped[dropped["temp_band_c"] == centre]
|
|
300
|
+
t = sel["t_days"].to_numpy(float)
|
|
301
|
+
n_steps = sel["n_steps"].to_numpy(float)
|
|
302
|
+
est = _ratio.estimate_ratio(
|
|
303
|
+
t, sel["a"].to_numpy(float), sel["b"].to_numpy(float), np.zeros(len(sel), dtype=int), at_days,
|
|
304
|
+
config.tau_days, level, config.resistance_min_days, 0.0, math.inf,
|
|
305
|
+
)
|
|
306
|
+
for k, (when, tq) in enumerate(zip(at, at_days)):
|
|
307
|
+
e = est.iloc[k]
|
|
308
|
+
use = t <= tq
|
|
309
|
+
lam = np.exp(-(tq - t[use]) / config.tau_days) if config.tau_days > 0 else np.ones(int(use.sum()))
|
|
310
|
+
row = {
|
|
311
|
+
"time": when, "temp_band_c": float(centre), "headline": bool(centre == float(temp_ref_c)),
|
|
312
|
+
"resistance_ohm": math.nan, "resistance_ohm_low": math.nan, "resistance_ohm_high": math.nan,
|
|
313
|
+
"n_days": float(e["n_events"]), "n_steps": float((lam * n_steps[use]).sum()),
|
|
314
|
+
"status": _status(int(e["status"]), centre),
|
|
315
|
+
}
|
|
316
|
+
if int(e["status"]) == _core.TOO_FEW_EVENTS:
|
|
317
|
+
refresh = _refresh_status(sel, sel_dropped, tq, config.tau_days, config.resistance_min_days)
|
|
318
|
+
row["status"] = refresh or row["status"]
|
|
319
|
+
if int(e["status"]) == _core.OK:
|
|
320
|
+
r = float(e["value"])
|
|
321
|
+
half = _systematic_half(float(e["high"]) - r, r, level, config)
|
|
322
|
+
row.update(resistance_ohm=r, resistance_ohm_low=r - half, resistance_ohm_high=r + half)
|
|
323
|
+
rows.append(row)
|
|
324
|
+
out = pd.DataFrame(rows, columns=RESISTANCE_COLUMNS)
|
|
325
|
+
out.attrs.update(
|
|
326
|
+
config_hash=config_hash(config),
|
|
327
|
+
capacity_config_hash=config_hash(capacity_config),
|
|
328
|
+
sample_s=float(reduced.sample_s),
|
|
329
|
+
events=events,
|
|
330
|
+
**counts,
|
|
331
|
+
)
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _delta_half(grad, cov, k_t: float) -> float:
|
|
336
|
+
"""``k_t sqrt(grad' cov grad)``; NaN when that variance is negative (the sandwich is not
|
|
337
|
+
positive by construction)."""
|
|
338
|
+
var = 0.0
|
|
339
|
+
for r in range(2):
|
|
340
|
+
for s in range(2):
|
|
341
|
+
var += grad[r] * cov[r][s] * grad[s]
|
|
342
|
+
return k_t * math.sqrt(var) if var >= 0.0 else math.nan
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def resistance_growth(
|
|
346
|
+
frame: pd.DataFrame | None,
|
|
347
|
+
spec: PackSpec,
|
|
348
|
+
temp_ref_c: float = 25.0,
|
|
349
|
+
level: float = 0.90,
|
|
350
|
+
*,
|
|
351
|
+
config: RecordConfig | None = None,
|
|
352
|
+
capacity_config: CapacityConfig | None = None,
|
|
353
|
+
reduced=None,
|
|
354
|
+
at=None,
|
|
355
|
+
mask=None,
|
|
356
|
+
) -> dict:
|
|
357
|
+
"""The growth of the 1-second resistance over the whole record, and the remaining power capability.
|
|
358
|
+
|
|
359
|
+
Fit: ``R = k0 + k1 y`` over every kept day of the headline band (``day_band_events``:
|
|
360
|
+
band-days whose voltage was not refreshed with the current are left out) up to ``at`` (default: the
|
|
361
|
+
end of the record's last day), no forgetting, ``y`` in years since the first day with
|
|
362
|
+
a step in that band (the through-origin growth fit of ``besslib.soh._core``: ``b =
|
|
363
|
+
(k0 + k1 y) a``, the lag-1 sandwich without links, Student-t quantile). It needs days
|
|
364
|
+
spanning ``growth_min_span_years``.
|
|
365
|
+
|
|
366
|
+
``growth_percent_per_year = 100 k1 / k0``, the growth as a share of the start value.
|
|
367
|
+
``power_capability_share = k0 / (k0 + k1 y_at)``: the share of the start power
|
|
368
|
+
capability that remains at ``at``, *derived from the resistance over one sampling
|
|
369
|
+
interval, not measured* (``power_capability_label`` names the interval). Reason:
|
|
370
|
+
with an ohmic model the power a pack can give at a fixed voltage limit is ``V_lim
|
|
371
|
+
(OCV - V_lim) / R``, proportional to ``1 / R`` (Regulation (EU) 2023/1542, Annex IV
|
|
372
|
+
(4), defines the power fade by that power). Both bands are by
|
|
373
|
+
the delta method from the fit's covariance, with the t quantile; a negative
|
|
374
|
+
delta-method variance gives no band (status). A constant gain error of either sensor
|
|
375
|
+
scales ``k0`` and ``k1`` by the same factor and cancels in both ratios, so no
|
|
376
|
+
systematic term is added to them.
|
|
377
|
+
|
|
378
|
+
Both ratios are linearised around their denominators, ``k0`` and ``R_at = k0 + k1
|
|
379
|
+
y_at``. When the band of either reaches zero or below, the ratio has no finite
|
|
380
|
+
variance and its linear band means nothing (a share band below zero, a growth band of
|
|
381
|
+
thousands of per cent); the status is then *not possible*, with the reason, and no
|
|
382
|
+
ratio is given. This happens when a straight line is a poor model of the record, for
|
|
383
|
+
example when the resistance triples, or when the voltage signal changes its timing
|
|
384
|
+
within the record.
|
|
385
|
+
|
|
386
|
+
``power_capability_w = V_min (OCV - V_min) / R_at`` with ``V_min = spec.voltage_min_v``
|
|
387
|
+
(the pack's lower voltage limit), ``R_at = k0 + k1 y_at``, and the open-circuit
|
|
388
|
+
voltage of the last ``full`` rest before ``at`` (``rests.operating_rests``): the
|
|
389
|
+
discharge power at full charge at which the terminal voltage would reach the limit.
|
|
390
|
+
It has its own status; without ``spec.voltage_min_v`` it is not computed. Its band
|
|
391
|
+
holds the statistical part of ``R_at`` (t quantile), the open-circuit voltage's own
|
|
392
|
+
uncertainty (``ocv_sigma_v``, normal quantile) and the gain errors as a systematic
|
|
393
|
+
term: relative ``sqrt(sigma_I^2 + (sigma_V V_min / (OCV - V_min))^2)``, because a
|
|
394
|
+
voltage gain error scales the open-circuit voltage and the resistance alike.
|
|
395
|
+
|
|
396
|
+
Returns a dict: ``resistance_start_ohm`` (``k0``), ``resistance_at_ohm``,
|
|
397
|
+
``growth_percent_per_year`` with ``_low`` and ``_high``, ``power_capability_share``
|
|
398
|
+
with ``_low`` and ``_high``, ``power_capability_w`` with ``_low``, ``_high`` and
|
|
399
|
+
``power_capability_w_status``, ``power_capability_label``, ``temp_band_c``,
|
|
400
|
+
``first_day``, ``at``, ``n_days``, ``n_days_unrefreshed`` (band-days left out by the
|
|
401
|
+
voltage-refresh rule), ``span_years``, ``dof``, ``status``, ``sample_s``,
|
|
402
|
+
``config_hash``, ``capacity_config_hash``.
|
|
403
|
+
"""
|
|
404
|
+
config = config or RecordConfig()
|
|
405
|
+
capacity_config = capacity_config or CapacityConfig()
|
|
406
|
+
reduced = _reduced(frame, spec, reduced, capacity_config)
|
|
407
|
+
events, counts = day_band_events(reduced.steps, spec, config, temp_ref_c, mask)
|
|
408
|
+
sel = events[events["temp_band_c"] == float(temp_ref_c)]
|
|
409
|
+
sel_dropped = counts["dropped"][counts["dropped"]["temp_band_c"] == float(temp_ref_c)]
|
|
410
|
+
nan = math.nan
|
|
411
|
+
out = {
|
|
412
|
+
"resistance_start_ohm": nan, "resistance_at_ohm": nan,
|
|
413
|
+
"growth_percent_per_year": nan, "growth_percent_per_year_low": nan, "growth_percent_per_year_high": nan,
|
|
414
|
+
"power_capability_share": nan, "power_capability_share_low": nan, "power_capability_share_high": nan,
|
|
415
|
+
"power_capability_w": nan, "power_capability_w_low": nan, "power_capability_w_high": nan,
|
|
416
|
+
"power_capability_w_status": f"{_NOT}no growth fit",
|
|
417
|
+
"power_capability_label": power_label(float(reduced.sample_s)),
|
|
418
|
+
"temp_band_c": float(temp_ref_c), "first_day": pd.NaT, "at": pd.NaT,
|
|
419
|
+
"n_days": 0.0, "n_days_unrefreshed": 0, "span_years": 0.0, "dof": 0.0,
|
|
420
|
+
"status": _status(_core.TOO_FEW_EVENTS, float(temp_ref_c)),
|
|
421
|
+
"sample_s": float(reduced.sample_s),
|
|
422
|
+
"config_hash": config_hash(config), "capacity_config_hash": config_hash(capacity_config),
|
|
423
|
+
}
|
|
424
|
+
if at is None:
|
|
425
|
+
known = pd.DatetimeIndex(reduced.daily["day"]) if len(reduced.daily) else pd.DatetimeIndex([])
|
|
426
|
+
if len(known) == 0:
|
|
427
|
+
raise ValueError("no data to estimate from")
|
|
428
|
+
at = known.max() + pd.Timedelta(days=1)
|
|
429
|
+
at = pd.Timestamp(at)
|
|
430
|
+
out["at"] = at
|
|
431
|
+
tq = float(days([at])[0])
|
|
432
|
+
sel = sel[sel["t_days"] <= tq]
|
|
433
|
+
sel_dropped = sel_dropped[sel_dropped["t_days"] <= tq]
|
|
434
|
+
out["n_days_unrefreshed"] = int(len(sel_dropped))
|
|
435
|
+
refresh = _refresh_status(sel, sel_dropped, tq, 0.0, config.resistance_min_days)
|
|
436
|
+
if len(sel) == 0:
|
|
437
|
+
out["status"] = refresh or out["status"]
|
|
438
|
+
return out
|
|
439
|
+
t = sel["t_days"].to_numpy(float)
|
|
440
|
+
t0 = float(t[0])
|
|
441
|
+
out["first_day"] = pd.Timestamp(sel["day"].iloc[0])
|
|
442
|
+
fit = _ratio.estimate_growth(
|
|
443
|
+
t, sel["a"].to_numpy(float), sel["b"].to_numpy(float), np.zeros(len(sel), dtype=int), t0, tq, level,
|
|
444
|
+
config.resistance_min_days, config.growth_min_span_years, 0.0, math.inf,
|
|
445
|
+
)
|
|
446
|
+
code = int(fit["status"])
|
|
447
|
+
out.update(n_days=float(fit["n_events"]), span_years=float(fit["span_years"]), dof=float(fit["dof"]),
|
|
448
|
+
status=_status(code, float(temp_ref_c)))
|
|
449
|
+
if code == _core.TOO_FEW_EVENTS:
|
|
450
|
+
out["status"] = refresh or out["status"]
|
|
451
|
+
if code != _core.OK:
|
|
452
|
+
return out
|
|
453
|
+
k0, k1, cov = float(fit["k0"]), float(fit["k1"]), fit["cov"]
|
|
454
|
+
y = (tq - t0) / 365.25
|
|
455
|
+
r_at = k0 + k1 * y
|
|
456
|
+
k_t = _core.t_quantile(_z(level), float(fit["dof"]))
|
|
457
|
+
growth = k1 / k0
|
|
458
|
+
growth_half = _delta_half((-k1 / k0**2, 1.0 / k0), cov, k_t)
|
|
459
|
+
share = k0 / r_at
|
|
460
|
+
share_half = _delta_half((k1 * y / r_at**2, -k0 * y / r_at**2), cov, k_t)
|
|
461
|
+
k0_half = _delta_half((1.0, 0.0), cov, k_t)
|
|
462
|
+
r_at_half = _delta_half((1.0, y), cov, k_t)
|
|
463
|
+
if not (k0 - k0_half > 0.0 and r_at - r_at_half > 0.0):
|
|
464
|
+
out["status"] = (f"{_NOT}the growth fit near {float(temp_ref_c):g} °C does not separate the resistance "
|
|
465
|
+
"at the start or at the date from zero")
|
|
466
|
+
return out
|
|
467
|
+
if math.isnan(growth_half) or math.isnan(share_half):
|
|
468
|
+
out["status"] = _core.STATUS_TEXT[_core.NO_BAND]
|
|
469
|
+
return out
|
|
470
|
+
out.update(
|
|
471
|
+
resistance_start_ohm=k0,
|
|
472
|
+
resistance_at_ohm=r_at,
|
|
473
|
+
growth_percent_per_year=100.0 * growth,
|
|
474
|
+
growth_percent_per_year_low=100.0 * (growth - growth_half),
|
|
475
|
+
growth_percent_per_year_high=100.0 * (growth + growth_half),
|
|
476
|
+
power_capability_share=share,
|
|
477
|
+
power_capability_share_low=share - share_half,
|
|
478
|
+
power_capability_share_high=share + share_half,
|
|
479
|
+
)
|
|
480
|
+
out.update(_power_w(reduced, spec, capacity_config, config, mask, at, r_at, (1.0, y), cov, k_t, level))
|
|
481
|
+
return out
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _power_w(reduced, spec, capacity_config, config, mask, at, r_at, grad, cov, k_t, level) -> dict:
|
|
485
|
+
"""``power_capability_w`` with its band and status (see ``resistance_growth``)."""
|
|
486
|
+
nan = math.nan
|
|
487
|
+
out = {"power_capability_w": nan, "power_capability_w_low": nan, "power_capability_w_high": nan}
|
|
488
|
+
v_min = spec.voltage_min_v
|
|
489
|
+
if v_min is None:
|
|
490
|
+
out["power_capability_w_status"] = f"{_NOT}voltage limits not given"
|
|
491
|
+
return out
|
|
492
|
+
rests = operating_rests(reduced.rests, spec, capacity_config, mask)
|
|
493
|
+
full = rests[(rests["kind"] == "full") & (rests["start"] <= at) & np.isfinite(rests["ocv_v"].to_numpy(float))]
|
|
494
|
+
if len(full) == 0:
|
|
495
|
+
out["power_capability_w_status"] = f"{_NOT}no full rest before the date"
|
|
496
|
+
return out
|
|
497
|
+
last = full.sort_values("start").iloc[-1]
|
|
498
|
+
ocv = float(last["ocv_v"])
|
|
499
|
+
ocv_sigma = float(last["ocv_sigma_v"]) if np.isfinite(last["ocv_sigma_v"]) else 0.0
|
|
500
|
+
if not ocv > v_min:
|
|
501
|
+
out["power_capability_w_status"] = f"{_NOT}the open-circuit voltage at full charge is not above the lower limit"
|
|
502
|
+
return out
|
|
503
|
+
power = v_min * (ocv - v_min) / r_at
|
|
504
|
+
r_half = _delta_half(grad, cov, k_t)
|
|
505
|
+
if math.isnan(r_half):
|
|
506
|
+
out["power_capability_w_status"] = _core.STATUS_TEXT[_core.NO_BAND]
|
|
507
|
+
return out
|
|
508
|
+
z = _z(level)
|
|
509
|
+
sigma_i = config.current_accuracy / math.sqrt(3.0)
|
|
510
|
+
sigma_v = config.voltage_accuracy / math.sqrt(3.0)
|
|
511
|
+
rel_sys = math.hypot(sigma_i, sigma_v * v_min / (ocv - v_min))
|
|
512
|
+
half = math.sqrt((power / r_at * r_half) ** 2 + (z * v_min / r_at * ocv_sigma) ** 2 + (z * rel_sys * power) ** 2)
|
|
513
|
+
out.update(
|
|
514
|
+
power_capability_w=power,
|
|
515
|
+
power_capability_w_low=power - half,
|
|
516
|
+
power_capability_w_high=power + half,
|
|
517
|
+
power_capability_w_status=_OK,
|
|
518
|
+
)
|
|
519
|
+
return out
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def resistance_of_steps(steps: pd.DataFrame, spec: PackSpec, config: RecordConfig | None = None) -> dict:
|
|
523
|
+
"""The same estimator on any short window: ``R = sum dI dV / sum dI^2`` over the qualifying rows of ``steps``.
|
|
524
|
+
|
|
525
|
+
For a window too short for days, such as the first minute of a capacity test. Each
|
|
526
|
+
step is one event of the through-origin fit, so with two steps or more the
|
|
527
|
+
statistical band is the heteroskedasticity-consistent sandwich over the steps, with
|
|
528
|
+
the t quantile on ``n_steps - 1`` degrees of freedom; one step gives no scatter, and
|
|
529
|
+
the band then holds the systematic term only (``band`` says which). The
|
|
530
|
+
voltage-refresh rule of ``day_band_events`` applies to the window as to a day: when
|
|
531
|
+
more than ``config.unrefreshed_max_share`` of its steps show no voltage change, no
|
|
532
|
+
value is given. Returns ``resistance_ohm`` with ``_low`` and ``_high``, ``n_steps``,
|
|
533
|
+
``n_unrefreshed``, ``band`` (``"statistical and systematic"`` or ``"systematic only:
|
|
534
|
+
one step"``) and ``status``.
|
|
535
|
+
"""
|
|
536
|
+
config = config or RecordConfig()
|
|
537
|
+
use = qualifying_steps(steps, spec, config)
|
|
538
|
+
d_i = use["d_current_a"].to_numpy(float)
|
|
539
|
+
d_v = use["d_voltage_v"].to_numpy(float)
|
|
540
|
+
n = int(len(use))
|
|
541
|
+
nan = math.nan
|
|
542
|
+
n_unref = int((d_v == 0.0).sum())
|
|
543
|
+
out = {"resistance_ohm": nan, "resistance_ohm_low": nan, "resistance_ohm_high": nan, "n_steps": n,
|
|
544
|
+
"n_unrefreshed": n_unref, "band": ""}
|
|
545
|
+
if n == 0:
|
|
546
|
+
out["status"] = f"{_NOT}no qualifying current step"
|
|
547
|
+
return out
|
|
548
|
+
if n_unref > config.unrefreshed_max_share * n:
|
|
549
|
+
out["status"] = unrefreshed_text(n_unref / n)
|
|
550
|
+
return out
|
|
551
|
+
a = d_i * d_i
|
|
552
|
+
b = d_i * d_v
|
|
553
|
+
r = float(b.sum() / a.sum())
|
|
554
|
+
if not r > 0.0:
|
|
555
|
+
out["status"] = f"{_NOT}the current steps give a resistance at or below zero"
|
|
556
|
+
return out
|
|
557
|
+
stat_half = 0.0
|
|
558
|
+
out["band"] = "systematic only: one step"
|
|
559
|
+
if n >= 2:
|
|
560
|
+
# Ordered placeholder times: the fit has no forgetting here, so only the order matters.
|
|
561
|
+
e = _ratio.estimate_ratio(np.arange(n, dtype=float), a, b, np.zeros(n, dtype=int), [float(n)], 0.0,
|
|
562
|
+
config.level, 2.0, 0.0, math.inf).iloc[0]
|
|
563
|
+
if int(e["status"]) != _core.OK:
|
|
564
|
+
out["status"] = _status(int(e["status"]), nan)
|
|
565
|
+
return out
|
|
566
|
+
stat_half = float(e["high"]) - r
|
|
567
|
+
out["band"] = "statistical and systematic"
|
|
568
|
+
half = _systematic_half(stat_half, r, config.level, config)
|
|
569
|
+
out.update(resistance_ohm=r, resistance_ohm_low=r - half, resistance_ohm_high=r + half, status=_OK)
|
|
570
|
+
return out
|