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,205 @@
|
|
|
1
|
+
"""Measure a field capacity test that is recorded inside the operating data.
|
|
2
|
+
|
|
3
|
+
A field capacity test, as in Figgener et al. (2024, Supplementary Note 6): the
|
|
4
|
+
system is charged until it stops by itself, then discharged at its maximum power
|
|
5
|
+
until it stops by itself. The usable capacity is the integral of the current over
|
|
6
|
+
the discharge, the usable energy the integral of the power.
|
|
7
|
+
|
|
8
|
+
This module finds that discharge near a documented start time and integrates it.
|
|
9
|
+
It is the *reference* of besslib's validation, so it uses no estimator: only the
|
|
10
|
+
measured current, the measured power and three plain rules for where the
|
|
11
|
+
discharge begins and ends.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import asdict, dataclass
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
from besslib.frames import PackSpec, check_frame
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class CapacityTest:
|
|
26
|
+
"""One measured capacity test. ``status`` is ``"ok"`` or says what went wrong."""
|
|
27
|
+
|
|
28
|
+
status: str
|
|
29
|
+
documented_start: pd.Timestamp
|
|
30
|
+
onset: pd.Timestamp | None = None
|
|
31
|
+
end: pd.Timestamp | None = None
|
|
32
|
+
duration_min: float = np.nan
|
|
33
|
+
capacity_ah: float = np.nan
|
|
34
|
+
energy_kwh: float = np.nan
|
|
35
|
+
soh_capacity: float = np.nan
|
|
36
|
+
reference_capacity_ah: float = np.nan
|
|
37
|
+
c_rate: float = np.nan
|
|
38
|
+
test_c_rate: float = np.nan
|
|
39
|
+
charge_end: pd.Timestamp | None = None
|
|
40
|
+
rest_before_min: float = np.nan
|
|
41
|
+
pre_start_ah: float = np.nan
|
|
42
|
+
voltage_before_v: float = np.nan
|
|
43
|
+
voltage_min_v: float = np.nan
|
|
44
|
+
temp_pack_mean_c: float = np.nan
|
|
45
|
+
interpolated_share: float = np.nan
|
|
46
|
+
missing_seconds: int = 0
|
|
47
|
+
probe_delay_min: float = np.nan
|
|
48
|
+
discharged_hour_before_ah: float = np.nan
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> dict:
|
|
51
|
+
return asdict(self)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def measure_capacity_test(
|
|
55
|
+
frame: pd.DataFrame,
|
|
56
|
+
spec: PackSpec,
|
|
57
|
+
start: str | pd.Timestamp,
|
|
58
|
+
*,
|
|
59
|
+
search_min: float = 60.0,
|
|
60
|
+
probe_c_rate: float = 0.1,
|
|
61
|
+
probe_search_min: int = 60,
|
|
62
|
+
onset_fraction: float = 0.2,
|
|
63
|
+
end_fraction: float = 0.05,
|
|
64
|
+
end_hold_s: int = 300,
|
|
65
|
+
tail_fraction: float = 0.01,
|
|
66
|
+
charge_c_rate: float = 0.02,
|
|
67
|
+
max_hours: float = 12.0,
|
|
68
|
+
) -> CapacityTest:
|
|
69
|
+
"""Find the full-power discharge near ``start`` and integrate it.
|
|
70
|
+
|
|
71
|
+
Rules
|
|
72
|
+
-----
|
|
73
|
+
1. The *test current* is the median current from 2 to 12 minutes after the probe
|
|
74
|
+
start. The probe starts at ``start``; while that median is not a discharge of at
|
|
75
|
+
least ``probe_c_rate`` × C, the probe start moves one minute later, at most
|
|
76
|
+
``probe_search_min`` times. A moved probe must also begin inside the discharge:
|
|
77
|
+
the 10-second mean current at its first second is a discharge of at least
|
|
78
|
+
``probe_c_rate`` × C. Some tests begin late or with a few minutes at low power,
|
|
79
|
+
so the full-power discharge can follow the documented start by minutes.
|
|
80
|
+
``probe_delay_min`` says how far the probe moved.
|
|
81
|
+
2. The discharge *begins* at the last moment before that where the 10-second mean
|
|
82
|
+
current is weaker than ``onset_fraction`` of the test current (searched up to
|
|
83
|
+
``search_min`` minutes before the probe start).
|
|
84
|
+
3. The discharge *ends* once the mean current stays weaker than ``end_fraction``
|
|
85
|
+
of the test current for ``end_hold_s`` seconds. The end is the last moment in
|
|
86
|
+
that time with more than ``tail_fraction`` of the test current, so a slow
|
|
87
|
+
taper is kept.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
frame
|
|
92
|
+
Operating data in the besslib frame format. It should cover at least one day
|
|
93
|
+
before ``start`` and ``max_hours`` after it.
|
|
94
|
+
spec
|
|
95
|
+
The pack; ``reference_capacity_ah`` is used for ``soh_capacity``.
|
|
96
|
+
start
|
|
97
|
+
The documented start time of the test.
|
|
98
|
+
|
|
99
|
+
Returns
|
|
100
|
+
-------
|
|
101
|
+
CapacityTest
|
|
102
|
+
``capacity_ah`` and ``energy_kwh`` are the charge and energy delivered from
|
|
103
|
+
the beginning to the end of the discharge. ``c_rate`` is the median discharge
|
|
104
|
+
current over that time, divided by the nominal capacity; ``test_c_rate`` is the
|
|
105
|
+
test current of rule 1, divided by the same. ``pre_start_ah`` is the charge that
|
|
106
|
+
left the battery between the end of the last charge and the beginning of the
|
|
107
|
+
test discharge; ``discharged_hour_before_ah`` counts only the discharge current
|
|
108
|
+
in the hour before the beginning. Both are reported, not added.
|
|
109
|
+
"""
|
|
110
|
+
check_frame(frame)
|
|
111
|
+
start = pd.Timestamp(start)
|
|
112
|
+
window = frame.loc[start - pd.Timedelta(hours=26) : start + pd.Timedelta(hours=max_hours + 1)]
|
|
113
|
+
if window.empty or window.index[0] > start or window.index[-1] < start + pd.Timedelta(minutes=12):
|
|
114
|
+
return CapacityTest("no data at the documented start", start)
|
|
115
|
+
|
|
116
|
+
current = window["current_a"]
|
|
117
|
+
smooth = current.rolling("10s").mean()
|
|
118
|
+
full_power = -probe_c_rate * spec.nominal_capacity_ah
|
|
119
|
+
# Rule 1: the test current, from a probe that may move later by whole minutes.
|
|
120
|
+
documented = start
|
|
121
|
+
for delay in range(probe_search_min + 1):
|
|
122
|
+
probe_start = documented + pd.Timedelta(minutes=delay)
|
|
123
|
+
probe = current.loc[probe_start + pd.Timedelta(minutes=2) : probe_start + pd.Timedelta(minutes=12)]
|
|
124
|
+
if len(probe) < 300:
|
|
125
|
+
return CapacityTest("data gap in the first minutes of the test", documented)
|
|
126
|
+
test_current = float(probe.median())
|
|
127
|
+
inside = delay == 0 or smooth.asof(probe_start + pd.Timedelta(minutes=2)) <= full_power
|
|
128
|
+
if test_current <= full_power and inside:
|
|
129
|
+
break
|
|
130
|
+
else:
|
|
131
|
+
return CapacityTest(
|
|
132
|
+
"no full-power discharge within %d min after the documented start" % probe_search_min, documented
|
|
133
|
+
)
|
|
134
|
+
start = probe_start
|
|
135
|
+
|
|
136
|
+
# Rule 2: the beginning of the discharge.
|
|
137
|
+
before = smooth.loc[start - pd.Timedelta(minutes=search_min) : start + pd.Timedelta(minutes=2)]
|
|
138
|
+
weak = before[before > onset_fraction * test_current]
|
|
139
|
+
if weak.empty:
|
|
140
|
+
return CapacityTest("the discharge began more than %d min before the probe start" % search_min, documented)
|
|
141
|
+
# The 10-second mean lags the current, so step back by its window.
|
|
142
|
+
onset = max(weak.index[-1] - pd.Timedelta(seconds=10), window.index[0])
|
|
143
|
+
|
|
144
|
+
# Rule 3: the end of the discharge.
|
|
145
|
+
tail = current.loc[onset + pd.Timedelta(minutes=2) :]
|
|
146
|
+
forward = tail[::-1].rolling(f"{end_hold_s}s").mean()[::-1]
|
|
147
|
+
calm = forward[forward > end_fraction * test_current]
|
|
148
|
+
calm = calm[calm.index <= tail.index[-1] - pd.Timedelta(seconds=end_hold_s)]
|
|
149
|
+
if calm.empty:
|
|
150
|
+
return CapacityTest("the end of the discharge was not found", documented, onset=onset)
|
|
151
|
+
# Keep the tail: the last moment in the hold time with more than 1 % of the test current.
|
|
152
|
+
hold = smooth.loc[calm.index[0] : calm.index[0] + pd.Timedelta(seconds=end_hold_s)]
|
|
153
|
+
tail_end = hold[hold < tail_fraction * test_current]
|
|
154
|
+
end = tail_end.index[-1] if len(tail_end) else calm.index[0]
|
|
155
|
+
|
|
156
|
+
segment = window.loc[onset:end]
|
|
157
|
+
seconds = (segment.index - segment.index[0]).total_seconds().to_numpy()
|
|
158
|
+
capacity_ah = -np.trapezoid(segment["current_a"].to_numpy(), seconds) / 3600.0
|
|
159
|
+
energy_kwh = -np.trapezoid(segment["power_w"].to_numpy(), seconds) / 3.6e6
|
|
160
|
+
steps = np.diff(seconds)
|
|
161
|
+
missing = int(round(float((steps[steps > 1.5] - 1.0).sum()))) if len(steps) else 0
|
|
162
|
+
|
|
163
|
+
# Discharge only, in the hour before the beginning: shows a test that did not start full.
|
|
164
|
+
hour = window.loc[onset - pd.Timedelta(hours=1) : onset - pd.Timedelta(seconds=1)]
|
|
165
|
+
discharged_hour_before_ah = 0.0
|
|
166
|
+
if len(hour) > 1:
|
|
167
|
+
hour_s = (hour.index - hour.index[0]).total_seconds().to_numpy()
|
|
168
|
+
discharged_hour_before_ah = -np.trapezoid(np.minimum(hour["current_a"].to_numpy(), 0.0), hour_s) / 3600.0
|
|
169
|
+
|
|
170
|
+
# The end of the last charge before the test, and what left the battery since.
|
|
171
|
+
charge_limit = charge_c_rate * spec.nominal_capacity_ah
|
|
172
|
+
charging = smooth.loc[:onset]
|
|
173
|
+
charging = charging[charging > charge_limit]
|
|
174
|
+
if charging.empty:
|
|
175
|
+
charge_end, rest_before_min, pre_start_ah = None, np.nan, np.nan
|
|
176
|
+
else:
|
|
177
|
+
charge_end = charging.index[-1]
|
|
178
|
+
gap = window.loc[charge_end:onset]
|
|
179
|
+
gap_s = (gap.index - gap.index[0]).total_seconds().to_numpy()
|
|
180
|
+
pre_start_ah = -np.trapezoid(gap["current_a"].to_numpy(), gap_s) / 3600.0
|
|
181
|
+
rest_before_min = (onset - charge_end).total_seconds() / 60.0
|
|
182
|
+
|
|
183
|
+
return CapacityTest(
|
|
184
|
+
status="ok",
|
|
185
|
+
documented_start=documented,
|
|
186
|
+
onset=onset,
|
|
187
|
+
end=end,
|
|
188
|
+
duration_min=(end - onset).total_seconds() / 60.0,
|
|
189
|
+
capacity_ah=float(capacity_ah),
|
|
190
|
+
energy_kwh=float(energy_kwh),
|
|
191
|
+
soh_capacity=float(capacity_ah / spec.reference_capacity_ah),
|
|
192
|
+
reference_capacity_ah=float(spec.reference_capacity_ah),
|
|
193
|
+
c_rate=float(-segment["current_a"].median() / spec.nominal_capacity_ah),
|
|
194
|
+
test_c_rate=float(-test_current / spec.nominal_capacity_ah),
|
|
195
|
+
charge_end=charge_end,
|
|
196
|
+
rest_before_min=float(rest_before_min),
|
|
197
|
+
pre_start_ah=float(pre_start_ah),
|
|
198
|
+
voltage_before_v=float(window["voltage_v"].loc[: onset - pd.Timedelta(seconds=1)].iloc[-10:].mean()),
|
|
199
|
+
voltage_min_v=float(segment["voltage_v"].min()),
|
|
200
|
+
temp_pack_mean_c=float(segment["temp_pack_c"].mean()),
|
|
201
|
+
interpolated_share=float(segment["interpolated"].mean()) if "interpolated" in segment else np.nan,
|
|
202
|
+
missing_seconds=missing,
|
|
203
|
+
probe_delay_min=float(delay),
|
|
204
|
+
discharged_hour_before_ah=float(discharged_hour_before_ah),
|
|
205
|
+
)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Apparent charge loss: the charge the battery loses that its meter does not see.
|
|
2
|
+
|
|
3
|
+
Annex VII of Regulation (EU) 2023/1542 asks for "the evolution of self-discharging
|
|
4
|
+
rates". Operating data cannot separate cell self-discharge from the other currents that
|
|
5
|
+
bypass the meter, so besslib reports what it can measure and names it for what it is.
|
|
6
|
+
|
|
7
|
+
Method: the capacity fit (``besslib.soh.capacity``, ``besslib.soh._core``) models the
|
|
8
|
+
measured charge of each pair of rests as ``q = C x + beta dt``, and reports the *offset
|
|
9
|
+
current* ``-beta / 24`` A. The apparent charge loss is minus that current, in mA:
|
|
10
|
+
positive when the battery loses charge the meter does not see. It is therefore an upper
|
|
11
|
+
bound for cell self-discharge that also holds the BMS supply, balancing currents and the
|
|
12
|
+
current sensor's zero offset, and in a home storage system it is mostly not cell
|
|
13
|
+
self-discharge. A negative value is possible (a sensor offset can have either sign) and
|
|
14
|
+
is reported as it is.
|
|
15
|
+
|
|
16
|
+
Band: a Student-t interval on the offset's lag-1 sandwich standard error, with the
|
|
17
|
+
degrees of freedom of the capacity fit (decayed pair count minus 2), and the current
|
|
18
|
+
sensor's gain error as a systematic term (``RecordConfig.charge_sigma``; JCGM 100:2008,
|
|
19
|
+
4.3.7): a gain error scales every measured charge, and so the fitted offset, by the same
|
|
20
|
+
factor.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
from statistics import NormalDist
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
import pandas as pd
|
|
30
|
+
|
|
31
|
+
from besslib.frames import PackSpec
|
|
32
|
+
from besslib.soh import _core
|
|
33
|
+
from besslib.soh.config import RecordConfig, config_hash
|
|
34
|
+
|
|
35
|
+
#: Hours in an average month (365.25 x 24 / 12).
|
|
36
|
+
HOURS_PER_MONTH = 730.5
|
|
37
|
+
|
|
38
|
+
NO_OFFSET_BAND = "not possible from this data: the band of the offset current could not be computed"
|
|
39
|
+
|
|
40
|
+
#: Columns of the ``charge_loss`` table.
|
|
41
|
+
LOSS_COLUMNS = [
|
|
42
|
+
"charge_loss_ma", "charge_loss_ma_low", "charge_loss_ma_high", "charge_loss_sigma_ma",
|
|
43
|
+
"charge_loss_percent_per_month", "charge_loss_percent_per_month_low", "charge_loss_percent_per_month_high",
|
|
44
|
+
"n_pairs", "status",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _z(level: float) -> float:
|
|
49
|
+
return NormalDist().inv_cdf(0.5 + level / 2.0)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def charge_loss(
|
|
53
|
+
capacity: pd.DataFrame,
|
|
54
|
+
spec: PackSpec,
|
|
55
|
+
level: float = 0.90,
|
|
56
|
+
config: RecordConfig | None = None,
|
|
57
|
+
) -> pd.DataFrame:
|
|
58
|
+
"""The apparent charge loss at each time of a capacity table.
|
|
59
|
+
|
|
60
|
+
``capacity`` is the output of ``capacity.estimate_capacity`` (index: time). Returns,
|
|
61
|
+
with the same index: ``charge_loss_ma`` (= -1000 x ``offset_current_a``; positive =
|
|
62
|
+
the battery loses charge the meter does not see) with ``_low`` and ``_high``;
|
|
63
|
+
``charge_loss_sigma_ma`` (its statistical standard error, without the gain term);
|
|
64
|
+
the same loss in % of ``spec.reference_capacity_ah`` per month of 730.5 hours
|
|
65
|
+
(``charge_loss_percent_per_month``, ``_low``, ``_high``); ``n_pairs`` (decayed pair
|
|
66
|
+
count of the fit) and ``status``.
|
|
67
|
+
|
|
68
|
+
The value is an upper bound for cell self-discharge: it also holds the BMS supply,
|
|
69
|
+
balancing and the current sensor's zero offset (module docstring). A row is
|
|
70
|
+
``estimated`` only when the capacity row is, and the offset's sandwich variance is
|
|
71
|
+
positive; otherwise all values are NaN and the status gives the reason.
|
|
72
|
+
"""
|
|
73
|
+
config = config or RecordConfig()
|
|
74
|
+
z = _z(level)
|
|
75
|
+
rel = config.charge_sigma
|
|
76
|
+
per_month = HOURS_PER_MONTH / spec.reference_capacity_ah * 100.0 / 1000.0 # mA -> % of reference per month
|
|
77
|
+
rows = []
|
|
78
|
+
for status, off, sig, n in zip(
|
|
79
|
+
capacity["status"], capacity["offset_current_a"], capacity["offset_current_sigma_a"], capacity["n_pairs"]
|
|
80
|
+
):
|
|
81
|
+
row = dict.fromkeys(LOSS_COLUMNS[:-2], math.nan)
|
|
82
|
+
row["n_pairs"] = float(n)
|
|
83
|
+
if status != _core.STATUS_TEXT[_core.OK]:
|
|
84
|
+
row["status"] = status
|
|
85
|
+
elif not (math.isfinite(sig) and math.isfinite(off)):
|
|
86
|
+
row["status"] = NO_OFFSET_BAND
|
|
87
|
+
else:
|
|
88
|
+
value = -1000.0 * float(off)
|
|
89
|
+
stat = 1000.0 * float(sig)
|
|
90
|
+
k = _core.t_quantile(z, float(n) - 2.0)
|
|
91
|
+
half = math.sqrt((k * stat) ** 2 + (z * rel * value) ** 2)
|
|
92
|
+
row.update(
|
|
93
|
+
charge_loss_ma=value,
|
|
94
|
+
charge_loss_ma_low=value - half,
|
|
95
|
+
charge_loss_ma_high=value + half,
|
|
96
|
+
charge_loss_sigma_ma=stat,
|
|
97
|
+
charge_loss_percent_per_month=value * per_month,
|
|
98
|
+
charge_loss_percent_per_month_low=(value - half) * per_month,
|
|
99
|
+
charge_loss_percent_per_month_high=(value + half) * per_month,
|
|
100
|
+
status=_core.STATUS_TEXT[_core.OK],
|
|
101
|
+
)
|
|
102
|
+
rows.append(row)
|
|
103
|
+
out = pd.DataFrame(rows, index=capacity.index, columns=LOSS_COLUMNS)
|
|
104
|
+
out.index.name = "time"
|
|
105
|
+
out.attrs["config_hash"] = config_hash(config)
|
|
106
|
+
out.attrs["capacity_config_hash"] = capacity.attrs.get("config_hash")
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def year_end_values(loss: pd.DataFrame) -> pd.DataFrame:
|
|
111
|
+
"""The value at the end of each calendar year: the last ``estimated`` row of each year.
|
|
112
|
+
|
|
113
|
+
For the last year of a record that does not reach 31 December it is the last
|
|
114
|
+
estimated row of that year; the ``time`` column says when.
|
|
115
|
+
"""
|
|
116
|
+
ok = loss[loss["status"] == _core.STATUS_TEXT[_core.OK]]
|
|
117
|
+
if len(ok) == 0:
|
|
118
|
+
return pd.DataFrame(columns=["year", "time", "charge_loss_ma", "charge_loss_ma_low", "charge_loss_ma_high",
|
|
119
|
+
"charge_loss_sigma_ma", "n_pairs"])
|
|
120
|
+
ok = ok.sort_index()
|
|
121
|
+
last = ok.groupby(ok.index.year).tail(1)
|
|
122
|
+
out = last[["charge_loss_ma", "charge_loss_ma_low", "charge_loss_ma_high", "charge_loss_sigma_ma", "n_pairs"]].copy()
|
|
123
|
+
out.insert(0, "time", last.index)
|
|
124
|
+
out.insert(0, "year", last.index.year)
|
|
125
|
+
return out.reset_index(drop=True)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def charge_loss_trend(loss: pd.DataFrame, config: RecordConfig | None = None, level: float = 0.90) -> dict:
|
|
129
|
+
"""The evolution of the apparent charge loss: a weighted straight line through its year-end values.
|
|
130
|
+
|
|
131
|
+
``loss`` is the output of ``charge_loss`` (at month ends, or at any times that
|
|
132
|
+
include the year ends). Weights: ``1 / charge_loss_sigma_ma**2``, the statistical
|
|
133
|
+
part of each value's band. The gain error is left out of the weights because it moves
|
|
134
|
+
every value by the same factor; for the same reason it is added to the slope's band
|
|
135
|
+
as a systematic term. The weights set only the relative size of the errors; the
|
|
136
|
+
slope's standard error is scaled by the scatter of the values about the line (the
|
|
137
|
+
reduced chi-square), and its band uses a Student-t quantile with ``n - 2`` degrees of
|
|
138
|
+
freedom. The year-end values are treated as independent; with a memory time of half a
|
|
139
|
+
year, neighbouring values share about ``exp(-365 / tau_days)`` of their weight, which
|
|
140
|
+
this band does not include.
|
|
141
|
+
|
|
142
|
+
Needs ``config.charge_loss_min_years`` year-end values. Returns ``year_end`` (the
|
|
143
|
+
table of ``year_end_values``), ``slope_ma_per_year`` with ``_low``, ``_high`` and
|
|
144
|
+
``slope_sigma_ma_per_year``, ``intercept_ma`` (the line's value at the first year-end
|
|
145
|
+
time ``t0``), ``n_years``, ``dof``, ``span_years``, ``status`` and ``config_hash``.
|
|
146
|
+
"""
|
|
147
|
+
config = config or RecordConfig()
|
|
148
|
+
table = year_end_values(loss)
|
|
149
|
+
n = len(table)
|
|
150
|
+
out = {
|
|
151
|
+
"year_end": table,
|
|
152
|
+
"slope_ma_per_year": math.nan,
|
|
153
|
+
"slope_ma_per_year_low": math.nan,
|
|
154
|
+
"slope_ma_per_year_high": math.nan,
|
|
155
|
+
"slope_sigma_ma_per_year": math.nan,
|
|
156
|
+
"intercept_ma": math.nan,
|
|
157
|
+
"t0": table["time"].iloc[0] if n else pd.NaT,
|
|
158
|
+
"n_years": n,
|
|
159
|
+
"dof": float(max(n - 2, 0)),
|
|
160
|
+
"span_years": 0.0,
|
|
161
|
+
"status": _core.STATUS_TEXT[_core.OK],
|
|
162
|
+
"config_hash": config_hash(config),
|
|
163
|
+
}
|
|
164
|
+
need = max(int(config.charge_loss_min_years), 3) # a line with a band needs three points
|
|
165
|
+
if n < need:
|
|
166
|
+
out["status"] = f"not possible from this data: fewer than {need} year-end values"
|
|
167
|
+
return out
|
|
168
|
+
sig = table["charge_loss_sigma_ma"].to_numpy(float)
|
|
169
|
+
if not (np.all(np.isfinite(sig)) and np.all(sig > 0.0)):
|
|
170
|
+
out["status"] = "not possible from this data: a year-end value has no positive standard error"
|
|
171
|
+
return out
|
|
172
|
+
years = (pd.DatetimeIndex(table["time"]) - table["time"].iloc[0]).total_seconds().to_numpy() / (365.25 * 86400.0)
|
|
173
|
+
y = table["charge_loss_ma"].to_numpy(float)
|
|
174
|
+
w = 1.0 / sig**2
|
|
175
|
+
sw = w.sum()
|
|
176
|
+
tm = (w * years).sum() / sw
|
|
177
|
+
ym = (w * y).sum() / sw
|
|
178
|
+
stt = (w * (years - tm) ** 2).sum()
|
|
179
|
+
out["span_years"] = float(years[-1] - years[0])
|
|
180
|
+
if stt <= 0.0:
|
|
181
|
+
out["status"] = "not possible from this data: the year-end values do not span time"
|
|
182
|
+
return out
|
|
183
|
+
slope = float((w * (years - tm) * (y - ym)).sum() / stt)
|
|
184
|
+
intercept = float(ym - slope * tm)
|
|
185
|
+
dof = n - 2
|
|
186
|
+
chi2 = float((w * (y - intercept - slope * years) ** 2).sum())
|
|
187
|
+
stat = math.sqrt(chi2 / dof / stt)
|
|
188
|
+
z = _z(level)
|
|
189
|
+
k = _core.t_quantile(z, float(dof))
|
|
190
|
+
half = math.sqrt((k * stat) ** 2 + (z * config.charge_sigma * slope) ** 2)
|
|
191
|
+
out.update(
|
|
192
|
+
slope_ma_per_year=slope,
|
|
193
|
+
slope_ma_per_year_low=slope - half,
|
|
194
|
+
slope_ma_per_year_high=slope + half,
|
|
195
|
+
slope_sigma_ma_per_year=stat,
|
|
196
|
+
intercept_ma=intercept,
|
|
197
|
+
dof=float(dof),
|
|
198
|
+
)
|
|
199
|
+
return out
|
besslib/soh/config.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""The settings of the estimators, in frozen records with a printable hash.
|
|
2
|
+
|
|
3
|
+
``CapacityConfig`` holds the settings of the capacity estimator, ``RecordConfig`` those
|
|
4
|
+
of the other fields of the Annex VII record. The defaults are the values frozen after
|
|
5
|
+
tuning on the development systems. Every result besslib writes carries
|
|
6
|
+
``config_hash(config)``, so a number can always be traced to the exact settings that
|
|
7
|
+
made it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
from dataclasses import asdict, dataclass, replace
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class CapacityConfig:
|
|
20
|
+
"""Settings for rest detection, pairing and the estimator.
|
|
21
|
+
|
|
22
|
+
Rest detection (Figgener et al. 2024, Supplementary Methods, "Relaxation phase
|
|
23
|
+
detection"): a rest is a stretch with ``|current| < current_c_rate * C`` that lasts
|
|
24
|
+
at least ``min_duration_min``; current excursions up to ``peak_s`` seconds are
|
|
25
|
+
tolerated, longer ones end the rest; at least ``min_throughput`` x C of charge must
|
|
26
|
+
have moved since the last accepted rest.
|
|
27
|
+
|
|
28
|
+
Rest kinds: the *edge voltage* of a rest is the median voltage in the
|
|
29
|
+
``pre_window_s`` seconds before it, while current still flows. ``full`` is a rest
|
|
30
|
+
after a charge whose edge voltage lies within ``edge_tolerance`` of the voltage span
|
|
31
|
+
below the system's end-of-charge level; ``empty`` likewise above the
|
|
32
|
+
end-of-discharge level. The levels are the ``edge_quantile`` and
|
|
33
|
+
``1 - edge_quantile`` quantiles of the edge voltages in the trailing
|
|
34
|
+
``level_window_days``, from at least ``min_level_rests`` rests of each direction.
|
|
35
|
+
|
|
36
|
+
The end-of-charge and end-of-discharge levels are properties of the system, not of
|
|
37
|
+
the season. A home storage system may not reach one of them for months: in summer it
|
|
38
|
+
is rarely emptied, in winter rarely filled. A shorter window would then move its
|
|
39
|
+
level into the normal operating range and call a half-empty stop empty. So the
|
|
40
|
+
window spans one operating year, and no level exists, and no rest is full or empty,
|
|
41
|
+
before ``level_warmup_days`` of history after the first accepted rest of the record.
|
|
42
|
+
|
|
43
|
+
Pairs: two consecutive full or empty rests form a pair while they are at most
|
|
44
|
+
``max_link_days`` apart and have at most ``max_missing_s`` seconds of missing data
|
|
45
|
+
between them; a masked interval between them also breaks the link.
|
|
46
|
+
|
|
47
|
+
Estimator: memory time ``tau_days``; band level ``level``; ``sigma_q_rel`` x charge
|
|
48
|
+
moved is the charge error of a pair and ``sigma_soc_edge`` the state-of-charge error
|
|
49
|
+
of one rest (both set the relative weights only; the band is taken from the scatter
|
|
50
|
+
of the pairs themselves); ``gain_error`` is the current sensor's systematic error
|
|
51
|
+
(0.5 %, Figgener et al. 2024, Supplementary Table 2). An estimate needs at least ``min_cross``
|
|
52
|
+
full-to-empty or empty-to-full pairs and ``min_same`` full-to-full or empty-to-empty
|
|
53
|
+
pairs in memory (decayed counts). The fade rate needs ``fade_min_span_years``.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
current_c_rate: float = 0.005 # frozen: validation/tune_capacity.py
|
|
57
|
+
min_duration_min: float = 20.0 # frozen: validation/tune_capacity.py
|
|
58
|
+
peak_s: float = 10.0
|
|
59
|
+
min_throughput: float = 0.2
|
|
60
|
+
pre_window_s: float = 60.0
|
|
61
|
+
break_gap_s: float = 60.0
|
|
62
|
+
edge_quantile: float = 0.9
|
|
63
|
+
edge_tolerance: float = 0.03 # validation/edge_tolerance.py
|
|
64
|
+
level_window_days: float = 365.0 # one operating year: every season once
|
|
65
|
+
level_warmup_days: float = 365.0 # no level before one year of history
|
|
66
|
+
min_level_rests: int = 10
|
|
67
|
+
ocv_fit_max_min: float = 120.0
|
|
68
|
+
max_link_days: float = 10.0
|
|
69
|
+
max_missing_s: float = 600.0
|
|
70
|
+
tau_days: float = 180.0 # frozen: validation/tune_capacity.py
|
|
71
|
+
level: float = 0.90
|
|
72
|
+
sigma_q_rel: float = 0.005
|
|
73
|
+
sigma_soc_edge: float = 0.02
|
|
74
|
+
gain_error: float = 0.005
|
|
75
|
+
min_cross: float = 3.0
|
|
76
|
+
min_same: float = 2.0
|
|
77
|
+
fade_min_span_years: float = 1.0
|
|
78
|
+
|
|
79
|
+
def with_(self, **changes) -> "CapacityConfig":
|
|
80
|
+
"""A copy with some settings changed."""
|
|
81
|
+
return replace(self, **changes)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class RecordConfig:
|
|
86
|
+
"""Settings for resistance, round-trip efficiency and the Annex VII record.
|
|
87
|
+
|
|
88
|
+
They are kept apart from ``CapacityConfig``, so the capacity estimator's settings
|
|
89
|
+
and hash do not change when these do.
|
|
90
|
+
|
|
91
|
+
Resistance: a *current step* is a change of at least ``min_step_c_rate`` x C between
|
|
92
|
+
two consecutive samples, after ``steady_s`` seconds in which the current stayed
|
|
93
|
+
within ``steady_tolerance`` x the step of its value before the step. Steps are
|
|
94
|
+
grouped by day and by pack-temperature band of ``temp_band_c`` degrees. A day in a
|
|
95
|
+
band is left out when more than ``unrefreshed_max_share`` of its steps show no voltage
|
|
96
|
+
change at all: the voltage was then not refreshed together with the current (a
|
|
97
|
+
current step moves the voltage of a pack by far more than the voltage sensor's
|
|
98
|
+
resolution, so a synchronous logger shows almost no exact zeros). An estimate
|
|
99
|
+
needs ``resistance_min_days`` days in memory in its band (decayed count); the growth
|
|
100
|
+
per year needs ``growth_min_span_years`` between its first and last day.
|
|
101
|
+
|
|
102
|
+
Round-trip efficiency: an estimate needs ``efficiency_min_loops`` closed loops in
|
|
103
|
+
memory (decayed count).
|
|
104
|
+
|
|
105
|
+
Shared: memory time ``tau_days`` (the frozen value of the capacity estimator, not
|
|
106
|
+
tuned again); band level ``level``. ``current_accuracy`` and ``voltage_accuracy``
|
|
107
|
+
are the sensors' stated accuracies (0.5 % and 0.25 %, Figgener et al. 2024,
|
|
108
|
+
Supplementary Table 2). Each accuracy is read as the half-width ``a`` of a
|
|
109
|
+
rectangular distribution, so its standard uncertainty is ``a / sqrt(3)`` (JCGM
|
|
110
|
+
100:2008, "Guide to the expression of uncertainty in measurement", 4.3.7, Eq. 7).
|
|
111
|
+
A gain error moves every reading of a sensor the same way, so averaging does not
|
|
112
|
+
reduce it: it enters a band as a systematic term. The trend of the apparent charge
|
|
113
|
+
loss needs ``charge_loss_min_years`` year-end values.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
min_step_c_rate: float = 0.05 # frozen after validation/tune_resistance.py (development systems only)
|
|
117
|
+
steady_s: float = 2.0 # frozen after validation/tune_resistance.py (development systems only)
|
|
118
|
+
steady_tolerance: float = 0.2
|
|
119
|
+
unrefreshed_max_share: float = 0.01
|
|
120
|
+
temp_band_c: float = 5.0
|
|
121
|
+
resistance_min_days: float = 10.0
|
|
122
|
+
growth_min_span_years: float = 1.0
|
|
123
|
+
efficiency_min_loops: float = 5.0
|
|
124
|
+
tau_days: float = 180.0
|
|
125
|
+
level: float = 0.90
|
|
126
|
+
current_accuracy: float = 0.005
|
|
127
|
+
voltage_accuracy: float = 0.0025
|
|
128
|
+
charge_loss_min_years: int = 3
|
|
129
|
+
|
|
130
|
+
def with_(self, **changes) -> "RecordConfig":
|
|
131
|
+
"""A copy with some settings changed."""
|
|
132
|
+
return replace(self, **changes)
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def charge_sigma(self) -> float:
|
|
136
|
+
"""Relative standard uncertainty of a charge (Ah) from the current sensor's gain."""
|
|
137
|
+
return self.current_accuracy / math.sqrt(3.0)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def energy_sigma(self) -> float:
|
|
141
|
+
"""Relative standard uncertainty of an energy (Wh): current and voltage gain combined."""
|
|
142
|
+
return math.hypot(self.current_accuracy, self.voltage_accuracy) / math.sqrt(3.0)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def resistance_sigma(self) -> float:
|
|
146
|
+
"""Relative standard uncertainty of a voltage step divided by a current step."""
|
|
147
|
+
return math.hypot(self.current_accuracy, self.voltage_accuracy) / math.sqrt(3.0)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def config_hash(config: CapacityConfig | RecordConfig) -> str:
|
|
151
|
+
"""The first 12 hex digits of the SHA-256 of the settings, as sorted JSON."""
|
|
152
|
+
text = json.dumps(asdict(config), sort_keys=True, separators=(",", ":"))
|
|
153
|
+
return hashlib.sha256(text.encode()).hexdigest()[:12]
|