Metadata-Version: 2.4
Name: mpcjax
Version: 0.5.0
Summary: A pure-JAX, CPU or GPU Model Predictive Control solver.
Author-email: Robert Dyro <robert.dyro@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/rdyro/mpcjax
Project-URL: Bug Tracker, https://github.com/rdyro/mpcjax/issues
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jax>=0.4.25
Requires-Dist: numpy
Requires-Dist: optax>=0.2.3
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

# mpcjax

Differentiable nonlinear Model Predictive Control (MPC) in pure JAX. Solves single or batched finite-horizon problems on CPU/GPU via condensed Sequential Convex Programming (SCP) or direct shooting, with reverse-mode differentiation through the implicit function theorem (`jax.grad(mpcjax.solve)`).

## Installation

```bash
pip install mpcjax
```

For local development:

```bash
pip install -e ".[dev]"
```

## Quick Start

```python
import jax
import jax.numpy as jnp
import mpcjax

# Pendulum dynamics: state [theta, omega], control [torque]
def f_fx_fu_fn(X, U, P=None):
    dt, th, om, u = 0.05, X[..., 0], X[..., 1], U[..., 0]
    f = jnp.stack([th + dt * om, om + dt * (-9.81 * jnp.sin(th) + u)], axis=-1)
    z, o = jnp.zeros_like(th), jnp.ones_like(th)
    fx = jnp.stack([jnp.stack([o, dt * o], axis=-1), jnp.stack([-dt * 9.81 * jnp.cos(th), o], axis=-1)], axis=-2)
    fu = jnp.stack([z, dt * o], axis=-1)[..., None]
    return f, fx, fu

N, xdim, udim = 20, 2, 1
Q = jnp.broadcast_to(jnp.diag(jnp.array([10.0, 1.0])), (N, xdim, xdim))
R = jnp.broadcast_to(1e-2 * jnp.eye(udim), (N, udim, udim))
x0 = jnp.array([0.8, 0.0])

X, U, info = mpcjax.solve(f_fx_fu_fn, Q, R, x0, u_l=-5.0, u_u=5.0)
print("iterations:", int(info["iterations"]), "final state:", X[-1])

# Differentiate through the solution via the implicit function theorem
dJ_dx0 = jax.grad(lambda x: jnp.sum(mpcjax.solve(f_fx_fu_fn, Q, R, x, u_l=-5.0, u_u=5.0)[0] ** 2))(x0)
```

## Dynamics Contract

`f_fx_fu_fn(X, U, P)` returns `(f, fx, fu)` (next state and Jacobians w.r.t. state and control):

| Context | `X` shape | `U` shape | `f` shape | `fx` shape | `fu` shape |
| --- | --- | --- | --- | --- | --- |
| SCP linearization (`direct_solve=False`) | `(N, xdim)` | `(N, udim)` | `(N, xdim)` | `(N, xdim, xdim)` | `(N, xdim, udim)` |
| Direct rollout, `jax.grad(solve)`, `optimality_fn` | `(xdim,)` | `(udim,)` | `(xdim,)` | `(xdim, xdim)` | `(xdim, udim)` |

Write `f_fx_fu_fn` with ellipsis indexing (`X[..., i]`) so both 1D and 2D shapes work seamlessly. `P` is optional (`None` by default); a 1D array or scalar is broadcast across all `N` steps, a 2D+ array with leading axis `N` is scanned per step, and arbitrary PyTrees of arrays are supported leaf-wise.

`solve` returns `(X, U, info)` where `X` has shape `(..., N + 1, xdim)` (`X[..., 0, :] == x0` and `X[..., 1:, :]` are the `N` predicted states), `U` has shape `(..., N, udim)`, and `info` contains `objs`, `resids` (length `max_it`, NaN-padded after convergence), and `iterations`.

## Key Options

- **Modes**: `direct_solve=False` (default, condensed linearized SCP) or `direct_solve=True` (nonlinear shooting).
- **Box constraints & slew penalties**: `x_l`, `x_u`, `u_l`, `u_u` (broadcastable, `None`/`nan` for unconstrained) enforced via a smooth log-barrier with tangential linear fallback controlled by `smooth_alpha` and `lam`; control smoothness via `slew_rate`, `slew0_rate`, and `u0_slew`.
- **Custom costs**: `lin_cost_fn(X, U, problem) -> (cx, cu)` for per-SCP-iteration linear terms, or `diff_cost_fn(X, U, problem) -> scalar` for arbitrary differentiable costs.
- **Batching**: pass batched `(M, ...)` arrays directly to `solve`, or a sequence of single-problem dicts/`Problem`s to `solve_problems(problems, split=True)`.
- **Problem builder**: `prob = mpcjax.Problem(N=20, xdim=2, udim=1, x0=x0, f_fx_fu_fn=f_fx_fu_fn)` validates shapes and unpacks directly into `mpcjax.solve(**prob)`.
- **Implicit differentiation**: `jax.grad` / `jax.jacrev` work directly on `solve` via a custom VJP; `mpcjax.optimality_fn(U, **prob)` exposes the unregularized first-order residual `dJ/dU` for custom sensitivity analysis.

### `SolverSettings`

Pass `solver_settings=mpcjax.SolverSettings(...)` to `solve`:

| Field | Default | Meaning |
| --- | --- | --- |
| `solver` | `"sqp"` | Inner optimizer: `"sqp"` (Cholesky-regularized Newton), `"cvx"` (Newton), `"lbfgs"` (`optax`), `"bfgs"` (`jax.scipy`). |
| `linesearch` | `"scan"` | Step search for Newton solvers: `"scan"`, `"backtracking"`, or `"binary_search"` (`"cvx"` only). |
| `max_it`, `maxls`, `tol` | `10`, `200`, `1e-9` | Inner iteration limit, line-search evaluations, and gradient norm tolerance. |
| `anderson_m`, `anderson_reg` | `0`, `1e-8` | Safeguarded Type-II Anderson acceleration history (`0` disables; try `3` to `5` for slow SCP convergence). |

## Persistent Compilation Cache

Enable JAX's built-in persistent cache to skip recompilation across runs:

```python
import jax

jax.config.update("jax_compilation_cache_dir", "/tmp/jax_cache")
```

## Changelog

- **0.5.0**: modernized for current JAX (`jax>=0.4.25`, `optax>=0.2.3`); added precomputed condensed SCP rollout, reverse-mode IFT `@jax.custom_vjp` on `solve`, optional safeguarded Type-II Anderson acceleration (`anderson_m`), and `pyproject.toml` packaging; dropped `jaxfi`, `jaxopt`, hand-rolled JIT caches, and legacy Redis/ZMQ server.
- **0.4.0**: added JIT-compatible `solve` and `optimality_fn`.
- **0.3.0**: added `direct_solve` mode.
