celltwin 0.3.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.
Files changed (48) hide show
  1. celltwin/__init__.py +119 -0
  2. celltwin/core/__init__.py +13 -0
  3. celltwin/core/history.py +252 -0
  4. celltwin/core/persistence.py +372 -0
  5. celltwin/core/twin.py +1078 -0
  6. celltwin/data/__init__.py +55 -0
  7. celltwin/data/adapters/__init__.py +61 -0
  8. celltwin/data/adapters/mcmaster.py +248 -0
  9. celltwin/data/adapters/nasa.py +387 -0
  10. celltwin/data/adapters/stanford.py +216 -0
  11. celltwin/data/dataset.py +274 -0
  12. celltwin/data/loader.py +305 -0
  13. celltwin/data/preprocessing.py +386 -0
  14. celltwin/data/synthetic.py +528 -0
  15. celltwin/data/validation.py +397 -0
  16. celltwin/estimation/__init__.py +106 -0
  17. celltwin/estimation/ageing_fitting.py +403 -0
  18. celltwin/estimation/capacity.py +489 -0
  19. celltwin/estimation/checkpoint.py +220 -0
  20. celltwin/estimation/electrochemical_fitting.py +296 -0
  21. celltwin/estimation/metrics.py +94 -0
  22. celltwin/estimation/ocv_extraction.py +225 -0
  23. celltwin/estimation/parameter_fitting.py +966 -0
  24. celltwin/estimation/parameter_tracking.py +355 -0
  25. celltwin/estimation/prediction.py +290 -0
  26. celltwin/estimation/resistance.py +142 -0
  27. celltwin/estimation/soc_dependent_fitting.py +558 -0
  28. celltwin/estimation/state_estimation.py +1004 -0
  29. celltwin/estimation/temperature.py +643 -0
  30. celltwin/estimation/thermal_fitting.py +187 -0
  31. celltwin/exceptions.py +70 -0
  32. celltwin/models/__init__.py +81 -0
  33. celltwin/models/degradation.py +313 -0
  34. celltwin/models/electrical.py +1300 -0
  35. celltwin/models/electrochemical.py +515 -0
  36. celltwin/models/ocv.py +268 -0
  37. celltwin/models/temperature.py +318 -0
  38. celltwin/models/thermal.py +325 -0
  39. celltwin/py.typed +0 -0
  40. celltwin/utils/__init__.py +6 -0
  41. celltwin/utils/arrays.py +66 -0
  42. celltwin/utils/units.py +121 -0
  43. celltwin/visualization/__init__.py +31 -0
  44. celltwin/visualization/plots.py +332 -0
  45. celltwin-0.3.0.dist-info/METADATA +523 -0
  46. celltwin-0.3.0.dist-info/RECORD +48 -0
  47. celltwin-0.3.0.dist-info/WHEEL +4 -0
  48. celltwin-0.3.0.dist-info/licenses/LICENSE +21 -0
