blowing-bubbles 0.2.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 (34) hide show
  1. blowing_bubbles/__init__.py +19 -0
  2. blowing_bubbles/circuit_impedance/__init__.py +15 -0
  3. blowing_bubbles/circuit_impedance/impedance.py +288 -0
  4. blowing_bubbles/classes/__init__.py +25 -0
  5. blowing_bubbles/classes/circuit_classes.py +999 -0
  6. blowing_bubbles/classes/data_classes.py +1036 -0
  7. blowing_bubbles/py.typed +0 -0
  8. blowing_bubbles/scripts/__init__.py +18 -0
  9. blowing_bubbles/scripts/fit_circuit.py +601 -0
  10. blowing_bubbles/scripts/global_minimize.py +1393 -0
  11. blowing_bubbles/scripts/quality.py +224 -0
  12. blowing_bubbles/ui/__init__.py +26 -0
  13. blowing_bubbles/ui/__main__.py +13 -0
  14. blowing_bubbles/ui/analysis.py +250 -0
  15. blowing_bubbles/ui/analysis_plots.py +127 -0
  16. blowing_bubbles/ui/app.py +613 -0
  17. blowing_bubbles/ui/assets/icon-128.png +0 -0
  18. blowing_bubbles/ui/assets/icon-16.png +0 -0
  19. blowing_bubbles/ui/assets/icon-256.png +0 -0
  20. blowing_bubbles/ui/assets/icon-32.png +0 -0
  21. blowing_bubbles/ui/assets/icon-48.png +0 -0
  22. blowing_bubbles/ui/assets/icon-512.png +0 -0
  23. blowing_bubbles/ui/assets/icon-64.png +0 -0
  24. blowing_bubbles/ui/assets/icon.png +0 -0
  25. blowing_bubbles/ui/assets/icon.svg +6 -0
  26. blowing_bubbles/ui/batch.py +250 -0
  27. blowing_bubbles/ui/desktop.py +219 -0
  28. blowing_bubbles/ui/folder_picker.py +73 -0
  29. blowing_bubbles/ui/live.py +129 -0
  30. blowing_bubbles/ui/plots.py +159 -0
  31. blowing_bubbles-0.2.0.dist-info/METADATA +108 -0
  32. blowing_bubbles-0.2.0.dist-info/RECORD +34 -0
  33. blowing_bubbles-0.2.0.dist-info/WHEEL +4 -0
  34. blowing_bubbles-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,999 @@
