Skip to main content

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

pip install mpcjax

For local development:

pip install -e ".[dev]"

Quick Start

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/Problems 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:

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.

Metadata

Release files for mpcjax 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for mpcjax 0.5.0
File Interpreter ABI Platform Actions
mpcjax-0.5.0-py3-none-any.whl Python 3 none any Details for mpcjax-0.5.0-py3-none-any.whl

Release files / mpcjax-0.5.0-py3-none-any.whl

Download URL mpcjax-0.5.0-py3-none-any.whl
Size 18.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
75674314ec96d7d12ef63f44543ed5050e391916ec0bc96e4108e132e354c392
BLAKE2b-256 checksum
How to use checksums
cea253395804a84fe7404892a68e55d66554f152546b463ddc9d3f32273369dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.4

Security for mpcjax 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page