Python, PyO3 & JAX API Reference¶
FlexMESA exposes a unified Python and JAX (float64) public interface backed by compiled Safe Rust workspace crates (flexmesa._rust, enforcing #![forbid(unsafe_code)] across all crates except the sole vendored crlibm FFI wrapper flexmesa-crlibm-sys) and XLA-compiled @jax.jit array kernels. Importing flexmesa automatically enables 64-bit IEEE-754 double precision in JAX (jax_enable_x64=True) so that spline interpolations, thermodynamic partials, nuclear networks, and block-tridiagonal Henyey solves maintain full floating-point precision by default.
Safe Rust crate documentation (crates/flexmesa-*) is built via cargo doc --workspace --no-deps and published at /rustdoc/ in the documentation deployment.
Domain API Reference Map¶
To keep each reference page fast to load and easy to navigate, the Python and JAX API is organized into eight domain-specific pages:
| Domain Reference Page | Python Subpackages | Primary Classes & Functions |
|---|---|---|
| 1D Stellar Structure & Evolution | flexmesa.star |
StarModel, HenyeySolverReport, EvolveStepReport, HistoryRow, JaxStarState, parse_inlist_bundle, run_test_suite_case, standalone atomic diffusion, shellular rotation, HLLC Riemann hydrodynamics, RSP2 turbulent pulsation (partial/unverified; #153, #156, #158), and GYRE/FGONG/OSC exporters (GYRE/ADIPLS runtime tracked in #170/#171) |
| Interacting Binaries & Accretors | flexmesa.binary |
BinarySystem, eval_rlobe, eval_ritter_mdot_thin, eval_kolb_mdot_thick, Eggleton Roche-lobe geometry, Kerr BH ISCO spin & Eddington accretion, orbital \(\dot{J}\), and Hut tidal evolution |
| Asteroseismology & Optimization | flexmesa.astero |
Acoustic radius/depth profiles, \(\Delta\nu\) and \(\nu_{\max}\) scaling relations, \(\Delta\Pi_1\) period spacing, He II/BCZ glitch depths, 5 surface corrections (BG14, Kjeldsen2008, Sonoi2015), separation ratios, \(\chi^2\), and Nelder-Mead/Powell/grid optimizers |
| Equations of State | flexmesa.eos |
7-component EOS (Ideal, HELM, PC, Skye, FreeEOS, OPAL/SCVH, CMS), \(C^2\) quintic polygonal blending (eos_dt_get), and \((P_{\mathrm{gas}}, T)\) root-finding inversions (eos_pt_get) |
| Opacity, Atmospheres & Photometry | flexmesa.kap, flexmesa.atm, flexmesa.colors |
Radiative (OPAL/OP/AESOPUS), conductive, and Compton opacities; Eddington/Krishna-Swamy/irradiated and tabulated model atmospheres; 3D cubic Hermite Kurucz SED synthesis and synthetic filter photometry |
| Nuclear Networks, Rates & Neutrinos | flexmesa.chem, flexmesa.ionization, flexmesa.neu, flexmesa.rates, flexmesa.net |
347 built-in reference nuclides and 10 solar abundance scales; partial ionization and \(\mathrm{Fe}^{56}\) in \(\mathrm{He}^4\) charge states; Itoh 5-channel thermal neutrinos; 316 REACLIB rates and plasma screening; basic.net/approx21.net RHS, analytical Jacobians, and 1-zone stiff burners |
| Foundational Numerics & Convection | flexmesa.constants, flexmesa.math, flexmesa.utils, flexmesa.auto_diff, flexmesa.interp_1d, flexmesa.interp_2d, flexmesa.mtx, flexmesa.num, flexmesa.turb |
Physical constants; IEEE-754 elementary intrinsics; dual and hyperdual automatic differentiation; 1D/2D monotonic and bicubic splines; dense, banded, bcyclic, and PCR block-tridiagonal solvers; root finders and Rosenbrock/RK integrators; MLT, TDC, semiconvection, and thermohaline mixing |
| I/O, Schemas, Plotting & Benchmarks | flexmesa.schema, flexmesa.data, flexmesa.testing, flexmesa.plotting, flexmesa.bench |
.defaults and &namelist parsers; .safetensors memory-mapped loaders and SHA-256 manifest verification; upstream test_output reference comparators (flexmesa.testing.golden) and MESA 26.4.1 history harness (flexmesa.testing.history_compare); HR, Kippenhahn, échelle, and binary RLOF plotting; 4-stage benchmark harnesses |
Python Subpackage Index¶
_rust: Compiled Safe Rust PyO3 extension (flexmesa._rust), the canonical engine behind every Python wrapper.astero: Asteroseismology and optimization (page).atm: Model atmospheres and T-tau relations (page).auto_diff: Forward-mode dual and hyperdual numbers (page).bench: Benchmark harnesses (page).binary: Interacting binaries and accretors (page).chem: Nuclide catalog, solar abundances and composition moments (page).colors: Synthetic photometry and SED synthesis (page).constants: Physical constants (page).data: Safetensors loaders and manifest verification (page).eos: Equations of state (page).interp_1d: 1D monotonic and piecewise-cubic interpolation (page).interp_2d: 2D bicubic and Akima interpolation (page).ionization: Partial ionization and effective ionic charges (page).kap: Radiative, conductive and Compton opacities (page).math: Run-level numerics modes and elementary intrinsics (page).mtx: Dense, banded and block-tridiagonal linear solvers (page).net: Nuclear reaction networks and 1-zone burners (page).neu: Thermal neutrino loss rates (page).num: Root finders, quadrature and stiff ODE integrators (page).plotting: Stellar and binary plotting (page).rates: Thermonuclear rates and plasma screening (page).schema:.defaultsand&namelistparsers (page).star: 1D stellar structure and evolution (page).testing: Reference comparators and the history harness (page).turb: Turbulent convection and mixing (page).utils: Array helpers, finiteness guards and checkpoint codec (page).
Top-Level Package Exports (flexmesa)¶
flexmesa
¶
FlexMESA: Modular stellar astrophysics in Safe Rust and Python/JAX.
This package provides the Python and JAX (float64) implementation of MESA's
foundational numerics, microphysics, and stellar evolution modules. Importing
flexmesa enables 64-bit floating-point precision in JAX (jax_enable_x64) so
that thermodynamic, spline, and linear-algebra calculations maintain IEEE-754
double precision by default.
enable_float64
¶
Backend Dispatch & Numerics Modes (flexmesa._dispatch)¶
Functions with both Safe Rust and derived JAX backends accept backend="auto" | "rust" | "jax", while Rust arithmetic defaults to hardware-independent "strict" mode (get_numerics_mode, set_numerics_mode, numerics_mode_context). Under backend="auto" (the default), resolve_backend inspects all scalar, array, and nested tuple/list/dict numeric inputs: calls without JAX leaves route to canonical flexmesa._rust, whereas calls carrying any jax.Array or JAX tracer (jax.grad, jax.vmap, jax.jit) route to the derived float64 JAX kernel (validated against Rust "strict" mode, #166; see the Backends, JAX Contract & Custom Gradients guide for per-module AD mode and device caveats).
import jax.numpy as jnp
import numpy as np
import flexmesa
# NumPy inputs resolve to the zero-copy Safe Rust backend
print("NumPy dispatch:", flexmesa.resolve_backend("auto", np.array([1.0, 2.0])))
# JAX arrays resolve to the XLA-compiled JAX backend
print("JAX dispatch: ", flexmesa.resolve_backend("auto", jnp.array([1.0, 2.0])))
flexmesa._dispatch
¶
Backend dispatch helper for canonical Safe Rust and derived JAX.
Provides the :data:Backend type alias ("auto" | "rust" | "jax") and
:func:resolve_backend so routines with both Safe Rust and JAX backends route:
- Python
float/intscalars and NumPyndarrayinputs to the canonical Safe Rustflexmesa._rust(PyO3) extension whenbackend == "auto"orbackend == "rust". - JAX
Arrayand traced differentiation values (jax.grad,jax.jvp,jax.vmap,jax.jit) to derived@jax.jitkernels (validated against Ruststrictmode) whenbackend == "auto"orbackend == "jax".
validate_numerics_mode
¶
Validate and normalize a "strict" / "fast" mode string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
Raw mode string to normalize. |
required |
label
|
str
|
Parameter or environment-variable name used in error messages. |
'numerics_mode'
|
Returns:
| Type | Description |
|---|---|
NumericsMode
|
Canonical lowercase :data: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
is_jax_input
¶
Return True if any argument in values is a JAX array or tracer.
Inspects top-level values as well as nested containers, dataclasses,
object-dtype NumPy arrays, __jax_array__ objects, and registered JAX
PyTrees so backend="auto" detects traced arguments inside composite
inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*values
|
Any
|
Positional scalar, array, or nested container arguments. |
()
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
bool
|
|
resolve_backend_with_jax
¶
Resolve backend and report whether values contain JAX inputs.
Avoids rescanning values when a caller needs both the resolved backend
and whether to preserve JAX arrays/tracers rather than unboxing scalars.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Backend
|
Requested backend selector ( |
required |
*values
|
Any
|
Input values whose runtime types determine automatic routing. |
()
|
Returns:
| Type | Description |
|---|---|
Literal['rust', 'jax']
|
Tuple |
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
resolve_backend
¶
Resolve backend ("auto" | "rust" | "jax") for given values.
When backend == "auto", inspects values via :func:is_jax_input
so JAX arrays and tracers route to "jax" while Python scalars and
NumPy ndarray inputs route to "rust".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
Backend
|
Requested backend selector ( |
required |
*values
|
Any
|
Input values whose runtime types determine automatic routing. |
()
|
Returns:
| Type | Description |
|---|---|
Literal['rust', 'jax']
|
Resolved backend string ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
as_c_f64
¶
Convert arr to a 1D C-contiguous float64 NumPy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Any
|
Array-like input. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Flat 1D C-contiguous |
get_numerics_mode
¶
Return the active Rust arithmetic mode ("strict" or "fast").
Returns:
| Name | Type | Description |
|---|---|---|
Active |
NumericsMode
|
data: |
set_numerics_mode
¶
Set the process-wide Rust arithmetic mode ("strict" or "fast").
"strict" (default) evaluates vendored crlibm (CRMATH) routines
with no fused multiply-add contraction and is the sole mode compared
against MESA. "fast" evaluates platform f64 methods with fma
enabled and is validated against "strict".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
NumericsMode | str
|
Target numerics mode ( |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
numerics_mode_context
¶
Temporarily switch the Rust arithmetic mode and restore on exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
NumericsMode | str
|
Target numerics mode ( |
required |
Yields:
| Type | Description |
|---|---|
NumericsMode
|
Normalized active :data: |
Command-Line Interface (flexmesa.cli)¶
The installed flexmesa console script dispatches subcommands such as flexmesa data fetch, flexmesa data verify, flexmesa data status, flexmesa data clean-cache, flexmesa trace, flexmesa harness (--numerics-mode {strict,fast}, --allow-unsupported-controls), and flexmesa --version.