Metadata-Version: 2.5
Name: impydance
Version: 0.1.0
Summary: Equivalent-circuit models and electrochemical impedance fitting
Project-URL: Repository, https://github.com/jvhemmer/impydance
Project-URL: Issues, https://github.com/jvhemmer/impydance/issues
Project-URL: Changelog, https://github.com/jvhemmer/impydance/releases
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Description-Content-Type: text/markdown

# impydance

impydance models and fits equivalent circuits for electrochemical impedance spectroscopy. The circuit elements and fitter come from the EIS code in pyspectbx. The package uses NumPy and SciPy.

## Fit a spectrum

Use frequencies in Hz and complex impedance in ohms. The example generates a spectrum from an analytical series resistor and parallel RC circuit.

```python
import numpy as np

from impydance import C, R, Parallel, Series, fit_eis

frequency = np.geomspace(0.1, 1e5, 70)
measured = 5 + 100 / (1 + 1j * 2 * np.pi * frequency * 100 * 20e-6)

circuit = Series(
    R("Rs", x0=10),
    Parallel(R("Rct", x0=40), C("Cdl", x0=1e-4)),
)
fit = fit_eis(circuit, frequency, measured, n_starts=4)

print(fit.parameters)
print(fit.solver_success, fit.jacobian_rank, fit.active_bounds)
```

Use `impedance_from_columns(real, imaginary, negative_imaginary=True)` for data with a column that stores −Z″. Leave the flag at its default for a Z″ column. Fitted values and residuals follow the input frequency order. Residuals are fitted minus observed.

## Define a circuit

The built-in elements are `R`, `L`, `C`, `CPE`, `WarburgSemiInf`, `WarburgFiniteOpen`, and `WarburgFiniteShort`. Combine them with `Series` and `Parallel`. Evaluate any circuit with `circuit.Z(frequency, parameters)`.

Use a unique name for each free parameter. To share a value between two elements, pass the same `ParamSpec` with `shared=True` to both. Set `fixed=True` to hold a value at its initial value. Equal lower and upper bounds also fix a parameter.

Use `circuit.to_dict()` to save a built-in circuit as a JSON-compatible dictionary. Restore it with `Block.from_dict(record)`. The record includes element types, topology, initial values, and bounds.

## Read fit results

- The solver minimizes real and imaginary residuals together. The default modulus weighting divides each residual by the measured impedance magnitude. Pass `weight="none"` for unweighted fitting.
- Pass `sigma` for independent measurement standard deviations in ohms. Supply a scalar, one value per frequency, or a two-column array for the real and imaginary components. Only this mode reports reduced chi-square.
- `solver_success` reports the SciPy termination status. `success` also requires full local Jacobian rank. Check residuals, conditioning, and active bounds when interpreting a fit.
- `n_starts=1` runs from the supplied guesses. The solver moves guesses near a bound into the feasible interior. Further starts perturb those guesses. Use `random_state` to reproduce the sequence. Set `nm_maxiter` to enable a Nelder–Mead warm-up on additional starts.

The result is a `FitResult` object. Access the fitted spectrum, residuals, parameters, and diagnostics by name.

## Check a spectrum with Lin-KK

Call the diagnostic on a measured spectrum or request it during a circuit fit.

```python
from impydance import fit_eis, validate_lin_kk

check = validate_lin_kk(frequency, measured)
print(check.metrics.rms_real_percent, check.metrics.rms_imag_percent)
print(check.metrics.rms_complex_percent, check.metrics.max_complex_percent)
print(check.n_rc, check.mu, check.order_selection)

fit = fit_eis(circuit, frequency, measured, lin_kk=True)
print(fit.lin_kk.metrics)

fit = fit_eis(circuit, frequency, measured, lin_kk={
    "rms_limit_percent": 1.0,
    "max_limit_percent": 5.0,
})
print(fit.lin_kk.passed)
```

The check fits both impedance components with a series resistance and an RC basis on a logarithmic time grid. It includes a series inductance by default. Set `include_capacitance=True` to include a series capacitive term. Use `n_rc` to fix the order. Automatic selection compares candidates by generalized cross-validation. It prefers a model that meets the signed-resistance cutoff (μ ≥ 0.85 by default) if its score is within 10% of the best score.

The result includes the fitted spectrum, raw residuals in ohms, and relative residuals divided by the measured impedance magnitude, with a 10⁻¹² Ω floor. To plot percent residuals, multiply `relative_residuals.real` and `relative_residuals.imag` by 100. Plot both against `frequencies`.

The example limits are illustrative. `passed` is `None` until you supply at least one limit. When supplied, the limits apply to complex residual magnitudes and require a full-rank validation model. The outcome is separate from circuit fit convergence and parameter identifiability.

[Original linear validation method](https://doi.org/10.1149/1.2044210) · [Signed-resistance criterion](https://doi.org/10.1016/j.electacta.2014.01.034)

## Develop locally

```sh
uv sync --locked
uv run --locked python -m unittest discover -s tests -v
uv build
```

## Release

A version tag such as `v0.1.0` must match the version in `pyproject.toml`. The release workflow builds the wheel and source archive. It tests the wheel on Linux, macOS, and Windows before publishing the same files to PyPI and GitHub.

Configure a PyPI Trusted Publisher for owner `jvhemmer`, repository `impydance`, workflow `release.yml`, and environment `pypi`. To make the first release, use a pending publisher for project `impydance`. [PyPI Trusted Publishing setup](https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/)

License: GPL-3.0-or-later.
