magpylib_jax

magpylib_jax

Analytic magnetic fields you can differentiate, compile, and optimize through.

PyPI CI License

B-field of a cuboid magnet

magpylib_jax is a clean-room, JAX-native reimplementation of Magpylib. It keeps Magpylib’s ergonomic object and functional APIs and its analytic field models, but swaps the numerical core for a differentiable, JIT-compilable, vmap-friendly one — so the same field computation you use for analysis drops straight into a jax.grad optimization loop, on CPU, GPU, or TPU.

import jax
jax.config.update("jax_enable_x64", True)   # float64, for magpylib parity
import magpylib_jax as mpj

src = mpj.magnet.Cuboid(polarization=(0, 0, 1.0), dimension=(1, 1, 1))
B = src.getB((2.0, 0.0, 0.0))                 # tesla
dBz_dh = jax.grad(lambda h:
    mpj.magnet.Cuboid(polarization=(0, 0, 1.0), dimension=(1, 1, h)).getB((2, 0, 0))[2])(1.0)

What you get

⚡ Differentiable

Exact grad / jacfwd / jacrev through getB/getH/getJ/getM and getFT, w.r.t. geometry, pose, and excitation — no finite differences.

🚀 Compiled & vectorized

The field core runs under jax.jit / vmap / XLA on CPU, GPU, and TPU.

🧲 Exact force & torque

getFT gives force and torque by autodiff of m·Beps-free and exact, unlike Magpylib’s finite-difference approach.

🔁 Drop-in for Magpylib

Same source classes, Collection, Sensor, motion, and getB/…/getFT/show/mu_0. Often just swap the import.

🎛️ Precision you control

Follows your JAX config: float32 by default, float64 for bit-level parity. The library never mutates the global config.

📐 Research-grade & tested

All 12 source families, ≥95% coverage, a full Magpylib parity suite, and derivations with citations.

Where to next

🏁 Getting started

Install, compute your first field and gradient, and pick a precision.

📖 User guide

Tutorials: fields, motion & paths, collections, visualization, force/torque, and optimization.

🧮 Theory & methods

The physical conventions, per-source closed-form models, numerics, differentiability, and the papers behind each kernel.

🔧 Reference

The API reference and a clickable map from the public API down to the analytic kernels.