From 694bed57bb270c829e693c2d2b8940e24559c8ad Mon Sep 17 00:00:00 2001 From: gaoflow Date: Mon, 1 Jun 2026 23:27:54 +0200 Subject: [PATCH] Fix ValueError when refitting after load(fitted_as_initial=True) CustomCircuit.load(..., fitted_as_initial=True) stores the fitted parameters as a numpy array in self.initial_guess. A subsequent call to fit() then evaluated self.initial_guess != [], which NumPy broadcasts element-wise, raising: ValueError: operands could not be broadcast together with shapes (n,) (0,) Check emptiness with len() instead so the guard works for both lists and numpy arrays. Fixes #310. --- impedance/models/circuits/circuits.py | 2 +- impedance/tests/test_model_io.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/impedance/models/circuits/circuits.py b/impedance/models/circuits/circuits.py index b670d198..97d0963f 100644 --- a/impedance/models/circuits/circuits.py +++ b/impedance/models/circuits/circuits.py @@ -96,7 +96,7 @@ def fit(self, frequencies, impedance, bounds=None, if len(frequencies) != len(impedance): raise TypeError('length of frequencies and impedance do not match') - if self.initial_guess != []: + if len(self.initial_guess) != 0: parameters, conf = circuit_fit(frequencies, impedance, self.circuit, self.initial_guess, constants=self.constants, diff --git a/impedance/tests/test_model_io.py b/impedance/tests/test_model_io.py index 7bdddd24..5e1affa3 100644 --- a/impedance/tests/test_model_io.py +++ b/impedance/tests/test_model_io.py @@ -31,3 +31,29 @@ def test_model_io(): fitted_template = CustomCircuit() fitted_template.load('test_io.json', fitted_as_initial=True) + + +def test_refit_after_load_fitted_as_initial(): + # Regression test for #310: loading a fitted model with + # fitted_as_initial=True stores initial_guess as a numpy array, which + # broke the subsequent ``fit`` call because the emptiness check compared + # the array against ``[]`` (raising a broadcasting ValueError). + data = np.genfromtxt(os.path.join(".", "data", + "exampleData.csv"), delimiter=',') + frequencies = data[:, 0] + Z = data[:, 1] + 1j * data[:, 2] + + randles = CustomCircuit(initial_guess=[.01, .005, .1, .005, .1, .9, + .001, 200], + circuit='R0-p(R1,C1)-p(R1,CPE1)-Wo1') + randles.fit(frequencies, Z) + randles.save('./test_io.json') + + reloaded = CustomCircuit() + reloaded.load('./test_io.json', fitted_as_initial=True) + assert isinstance(reloaded.initial_guess, np.ndarray) + + # Refitting must not raise; it previously failed with + # "operands could not be broadcast together with shapes (n,) (0,)" + reloaded.fit(frequencies, Z) + assert reloaded.parameters_ is not None