Eight Failures That Never Errored: The Fitter Quietly Returned My Initial Guess
Eight Failures That Never Errored: The Fitter Quietly Returned My Initial Guess
Search
Ask the AI

Eight Failures That Never Errored: The Fitter Quietly Returned My Initial Guess

While writing an equivalent-circuit fitter for impedance spectra, I found eight problems. Not one threw an exception. Not one printed a warning. Each produced plausible output. The most serious returned the initial guess while the interface reported success. This article records those numerical and display errors.

1. The expensive one: a sign error returns your initial guess

One step of Levenberg–Marquardt, with residuals defined as r = y − f(x) and Jacobian J = ∂r/∂x, descends along:

Δx = −(JᵀJ + λD)⁻¹ Jᵀr

I wrote:

x += (JᵀJ + λD)⁻¹ Jᵀr        // missing the minus sign

For a nonzero gradient and a positive-definite damped matrix, the wrong sign gives a local ascent direction. In this failure, all twelve λ attempts were rejected, the loop exited with iter = 0, and the function returned its initial input. Large steps in a nonlinear model also depend on curvature; this log records what this implementation did.

Which is the initial guess.

So the interface shows: a fitted curve (computed from the initial guess, roughly the right shape), a set of parameters (the ones you typed in), and a chi² value (finite, not absurd). Nothing anywhere indicates failure. With a decent starting guess the “result” even looks good.

I found the error with a synthetic parameter-recovery test: generate data from known parameters and fit from a different starting point. A noiseless, identifiable case with sufficient frequency coverage should recover the parameters within a preset tolerance. Noisy or unidentifiable cases require checks of prediction error and parameter intervals.

After each change to the numerical core, run a “synthetic data → known answer” test alongside finite-difference gradient checks and checks of termination status. Numerical routines can return finite values, so tests need to examine the answer directly.

2. A parameter runs to 1e154 while the residual does not move

A ZARC element — a resistor in parallel with a constant phase element — has impedance:

Z = R / (1 + R·Q·(jω)ⁿ)

Fix a positive Q, an exponent n and a nonzero frequency ω. Dividing numerator and denominator by R gives Z = 1 / (1/R + Q(jω)ⁿ). As R grows, the impedance tends to the pure-CPE value Z → 1/(Q(jω)ⁿ). Within a finite measurement window, the response becomes insensitive to R when |R·Q·(jω)ⁿ| ≫ 1.

The nearly flat direction has fixed Q and n, with sufficiently large R. If the positive product R·Q is held fixed, increasing R decreases Q: the denominator stays fixed and the impedance grows with R. The original account confused these paths and incorrectly said that R and Q could both tend to infinity.

The original 40 noise realisations included a recorded R1 ≈ 1e154 with chi² still in its normal range. I retain that value as the historical failure record. A small residual alone cannot establish that such a parameter is a reliable measurement.

A finite frequency window may leave sufficiently large R poorly constrained. More iterations do not add measurement information. These are the first two handling steps:

  1. Give every parameter physical bounds (no resistance is 1e154 ohms);
  2. When a parameter lands on a bound, mark it “unidentified” rather than printing the number.

The tool labels a bound hit “unidentified” to prompt further checks. A bound hit can also result from an overly narrow bound, model mismatch or local stagnation. Inspect sensitivity, frequency coverage and fits from multiple starting points before interpreting the parameter; the boundary value is not an independently determined physical measurement.

3. Distinguish stagnation, convergence and identifiability

With bounds in place I added a reliability guard: a fit only counts as converged if the last iteration’s relative improvement is below 1e-12. That sounds rigorous.

In the original record, the guard flagged 4 of 60 fits whose reduced chi² was in the same range as the others. This shows a mismatch between that single “last improvement” check and the observed fit behaviour. Similar reduced chi² alone does not establish correct parameter recovery.

The current implementation sets converged to true when a round of damping trials yields no improvement. The “last relative improvement” may then be absent or belong to the preceding accepted step. Exhausting retries indicates stagnation; it does not by itself establish convergence. LM implementations also check changes in cost, step size or gradient conditions. Report those diagnostics separately from an exhausted retry budget.