1
+ r"""Parameter containers and fit result wrappers for equivalent-circuit EIS.
2
+
3
+ :class:`CircuitParameters` holds the parameters of the R–CPE ladder (with JSON
4
+ save/load and Nyquist plotting), :class:`FitResults` wraps a SciPy least-squares
5
+ result together with parameter uncertainties, and :func:`align_axes_height`
6
+ lines up subplot boxes. See :mod:`blowing_bubbles.circuit_impedance` for the
7
+ impedance model.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import warnings
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, overload
16
+
17
+ import numpy as np
18
+ from scipy.optimize import OptimizeResult
19
+
20
+ if TYPE_CHECKING:
21
+ from matplotlib import pyplot as plt
22
+ from matplotlib.axes import Axes
23
+
24
+ from blowing_bubbles.circuit_impedance import circuit_impedance
25
+
26
+ _CIRCUIT_PARAMS_FORMAT_VERSION = 1
27
+ _CIRCUIT_PARAMS_FILE_TYPE = "blowing_bubbles.CircuitParameters"
28
+ _FIT_LABEL = r"$[R_s L(R_i C_i)]$ fit"
29
+ _TEXT_BBOX = {
30
+ "facecolor": "white",
31
+ "alpha": 0.8,
32
+ "edgecolor": "none",
33
+ "boxstyle": "round,pad=0.2",
34
+ }
35
+
36
+
37
+ def align_axes_height(
38
+ axes: list[Axes] | tuple[Axes, ...],
39
+ reference: Axes | None = None,
40
+ ) -> None:
41
+ """Match the box height and bottom edge of subplots to a reference axes.
42
+
43
+ Call after :meth:`matplotlib.figure.Figure.tight_layout`, which would
44
+ otherwise override the positions again.
45
+
46
+ Parameters
47
+ ----------
48
+ axes : list or tuple of matplotlib.axes.Axes
49
+ Axes to align; their positions are modified in place (x position and
50
+ width are kept).
51
+ reference : matplotlib.axes.Axes, optional
52
+ Axes whose bottom edge and height are copied. ``None`` (default) uses
53
+ the last element of *axes*.
54
+ """
55
+ if reference is None:
56
+ reference = axes[-1]
57
+ ref = reference.get_position()
58
+ for ax in axes:
59
+ pos = ax.get_position()
60
+ ax.set_position((pos.x0, ref.y0, pos.width, ref.height))
61
+
62
+
63
+ def _plot_full_fit(
64
+ freqs: np.ndarray,
65
+ parameters: CircuitParameters,
66
+ axis: plt.Axes | None = None,
67
+ unit: str | None = None,
68
+ ):
69
+ """Draw the total model curve and each branch arc; see ``plot_full_fit``.
70
+
71
+ The total curve is evaluated at *freqs*; each single-branch arc is drawn on
72
+ a fixed grid ``logspace(-10, 10, 500)`` Hz, shifted right by :math:`R_s`
73
+ plus the resistances of the preceding (smaller-tau) branches. Only the
74
+ inductance term is included in the first arc. Returns the axes drawn on.
75
+ """
76
+ if unit is None:
77
+ warnings.warn(
78
+ "No unit provided, using default unit: Omega cm^2",
79
+ stacklevel=2,
80
+ )
81
+ unit = r"$\Omega$ cm$^{2}$"
82
+ if axis is None:
83
+ from matplotlib import pyplot as plt
84
+
85
+ _, axis = plt.subplots()
86
+ Z_pred = parameters.get_impedance(freqs)
87
+
88
+ axis.plot(
89
+ Z_pred.real,
90
+ -Z_pred.imag,
91
+ label=_FIT_LABEL,
92
+ color="black",
93
+ ls="--",
94
+ )
95
+
96
+ n_groups = len(parameters)
97
+
98
+ for i in range(n_groups):
99
+ rs_i = parameters.resistance_source + np.sum(parameters.resistances[:i])
100
+ ri_i = parameters.resistances[i]
101
+ branch_freq = np.logspace(-10, 10, 500)
102
+ branch_r = np.array([ri_i])
103
+ branch_c = np.array([parameters.capacitances[i]])
104
+ branch_e = np.array([parameters.exponents[i]])
105
+
106
+ if i == 0:
107
+ # With inductance
108
+ _Zi_pred_L = np.atleast_1d(
109
+ circuit_impedance(
110
+ branch_freq,
111
+ resistance_source=rs_i,
112
+ resistances=branch_r,
113
+ capacitances=branch_c,
114
+ exponents=branch_e,
115
+ inductance=parameters.inductance,
116
+ inductance_exponent=parameters.inductance_exponent,
117
+ )
118
+ )
119
+ mask_L = _Zi_pred_L.imag < 0
120
+ axis.plot(
121
+ _Zi_pred_L.real[mask_L],
122
+ -_Zi_pred_L.imag[mask_L],
123
+ label=rf"$(R_{n_groups} C_{n_groups})$ fit with one group (with $L$)",
124
+ )
125
+ # Calculate and print R1 at the midpoint of this arc, at y=0
126
+ xline = _Zi_pred_L.real[mask_L]
127
+ if len(xline) > 1:
128
+ xmid = rs_i + ri_i / 2
129
+ axis.text(
130
+ xmid,
131
+ -np.max(np.abs(Z_pred.imag)) * 0.2,
132
+ rf"$R_{n_groups}$",
133
+ fontsize=12,
134
+ va="bottom",
135
+ ha="center",
136
+ color=axis.lines[-1].get_color(),
137
+ fontweight="bold",
138
+ bbox=_TEXT_BBOX,
139
+ )
140
+ else:
141
+ _Zi_pred = np.atleast_1d(
142
+ circuit_impedance(
143
+ branch_freq,
144
+ resistance_source=rs_i,
145
+ resistances=branch_r,
146
+ capacitances=branch_c,
147
+ exponents=branch_e,
148
+ inductance=0,
149
+ inductance_exponent=1,
150
+ )
151
+ )
152
+ mask = _Zi_pred.imag < 0
153
+ axis.plot(
154
+ _Zi_pred.real[mask],
155
+ -_Zi_pred.imag[mask],
156
+ label=rf"$(R_{n_groups - i} C_{n_groups - i})$ fit with one group",
157
+ )
158
+ # Calculate and print Ri at the midpoint of this arc, at y=0
159
+ xline = _Zi_pred.real[mask]
160
+ if len(xline) > 1:
161
+ xmid = rs_i + ri_i / 2
162
+ axis.text(
163
+ xmid,
164
+ -np.max(np.abs(Z_pred.imag)) * 0.2,
165
+ rf"$R_{n_groups - i}$",
166
+ fontsize=12,
167
+ va="bottom",
168
+ ha="center",
169
+ color=axis.lines[-1].get_color(),
170
+ fontweight="bold",
171
+ bbox=_TEXT_BBOX,
172
+ )
173
+
174
+ # datalim: equal aspect adjusts limits, not axes box height
175
+ axis.set_aspect("equal", adjustable="datalim")
176
+ axis.grid(True)
177
+ axis.spines["right"].set_visible(False)
178
+ axis.spines["top"].set_visible(False)
179
+ axis.set_xlabel("Z' " + unit)
180
+ axis.set_ylabel("-Z'' " + unit)
181
+ return axis
182
+
183
+
184
+ def _tau_sort_index(resistances: np.ndarray, capacitances: np.ndarray) -> np.ndarray:
185
+ r"""Branch order used by :meth:`CircuitParameters.sort_by_tau` (by :math:`R C`)."""
186
+ return np.argsort(np.asarray(capacitances) * np.asarray(resistances))
187
+
188
+
189
+ class CircuitParameters:
190
+ r"""Parameters of the R–CPE ladder used in BlowingBubbles EIS fitting.
191
+
192
+ Parameters
193
+ ----------
194
+ resistance_source : float
195
+ Series resistance :math:`R_s` (Ω).
196
+ inductance : float
197
+ Inductance :math:`L` (H for :math:`n_L = 1`) of the constant-phase
198
+ inductor term.
199
+ inductance_exponent : float
200
+ Inductor exponent :math:`n_L`.
201
+ resistances : numpy.ndarray, shape (n_branches,)
202
+ Branch resistances :math:`R_i` (Ω).
203
+ capacitances : numpy.ndarray, shape (n_branches,)
204
+ Branch (pseudo-)capacitances :math:`C_i` (F for :math:`e_i = 1`).
205
+ exponents : numpy.ndarray, shape (n_branches,)
206
+ Branch CPE exponents :math:`e_i` (1 for an ideal capacitor).
207
+
208
+ Attributes
209
+ ----------
210
+ resistance_source, inductance, inductance_exponent : float
211
+ Global parameters :math:`R_s`, :math:`L`, :math:`n_L`.
212
+ resistances, capacitances, exponents : numpy.ndarray, shape (n_branches,)
213
+ Branch parameters, sorted by increasing :math:`\tau_i`.
214
+ taus : numpy.ndarray, shape (n_branches,)
215
+ Products :math:`\tau_i = R_i C_i` (units :math:`\mathrm{s}^{e_i}`),
216
+ kept in sync with the branch arrays.
217
+
218
+ See Also
219
+ --------
220
+ FitResults : Fit result holding a fitted ``CircuitParameters``.
221
+ blowing_bubbles.circuit_impedance.circuit_impedance : Impedance model.
222
+
223
+ Notes
224
+ -----
225
+ The impedance model is (see
226
+ :func:`~blowing_bubbles.circuit_impedance.circuit_impedance`):
227
+
228
+ .. math::
229
+
230
+ Z(\omega) = R_s + (j\omega)^{n_L} L
231
+ + \sum_{i=1}^{n} \frac{R_i}{1 + R_i C_i (j\omega)^{e_i}}
232
+
233
+ with :math:`\omega = 2\pi f`. The constructor copies the input arrays and
234
+ sorts the branches by increasing :math:`\tau_i = R_i C_i`; the mutating
235
+ methods (:meth:`add_branch`, :meth:`drop_branch`, :meth:`pop_branch`)
236
+ preserve this order, while :meth:`sort_by_capacitance` replaces it. For
237
+ area-normalized spectra the resistances are in Ω·cm² and the capacitances
238
+ in F/cm².
239
+ """
240
+
241
+ def __init__(
242
+ self,
243
+ resistance_source: float,
244
+ inductance: float,
245
+ inductance_exponent: float,
246
+ resistances: np.ndarray,
247
+ capacitances: np.ndarray,
248
+ exponents: np.ndarray,
249
+ ):
250
+ r"""Build parameters and sort branches by :math:`\tau_i = R_i C_i`."""
251
+ self.resistance_source = float(resistance_source)
252
+ self.inductance = float(inductance)
253
+ self.inductance_exponent = float(inductance_exponent)
254
+ self.resistances = np.array(resistances)
255
+ self.capacitances = np.array(capacitances)
256
+ self.exponents = np.array(exponents)
257
+ self.taus = self.capacitances * self.resistances
258
+ self.sort_by_tau()
259
+
260
+ @property
261
+ def characteristic_times(self) -> np.ndarray:
262
+ r"""Characteristic time constants :math:`\tau_{c,i} = (R_i C_i)^{1/e_i}` (s).
263
+
264
+ Array of shape ``(n_branches,)`` in the stored branch order.
265
+ ``taus`` stores the product :math:`R_i C_i` (units
266
+ :math:`\mathrm{s}^{e_i}`), which is what the optimiser orders and
267
+ parameterises. The apex of branch :math:`i` lies at
268
+ :math:`\omega_i = 1/\tau_{c,i}`.
269
+ """
270
+ return np.power(self.resistances * self.capacitances, 1.0 / self.exponents)
271
+
272
+ @property
273
+ def peak_frequencies(self) -> np.ndarray:
274
+ r"""Apex frequencies :math:`f_i = 1 / (2\pi\,\tau_{c,i})` (Hz).
275
+
276
+ Array of shape ``(n_branches,)``; see :attr:`characteristic_times`.
277
+ """
278
+ return 1.0 / (2.0 * np.pi * self.characteristic_times)
279
+
280
+ def sort_by_tau(self):
281
+ r"""Sort the branches by increasing :math:`\tau_i = R_i C_i`, in place.
282
+
283
+ ``resistances``, ``capacitances``, ``exponents`` and ``taus`` are
284
+ reordered together.
285
+ """
286
+ sort_idx = _tau_sort_index(self.resistances, self.capacitances)
287
+ self.resistances = self.resistances[sort_idx]
288
+ self.capacitances = self.capacitances[sort_idx]
289
+ self.exponents = self.exponents[sort_idx]
290
+ self.taus = self.capacitances * self.resistances
291
+
292
+ def sort_by_capacitance(self):
293
+ """Sort the branches by increasing capacitance, in place.
294
+
295
+ ``resistances``, ``capacitances``, ``exponents`` and ``taus`` are
296
+ reordered together.
297
+
298
+ Notes
299
+ -----
300
+ This replaces the tau order established by the constructor. Methods
301
+ that refer to tau order (e.g. :meth:`pop_branch`, which removes the
302
+ last branch) then act on the capacitance order instead.
303
+ """
304
+ sort_idx = np.argsort(self.capacitances)
305
+ self.resistances = self.resistances[sort_idx]
306
+ self.capacitances = self.capacitances[sort_idx]
307
+ self.exponents = self.exponents[sort_idx]
308
+ self.taus = self.capacitances * self.resistances
309
+
310
+ def _set_branches(
311
+ self,
312
+ resistances: np.ndarray,
313
+ capacitances: np.ndarray,
314
+ exponents: np.ndarray,
315
+ ) -> None:
316
+ """Replace the branch arrays and recompute ``taus`` (no re-sorting)."""
317
+ self.resistances = np.asarray(resistances, dtype=float)
318
+ self.capacitances = np.asarray(capacitances, dtype=float)
319
+ self.exponents = np.asarray(exponents, dtype=float)
320
+ self.taus = self.capacitances * self.resistances
321
+
322
+ def add_branch(
323
+ self,
324
+ resistance: float,
325
+ capacitance: float,
326
+ exponent: float = 1.0,
327
+ ) -> None:
328
+ """Add an R–CPE branch and re-sort the branches by tau, in place.
329
+
330
+ Parameters
331
+ ----------
332
+ resistance : float
333
+ Branch resistance :math:`R` (Ω).
334
+ capacitance : float
335
+ Branch capacitance :math:`C` (F for an ideal capacitor).
336
+ exponent : float, default 1.0
337
+ CPE exponent :math:`e` (1 gives an ideal RC branch).
338
+ """
339
+ self._set_branches(
340
+ np.append(self.resistances, resistance),
341
+ np.append(self.capacitances, capacitance),
342
+ np.append(self.exponents, exponent),
343
+ )
344
+ self.sort_by_tau()
345
+
346
+ def drop_branch(self, index: int) -> None:
347
+ """Remove the branch at *index*, in place.
348
+
349
+ Parameters
350
+ ----------
351
+ index : int
352
+ Position in the stored (tau-sorted) branch order; negative indices
353
+ count from the end.
354
+
355
+ Raises
356
+ ------
357
+ IndexError
358
+ If *index* is out of range for the number of branches.
359
+ """
360
+ n = len(self)
361
+ if index < 0:
362
+ index += n
363
+ if not 0 <= index < n:
364
+ raise IndexError(f"branch index {index} out of range for {n} branches")
365
+ keep = np.delete(np.arange(n), index)
366
+ self._set_branches(
367
+ self.resistances[keep],
368
+ self.capacitances[keep],
369
+ self.exponents[keep],
370
+ )
371
+
372
+ def pop_branch(self) -> tuple[float, float, float]:
373
+ """Remove and return the last branch (largest tau), in place.
374
+
375
+ Returns
376
+ -------
377
+ resistance : float
378
+ Resistance of the removed branch (Ω).
379
+ capacitance : float
380
+ Capacitance of the removed branch.
381
+ exponent : float
382
+ CPE exponent of the removed branch.
383
+
384
+ Raises
385
+ ------
386
+ IndexError
387
+ If there are no branches.
388
+ """
389
+ if len(self) == 0:
390
+ raise IndexError("no branches to pop")
391
+ r = float(self.resistances[-1])
392
+ c = float(self.capacitances[-1])
393
+ e = float(self.exponents[-1])
394
+ self.drop_branch(-1)
395
+ return r, c, e
396
+
397
+ def as_dict(self) -> dict:
398
+ """Return the parameters as a flat dict of floats and arrays.
399
+
400
+ Returns
401
+ -------
402
+ params : dict
403
+ Keys ``resistance_source``, ``inductance``, ``inductance_exponent``
404
+ (float) and ``resistances``, ``capacitances``, ``exponents``,
405
+ ``taus`` (numpy.ndarray, shape ``(n_branches,)``). The arrays are
406
+ the instance's own arrays, not copies.
407
+
408
+ See Also
409
+ --------
410
+ to_dict : JSON-friendly nested layout used by :meth:`save`.
411
+ """
412
+ return {
413
+ "resistance_source": self.resistance_source,
414
+ "inductance": self.inductance,
415
+ "inductance_exponent": self.inductance_exponent,
416
+ "resistances": self.resistances,
417
+ "capacitances": self.capacitances,
418
+ "exponents": self.exponents,
419
+ "taus": self.taus,
420
+ }
421
+
422
+ def __len__(self):
423
+ """Return the number of parallel branches."""
424
+ return len(self.taus)
425
+
426
+ def __str__(self):
427
+ """Return a multi-line, fixed-width summary of all parameters."""
428
+ # Format floats to 8 chars (sign, int, dot, decimals).
429
+
430
+ def _format_arr(arr):
431
+ if isinstance(arr, np.ndarray):
432
+ # For 1D array of floats
433
+ return "[" + " ".join([f"{x:10.4e}" for x in arr]) + "]"
434
+
435
+ else:
436
+ return str(arr)
437
+
438
+ return (
439
+ f" Resistance Source: {self.resistance_source:12.4e}\n"
440
+ f" Inductance: {self.inductance:12.4e}\n"
441
+ f" Inductance Exponent: {self.inductance_exponent:12.4e}\n"
442
+ f" Resistances: {_format_arr(self.resistances)}\n"
443
+ f" Capacitances: {_format_arr(self.capacitances)}\n"
444
+ f" Exponents: {_format_arr(self.exponents)}\n"
445
+ f" Taus: {_format_arr(self.taus)}\n"
446
+ )
447
+
448
+ def to_array(self):
449
+ """Return the parameters as a flat vector.
450
+
451
+ Returns
452
+ -------
453
+ array : numpy.ndarray, shape (3 + 3 * n_branches,)
454
+ ``[R_s, L, n_L, R_1..R_n, C_1..C_n, e_1..e_n]`` with the branches
455
+ in the stored (tau-sorted) order.
456
+
457
+ See Also
458
+ --------
459
+ from_array : Inverse operation.
460
+ """
461
+ return np.array(
462
+ [
463
+ self.resistance_source,
464
+ self.inductance,
465
+ self.inductance_exponent,
466
+ *self.resistances,
467
+ *self.capacitances,
468
+ *self.exponents,
469
+ ]
470
+ )
471
+
472
+ def copy(self):
473
+ """Return an independent copy (branch arrays are copied).
474
+
475
+ Returns
476
+ -------
477
+ params : CircuitParameters
478
+ New instance with the same parameter values.
479
+ """
480
+ return CircuitParameters(
481
+ resistance_source=self.resistance_source,
482
+ inductance=self.inductance,
483
+ inductance_exponent=self.inductance_exponent,
484
+ resistances=self.resistances.copy(),
485
+ capacitances=self.capacitances.copy(),
486
+ exponents=self.exponents.copy(),
487
+ )
488
+
489
+ @classmethod
490
+ def from_array(cls, array: np.ndarray, n_groups: int) -> CircuitParameters:
491
+ """Build parameters from a flat vector (inverse of :meth:`to_array`).
492
+
493
+ Parameters
494
+ ----------
495
+ array : numpy.ndarray, shape (3 + 3 * n_groups,)
496
+ ``[R_s, L, n_L, R_1..R_n, C_1..C_n, e_1..e_n]``. All entries after
497
+ the capacitances are taken as exponents.
498
+ n_groups : int
499
+ Number of parallel branches :math:`n`.
500
+
501
+ Returns
502
+ -------
503
+ params : CircuitParameters
504
+ New instance; branches are re-sorted by tau.
505
+ """
506
+ return cls(
507
+ resistance_source=array[0],
508
+ inductance=array[1],
509
+ inductance_exponent=array[2],
510
+ resistances=array[3 : 3 + n_groups],
511
+ capacitances=array[3 + n_groups : 3 + 2 * n_groups],
512
+ exponents=array[3 + 2 * n_groups :],
513
+ )
514
+
515
+ def to_dict(self) -> dict:
516
+ """Serialize to a JSON-friendly dict (branches in the stored tau order).
517
+
518
+ Returns
519
+ -------
520
+ data : dict
521
+ Nested dict of plain Python floats, see Notes.
522
+
523
+ See Also
524
+ --------
525
+ from_dict : Inverse operation.
526
+ save : Write this dict to a JSON file.
527
+
528
+ Notes
529
+ -----
530
+ Layout (``tau`` is informational and ignored by :meth:`from_dict`)::
531
+
532
+ {
533
+ "format_version": 1,
534
+ "type": "blowing_bubbles.CircuitParameters",
535
+ "global": {"resistance_source": ..., "inductance": ...,
536
+ "inductance_exponent": ...},
537
+ "branches": [
538
+ {"resistance": ..., "capacitance": ..., "exponent": ...,
539
+ "tau": ...},
540
+ ...
541
+ ]
542
+ }
543
+ """
544
+ return {
545
+ "format_version": _CIRCUIT_PARAMS_FORMAT_VERSION,
546
+ "type": _CIRCUIT_PARAMS_FILE_TYPE,
547
+ "global": {
548
+ "resistance_source": self.resistance_source,
549
+ "inductance": self.inductance,
550
+ "inductance_exponent": self.inductance_exponent,
551
+ },
552
+ "branches": [
553
+ {
554
+ "resistance": float(r),
555
+ "capacitance": float(c),
556
+ "exponent": float(e),
557
+ "tau": float(t),
558
+ }
559
+ for r, c, e, t in zip(
560
+ self.resistances,
561
+ self.capacitances,
562
+ self.exponents,
563
+ self.taus,
564
+ strict=False,
565
+ )
566
+ ],
567
+ }
568
+
569
+ @classmethod
570
+ def from_dict(cls, data: dict) -> CircuitParameters:
571
+ """Build parameters from a dict produced by :meth:`to_dict`.
572
+
573
+ Parameters
574
+ ----------
575
+ data : dict
576
+ Either the nested layout of :meth:`to_dict` (recognized by its
577
+ ``"type"`` and ``"global"`` keys) or the legacy flat layout with
578
+ keys ``resistance_source``, ``inductance``, ``inductance_exponent``,
579
+ ``resistances``, ``capacitances`` and ``exponents`` (as returned by
580
+ :meth:`as_dict`).
581
+
582
+ Returns
583
+ -------
584
+ params : CircuitParameters
585
+ New instance; branches are re-sorted by tau.
586
+ """
587
+ if data.get("type") == _CIRCUIT_PARAMS_FILE_TYPE and "global" in data:
588
+ g = data["global"]
589
+ branches = data.get("branches", [])
590
+ return cls(
591
+ resistance_source=g["resistance_source"],
592
+ inductance=g["inductance"],
593
+ inductance_exponent=g["inductance_exponent"],
594
+ resistances=np.array([b["resistance"] for b in branches]),
595
+ capacitances=np.array([b["capacitance"] for b in branches]),
596
+ exponents=np.array([b["exponent"] for b in branches]),
597
+ )
598
+ # Legacy / flat layout (arrays at top level)
599
+ return cls(
600
+ resistance_source=data["resistance_source"],
601
+ inductance=data["inductance"],
602
+ inductance_exponent=data["inductance_exponent"],
603
+ resistances=data["resistances"],
604
+ capacitances=data["capacitances"],
605
+ exponents=data["exponents"],
606
+ )
607
+
608
+ def save(self, path: str | Path) -> None:
609
+ """Write the parameters to a human-readable JSON file.
610
+
611
+ Parameters
612
+ ----------
613
+ path : str or pathlib.Path
614
+ Output file. Missing parent directories are created and an
615
+ existing file is overwritten.
616
+
617
+ See Also
618
+ --------
619
+ load : Read the file back.
620
+ to_dict : Layout of the written JSON object.
621
+
622
+ Notes
623
+ -----
624
+ The file is UTF-8 encoded, indented by two spaces and ends with a
625
+ newline. Branch rows include R, C, exponent and tau (tau is
626
+ informational only).
627
+ """
628
+ path = Path(path)
629
+ path.parent.mkdir(parents=True, exist_ok=True)
630
+ with path.open("w", encoding="utf-8") as f:
631
+ json.dump(self.to_dict(), f, indent=2)
632
+ f.write("\n")
633
+
634
+ @classmethod
635
+ def load(cls, path: str | Path) -> CircuitParameters:
636
+ """Load parameters from a JSON file written by :meth:`save`.
637
+
638
+ Parameters
639
+ ----------
640
+ path : str or pathlib.Path
641
+ JSON file in the :meth:`to_dict` layout (the legacy flat layout
642
+ is also accepted, see :meth:`from_dict`).
643
+
644
+ Returns
645
+ -------
646
+ params : CircuitParameters
647
+ Loaded parameters, branches sorted by tau.
648
+ """
649
+ with Path(path).open(encoding="utf-8") as f:
650
+ return cls.from_dict(json.load(f))
651
+
652
+ @overload
653
+ def get_impedance(self, freq: float) -> np.complex128: ...
654
+
655
+ @overload
656
+ def get_impedance(self, freq: np.ndarray) -> np.ndarray: ...
657
+
658
+ def get_impedance(self, freq: float | np.ndarray) -> np.complex128 | np.ndarray:
659
+ r"""Evaluate the model impedance :math:`Z(\omega)` at *freq*.
660
+
661
+ Parameters
662
+ ----------
663
+ freq : float or numpy.ndarray
664
+ Frequency or frequencies :math:`f` (Hz), with
665
+ :math:`\omega = 2\pi f`.
666
+
667
+ Returns
668
+ -------
669
+ Z : numpy.complex128 or numpy.ndarray
670
+ Complex impedance (same unit as the resistances); a scalar for a
671
+ scalar *freq*, otherwise an array with one entry per frequency.
672
+ Capacitive behaviour gives :math:`\mathrm{Im}(Z) < 0`.
673
+
674
+ See Also
675
+ --------
676
+ blowing_bubbles.circuit_impedance.circuit_impedance : Evaluated model.
677
+ """
678
+ return circuit_impedance(
679
+ freq,
680
+ self.resistance_source,
681
+ self.inductance,
682
+ self.inductance_exponent,
683
+ self.resistances,
684
+ self.capacitances,
685
+ self.exponents,
686
+ )
687
+
688
+ def plot_nyquist(
689
+ self,
690
+ freq: np.ndarray | None = None,
691
+ axis: plt.Axes | None = None,
692
+ unit: str | None = None,
693
+ ):
694
+ r"""Plot the full-model Nyquist curve (:math:`Z'` vs. :math:`-Z''`).
695
+
696
+ Parameters
697
+ ----------
698
+ freq : numpy.ndarray, optional
699
+ Frequencies (Hz) at which the model is evaluated. ``None``
700
+ (default) uses ``numpy.logspace(-5, 5, 1000)``.
701
+ axis : matplotlib.axes.Axes, optional
702
+ Axes to draw on. ``None`` (default) creates a new figure and axes.
703
+ unit : str, optional
704
+ Unit appended to the axis labels. ``None`` (default) uses
705
+ :math:`\Omega\,\mathrm{cm}^2` and emits a warning.
706
+
707
+ Returns
708
+ -------
709
+ axis : matplotlib.axes.Axes
710
+ The axes drawn on (the given one or the newly created one).
711
+
712
+ Warns
713
+ -----
714
+ UserWarning
715
+ If *unit* is ``None``.
716
+
717
+ See Also
718
+ --------
719
+ plot_full_fit : Same curve plus the individual branch arcs.
720
+
721
+ Notes
722
+ -----
723
+ The curve is drawn as a dashed black line, the aspect ratio is set to
724
+ equal, a grid is enabled and the top and right spines are hidden.
725
+ """
726
+ if unit is None:
727
+ warnings.warn(
728
+ "No unit provided, using default unit: Omega cm^2",
729
+ stacklevel=2,
730
+ )
731
+ unit = r"$\Omega$ cm$^{2}$"
732
+ if axis is None:
733
+ from matplotlib import pyplot as plt
734
+
735
+ _, axis = plt.subplots()
736
+ if freq is None:
737
+ freq = np.logspace(-5, 5, 1000)
738
+ Z_pred = self.get_impedance(freq)
739
+ axis.plot(
740
+ Z_pred.real,
741
+ -Z_pred.imag,
742
+ label=_FIT_LABEL,
743
+ color="black",
744
+ ls="--",
745
+ )
746
+ axis.set_aspect("equal")
747
+ axis.grid(True)
748
+ axis.spines["right"].set_visible(False)
749
+ axis.spines["top"].set_visible(False)
750
+ axis.set_xlabel("Z' " + unit)
751
+ axis.set_ylabel("-Z'' " + unit)
752
+ return axis
753
+
754
+ def plot_full_fit(
755
+ self,
756
+ freq: np.ndarray | None = None,
757
+ axis: plt.Axes | None = None,
758
+ unit: str | None = None,
759
+ ):
760
+ r"""Plot the total model Nyquist curve plus the decomposed branch arcs.
761
+
762
+ Overlays the combined model (dashed black) and single-branch
763
+ contributions, with a resistance label below each semicircle.
764
+
765
+ Parameters
766
+ ----------
767
+ freq : numpy.ndarray, optional
768
+ Frequencies (Hz) for the total model curve. ``None`` (default) uses
769
+ ``numpy.logspace(-5, 5, 1000)``.
770
+ axis : matplotlib.axes.Axes, optional
771
+ Axes to draw on. ``None`` (default) creates a new figure and axes.
772
+ unit : str, optional
773
+ Unit appended to the axis labels. ``None`` (default) uses
774
+ :math:`\Omega\,\mathrm{cm}^2` and emits a warning.
775
+
776
+ Returns
777
+ -------
778
+ axis : matplotlib.axes.Axes
779
+ The axes drawn on (the given one or the newly created one).
780
+
781
+ Warns
782
+ -----
783
+ UserWarning
784
+ If *unit* is ``None``.
785
+
786
+ See Also
787
+ --------
788
+ plot_nyquist : Total model curve only.
789
+
790
+ Notes
791
+ -----
792
+ Each branch arc is evaluated on the fixed grid
793
+ ``numpy.logspace(-10, 10, 500)`` Hz (independent of *freq*) and shifted
794
+ along :math:`Z'` by :math:`R_s` plus the resistances of the preceding
795
+ branches; only its capacitive part (:math:`\mathrm{Im}(Z) < 0`) is
796
+ drawn. The inductance is included only in the first (smallest-tau) arc.
797
+ Labels number the branches in reverse tau order: the smallest-tau
798
+ branch is labelled :math:`R_n`, the largest-tau branch :math:`R_1`.
799
+ The aspect ratio is set to equal (adjusting the data limits).
800
+ """
801
+ if freq is None:
802
+ freq = np.logspace(-5, 5, 1000)
803
+ return _plot_full_fit(freq, self, axis, unit)
804
+
805
+
806
+ class FitResults(OptimizeResult):
807
+ r"""Result of an equivalent-circuit fit, built from a SciPy least-squares result.
808
+
809
+ Parameters
810
+ ----------
811
+ res_ls : scipy.optimize.OptimizeResult
812
+ Least-squares result. ``res_ls.x`` holds capacitances (the
813
+ optimizer's :math:`\Delta\tau` already converted back) in the layout
814
+ given in Notes; ``res_ls.fun`` holds the stacked real and imaginary
815
+ impedance residuals ``[Re(r_1..r_M), Im(r_1..r_M)]``.
816
+ n_groups : int
817
+ Number of parallel branches :math:`n` in the fit.
818
+ complex_fit : bool
819
+ Layout of ``res_ls.x``: ``True`` if the CPE exponents were fitted. If
820
+ ``False``, :math:`n_L` and all :math:`e_i` are set to 1.
821
+ tau_bounds : tuple of float, optional
822
+ Time-constant bounds used in the fit, stored for reference.
823
+ initialize_rc_groups : int, optional
824
+ Requested maximum number of branches, stored for reference.
825
+ covariance : numpy.ndarray, shape (3 + 3n, 3 + 3n), optional
826
+ Parameter covariance in :meth:`CircuitParameters.to_array` layout with
827
+ branches in the same (optimizer) order as ``res_ls.x``. It is permuted
828
+ to the tau-sorted branch order of :attr:`parameters`. ``None``
829
+ (default) leaves all uncertainty attributes ``None``.
830
+
831
+ Attributes
832
+ ----------
833
+ parameters : CircuitParameters
834
+ Fitted parameters rebuilt from the solution vector (sorted by tau).
835
+ residuals : numpy.ndarray of complex, shape (M,)
836
+ Complex residuals :math:`\hat{Z}_k - Z_k` per frequency, rebuilt from
837
+ ``res_ls.fun``.
838
+ residuals_magnitude : numpy.ndarray, shape (M,)
839
+ :math:`|\hat{Z}_k - Z_k|`.
840
+ n_groups : int
841
+ Number of parallel branches in the fit.
842
+ covariance : numpy.ndarray or None
843
+ ``(3 + 3n, 3 + 3n)`` covariance matrix of the reported parameters in
844
+ :meth:`CircuitParameters.to_array` order
845
+ ``[R_s, L, n_L, R_1..R_n, C_1..C_n, e_1..e_n]`` (branches in the
846
+ tau-sorted order of ``parameters``); ``None`` if not computed.
847
+ standard_errors : numpy.ndarray or None
848
+ ``sqrt(diag(covariance))`` (negative variances clipped to 0), same
849
+ order. See :meth:`parameter_uncertainties` for a dict keyed like
850
+ :meth:`CircuitParameters.as_dict` and :attr:`parameter_names` for
851
+ labels.
852
+ correlation : numpy.ndarray or None
853
+ Correlation matrix, same order; rows/columns of parameters with zero
854
+ variance (fixed parameters) are 0.
855
+ tau_bounds : tuple of float or None
856
+ As passed in.
857
+ initialize_rc_groups : int or None
858
+ As passed in, or set by :meth:`add_initial_rc_groups`.
859
+ success, status, message, jac, cost, grad, optimality, active_mask, nfev, njev
860
+ Copied from ``res_ls`` (see :func:`scipy.optimize.least_squares`).
861
+
862
+ See Also
863
+ --------
864
+ CircuitParameters : Container for the fitted parameters.
865
+ blowing_bubbles.scripts.global_minimize.impedance_fit : Produces this
866
+ result.
867
+
868
+ Notes
869
+ -----
870
+ Layout of ``res_ls.x`` depending on ``complex_fit``:
871
+
872
+ - ``complex_fit=False``: ``[R_s, L, R_1..R_n, C_1..C_n]``
873
+ - ``complex_fit=True``: ``[R_s, L, n_L, R_1..R_n, C_1..C_n, e_1..e_n]``
874
+
875
+ Branches in ``res_ls.x`` (and in a ``covariance`` passed in) are in
876
+ optimizer order; ``parameters`` and the stored uncertainties are sorted by
877
+ tau.
878
+
879
+ The uncertainties are a local linearization of the weighted least-squares
880
+ problem at the solution; see
881
+ :func:`~blowing_bubbles.scripts.global_minimize.impedance_fit`.
882
+ """
883
+
884
+ def __init__(
885
+ self,
886
+ res_ls: OptimizeResult,
887
+ n_groups: int,
888
+ complex_fit: bool,
889
+ tau_bounds: tuple[float, float] | None = None,
890
+ initialize_rc_groups: int | None = None,
891
+ covariance: np.ndarray | None = None,
892
+ ):
893
+ """Populate the result from a least-squares solution."""
894
+ # Parameter layout (must match impedance_fit least-squares vector):
895
+ # complex_fit=False: [Rs, L, R_1..R_n, C_1..C_n]
896
+ # complex_fit=True: [Rs, L, n_L, R_1..R_n, C_1..C_n, e_1..e_n]
897
+ head = 3 if complex_fit else 2
898
+ resistances = res_ls.x[head : head + n_groups]
899
+ capacitances = res_ls.x[head + n_groups : head + 2 * n_groups]
900
+ self.parameters = CircuitParameters(
901
+ resistance_source=res_ls.x[0],
902
+ inductance=res_ls.x[1],
903
+ inductance_exponent=res_ls.x[2] if complex_fit else 1.0,
904
+ resistances=resistances,
905
+ capacitances=capacitances,
906
+ exponents=(
907
+ res_ls.x[head + 2 * n_groups : head + 3 * n_groups]
908
+ if complex_fit
909
+ else np.ones(n_groups)
910
+ ),
911
+ )
912
+ self.covariance = None
913
+ self.standard_errors = None
914
+ self.correlation = None
915
+ if covariance is not None:
916
+ # Apply the same branch permutation as CircuitParameters.sort_by_tau.
917
+ idx = _tau_sort_index(np.array(resistances), np.array(capacitances))
918
+ perm = np.concatenate(
919
+ [[0, 1, 2], 3 + idx, 3 + n_groups + idx, 3 + 2 * n_groups + idx]
920
+ )
921
+ cov = np.asarray(covariance, dtype=float)[np.ix_(perm, perm)]
922
+ std = np.sqrt(np.clip(np.diag(cov), 0.0, None))
923
+ denom = np.outer(std, std)
924
+ corr = np.zeros_like(cov)
925
+ np.divide(cov, denom, out=corr, where=denom > 0)
926
+ self.covariance = cov
927
+ self.standard_errors = std
928
+ self.correlation = corr
929
+ res_real = res_ls.fun[: res_ls.fun.size // 2]
930
+ res_imag = res_ls.fun[res_ls.fun.size // 2 :]
931
+ self.residuals = res_real + 1j * res_imag
932
+ self.residuals_magnitude = np.sqrt(res_real**2 + res_imag**2)
933
+ self.success = res_ls.success
934
+ self.status = res_ls.status
935
+ self.message = res_ls.message
936
+ self.jac = res_ls.jac
937
+ self.cost = res_ls.cost
938
+ self.grad = res_ls.grad
939
+ self.optimality = res_ls.optimality
940
+ self.active_mask = res_ls.active_mask
941
+ self.nfev = res_ls.nfev
942
+ self.njev = res_ls.njev
943
+ self.n_groups = n_groups
944
+ self.tau_bounds = tau_bounds
945
+ self.initialize_rc_groups = initialize_rc_groups
946
+
947
+ @property
948
+ def parameter_names(self) -> list[str]:
949
+ """Labels for the :attr:`covariance` / :attr:`standard_errors` entries.
950
+
951
+ ``["R_s", "L", "n_L", "R_1", ..., "C_1", ..., "e_1", ...]``, numbered
952
+ in the tau-sorted branch order of :attr:`parameters` (``R_1`` has the
953
+ smallest tau).
954
+ """
955
+ n = self.n_groups
956
+ return (
957
+ ["R_s", "L", "n_L"]
958
+ + [f"R_{i + 1}" for i in range(n)]
959
+ + [f"C_{i + 1}" for i in range(n)]
960
+ + [f"e_{i + 1}" for i in range(n)]
961
+ )
962
+
963
+ def parameter_uncertainties(self) -> dict | None:
964
+ """Return the standard errors keyed like :meth:`CircuitParameters.as_dict`.
965
+
966
+ Returns
967
+ -------
968
+ uncertainties : dict or None
969
+ Keys ``resistance_source``, ``inductance``, ``inductance_exponent``
970
+ (float) and ``resistances``, ``capacitances``, ``exponents``
971
+ (numpy.ndarray, shape ``(n_groups,)``, copies) in the tau-sorted
972
+ order of :attr:`parameters`. ``None`` if no covariance was
973
+ computed.
974
+ """
975
+ if self.standard_errors is None:
976
+ return None
977
+ n = self.n_groups
978
+ se = self.standard_errors
979
+ return {
980
+ "resistance_source": float(se[0]),
981
+ "inductance": float(se[1]),
982
+ "inductance_exponent": float(se[2]),
983
+ "resistances": se[3 : 3 + n].copy(),
984
+ "capacitances": se[3 + n : 3 + 2 * n].copy(),
985
+ "exponents": se[3 + 2 * n : 3 + 3 * n].copy(),
986
+ }
987
+
988
+ def add_initial_rc_groups(self, rc_groups: int) -> None:
989
+ """Record the requested maximum number of RC groups.
990
+
991
+ Only sets :attr:`initialize_rc_groups` (in place); the fitted
992
+ parameters are not changed.
993
+
994
+ Parameters
995
+ ----------
996
+ rc_groups : int
997
+ Value stored in :attr:`initialize_rc_groups`.
998
+ """
999
+ self.initialize_rc_groups = rc_groups