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.
@@ -0,0 +1,270 @@
1
+ """Round-trip efficiency over closed loops between rests at the same state of charge.
2
+
3
+ Annex VII of Regulation (EU) 2023/1542 asks, "where possible", for "the remaining round
4
+ trip efficiency"; Annex IV (6) defines it by the energy delivered in a discharge against
5
+ the energy needed to restore the initial state of charge. Operating data hold no planned
6
+ cycle, so besslib closes the cycle between two rests at the same edge of the charge: a
7
+ *loop* runs from one ``full`` rest to the next ``full`` rest of the same linked run of the
8
+ rest chain (``rests.rest_chain``; a loop never crosses a break of the chain). Its energy
9
+ in and out are the differences of the running energy counters at the two rests. The
10
+ estimate is ``eta = sum(lambda * energy out) / sum(lambda * energy in)`` over the loops in
11
+ memory, with ``lambda = exp(-age / tau_days)``.
12
+
13
+ Band: the loop band of ``besslib.soh._core.loop_solve``. A loop does not close exactly:
14
+ the energy stored at a full rest differs a little from one rest to the next, because a
15
+ voltage stop does not land at exactly the same state of charge. That error of rest ``j``
16
+ enters the loop that ends there with one sign and the linked loop that starts there with
17
+ the other. The band holds the ratio over the loops in memory had each of them closed
18
+ exactly (the loops' own variation from one to the next is part of that value, not of its
19
+ error), and its width comes from the rests' errors only: ``sigma = sqrt(s2 C2) / A``,
20
+ where ``A`` is the weighted energy in, ``C2`` the sum of the rests' squared weights in
21
+ the estimate (the first and the last rest of each linked run without forgetting; the
22
+ latest rest, mostly, with forgetting), and ``s2`` the variance of a rest's error. With
23
+ the scores ``energy out - eta * energy in``, ``s2`` is the mean product of the scores of
24
+ two loops with one loop between them (loops ``k`` and ``k - 2`` of three in a row, which share no rest)
25
+ minus the mean product of two linked loops (which share one): a slow drift of the loops'
26
+ own efficiency adds to both and cancels in the difference. Its degrees of freedom are
27
+ those of that difference (``_core``); below one there is no band. No
28
+ systematic sensor term is added: a gain error of the current or the voltage sensor
29
+ scales energy in and energy out by the same factor and cancels in their ratio. A zero
30
+ offset of the current sensor does not cancel; it is not in the band.
31
+
32
+ Reported next to it: the *coulombic part* ``sum(lambda * Ah out) / sum(lambda * Ah in)``
33
+ over the same loops with the same weights, and the *voltage part* ``eta`` divided by
34
+ it. ``kind="empty"`` gives the same from loops between ``empty`` rests, a cross-check
35
+ with other loops of the same record.
36
+
37
+ Limits. It is the DC efficiency at the battery terminals, not the AC efficiency of the
38
+ plant with its inverter. It depends on the use (current, depth and time at rest;
39
+ Schimpe et al., Applied Energy 210, 211 (2018), doi:10.1016/j.apenergy.2017.10.129), so it
40
+ describes this battery under its own operation over the loops in memory, not a rated
41
+ value and not the efficiency under other use. The energy in also restores the charge the
42
+ meter does not see (BMS supply, balancing, self-discharge), which lowers the value. The
43
+ band takes the rests' errors as independent and of one size; they are not quite, since
44
+ the state of charge at a voltage stop depends on the current before it. A change of the
45
+ loops' own efficiency that is fast against two loops is not cancelled: when it makes
46
+ neighbouring loops more alike than loops two apart, the rest error and the band come out
47
+ too small. The difference of two means is noisier than one mean, so the band rests on
48
+ fewer degrees of freedom than the number of loops suggests, and more records have none.
49
+ The degrees of freedom assume normal scores and no correlation of the scores beyond two
50
+ loops. With forgetting the latest rest
51
+ carries most of the band, so the band rests on the error of one rest whose size is
52
+ learnt from the others. A zero offset of the current sensor is not in the band. No full
53
+ or empty rest exists before the levels are set (``CapacityConfig.level_warmup_days``), so
54
+ the first year of a record has no value.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import math
60
+
61
+ import numpy as np
62
+ import pandas as pd
63
+
64
+ from besslib.frames import PackSpec
65
+ from besslib.soh import _core, _ratio
66
+ from besslib.soh.capacity import days
67
+ from besslib.soh.config import CapacityConfig, RecordConfig, config_hash
68
+ from besslib.soh.rests import detect_rests, levels_from, operating_rests, rest_chain
69
+
70
+ #: Columns of the loop table.
71
+ LOOP_COLUMNS = ["t_start", "t_end", "energy_in_wh", "energy_out_wh", "ah_in", "ah_out", "linked"]
72
+
73
+ #: Columns of the estimate table.
74
+ EFFICIENCY_COLUMNS = [
75
+ "round_trip_efficiency", "round_trip_efficiency_low", "round_trip_efficiency_high", "round_trip_efficiency_sigma",
76
+ "coulombic_efficiency", "voltage_efficiency", "n_loops", "dof", "rho", "rest_error_wh", "status",
77
+ ]
78
+
79
+ TOO_FEW_LOOPS = "not possible from this data: too few closed loops"
80
+ OUT_EXCEEDS_IN = "not possible from this data: energy out exceeds energy in over closed loops"
81
+ NO_ENERGY_OUT = "not possible from this data: no energy out over closed loops"
82
+ NO_ENERGY_IN = "not possible from this data: no energy in over closed loops"
83
+ NO_SHARED_REST = (
84
+ "not possible from this data: no three loops in a row share their rests, so the rest error cannot be told from "
85
+ "a slow drift"
86
+ )
87
+ NO_REST_ERROR = (
88
+ "not possible from this data: the loop scores show no state-of-charge error at the shared rests (their lag-1 "
89
+ "products are not below their lag-2 products)"
90
+ )
91
+ REST_ERROR_UNKNOWN = "not possible from this data: the rest error is not known well enough"
92
+
93
+
94
+ def efficiency_loops(rests: pd.DataFrame, chain: pd.DataFrame, kind: str = "full") -> pd.DataFrame:
95
+ """The closed loops from one ``kind`` rest to the next one in the same run of ``chain``.
96
+
97
+ ``rests`` is the rest table the chain was made from (it carries the running counters
98
+ ``energy_in_wh`` and ``energy_out_wh``, joined to the chain by the rest's start
99
+ time); ``chain`` the output of ``rests.rest_chain``. A loop never crosses a row with
100
+ ``new_segment``. ``ah_in`` and ``ah_out`` are (throughput +/- net charge) / 2 between
101
+ the rests. ``linked`` is 1 when the loop starts at the rest where the previous loop
102
+ ended.
103
+ """
104
+ if kind not in ("full", "empty"):
105
+ raise ValueError("kind must be 'full' or 'empty'")
106
+ missing = [c for c in ("start", "energy_in_wh", "energy_out_wh") if c not in rests.columns]
107
+ if missing:
108
+ raise ValueError(f"the rest table has no column {', '.join(missing)}")
109
+ energy = rests[["start", "energy_in_wh", "energy_out_wh"]].drop_duplicates("start").set_index("start")
110
+ joined = energy.reindex(pd.DatetimeIndex(chain["time"]))
111
+ if len(chain) and joined.isna().any().any():
112
+ raise ValueError("a rest of the chain has no energy counters in the rest table")
113
+ e_in = joined["energy_in_wh"].to_numpy(float)
114
+ e_out = joined["energy_out_wh"].to_numpy(float)
115
+ seg = np.cumsum(chain["new_segment"].to_numpy(int))
116
+ idx = np.flatnonzero((chain["kind"] == kind).to_numpy())
117
+ a, b = idx[:-1], idx[1:]
118
+ keep = seg[a] == seg[b] # no break of the chain at or before the loop's end
119
+ linked = np.r_[False, keep[:-1]] & keep # the loop before it ended at its start rest
120
+ a, b, linked = a[keep], b[keep], linked[keep]
121
+ time = pd.DatetimeIndex(chain["time"])
122
+ q = chain["q_ah"].to_numpy(float)
123
+ thr = chain["throughput_ah"].to_numpy(float)
124
+ dq, dthr = q[b] - q[a], thr[b] - thr[a]
125
+ return pd.DataFrame(
126
+ {
127
+ "t_start": time[a],
128
+ "t_end": time[b],
129
+ "energy_in_wh": e_in[b] - e_in[a],
130
+ "energy_out_wh": e_out[b] - e_out[a],
131
+ "ah_in": 0.5 * (dthr + dq),
132
+ "ah_out": 0.5 * (dthr - dq),
133
+ "linked": linked.astype(int),
134
+ },
135
+ columns=LOOP_COLUMNS,
136
+ )
137
+
138
+
139
+ def _decayed_ratio(t: np.ndarray, num: np.ndarray, den: np.ndarray, at: float, tau_days: float) -> float:
140
+ use = t <= at
141
+ lam = np.exp(-(at - t[use]) / tau_days) if tau_days > 0 else np.ones(int(use.sum()))
142
+ d = float((lam * den[use]).sum())
143
+ return float((lam * num[use]).sum()) / d if d > 0 else math.nan
144
+
145
+
146
+ def estimate_efficiency(
147
+ frame: pd.DataFrame | None,
148
+ spec: PackSpec,
149
+ rests: pd.DataFrame | None = None,
150
+ level: float = 0.90,
151
+ *,
152
+ config: RecordConfig | None = None,
153
+ capacity_config: CapacityConfig | None = None,
154
+ reduced=None,
155
+ at=None,
156
+ mask=None,
157
+ kind: str = "full",
158
+ ) -> pd.DataFrame:
159
+ """Round-trip efficiency with its band at each time in ``at`` (module docstring).
160
+
161
+ Parameters
162
+ ----------
163
+ frame
164
+ Operating data in the besslib frame format; may be ``None`` when ``rests`` or
165
+ ``reduced`` is given.
166
+ rests
167
+ Rest candidates with the energy counters (``reduce.Reduced.rests`` or
168
+ ``rests.detect_rests``), or rests already labelled by ``rests.operating_rests``
169
+ (a table with a ``kind`` column).
170
+ level
171
+ Band level.
172
+ config, capacity_config
173
+ Settings of the record and of the rest detection; defaults are the frozen ones.
174
+ reduced
175
+ A ``reduce.Reduced``; its rest table is used when ``rests`` is not given.
176
+ at
177
+ Times of the estimate. Default: the end of every calendar month in the data.
178
+ mask
179
+ Intervals ``(start, end)`` whose rests are left out; no loop spans one.
180
+ kind
181
+ ``"full"`` (loops from full to full) or ``"empty"`` (the cross-check).
182
+
183
+ Returns
184
+ -------
185
+ DataFrame indexed by time: ``round_trip_efficiency`` with ``_low``, ``_high`` and
186
+ ``_sigma`` (its standard error), ``coulombic_efficiency``, ``voltage_efficiency``,
187
+ ``n_loops`` (loops in memory, decayed), ``dof``, ``rho`` (lag-1 correlation of the
188
+ scores, a diagnostic), ``rest_error_wh`` (the standard deviation of the energy
189
+ stored at a rest, from which the band is formed), ``status``. A value is given only
190
+ when the status is ``estimated``; it is never above 1 or at or below 0. ``attrs`` hold the loops and
191
+ both configuration hashes.
192
+ """
193
+ config = config or RecordConfig()
194
+ capacity_config = capacity_config or CapacityConfig()
195
+ if rests is None:
196
+ if reduced is not None:
197
+ rests = reduced.rests
198
+ elif frame is not None:
199
+ rests = detect_rests(frame, spec, capacity_config)
200
+ else:
201
+ raise ValueError("give a frame, rests or reduced tables")
202
+ if "kind" not in rests.columns:
203
+ rests = operating_rests(rests, spec, capacity_config, mask=mask)
204
+ chain = rest_chain(rests, spec, capacity_config, mask=mask)
205
+ loops = efficiency_loops(rests, chain, kind)
206
+ ready = levels_from(rests, capacity_config)
207
+ ready_days = float(days([ready])[0]) if pd.notna(ready) else math.inf
208
+ if at is None:
209
+ times = loops["t_end"] if len(loops) else rests["start"] if len(rests) else frame.index if frame is not None else []
210
+ if len(times) == 0:
211
+ raise ValueError("no data to estimate from")
212
+ at = pd.date_range(pd.Timestamp(min(times)).normalize(), pd.Timestamp(max(times)), freq="ME")
213
+ at = pd.DatetimeIndex(at)
214
+ at_days = days(at)
215
+ t = days(loops["t_end"])
216
+ a = loops["energy_in_wh"].to_numpy(float)
217
+ b = loops["energy_out_wh"].to_numpy(float)
218
+ ah_in = loops["ah_in"].to_numpy(float)
219
+ ah_out = loops["ah_out"].to_numpy(float)
220
+ # The loops the core accepts (energy in > 0, both sums finite); the coulombic part and
221
+ # the reason of a refused estimate use the same ones.
222
+ kept = (a > 0.0) & np.isfinite(a) & np.isfinite(b)
223
+ est = _ratio.estimate_loops(
224
+ t, a, b, loops["linked"].to_numpy(int), at_days, config.tau_days, level,
225
+ config.efficiency_min_loops, 0.0, 1.0,
226
+ )
227
+ rows = []
228
+ for k, tq in enumerate(at_days):
229
+ e = est.iloc[k]
230
+ row = dict.fromkeys(EFFICIENCY_COLUMNS[:6] + ["rest_error_wh"], math.nan)
231
+ row.update(n_loops=float(e["n_events"]), dof=float(e["dof"]), rho=float(e["rho"]))
232
+ code = int(e["status"])
233
+ if tq < ready_days:
234
+ row["status"] = _core.STATUS_TEXT[_core.NO_LEVELS]
235
+ elif code == _core.OK:
236
+ eta = float(e["value"])
237
+ coulombic = _decayed_ratio(t[kept], ah_out[kept], ah_in[kept], float(tq), config.tau_days)
238
+ row.update(
239
+ round_trip_efficiency=eta,
240
+ round_trip_efficiency_low=float(e["low"]),
241
+ round_trip_efficiency_high=float(e["high"]),
242
+ round_trip_efficiency_sigma=float(e["sigma"]),
243
+ rest_error_wh=float(e["rest_error"]),
244
+ coulombic_efficiency=coulombic,
245
+ voltage_efficiency=eta / coulombic,
246
+ status=_core.STATUS_TEXT[_core.OK],
247
+ )
248
+ elif code == _core.TOO_FEW_EVENTS:
249
+ row["status"] = TOO_FEW_LOOPS
250
+ elif code == _core.OUT_OF_RANGE:
251
+ ratio = _decayed_ratio(t[kept], b[kept], a[kept], float(tq), config.tau_days)
252
+ row["status"] = OUT_EXCEEDS_IN if ratio > 1.0 else NO_ENERGY_OUT
253
+ elif code == _core.SINGULAR:
254
+ row["status"] = NO_ENERGY_IN
255
+ elif code == _core.NO_LINKS:
256
+ row["status"] = NO_SHARED_REST
257
+ elif code == _core.NO_BAND:
258
+ row["status"] = NO_REST_ERROR
259
+ elif code == _core.LOW_DOF:
260
+ row["status"] = REST_ERROR_UNKNOWN
261
+ else:
262
+ row["status"] = _core.STATUS_TEXT.get(code, f"not possible from this data: status {code}")
263
+ rows.append(row)
264
+ out = pd.DataFrame(rows, index=at, columns=EFFICIENCY_COLUMNS)
265
+ out.index.name = "time"
266
+ out.attrs["loops"] = loops
267
+ out.attrs["kind"] = kind
268
+ out.attrs["config_hash"] = config_hash(config)
269
+ out.attrs["capacity_config_hash"] = config_hash(capacity_config)
270
+ return out