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/_ratio.py ADDED
@@ -0,0 +1,277 @@
1
+ """The batch twin of the through-origin ratio fit in ``besslib.soh._core``.
2
+
3
+ ``estimate_ratio`` and ``estimate_growth`` build the core's state from sums in one step
4
+ (numpy) and solve it with ``_core.ratio_solve``; ``run_ratio_core`` feeds the core one
5
+ event at a time (the form a BMS or the C port uses). The tests keep the two paths equal.
6
+
7
+ An event is two sums ``(a, b)`` with ``a > 0``; the estimate is ``k = sum lambda b /
8
+ sum lambda a`` with ``lambda = exp(-age / tau_days)``. The band is the lag-1 sandwich on
9
+ the scores ``lambda (b - k a)`` (Newey and West, Econometrica 55, 703 (1987),
10
+ doi:10.2307/1913610); see ``_core`` for the conventions, and for where they depart
11
+ from the capacity fit. Events
12
+ with ``a <= 0`` or a non-finite sum are refused by both paths in the same way.
13
+
14
+ ``estimate_loops`` and ``run_loop_core`` are the same two paths for the loop band
15
+ (``_core.loop_solve``): the same value, with the band of the ratio over the loops in
16
+ memory from the error of the state of charge at their end rests, estimated as the mean
17
+ lag-2 product of the loop scores minus the mean lag-1 product (see ``_core``).
18
+
19
+ Time axis: days since 2000-01-01 (``besslib.soh.capacity.days``). An event counts at a
20
+ query time if its ``t_days`` is at or before it. Events must be in time order.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from statistics import NormalDist
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from besslib.soh import _core
31
+
32
+
33
+ def _z(level: float) -> float:
34
+ return NormalDist().inv_cdf(0.5 + level / 2.0)
35
+
36
+
37
+ def _events(t_days, a, b, linked):
38
+ """The accepted events and their effective links, as the core sees them."""
39
+ t = np.asarray(t_days, dtype=float)
40
+ a = np.asarray(a, dtype=float)
41
+ b = np.asarray(b, dtype=float)
42
+ linked = np.asarray(linked, dtype=int)
43
+ if not (len(t) == len(a) == len(b) == len(linked)):
44
+ raise ValueError("t_days, a, b and linked must have the same length")
45
+ if len(t) and (not np.isfinite(t).all() or (np.diff(t) < 0).any()):
46
+ raise ValueError("t_days must be finite and in time order")
47
+ kept = (a > 0) & np.isfinite(a) & np.isfinite(b)
48
+ eff = (linked != 0) & kept & np.r_[False, kept[:-1]]
49
+ return t[kept], a[kept], b[kept], eff[kept]
50
+
51
+
52
+ def _state_at(p: int, tau_days: float, t0_days: float, events, at: float) -> _core.Ratio:
53
+ """The core state at ``at``, built from sums in one step (the batch path)."""
54
+ t, a, b, eff = events
55
+ state = _core.Ratio(p, tau_days if p == 1 else 0.0, t0_days)
56
+ state.t_last = at
57
+ if len(t) == 0:
58
+ return state
59
+ state.k_ref = float(b[0] / a[0])
60
+ state.has_ref = 1
61
+ sel = t <= at
62
+ t, a, b, eff = t[sel], a[sel], b[sel], eff[sel]
63
+ if len(t) == 0:
64
+ return state
65
+ tau = state.tau_days
66
+ lam = np.exp(-(at - t) / tau) if tau > 0 else np.ones_like(t)
67
+ y = (t - t0_days) / 365.25
68
+ u = np.column_stack([np.ones_like(t), y])[:, :p]
69
+ z = np.column_stack([u * a[:, None], b - state.k_ref * a])
70
+ amat = np.einsum("n,nr,ns->rs", lam * a, u, u)
71
+ h = np.einsum("n,nr->r", lam * z[:, p], u)
72
+ s4 = np.einsum("n,nr,ns,ni,nj->rsij", lam * lam, u, u, z, z)
73
+ cur = np.flatnonzero(eff)
74
+ prev = cur - 1
75
+ c = lam[cur] * lam[prev]
76
+ uu = u[cur][:, :, None] * u[prev][:, None, :] + u[prev][:, :, None] * u[cur][:, None, :]
77
+ s4l = np.einsum("n,nrs,ni,nj->rsij", c, uu, z[cur], z[prev])
78
+ for r in range(p):
79
+ state.h[r] = float(h[r])
80
+ for s in range(p):
81
+ state.a[2 * r + s] = float(amat[r, s])
82
+ for i in range(p + 1):
83
+ for j in range(p + 1):
84
+ state.s4[((r * 2 + s) * 3 + i) * 3 + j] = float(s4[r, s, i, j])
85
+ state.s4l[((r * 2 + s) * 3 + i) * 3 + j] = float(s4l[r, s, i, j])
86
+ state.m = float(lam.sum())
87
+ state.m_lag = float(np.sqrt(c).sum())
88
+ state.m2 = float((lam * lam).sum())
89
+ state.m2_lag = float(c.sum())
90
+ follows = eff[cur - 1] if len(cur) else np.zeros(0, dtype=bool) # the link before this one exists too
91
+ state.m2_ll = float(c[follows].sum())
92
+ state.n = int(len(t))
93
+ state.y_min = float(y.min())
94
+ state.y_max = float(y.max())
95
+ return state
96
+
97
+
98
+ def _row(est: _core.RatioEstimate) -> dict:
99
+ return {
100
+ "value": est.theta[0] if est.status == _core.OK else np.nan,
101
+ "sigma": est.sigma[0] if est.status == _core.OK else np.nan,
102
+ "low": est.low,
103
+ "high": est.high,
104
+ "n_events": est.m,
105
+ "n_links": est.m_lag,
106
+ "dof": est.dof,
107
+ "rho": est.rho,
108
+ "status": int(est.status),
109
+ }
110
+
111
+
112
+ def estimate_ratio(t_days, a, b, linked, at_days, tau_days, level, min_events, lower, upper) -> pd.DataFrame:
113
+ """``k = sum lambda b / sum lambda a`` with its statistical band at each time in ``at_days``.
114
+
115
+ One row per query, in the order given: ``value``, ``sigma``, ``low``, ``high``
116
+ (statistical band only), ``n_events`` and ``n_links`` (decayed), ``dof``, ``rho``,
117
+ ``status`` (a ``_core`` code). ``value`` and ``sigma`` are NaN unless the status is OK.
118
+ """
119
+ events = _events(t_days, a, b, linked)
120
+ z = _z(level)
121
+ rows = []
122
+ for at in np.asarray(at_days, dtype=float):
123
+ state = _state_at(1, tau_days, 0.0, events, float(at))
124
+ rows.append(_row(_core.ratio_solve(state, float(at), z, min_events, 0.0, lower, upper)))
125
+ return pd.DataFrame(rows)
126
+
127
+
128
+ def run_ratio_core(t_days, a, b, linked, at_days, tau_days, level, min_events, lower, upper) -> pd.DataFrame:
129
+ """The same as ``estimate_ratio``, by one ``_core.ratio_update`` per event (the step-by-step path)."""
130
+ t = np.asarray(t_days, dtype=float)
131
+ a = np.asarray(a, dtype=float)
132
+ b = np.asarray(b, dtype=float)
133
+ linked = np.asarray(linked, dtype=int)
134
+ _events(t, a, b, linked) # the same input checks as the batch path
135
+ at = np.asarray(at_days, dtype=float)
136
+ z = _z(level)
137
+ state = _core.ratio_state(tau_days)
138
+ rows = [None] * len(at)
139
+ k = 0
140
+ for j in np.argsort(at, kind="stable"):
141
+ tq = float(at[j])
142
+ while k < len(t) and t[k] <= tq:
143
+ _core.ratio_update(state, float(t[k]), float(a[k]), float(b[k]), int(linked[k]))
144
+ k += 1
145
+ rows[j] = _row(_core.ratio_solve(state, tq, z, min_events, 0.0, lower, upper))
146
+ return pd.DataFrame(rows)
147
+
148
+
149
+ def estimate_growth(t_days, a, b, linked, t0_days, at_day, level, min_events, min_span_years, lower, upper) -> dict:
150
+ """The growth fit ``b = (k0 + k1 y) a`` over every event up to ``at_day``, no forgetting.
151
+
152
+ ``y`` is in years since ``t0_days``. Returns ``k0``, ``k1``, ``cov`` (2 x 2 list),
153
+ ``sigma0``, ``sigma1``, ``dof``, ``n_events``, ``n_links``, ``span_years``, ``rho``,
154
+ ``status`` (a ``_core`` code). The parameters are NaN unless the status is OK.
155
+ """
156
+ events = _events(t_days, a, b, linked)
157
+ state = _state_at(2, 0.0, float(t0_days), events, float(at_day))
158
+ est = _core.ratio_solve(state, float(at_day), _z(level), min_events, min_span_years, lower, upper)
159
+ return growth_dict(est)
160
+
161
+
162
+ def growth_dict(est: _core.RatioEstimate) -> dict:
163
+ """The output dict of ``estimate_growth`` from a core estimate."""
164
+ ok = est.status == _core.OK
165
+ nan = float("nan")
166
+ return {
167
+ "k0": est.theta[0] if ok else nan,
168
+ "k1": est.theta[1] if ok else nan,
169
+ "cov": [[est.cov[0], est.cov[1]], [est.cov[2], est.cov[3]]] if ok else [[nan, nan], [nan, nan]],
170
+ "sigma0": est.sigma[0] if ok else nan,
171
+ "sigma1": est.sigma[1] if ok else nan,
172
+ "dof": est.dof,
173
+ "n_events": est.m,
174
+ "n_links": est.m_lag,
175
+ "span_years": est.span_years,
176
+ "rho": est.rho,
177
+ "status": int(est.status),
178
+ }
179
+
180
+
181
+ # --- the loop band ---------------------------------------------------------------------
182
+
183
+
184
+ def _loop_state_at(tau_days: float, events, at: float) -> _core.Ratio:
185
+ """The core state at ``at`` with the loop band's sums, built in one step (the batch path)."""
186
+ state = _state_at(1, tau_days, 0.0, events, at)
187
+ t, a, b, eff = events
188
+ sel = t <= at
189
+ t, a, b, eff = t[sel], a[sel], b[sel], eff[sel]
190
+ n = len(t)
191
+ if n == 0:
192
+ return state
193
+ lam = np.exp(-(at - t) / tau_days) if tau_days > 0 else np.ones_like(t)
194
+ # Each rest's coefficient: an end rest -lambda_k, plus lambda_(k+1) when the next loop
195
+ # starts there; the start rest of an unlinked loop +lambda_k.
196
+ nxt = np.r_[lam[1:] * eff[1:], 0.0]
197
+ c2 = np.sum((nxt - lam) ** 2) + np.sum(lam[~eff] ** 2)
198
+ # Per event: the weight of its link (w1) and of its 2-link (w2), 0 where there is none.
199
+ two = np.r_[False, eff[1:] & eff[:-1]]
200
+ w1 = np.zeros(n)
201
+ w2 = np.zeros(n)
202
+ w1[1:] = np.where(eff[1:], lam[1:] * lam[:-1], 0.0)
203
+ w2[2:] = np.where(two[2:], lam[2:] * lam[:-2], 0.0)
204
+
205
+ def back(x, d): # x[k - d], 0 before the first event
206
+ return np.r_[np.zeros(min(d, n)), x[: max(n - d, 0)]]
207
+
208
+ z = np.column_stack([a, b - state.k_ref * a])
209
+ k2 = np.flatnonzero(two)
210
+ s4l2 = np.einsum("n,ni,nj->ij", w2[k2], z[k2], z[k2 - 2])
211
+ state.c2 = float(c2)
212
+ state.w4 = float(np.sum(w1 * w1))
213
+ state.w4l = float(np.sum(w1 * back(w1, 1)))
214
+ state.s11_2 = float(np.sum((w1 * back(w1, 2))[two])) # links k and k - 2 with k - 1 linked between them
215
+ state.m2_l2 = float(np.sum(w2))
216
+ state.s22_0 = float(np.sum(w2 * w2))
217
+ state.s22_1 = float(np.sum(w2 * back(w2, 1)))
218
+ state.s22_2 = float(np.sum(w2 * back(w2, 2)))
219
+ state.x0 = float(np.sum(w1 * w2))
220
+ state.xm1 = float(np.sum(back(w1, 1) * w2))
221
+ state.xp1 = float(np.sum(w1 * back(w2, 1)))
222
+ state.xm2 = float(np.sum(back(w1, 2) * w2))
223
+ for i in range(2):
224
+ for j in range(2):
225
+ state.s4l2[i * 3 + j] = float(s4l2[i, j])
226
+ # The history the next event would use (0 across a break), as the step-by-step path keeps it.
227
+ run = eff[-1]
228
+ state.prev_lw = float(w1[-1])
229
+ state.prev_lw2 = float(w1[-2]) if run and n > 1 else 0.0
230
+ state.prev_w2 = float(w2[-1])
231
+ state.prev_w2b = float(w2[-2]) if run and n > 1 else 0.0
232
+ return state
233
+
234
+
235
+ def _loop_row(est: _core.RatioEstimate) -> dict:
236
+ row = _row(est)
237
+ row["rest_error"] = est.rest_error if est.status == _core.OK else np.nan
238
+ return row
239
+
240
+
241
+ def estimate_loops(t_days, a, b, linked, at_days, tau_days, level, min_events, lower, upper) -> pd.DataFrame:
242
+ """``k = sum lambda b / sum lambda a`` with the loop band at each time in ``at_days``.
243
+
244
+ The band holds the ratio over the loops in memory had each closed exactly, from the
245
+ error of the stored energy at their end rests (``_core.loop_solve``). One row per
246
+ query, in the order given, with the columns of ``estimate_ratio`` and ``rest_error``
247
+ (the standard deviation of that error, in the units of ``b``); ``value``, ``sigma``
248
+ and ``rest_error`` are NaN unless the status is OK.
249
+ """
250
+ events = _events(t_days, a, b, linked)
251
+ z = _z(level)
252
+ rows = []
253
+ for at in np.asarray(at_days, dtype=float):
254
+ state = _loop_state_at(tau_days, events, float(at))
255
+ rows.append(_loop_row(_core.loop_solve(state, float(at), z, min_events, lower, upper)))
256
+ return pd.DataFrame(rows)
257
+
258
+
259
+ def run_loop_core(t_days, a, b, linked, at_days, tau_days, level, min_events, lower, upper) -> pd.DataFrame:
260
+ """The same as ``estimate_loops``, by one ``_core.ratio_update`` per event, then ``_core.loop_solve``."""
261
+ t = np.asarray(t_days, dtype=float)
262
+ a = np.asarray(a, dtype=float)
263
+ b = np.asarray(b, dtype=float)
264
+ linked = np.asarray(linked, dtype=int)
265
+ _events(t, a, b, linked) # the same input checks as the batch path
266
+ at = np.asarray(at_days, dtype=float)
267
+ z = _z(level)
268
+ state = _core.ratio_state(tau_days)
269
+ rows = [None] * len(at)
270
+ k = 0
271
+ for j in np.argsort(at, kind="stable"):
272
+ tq = float(at[j])
273
+ while k < len(t) and t[k] <= tq:
274
+ _core.ratio_update(state, float(t[k]), float(a[k]), float(b[k]), int(linked[k]))
275
+ k += 1
276
+ rows[j] = _loop_row(_core.loop_solve(state, tq, z, min_events, lower, upper))
277
+ return pd.DataFrame(rows)
@@ -0,0 +1,332 @@
1
+ """Usable capacity with a band, and its fade rate, from pairs of rests at full and empty.
2
+
3
+ Method: rest-anchored coulomb counting as in Figgener et al., Nature Energy 9, 1438
4
+ (2024), doi:10.1038/s41560-024-01620-9, with besslib's own estimator: capacity and the
5
+ offset current are fitted together over many pairs (``besslib.soh._core``), so each
6
+ estimate carries a band and a count of the pairs it rests on.
7
+
8
+ The estimate at a time uses only pairs that end before it (causal, as in a BMS). With
9
+ memory time ``tau_days`` it lags a steady fade by about ``tau_days``. It measures the
10
+ capacity between the system's own end of charge and end of discharge under its normal
11
+ load. A field capacity test at full power may read lower; besslib does not correct for
12
+ that.
13
+
14
+ Two paths give the same numbers: ``run_core`` feeds the core one pair at a time (the
15
+ form a BMS or the C port uses); ``capacity_state_at`` builds the same state from sums
16
+ in one step (the fast path). The tests keep them equal.
17
+
18
+ The band is a band on the exponentially weighted capacity the estimate measures. It
19
+ does not include the lag of a fading capacity, nor a systematic offset of the usable
20
+ capacity (for example a field test at a different current).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from statistics import NormalDist
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from besslib.frames import PackSpec
31
+ from besslib.soh import _core
32
+ from besslib.soh.config import CapacityConfig, config_hash
33
+ from besslib.soh.rests import find_rests, rest_chain, rest_pairs
34
+ from besslib.soh.rests import levels_from as rest_levels_from
35
+
36
+ _EPOCH = pd.Timestamp("2000-01-01")
37
+
38
+
39
+ def days(times) -> np.ndarray:
40
+ """Days since 2000-01-01 (the core's time axis)."""
41
+ return ((pd.DatetimeIndex(times) - _EPOCH).total_seconds() / 86400.0).to_numpy(dtype=float)
42
+
43
+
44
+ def _z(level: float) -> float:
45
+ return NormalDist().inv_cdf(0.5 + level / 2.0)
46
+
47
+
48
+ def _columns(pairs: pd.DataFrame):
49
+ return (
50
+ days(pairs["t_end"]),
51
+ pairs["x"].to_numpy(float),
52
+ pairs["dt_days"].to_numpy(float),
53
+ pairs["q_ah"].to_numpy(float),
54
+ pairs["sigma_q_ah"].to_numpy(float),
55
+ pairs["sigma_x"].to_numpy(float),
56
+ pairs["linked"].to_numpy(int),
57
+ )
58
+
59
+
60
+ def capacity_state_at(pairs: pd.DataFrame, spec: PackSpec, config: CapacityConfig, t_days: float) -> _core.Fit:
61
+ """The core state at ``t_days``, built from sums in one step (the batch path)."""
62
+ t, x, dt, q, sq, sx, linked = _columns(pairs)
63
+ keep = t <= t_days
64
+ t, x, dt, q, sq, sx, linked = t[keep], x[keep], dt[keep], q[keep], sq[keep], sx[keep], linked[keep]
65
+ state = _core.capacity_state(spec.nominal_capacity_ah, config.tau_days)
66
+ state.t_last = t_days
67
+ if len(t) == 0:
68
+ return state
69
+ lam = np.exp(-(t_days - t) / config.tau_days) if config.tau_days > 0 else np.ones_like(t)
70
+ w = 1.0 / (sq * sq + (spec.nominal_capacity_ah * sx) ** 2)
71
+ rows = np.column_stack([x, dt])
72
+ zs = np.column_stack([x, dt, q - spec.nominal_capacity_ah * x])
73
+ lw = lam * w
74
+ a = (lw[:, None, None] * rows[:, :, None] * rows[:, None, :]).sum(axis=0)
75
+ h = (lw[:, None] * rows * q[:, None]).sum(axis=0)
76
+ s4 = np.einsum("n,nr,ns,ni,nj->rsij", lam * w * w, rows, rows, zs, zs)
77
+ lag = np.r_[False, linked[1:] == 1]
78
+ cur_i = np.flatnonzero(lag)
79
+ prev_i = cur_i - 1
80
+ g = np.exp(-(t[cur_i] - t[prev_i]) / (2.0 * config.tau_days)) if config.tau_days > 0 else np.ones(len(cur_i))
81
+ lg = lam[cur_i] * g
82
+ lv = lg * np.sqrt(w[cur_i] * w[prev_i])
83
+ cur, prev = rows[cur_i], rows[prev_i]
84
+ qc, qp = q[cur_i], q[prev_i]
85
+ lmat = (lv[:, None, None] * cur[:, :, None] * prev[:, None, :]).sum(axis=0)
86
+ u = lg * w[cur_i] * w[prev_i]
87
+ aa = cur[:, :, None] * prev[:, None, :] + prev[:, :, None] * cur[:, None, :]
88
+ s4l = np.einsum("n,nrs,ni,nj->rsij", u, aa, zs[cur_i], zs[prev_i])
89
+ for r in range(2):
90
+ for k in range(2):
91
+ state.a[3 * r + k] = float(a[r, k])
92
+ state.l[3 * r + k] = float(lmat[r, k])
93
+ for i in range(3):
94
+ for j in range(3):
95
+ state.s4[((r * 3 + k) * 4 + i) * 4 + j] = float(s4[r, k, i, j])
96
+ state.s4l[((r * 3 + k) * 4 + i) * 4 + j] = float(s4l[r, k, i, j])
97
+ state.h[r] = float(h[r])
98
+ state.ly[r] = float((lv * qc * prev[:, r]).sum())
99
+ state.yl[r] = float((lv * cur[:, r] * qp).sum())
100
+ state.c = float((lw * q * q).sum())
101
+ state.yy1 = float((lv * qc * qp).sum())
102
+ state.m = float(lam.sum())
103
+ state.m_lag = float(lg.sum())
104
+ cross = x != 0
105
+ state.m_cross = float(lam[cross].sum())
106
+ state.m_same = float(lam[~cross].sum())
107
+ state.t_last_cross = float(t[cross].max()) if cross.any() else _core._NEVER
108
+ state.n = int(len(t))
109
+ return state
110
+
111
+
112
+ def run_core(pairs: pd.DataFrame, spec: PackSpec, config: CapacityConfig, at) -> list:
113
+ """The step-by-step path: one ``_core.update`` per pair, ``_core.solve`` at each time in ``at``."""
114
+ t, x, dt, q, sq, sx, linked = _columns(pairs)
115
+ queries = sorted(zip(days(at), range(len(at))))
116
+ z = _z(config.level)
117
+ state = _core.capacity_state(spec.nominal_capacity_ah, config.tau_days)
118
+ out = [None] * len(queries)
119
+ k = 0
120
+ for tq, j in queries:
121
+ while k < len(t) and t[k] <= tq:
122
+ _core.update(state, float(t[k]), float(x[k]), float(dt[k]), float(q[k]), float(sq[k]), float(sx[k]), int(linked[k]))
123
+ k += 1
124
+ out[j] = _solve(state, float(tq), z, config)
125
+ return out
126
+
127
+
128
+ def _solve(state: _core.Fit, t: float, z: float, config: CapacityConfig) -> _core.Estimate:
129
+ return _core.solve(state, t, z, config.gain_error, config.min_cross, config.min_same, config.fade_min_span_years)
130
+
131
+
132
+ def estimate_capacity(
133
+ frame: pd.DataFrame | None,
134
+ spec: PackSpec,
135
+ rests: pd.DataFrame | None = None,
136
+ config: CapacityConfig | None = None,
137
+ at=None,
138
+ mask=None,
139
+ pairs: pd.DataFrame | None = None,
140
+ levels_from: pd.Timestamp | None = None,
141
+ ) -> pd.DataFrame:
142
+ """Usable capacity with its band at each time in ``at``.
143
+
144
+ Parameters
145
+ ----------
146
+ frame
147
+ Operating data in the besslib frame format; may be ``None`` when ``rests`` or
148
+ ``pairs`` are given.
149
+ spec
150
+ The pack. ``soh_capacity`` is the capacity divided by
151
+ ``spec.reference_capacity_ah``, which is printed in every row.
152
+ rests, pairs
153
+ Precomputed outputs of ``find_rests`` or ``rest_pairs``.
154
+ config
155
+ Settings; the defaults are the frozen ones.
156
+ at
157
+ Times for the estimate. Default: the end of every calendar month in the data.
158
+ mask
159
+ Intervals ``(start, end)`` whose rests are left out and across which no two rests
160
+ are paired.
161
+ levels_from
162
+ The first time at which the full and empty levels exist (``rests.levels_from``).
163
+ Taken from ``rests`` (or ``frame``) when they are given; with ``pairs`` alone it
164
+ must be passed to be known. Before it, the status says that the record has not
165
+ enough history yet to set the levels.
166
+
167
+ Returns
168
+ -------
169
+ DataFrame, one row per time: ``capacity_ah``, ``capacity_ah_low``, ``capacity_ah_high``,
170
+ ``soh_capacity`` (with ``_low`` and ``_high``), ``reference_capacity_ah``,
171
+ ``offset_current_a`` (negative = the battery loses charge the meter does not see),
172
+ ``n_pairs``, ``n_full_empty``, ``n_same_kind`` (pairs in memory, decayed), ``birge``
173
+ (reduced chi-square: below 1 when the pairs scatter less than the settings'
174
+ ``sigma_q_rel`` and ``sigma_soc_edge`` assume), ``rho`` (lag-1 correlation of the
175
+ weighted residuals), ``status``. Both diagnostics are reported only; the band comes
176
+ from the residuals themselves (``besslib.soh._core``). ``attrs`` hold the pairs and
177
+ the configuration hash.
178
+ """
179
+ config = config or CapacityConfig()
180
+ if pairs is None:
181
+ if rests is None:
182
+ if frame is None:
183
+ raise ValueError("give a frame, rests or pairs")
184
+ rests = find_rests(frame, spec, config)
185
+ pairs = rest_pairs(rest_chain(rests, spec, config, mask=mask), config)
186
+ if levels_from is None and rests is not None:
187
+ levels_from = rest_levels_from(rests, config)
188
+ ready = float(days([levels_from])[0]) if levels_from is not None and pd.notna(levels_from) else -np.inf
189
+ if at is None:
190
+ times = pairs["t_end"] if len(pairs) else (frame.index if frame is not None else [])
191
+ if len(times) == 0:
192
+ raise ValueError("no data to estimate from")
193
+ at = pd.date_range(pd.Timestamp(min(times)).normalize(), pd.Timestamp(max(times)), freq="ME")
194
+ at = pd.DatetimeIndex(at)
195
+ z = _z(config.level)
196
+ rows = []
197
+ for t in days(at):
198
+ if t < ready:
199
+ est = _core.Estimate()
200
+ est.status = _core.NO_LEVELS
201
+ else:
202
+ est = _solve(capacity_state_at(pairs, spec, config, float(t)), float(t), z, config)
203
+ rows.append(estimate_row(est, spec))
204
+ out = pd.DataFrame(rows, index=at)
205
+ out.index.name = "time"
206
+ out.attrs["pairs"] = pairs
207
+ out.attrs["config_hash"] = config_hash(config)
208
+ return out
209
+
210
+
211
+ def estimate_row(est: _core.Estimate, spec: PackSpec) -> dict:
212
+ """One output row from a core estimate."""
213
+ ref = spec.reference_capacity_ah
214
+ cap = est.theta[0]
215
+ return {
216
+ "capacity_ah": cap,
217
+ "capacity_ah_low": est.low,
218
+ "capacity_ah_high": est.high,
219
+ "soh_capacity": cap / ref,
220
+ "soh_capacity_low": est.low / ref,
221
+ "soh_capacity_high": est.high / ref,
222
+ "reference_capacity_ah": ref,
223
+ "offset_current_a": -est.theta[1] / 24.0,
224
+ "offset_current_sigma_a": est.sigma[1] / 24.0,
225
+ "n_pairs": est.m,
226
+ "n_full_empty": est.m_cross,
227
+ "n_same_kind": est.m_same,
228
+ "birge": est.birge,
229
+ "rho": est.rho,
230
+ "status": _core.STATUS_TEXT[est.status],
231
+ }
232
+
233
+
234
+ def fade_rate(
235
+ pairs: pd.DataFrame,
236
+ spec: PackSpec,
237
+ config: CapacityConfig | None = None,
238
+ n_boot: int = 500,
239
+ seed: int = 0,
240
+ ) -> dict:
241
+ """The fade rate over the whole record: ``q = (c0 + r y) x + beta dt`` over all pairs.
242
+
243
+ The band is the core's: a Student-t interval on the lag-1 sandwich standard error,
244
+ which allows for scatter that differs between kinds of pair and for the correlation
245
+ of pairs that share a rest (``besslib.soh._core``). A bootstrap that resamples whole
246
+ calendar months of pairs (``n_boot`` times, fixed ``seed``) is reported next to it as
247
+ a check (``rate_boot_low``, ``rate_boot_high``): it also keeps any correlation
248
+ within a month (temperature, season, operation) that the core does not model. A band
249
+ much narrower than the bootstrap's points to such correlation. The two are not
250
+ merged: the union of two 90 % intervals holds the truth more often than 90 %.
251
+
252
+ Returns, in points of ``spec.reference_capacity_ah``: ``rate_points_per_year``
253
+ (negative = fade) with ``_low`` and ``_high``; the same per 100 equivalent full
254
+ cycles (charge throughput / (2 x reference capacity)); ``capacity_start_ah``;
255
+ ``offset_current_a``; ``n_pairs``; ``span_years``; ``status``; and the diagnostics
256
+ ``birge`` (reduced chi-square of the weighted fit) and ``rho`` (lag-1 correlation
257
+ of its weighted residuals).
258
+ """
259
+ config = config or CapacityConfig()
260
+ ref = spec.reference_capacity_ah
261
+ t, x, dt, q, sq, sx, linked = _columns(pairs)
262
+ out = {"reference_capacity_ah": ref, "config_hash": config_hash(config), "n_pairs": int(len(t))}
263
+ t0 = float(t[0]) if len(t) else 0.0
264
+ state = _core.fade_state(spec.nominal_capacity_ah, t0)
265
+ for k in range(len(t)):
266
+ _core.update(state, float(t[k]), float(x[k]), float(dt[k]), float(q[k]), float(sq[k]), float(sx[k]), int(linked[k]))
267
+ z = _z(config.level)
268
+ est = _solve(state, float(t[-1]) if len(t) else 0.0, z, config)
269
+ out.update(
270
+ status=_core.STATUS_TEXT[est.status],
271
+ span_years=est.span_years,
272
+ n_full_empty=int(est.m_cross),
273
+ n_same_kind=int(est.m_same),
274
+ )
275
+ if est.status != _core.OK:
276
+ out.update(rate_points_per_year=np.nan, rate_points_per_year_low=np.nan, rate_points_per_year_high=np.nan)
277
+ return out
278
+ pts = 100.0 / ref
279
+ low, high = est.low, est.high
280
+ boot = _bootstrap(pairs, spec, t, t0, n_boot, seed) if n_boot > 0 else np.array([])
281
+ boot_low = boot_high = np.nan
282
+ if n_boot > 0 and len(boot) >= 0.9 * n_boot:
283
+ a = (1.0 - config.level) / 2.0
284
+ boot_low, boot_high = np.quantile(boot, [a, 1.0 - a])
285
+ years = (t[-1] - t[0]) / 365.25
286
+ throughput = float(pairs["throughput_ah"].abs().sum())
287
+ efc_per_year = throughput / (2.0 * ref) / years if years > 0 else np.nan
288
+ out.update(
289
+ capacity_start_ah=est.theta[0],
290
+ rate_points_per_year=est.theta[1] * pts,
291
+ rate_points_per_year_low=low * pts,
292
+ rate_points_per_year_high=high * pts,
293
+ rate_t_band_low=est.low * pts,
294
+ rate_t_band_high=est.high * pts,
295
+ rate_boot_low=boot_low * pts,
296
+ rate_boot_high=boot_high * pts,
297
+ offset_current_a=-est.theta[2] / 24.0,
298
+ birge=est.birge,
299
+ rho=est.rho,
300
+ efc_per_year=efc_per_year,
301
+ )
302
+ k = 100.0 / efc_per_year if np.isfinite(efc_per_year) and efc_per_year > 0 else np.nan
303
+ out.update(
304
+ rate_points_per_100_efc=out["rate_points_per_year"] * k,
305
+ rate_points_per_100_efc_low=out["rate_points_per_year_low"] * k,
306
+ rate_points_per_100_efc_high=out["rate_points_per_year_high"] * k,
307
+ )
308
+ return out
309
+
310
+
311
+ def _bootstrap(pairs: pd.DataFrame, spec: PackSpec, t: np.ndarray, t0: float, n_boot: int, seed: int) -> np.ndarray:
312
+ """Fade rates (Ah per year) from resampled calendar months of pairs, by weighted least squares."""
313
+ x = pairs["x"].to_numpy(float)
314
+ y = (t - t0) / 365.25
315
+ rows = np.column_stack([x, x * y, pairs["dt_days"].to_numpy(float)])
316
+ q = pairs["q_ah"].to_numpy(float)
317
+ w = 1.0 / (pairs["sigma_q_ah"].to_numpy(float) ** 2 + (spec.nominal_capacity_ah * pairs["sigma_x"].to_numpy(float)) ** 2)
318
+ month = np.unique(pd.DatetimeIndex(pairs["t_end"]).to_period("M").asi8, return_inverse=True)[1]
319
+ nmonth = month.max() + 1
320
+ am = np.zeros((nmonth, 3, 3))
321
+ hm = np.zeros((nmonth, 3))
322
+ np.add.at(am, month, w[:, None, None] * rows[:, :, None] * rows[:, None, :])
323
+ np.add.at(hm, month, w[:, None] * rows * q[:, None])
324
+ rng = np.random.default_rng(seed)
325
+ rates = []
326
+ for _ in range(n_boot):
327
+ counts = np.bincount(rng.integers(0, nmonth, nmonth), minlength=nmonth).astype(float)
328
+ a = np.tensordot(counts, am, axes=1)
329
+ if np.linalg.cond(a) > 1e12:
330
+ continue
331
+ rates.append(np.linalg.solve(a, counts @ hm)[1])
332
+ return np.asarray(rates)