Metadata-Version: 2.4
Name: py-magpi
Version: 0.1.0b1
Summary: Manifold-constrained Gaussian Process Inference for ODE parameters, by profiling the states out and tempering the parameters onto them
Author: Jamie Liu
License: MIT License
        
        Copyright (c) 2026 Jamie Liu
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/jsliu02/py-magpi
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: jax
Requires-Dist: optax
Provides-Extra: nuts
Requires-Dist: blackjax; extra == "nuts"
Dynamic: license-file

### NOTE: This package is still in beta development.

# magpi

ODE parameter inference from noisy, sparsely observed trajectories, in JAX.

Installed as **`py-magpi`**, imported as **`magpi`**.

`magpi` implements MAGI — manifold-constrained Gaussian process inference ([Yang, Wong & Kou,
*PNAS* 2021](https://doi.org/10.1073/pnas.2020397118)). A Gaussian process prior is placed on each
state component, evaluated on a discretisation grid, and conditioned on the event that the GP
satisfies the ODE on that grid. You get a posterior over the parameters **and** the trajectory,
including the parts you never observed, without ever calling a numerical integrator.

The recommended estimator differs from the reference implementation in two ways: the states are
integrated out by a profiling argument that is *exact* whenever the vector field is affine in the
state at fixed parameters, and the remaining low-dimensional parameter integral is done by
adaptive-tempering sequential Monte Carlo rather than by MCMC on the joint.

Against long NUTS references (4 chains × 9000 draws), the profiled route's largest parameter error
is at or below the level at which two independent halves of that reference agree with each other —
0.0166 against a floor of 0.0239 on FitzHugh–Nagumo, 0.0086 against 0.0074 on HIV, 0.0352 against
0.0669 on the chaotic Lorenz. The mode alone is 1.02, 0.15 and 1.77 standard deviations out.

## Installation

```
pip install py-magpi
```

`nuts()` additionally needs blackjax, which is not pulled in by default:

```
pip install py-magpi[nuts]
```

Requires Python ≥ 3.10. Depends on `numpy`, `scipy`, `jax` and `optax`. Install the JAX build
matching your accelerator; everything here runs on CPU as well, only slower.

## Quickstart

```python
from magpi import MAGI, tests

model = tests.FitzHughNagumo
data  = model.dataset(seed=0)          # (n, 1+D): column 0 is the grid, NaN where unobserved

m = MAGI(model.ode, data, theta_mean=[1, 1, 1], theta_prec=1e-3,
         sigmas=model.hyperparams["sigma"])

m.diagnose()                           # is the question well posed?  seconds, no sampling
post = m.fit()                         # the recommended posterior
Xs, thetas, sigmas = post.sample(k=2000)

import numpy as np
print(np.round(post.mean[:m.p], 4))                       # theta posterior mean
print(np.round(np.sqrt(np.diag(post.theta_cov)), 4))      # and its marginal sd
```

`diagnose()` and `fit()` each print a report; the two lines above then give

```
[0.1852 0.2671 2.9298]
[0.0228 0.0825 0.0728]
```

against a truth of `[0.2, 0.2, 3.0]`.

Write `ode` **pointwise**, for one time point: it is called as `ode(x_i, theta, t_i)` with `x_i` of
shape `(D,)`, `theta` of shape `(p,)` and `t_i` a scalar, returning `D` derivatives. The package
vmaps it over the grid. The output shape is checked at construction.

## The public surface

The package exports five names:

| name | what it is |
|---|---|
| `MAGI` | the model — the only thing most callers need |
| `MAGIPosterior` | what `fit()` and `laplace()` return |
| `tests` | five example systems, ready to run |
| `jax_cache_info`, `clear_jax_cache` | inspect and empty the persistent compilation cache |

Every algorithm is a method on `MAGI` rather than an import. The implementation lives in
`magpi._internal`, which is private by convention — nothing in it is re-exported and anything in
it may be renamed without that counting as a change to the package.

## Methods

| call | returns | notes |
|---|---|---|
| `diagnose()` | dict | Is the mode a maximum, the only one, identified, and is the posterior proper? Run this first. |
| `fit()` | `MAGIPosterior` | The recommended route: states profiled out, parameters tempered. |
| `map_solve()` | `(X, theta, sigma)` | The mode, by Gauss–Newton on the exact least-squares form. Cheapest; everything else builds on it. |
| `laplace()` | `MAGIPosterior` | A Gaussian at the mode. Inherits the mode's displacement from the mean. |
| `nuts()` | `(X, theta, sigma)` draws | The exact fallback. Also leaves `m.nuts_draws`. |
| `svgd()` | `(particles, diagnostics)` | Kept for the record; **not** recommended for parameter estimates. |
| `condition_A()` | float | 0 iff the field is affine in the state, so the profiling is exact. |
| `verify_map()` / `sample_map()` | dict / `(X, theta, sigma)` | Check the mode against a sample, using no optimiser; and a mode estimate from a sample. |

A `MAGIPosterior` exposes `mean`, `theta_cov`, `sample(k)`, `cov_theta_state()` and `report()`, and
is left on `m.posterior`. `report()` *returns* rather than prints, and is also the object's
`__repr__`, so it displays in a REPL and is silent as a bare statement in a script.

**Which one?** `diagnose()` then `fit()` covers nearly everything. Reach for `nuts()` when you want
an answer that shares none of `fit()`'s machinery, and for `map_solve()` alone when you only need a
point estimate and know the mode is not the answer.

## Constraining parameters

`theta_pos` marks components that cannot be negative — rate constants, concentrations, variances:

```python
m = MAGI(ode, data, theta_mean=..., theta_prec=1e-3, theta_pos=True)     # or a length-p boolean
```

It is implemented as a **truncation of the prior**, so the posterior is the same density restricted
to the orthant. This is what removes the spurious mirror modes that fields with rate parameters
routinely admit: on Hes1 an unconstrained `fit()` puts *all* of its mass on a negative-rate mode
that beats the truth by 22 nats, reporting θ₅ = −7.41 against a truth of 20 with `STATUS: OK`. With
`theta_pos` the same fit reports 19.27 and one mode.

Each method enforces it differently — the density carries it for `fit()` and the diagnostics, the
optimisers project, `nuts()` meets a hard wall, `laplace()` rejection-samples, and `svgd()` changes
variables to log θ. The details, and where each fails, are in the package document.

## Precision and devices

float32 is the default and is usually right: it matches float64 on FitzHugh–Nagumo and Lorenz and
beats it on HIV. Call `m.put(jnp.float64)` to change dtype or device.

Expose one accelerator at a time with `CUDA_VISIBLE_DEVICES` rather than selecting with `device=`.
A cached XLA executable binds to `devices()[0]` when it is loaded, whatever device built it, so on a
machine with two different cards a process on the second one succeeds cold and fails on the next
run when it reads its own cache entries back. The package detects this and disables the cache
rather than letting it happen.

## Example systems

`magpi.tests` carries five: `FitzHughNagumo`, `Hes1`, `HIV`, `Lorenz`, and `Decay` — an exactly
affine control whose truncated posterior is known by quadrature. They range from d = 42 to d = 608
unknowns. Each has `ode`, `hyperparams` and `dataset(seed)`; `dataset` also integrates the truth, so
`truth_at(t)` is available afterwards for scoring or plotting.

```python
from magpi.tests import SYSTEMS
for name, s in SYSTEMS.items():
    ...
```

## Documentation

`documentation/` holds the writeups, source and built:

- **`magi_package.tex`** — every method a user can call: the algorithm it runs, the approximation it
  makes, a proof that it is correct up to that approximation, the conditions under which it fails,
  the precision each step needs, and its cost relative to the others.
- **`magi_svgd.tex`** — why SVGD is not the recommended route, in three obstructions.
- **`posterior_gaussianity.tex`** — what an affine vector field does and does not buy.
- `magi_paper.pdf` — Wong, Yang & Kou's paper on the original R `magi` package, for reference.

## Tests and benchmarks

`test_magi.py` is a single script with its own harness, not pytest:

```
python test_magi.py --dev cpu        # also: --dev gpu, --quick, --fail-fast, --x64
```

`benchmarking/benchmark.py` times every method on one model and writes per-method wall clock,
posterior moments and quantiles to CSV, with diagnostics to a separate log.

## License

MIT.