celltwin/__init__.py ADDED
@@ -0,0 +1,119 @@
1
+ """CellTwin: calibrated lithium-ion battery models from experimental cycling data.
2
+
3
+ Current sign convention throughout the package: **positive current = discharge**.
4
+
5
+ Main entry points
6
+ -----------------
7
+ * :class:`DigitalTwin` - high-level workflow (load, set OCV, fit, simulate, evaluate).
8
+ * :func:`load_csv` / :class:`ColumnMapping` - data import with unit conversion.
9
+ * :class:`TheveninModel` / :class:`TheveninParameters` - one- or two-RC ECM.
10
+ * :func:`fit_thevenin` - nonlinear least-squares parameter estimation.
11
+ * :class:`ExtendedKalmanFilter` - online SOC and state estimation from measurements.
12
+ * :class:`ParameterTracker` - online resistance and capacity estimation with the filter.
13
+ * :class:`ElectroThermalModel` / :func:`fit_thermal` - lumped thermal model.
14
+ * :func:`fit_ageing` / :func:`forecast_ageing` - semi-empirical ageing.
15
+ * :class:`ElectrochemicalModel` - single-particle models through PyBaMM (optional).
16
+ """
17
+
18
+ from celltwin.core.history import CellHistory, HistoryRecord
19
+ from celltwin.core.twin import DigitalTwin, EvaluationResult, ModelVersion, RecalibrationReport
20
+ from celltwin.data.dataset import CyclingData
21
+ from celltwin.data.loader import ColumnMapping, from_dataframe, load_csv
22
+ from celltwin.estimation.ageing_fitting import AgeingRecord, fit_ageing, forecast_ageing
23
+ from celltwin.estimation.capacity import CapacityEstimator
24
+ from celltwin.estimation.electrochemical_fitting import (
25
+ fit_electrochemical,
26
+ fit_stoichiometry_window,
27
+ )
28
+ from celltwin.estimation.metrics import ErrorMetrics, compute_error_metrics
29
+ from celltwin.estimation.parameter_fitting import FitResult, fit_thevenin
30
+ from celltwin.estimation.parameter_tracking import ParameterTracker
31
+ from celltwin.estimation.prediction import PredictionResult, predict_ahead
32
+ from celltwin.estimation.resistance import ResistanceEstimator
33
+ from celltwin.estimation.soc_dependent_fitting import fit_thevenin_soc_dependent
34
+ from celltwin.estimation.state_estimation import (
35
+ EKFNoise,
36
+ ExtendedKalmanFilter,
37
+ StateEstimationResult,
38
+ )
39
+ from celltwin.estimation.thermal_fitting import fit_thermal, measured_heat_w
40
+ from celltwin.models.degradation import (
41
+ AgeingParameters,
42
+ UsageProfile,
43
+ aged_parameters,
44
+ simulate_ageing,
45
+ )
46
+ from celltwin.models.electrical import (
47
+ OperatingLimits,
48
+ SimulationResult,
49
+ SOCDependentParameters,
50
+ TheveninModel,
51
+ TheveninParameters,
52
+ )
53
+ from celltwin.models.electrochemical import (
54
+ ElectrochemicalModel,
55
+ ElectrochemicalParameters,
56
+ StoichiometryWindow,
57
+ )
58
+ from celltwin.models.ocv import OCVCurve
59
+ from celltwin.models.temperature import TemperatureDependentParameters
60
+ from celltwin.models.thermal import (
61
+ ElectroThermalModel,
62
+ ThermalParameters,
63
+ heat_generation_w,
64
+ simulate_temperature,
65
+ )
66
+
67
+ __version__ = "0.3.0"
68
+
69
+ __all__ = [
70
+ "AgeingParameters",
71
+ "AgeingRecord",
72
+ "CapacityEstimator",
73
+ "CellHistory",
74
+ "ColumnMapping",
75
+ "CyclingData",
76
+ "DigitalTwin",
77
+ "EKFNoise",
78
+ "ElectroThermalModel",
79
+ "ElectrochemicalModel",
80
+ "ElectrochemicalParameters",
81
+ "ErrorMetrics",
82
+ "EvaluationResult",
83
+ "ExtendedKalmanFilter",
84
+ "FitResult",
85
+ "HistoryRecord",
86
+ "ModelVersion",
87
+ "OCVCurve",
88
+ "OperatingLimits",
89
+ "ParameterTracker",
90
+ "PredictionResult",
91
+ "RecalibrationReport",
92
+ "ResistanceEstimator",
93
+ "SOCDependentParameters",
94
+ "SimulationResult",
95
+ "StateEstimationResult",
96
+ "StoichiometryWindow",
97
+ "TemperatureDependentParameters",
98
+ "ThermalParameters",
99
+ "TheveninModel",
100
+ "TheveninParameters",
101
+ "UsageProfile",
102
+ "__version__",
103
+ "aged_parameters",
104
+ "compute_error_metrics",
105
+ "fit_ageing",
106
+ "fit_electrochemical",
107
+ "fit_stoichiometry_window",
108
+ "fit_thermal",
109
+ "fit_thevenin",
110
+ "fit_thevenin_soc_dependent",
111
+ "forecast_ageing",
112
+ "from_dataframe",
113
+ "heat_generation_w",
114
+ "load_csv",
115
+ "measured_heat_w",
116
+ "predict_ahead",
117
+ "simulate_ageing",
118
+ "simulate_temperature",
119
+ ]
@@ -0,0 +1,13 @@
1
+ """High-level workflow objects."""
2
+
3
+ from celltwin.core.history import CellHistory, HistoryRecord
4
+ from celltwin.core.twin import DigitalTwin, EvaluationResult, ModelVersion, RecalibrationReport
5
+
6
+ __all__ = [
7
+ "CellHistory",
8
+ "DigitalTwin",
9
+ "EvaluationResult",
10
+ "HistoryRecord",
11
+ "ModelVersion",
12
+ "RecalibrationReport",
13
+ ]
@@ -0,0 +1,252 @@
1
+ """Persistent record of a cell's estimated capacity and resistance over time.
2
+
3
+ A :class:`CellHistory` holds one :class:`HistoryRecord` per ingested measurement
4
+ record, an optional new-cell **baseline**, and the capacity segments carried from one
5
+ record to the next. It is what lets estimates continue across sessions and be compared
6
+ over a cell's life.
7
+
8
+ State of health here means a ratio to the baseline: capacity divided by baseline
9
+ capacity, and resistance factor divided by baseline factor. Neither is meaningful
10
+ without a baseline, and both inherit the estimators' errors; in particular they depend
11
+ on temperature unless the model accounts for it.
12
+
13
+ A resistance factor is a multiplier on one particular set of model parameters. Every
14
+ record and the resistance baseline therefore carry that set's hash, and factors
15
+ measured against different parameter sets (for example before and after a
16
+ recalibration) are never carried over or divided by one another. Capacity is in
17
+ ampere-hours and does not depend on the circuit parameters.
18
+
19
+ Records hold estimates and provenance (a content hash of the data), never the
20
+ measurements themselves. Values that could not be estimated are None, not filled in.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from collections.abc import Sequence
27
+ from dataclasses import asdict, dataclass, field, fields
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ from celltwin.core.persistence import (
35
+ _finite_numbers,
36
+ _number,
37
+ _object,
38
+ _read_json,
39
+ _text,
40
+ _write_json,
41
+ )
42
+ from celltwin.estimation.capacity import CapacitySegment
43
+ from celltwin.exceptions import ModelFormatError, ParameterError
44
+
45
+ HISTORY_SCHEMA_VERSION = 2
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class HistoryRecord:
50
+ """Estimates obtained from one measurement record.
51
+
52
+ ``capacity_ah`` is the estimate from all capacity segments collected up to and
53
+ including this record; ``new_capacity_segments`` says how many this record added.
54
+ """
55
+
56
+ data_hash: str
57
+ model_hash: str
58
+ label: str | None
59
+ timestamp: str | None
60
+ duration_s: float
61
+ discharge_throughput_ah: float
62
+ mean_temperature_c: float | None
63
+ final_soc: float
64
+ final_soc_std: float
65
+ capacity_ah: float | None
66
+ capacity_std_ah: float | None
67
+ new_capacity_segments: int
68
+ resistance_factor: float | None
69
+ resistance_factor_std: float | None
70
+ resistance_updates: int
71
+
72
+
73
+ _TEXT_FIELDS = {"data_hash", "model_hash", "label", "timestamp"}
74
+ _OPTIONAL_FIELDS = {
75
+ "label",
76
+ "timestamp",
77
+ "mean_temperature_c",
78
+ "capacity_ah",
79
+ "capacity_std_ah",
80
+ "resistance_factor",
81
+ "resistance_factor_std",
82
+ }
83
+
84
+
85
+ @dataclass
86
+ class CellHistory:
87
+ """Estimates over a cell's life; see the module documentation."""
88
+
89
+ records: list[HistoryRecord] = field(default_factory=list)
90
+ capacity_segments: list[CapacitySegment] = field(default_factory=list)
91
+ baseline_capacity_ah: float | None = None
92
+ baseline_resistance_factor: float | None = None
93
+ baseline_model_hash: str | None = None
94
+
95
+ def __len__(self) -> int:
96
+ return len(self.records)
97
+
98
+ def contains(self, data_hash: str) -> bool:
99
+ """True if a record with this data hash was already added."""
100
+ return any(record.data_hash == data_hash for record in self.records)
101
+
102
+ def set_baseline(
103
+ self,
104
+ *,
105
+ capacity_ah: float | None = None,
106
+ resistance_factor: float | None = None,
107
+ model_hash: str | None = None,
108
+ ) -> None:
109
+ """Declare the new-cell values; None leaves a value unchanged.
110
+
111
+ A resistance factor belongs to a parameter set. ``model_hash`` names it
112
+ (:attr:`DigitalTwin.parameter_hash`); by default it is that of the latest
113
+ record holding a resistance factor.
114
+ """
115
+ for name, value in (
116
+ ("capacity_ah", capacity_ah),
117
+ ("resistance_factor", resistance_factor),
118
+ ):
119
+ if value is not None and not (np.isfinite(value) and value > 0.0):
120
+ raise ParameterError(f"{name} must be positive and finite.")
121
+ if resistance_factor is not None and model_hash is None:
122
+ measured = [r for r in self.records if r.resistance_factor is not None]
123
+ if not measured:
124
+ raise ParameterError(
125
+ "No record holds a resistance factor yet; pass model_hash "
126
+ "(DigitalTwin.parameter_hash) with the baseline."
127
+ )
128
+ model_hash = measured[-1].model_hash
129
+ if capacity_ah is not None:
130
+ self.baseline_capacity_ah = float(capacity_ah)
131
+ if resistance_factor is not None:
132
+ self.baseline_resistance_factor = float(resistance_factor)
133
+ self.baseline_model_hash = model_hash
134
+
135
+ def latest(self, name: str, *, model_hash: str | None = None) -> float | None:
136
+ """Most recent non-None value of a record field, or None.
137
+
138
+ With ``model_hash`` only records made with that parameter set are considered.
139
+ """
140
+ for record in reversed(self.records):
141
+ if model_hash is not None and record.model_hash != model_hash:
142
+ continue
143
+ value = getattr(record, name)
144
+ if value is not None:
145
+ return float(value)
146
+ return None
147
+
148
+ def to_frame(self) -> pd.DataFrame:
149
+ """One row per record, with state-of-health ratios where a baseline exists."""
150
+ columns = [f.name for f in fields(HistoryRecord)]
151
+ frame = pd.DataFrame([asdict(r) for r in self.records], columns=columns)
152
+ if self.baseline_capacity_ah is not None:
153
+ frame["capacity_soh"] = frame.capacity_ah.astype(float) / self.baseline_capacity_ah
154
+ if self.baseline_resistance_factor is not None:
155
+ ratio = frame.resistance_factor.astype(float) / self.baseline_resistance_factor
156
+ frame["resistance_ratio"] = ratio.where(frame.model_hash == self.baseline_model_hash)
157
+ return frame
158
+
159
+ # ------------------------------------------------------------------ files
160
+ def save(self, path: str | Path, *, overwrite: bool = False) -> Path:
161
+ """Atomically write the history as versioned JSON."""
162
+ document = {
163
+ "format": "celltwin.history",
164
+ "schema_version": HISTORY_SCHEMA_VERSION,
165
+ "baseline": {
166
+ "capacity_ah": self.baseline_capacity_ah,
167
+ "resistance_factor": self.baseline_resistance_factor,
168
+ "model_hash": self.baseline_model_hash,
169
+ },
170
+ "records": [asdict(r) for r in self.records],
171
+ "capacity_segments": [asdict(s) for s in self.capacity_segments],
172
+ }
173
+ try:
174
+ _restore(document)
175
+ payload = json.dumps(document, indent=2, allow_nan=False) + "\n"
176
+ except (ValueError, TypeError, KeyError, OverflowError) as error:
177
+ if isinstance(error, ModelFormatError):
178
+ raise
179
+ raise ModelFormatError(f"Cannot save invalid history: {error}") from error
180
+ return _write_json(payload, Path(path), overwrite=overwrite)
181
+
182
+ @classmethod
183
+ def load(cls, path: str | Path) -> CellHistory:
184
+ """Read a history written by :meth:`save`."""
185
+ try:
186
+ return _restore(_read_json(path))
187
+ except (ValueError, TypeError, KeyError, OverflowError) as error:
188
+ if isinstance(error, ModelFormatError):
189
+ raise
190
+ raise ModelFormatError(f"Invalid history: {error}") from error
191
+
192
+
193
+ def _positive_or_none(value: Any) -> float | None:
194
+ if value is None:
195
+ return None
196
+ number = _number(value)
197
+ if not number > 0.0:
198
+ raise ModelFormatError("Baseline values must be positive.")
199
+ return number
200
+
201
+
202
+ def _record(document: Any) -> HistoryRecord:
203
+ values = _object(document, {f.name for f in fields(HistoryRecord)})
204
+ for name, value in values.items():
205
+ if value is None:
206
+ if name not in _OPTIONAL_FIELDS:
207
+ raise ModelFormatError(f"History field {name} must not be null.")
208
+ elif name in _TEXT_FIELDS:
209
+ if not isinstance(value, str):
210
+ raise ModelFormatError(f"History field {name} must be a string.")
211
+ else:
212
+ _number(value)
213
+ return HistoryRecord(**values)
214
+
215
+
216
+ def _segment(document: Any, version: int) -> CapacitySegment:
217
+ names = {f.name for f in fields(CapacitySegment)}
218
+ if version == 1:
219
+ names.remove("soc_change_bias") # added in version 2; zero for older segments
220
+ values = _object(document, names)
221
+ segment = CapacitySegment(**{name: _number(value) for name, value in values.items()})
222
+ if segment.charge_std_ah < 0.0 or not segment.soc_change_std > 0.0:
223
+ raise ModelFormatError("Segment uncertainties are invalid.")
224
+ return segment
225
+
226
+
227
+ def _restore(document: Any) -> CellHistory:
228
+ _finite_numbers(document)
229
+ doc = _object(
230
+ document,
231
+ {"format", "schema_version", "baseline", "records", "capacity_segments"},
232
+ )
233
+ if doc["format"] != "celltwin.history":
234
+ raise ModelFormatError("Not a CellTwin history document.")
235
+ version = doc["schema_version"]
236
+ if type(version) is not int or version not in (1, HISTORY_SCHEMA_VERSION):
237
+ raise ModelFormatError(f"Unsupported schema_version: {doc['schema_version']!r}.")
238
+ baseline = _object(doc["baseline"], {"capacity_ah", "resistance_factor", "model_hash"})
239
+ model_hash = _text(baseline["model_hash"])
240
+ if (model_hash is None) != (baseline["resistance_factor"] is None):
241
+ raise ModelFormatError("A resistance baseline and its model_hash belong together.")
242
+ records: Sequence[Any] = doc["records"]
243
+ segments: Sequence[Any] = doc["capacity_segments"]
244
+ if not isinstance(records, list) or not isinstance(segments, list):
245
+ raise ModelFormatError("records and capacity_segments must be lists.")
246
+ return CellHistory(
247
+ [_record(r) for r in records],
248
+ [_segment(s, version) for s in segments],
249
+ _positive_or_none(baseline["capacity_ah"]),
250
+ _positive_or_none(baseline["resistance_factor"]),
251
+ model_hash,
252
+ )