# Convergio

**Automatic convergence detection for iterative numerical methods.**

Stop wasting compute. One function call tells you if your solver has converged, is oscillating, is stuck between two states, or is diverging.

*"Your solver finished 3000 iterations ago."*

## Install

```bash
pip install convergio
```

Only dependency: NumPy.

## Usage

### Analyze a completed run

```python
from convergio import detect

result = detect(my_residual_history)

print(result.state)        # "converged" | "oscillating" | "bistable" | "diverging"
print(result.quality)      # 0.0 — 1.0
print(result.converged_at) # step where convergence was detected
print(result.n_modes)      # number of distinct stable states
```

### Monitor a running simulation

```python
from convergio import watch

mon = watch(var_threshold=1e-6)

for step in range(10000):
    residual = solver.step()
    stop, info = mon.step(residual)
    if stop:
        print(f"Converged at step {step}")
        break
```

## What it detects

| State | Meaning | Recommendation |
|-------|---------|----------------|
| `converged` | Signal has stabilized | Stop |
| `oscillating` | Signal oscillates without settling | Continue or adjust parameters |
| `bistable` | Signal jumps between 2+ distinct states | Investigate — multiple solutions exist |
| `diverging` | Variance is growing | Restart with different parameters |
| `warming_up` | Not enough data yet | Continue |

## Works with

- FEM / CFD solvers (residual monitoring)
- ML training (loss convergence)
- Monte Carlo simulations (running averages)
- Optimization loops (objective function)
- Molecular dynamics (energy equilibration)
- Any iterative numerical process that produces a scalar time series

## API

### `detect(signal, window=0, var_threshold=1e-6)`

Analyze a complete time series. Returns `ConvergenceResult`.

### `watch(var_threshold=1e-6, check_every=50, min_steps=100)`

Create a live monitor. Returns `Watch` object. Call `.step(value)` each iteration.

### `ConvergenceResult`

| Field | Type | Description |
|-------|------|-------------|
| `state` | str | converged, oscillating, bistable, diverging, warming_up |
| `quality` | float | 0.0 — 1.0 convergence quality |
| `converged_at` | int or None | Step where convergence detected |
| `final_variance` | float | Variance of last window |
| `oscillation_freq` | float | Detected oscillation frequency |
| `n_modes` | int | Number of distinct stable states |
| `recommendation` | str | stop, continue, restart |

## License

MIT

## Author

Maximilian Jurak — [3 Kaiserberge Engineering & Research](https://3kaiserberge.com)

max.jurak@3kaiserberge.com