Reliability warnings need a diagnostic that readers can check. Repeated labels that disagree with those diagnostics make it harder to distinguish algorithmic stagnation, unidentifiable parameters and results that meet a convergence condition.

Reliability messages should distinguish satisfied convergence conditions, exhausted iteration or retry budgets, and unidentifiable parameters. Retaining a diagnostic for each status allows both false positives and missed failures to be checked.

4. Weighting is not a setting, it is part of the result

Fitting an impedance spectrum requires choosing a residual weighting. Two common ones: unit weighting (every point equal) and modulus weighting (normalised by |Z|). Impedance magnitude can span several orders across a single spectrum, so this is not a detail.

The table retains the original summary from 60 independent noise realisations, using R0 relative recovery error. It describes that synthetic test; a different noise model requires a new weighting comparison:

Weighting R0 relative error Hit a bound
Modulus −0.04% ± 0.19% 0 / 60
Unit −10.03% ± 30.37% 6 / 60 (R1)

Using the rounded table entries, the ratio of absolute mean errors is about 250 and the ratio of spreads is about 160. Weighting changed R0 recovery substantially in this test. Modulus weighting suits errors whose scale grows with |Z|; unit weighting suits approximately constant absolute error scales in the real and imaginary parts.

So in this tool the weighting is an explicit control, and it is printed alongside the results. Hiding it behind a default hands the reader a number nobody can reproduce.

5. The remaining four: all in the display layer, all silent

A Nyquist plot must use equal axis scaling

Use the same length per impedance unit on both Nyquist axes. A free aspect ratio changes the apparent flattening of an arc and makes semicircles harder to compare with depressed arcs. Their complete shapes still differ. Lock the axis scales before interpreting the degree of depression.

Do not generate ticks by accumulation

// bad: floating-point error accumulates
for (let v = lo; v <= hi; v += step) ticks.push(v);

// good: integer multiples
for (let k = 0; k <= n; k++) ticks.push(lo + k * step);

Accumulation turns a tick that should be exactly 0 into 1.7e-18. On its own that is harmless — but SI prefix formatting then renders it as 0.000001735 p, a string long enough to push the whole axis outside the viewBox. A 1e-18 numerical error presents as a broken chart.

Dimensionless quantities must not get SI prefixes

The CPE exponent n was about 0.86 in this case and is dimensionless. The formatter displayed “859.6 m”, attaching the SI prefix m to a number on its own. Display the exponent as an ordinary number such as 0.8596; a quantity with unit one cannot carry a standalone SI prefix.

The test environment lies to you too

Twice during debugging I was certain a change had not taken effect, and both times it was the environment:

  • headless Chrome reusing a --user-data-dir serves the old page out of its disk cache;
  • a page URL without a cache-busting parameter serves the CDN edge copy — and note that the parameter name itself may be ignored by the cache rules. I used one that had no effect and misdiagnosed a whole round because of it.

Before verifying "did my change take effect," verify "am I looking at the new version."

6. What the eight have in common

The eight problems share one feature:

The problem How it presents
LM sign error a successful fit
R–Q degeneracy a normal chi²
Wrong convergence test a reliability warning
Wrong weighting parameters quoted to two decimals
Free aspect ratio a good-looking plot
Accumulated ticks a clipped axis
SI prefix misuse "859.6 m"
Cache not bypassed "my change didn't take"

None of these eight problems raised an exception. They affected the iteration direction, interpretation of parameters, termination status and display. Numerical checks and interface checks each need explicit expected results.

The first four problems were found through synthetic-data tests. Keep the known-answer inputs, original outputs and reproduction code, then rerun them after changes to the numerical core to check for regressions.

References

Related: the EIS equivalent-circuit fitter (the tool described here), parameter fitting and identifiability (why "the fit converged" does not mean "the parameters are right"), and the HPPC pulse resistance analyser and dQ/dV incremental capacity analyser (the other two characterisation methods).

Leave a Reply

Scroll down