Skip to content

Installation & Environment Setup

FlexMESA combines a compiled Safe Rust workspace (crates/flexmesa-*) with a Python and JAX package (src/flexmesa/) bridged via PyO3 and maturin. This guide covers installing prerequisites, building FlexMESA from source, configuring multi-core CPU thread pools and 64-bit JAX execution on CPU or GPU, and managing .safetensors microphysics data tables.


1. Prerequisites

Building and running FlexMESA requires:

  • Python (>= 3.12): Required for modern type annotations (type aliases and PEP 695 generics) and tomllib manifest parsing.
  • Rust Toolchain (>= 1.80, stable): Required to compile the Cargo workspace crates (crates/flexmesa-*, enforcing #![forbid(unsafe_code)] across all crates except the sole vendored crlibm FFI wrapper flexmesa-crlibm-sys) and the flexmesa._rust native extension module via cargo and maturin.
  • C/C++ Compiler & Linker (gcc or clang): Compiles the vendored C99 crlibm 1.0beta4 sources inside crates/flexmesa-crlibm-sys using fixed committed target headers (no autoconf or system crlibm required) and links the shared PyO3 library (_rust.abi3.so on Linux/macOS or _rust.pyd on Windows). No Fortran compiler (gfortran) or MESA SDK installation is required to build or run FlexMESA.

To verify your Python and Rust toolchains before installation:

python3 --version
rustc --version
cargo --version

If Rust is not yet installed on your system, install the standard stable toolchain via rustup:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

2. Installing from Source (uv or pip + maturin)

Clone the FlexMESA repository and install the package in release mode. Because pyproject.toml declares maturin as the PEP 517 build backend, installing with uv pip install or pip install automatically compiles the Rust workspace and installs the Python and JAX modules alongside all required runtime dependencies (numpy>=2.0, scipy>=1.12, jax>=0.4.30, safetensors>=0.4, and matplotlib>=3.9).

git clone https://github.com/joshspeagle/FlexMESA.git
cd FlexMESA
uv pip install -e ".[test,docs]"
git clone https://github.com/joshspeagle/FlexMESA.git
cd FlexMESA
pip install -e ".[test,docs]"

When iterating on the Safe Rust crates in crates/, invoke maturin develop --release directly to recompile flexmesa._rust with full Link-Time Optimization (lto = "thin") and opt-level = 3 in place:

maturin develop --release

Installing GPU-Accelerated JAX (Optional)

By default, jax>=0.4.30 installs the CPU backend (jaxlib). On Linux workstations or cluster nodes equipped with NVIDIA GPUs, install the matching CUDA 12 plugin so @jax.jit, jax.vmap, and Parallel Cyclic Reduction (solver_mode="pcr") execute on the GPU:

pip install -U "jax[cuda12]"

3. Verifying the Installation

Run the following one-liner to verify that the compiled flexmesa._rust extension, the built-in .safetensors physics tables, and 64-bit JAX precision are active:

python3 -c "import flexmesa, jax; print('FlexMESA', flexmesa.__version__, '| x64:', jax.config.jax_enable_x64, '| devices:', jax.devices())"

To run the fast verification suite across Python/JAX (pytest) and the Safe Rust workspace (cargo test):

pytest -q
cargo test --workspace --release

4. Runtime Configuration: Thread Pools & float64 Precision

Automatic IEEE-754 float64 Precision in JAX

Stellar structure equations, bicubic and biquintic thermodynamic splines, and block-tridiagonal Henyey Jacobians require 64-bit IEEE-754 floating-point arithmetic (f64 / jnp.float64) because 32-bit float32 rounding errors (\(\sim 10^{-7}\)) exceed the convergence tolerance of hydrostatic equilibrium (\(\le 10^{-10}\)) and amplify curvature noise in second-order Helmholtz free-energy derivatives. Importing flexmesa automatically calls flexmesa.enable_float64(), which sets jax_enable_x64 = True.

If you import jax and allocate arrays before importing flexmesa, either set the environment variable before launching Python:

export JAX_ENABLE_X64=1

or call flexmesa.enable_float64() at the top of your script. To force CPU execution on a machine that also has a GPU (for example, in deterministic CI jobs or small single-zone scripts), set:

export JAX_PLATFORMS=cpu

Controlling Safe Rust CPU Parallelism (RAYON_NUM_THREADS)

Multi-zone microphysics evaluators (neu, turb, chem, ionization, colors, eos, kap, rates, net, atm) and the Hirshman et al. (2010) bcyclic block-tridiagonal solver parallelize across radial shells using a persistent rayon worker pool in flexmesa._rust. You can control the number of CPU worker threads via standard environment variables:

export RAYON_NUM_THREADS=4
export OMP_NUM_THREADS=4
export OPENBLAS_NUM_THREADS=4

Setting RAYON_NUM_THREADS to match the physical core count (typically 4 to 8 threads for a single stellar track of \(N_{\mathrm{zones}} \sim 10^3\) to \(4 \times 10^3\)) avoids thread-contention overhead when running ensembles of stellar tracks in parallel.


5. Physics Data Tables (flexmesa data fetch & FLEXMESA_DATA_DIR)

Upstream Fortran MESA distributes over 2 GiB of ASCII text tables paired with platform-dependent Fortran unformatted binary cache files. FlexMESA replaces these with content-addressed, zero-copy .safetensors and IEEE-754 little-endian binary table bundles verified by SHA-256 checksums:

  • Full-Resolution data-v1 Physics Bundles (flexmesa data fetch): After installing FlexMESA, fetch and checksum-validate the canonical full-resolution physics tables (helm_table_full.bin, full radiative and conductive opacity tables kap_tables_full.bin, and the 116 OPAL/SCVH, FreeEOS, and CMS 4D EOS composition slices) into the read-only $FLEXMESA_DATA_DIR directory (defaulting to $XDG_CACHE_HOME/flexmesa/data or ~/.cache/flexmesa/data):
flexmesa data fetch
flexmesa data verify
flexmesa data status
flexmesa data clean-cache

To also download the SHA-256-verified MESA release 26.4.1 test_output fixtures, Fortran source, test_suite inputs (mesa-test-inputs-v2), exact IEEE-754 hexadecimal module test outputs (mesa-module-hex-v1), full reference trajectories (mesa-histories-v4, adding per-stage stage_logs/, unthinned 53-column astero search tracks/, testhub.yml, command.txt, and inlists/ alongside thinned/), solver step dumps for flexmesa trace --compare (mesa-stepdumps-v2), the thinned search track archive (mesa-astero-tracks-v1), and MESA's star state and pulsation files at export_pulse_data calls (mesa-pulse-export-v1) into ~/.cache/flexmesa/, pass --include-test-inputs:

flexmesa data fetch --include-test-inputs

To reproduce or reassemble the full mesa-histories-v4 bundle from local MESA 26.4.1 runs (scripts/mesa_reference/run_mesa_case_26_4_1.sh with CAPTURE_STAGE_LOGS=1 / HISTORY_TAP_OBJ, orchestrated for the 16 multi-stage/multi-track cases by scripts/mesa_reference/capture_gap_cases.py), run scripts/mesa_reference/assemble_mesa_bundle.py.

The record/replay routine oracles of MESA 26.4.1 (mesa-replay-v1: the first two models of 18 star cases, 664 MB compressed and 4.7 GB unpacked) are opt-in and are never fetched by --include-test-inputs, nor required by flexmesa data verify or flexmesa data status. Name the bundle to fetch or verify it; it unpacks to mesa_replay/star/<case>.replay and <case>.stepdump under the data directory (flexmesa data path):

flexmesa data fetch --bundle mesa_replay
flexmesa data verify --bundle mesa_replay

The mid-run solver step-dump windows of MESA 26.4.1 (mesa-stepdump-windows-v1: 31 windows of 15 cases, 56 MB compressed and 243 MB unpacked; recipe in benchmarks/fortran_mesa/stepdumps/README.md) are opt-in in the same way:

flexmesa data fetch --bundle mesa_stepdump_windows
flexmesa data verify --bundle mesa_stepdump_windows

The full-chain MESA 26.4.1 run of star/make_pre_ccsn_13bvn that produced the case's regenerated part-6 starting model (mesa-13bvn-full-chain-v1: all six parts, 4 MB compressed and 31 MB unpacked; DECISIONS #93) is provenance only and opt-in in the same way; the harness reads the committed model:

flexmesa data fetch --bundle mesa_13bvn_full_chain
flexmesa data verify --bundle mesa_13bvn_full_chain

The OP monochromatic opacity data, which MESA 26.4.1 does not ship, are opt-in in the same way. Each bundle is the verbatim Zenodo file: op_mono_op4stars is OP4STARS_1.3.tar.xz (Zenodo record 4390522, 462 MB compressed and 875 MB unpacked) for op_mono_method = 'hu', and op_mono_master_grid is OP_mono_master_grid_MESA_emesh.txt.xz (Zenodo record 6858178, 1.2 GB compressed and 7.6 GB unpacked) for op_mono_method = 'mombarg'. A copy downloaded from Zenodo installs with --source-dir <download directory>. Once they are installed, the harness and flexmesa trace set MESA_OP_MONO_DATA_PATH and MESA_OP_MONO_MASTER_GRID to them unless these are already set, and the engine reads the variables when op_mono_data_path or emesh_data_for_op_mono_path is blank, as MESA does:

flexmesa data fetch --bundle op_mono_op4stars --bundle op_mono_master_grid
flexmesa data verify --bundle op_mono_op4stars --bundle op_mono_master_grid

--bundle is repeatable and replaces the default selection; an unknown name is an error. flexmesa data status lists the bundle as optional and reports whether it is present.

  • Bundled Core Catalogs: The reference nuclide catalog (347 built-in reference nuclides plus full isotopes.data parser), 286 solar isotopes across 10 solar abundance scales (AG89 through AAG21, including lodders03, gs98, and asplund09), the Kurucz (2003) stellar atmosphere SED atlas (lcb98cor.dat), the 316 built-in REACLIB nuclear rates, and the Zero-Age Main Sequence (ZAMS) stellar catalog are embedded directly into the repository.
  • Cryptographic Integrity (manifest.toml & bundles.toml): Every .safetensors table bundle in src/flexmesa/data/manifest.toml and every release archive in src/flexmesa/data/bundles.toml carries its exact byte size and 64-character lowercase hexadecimal SHA-256 digest. You can inspect both manifests from Python:
from flexmesa.data import fetch, manifest

catalog = manifest.load_default_manifest()
for name, artifact in catalog.items():
    print(f"{name}: {artifact.filename} ({artifact.size_bytes} bytes, sha256={artifact.sha256[:12]}...)")

repo, tag, bundles = fetch.load_bundles_manifest()
print(f"Release {repo}@{tag}: {len(bundles)} verified archives")
  • Read-Only Table Directory (FLEXMESA_DATA_DIR) & Isolated Runtime Caches (FLEXMESA_CACHE_DIR): When hosting physics table bundles on shared cluster storage, set FLEXMESA_DATA_DIR (or pass --dest / --data-dir to flexmesa data fetch, flexmesa data verify, flexmesa data path, and flexmesa data clean-cache), and optionally set MESA_DIR to point to the extracted mesa_test_inputs directory. $FLEXMESA_DATA_DIR is strictly read-only at runtime: flexmesa data verify checks archive and per-file SHA-256 manifests (bundle_hashes/*.sha256.tsv) and rejects any unexpected files or legacy caches inside data directories. Runtime-derived spline and binary caches (eos_4d_slices, helm, kap, ionization) are written to a separate versioned cache directory $FLEXMESA_CACHE_DIR/v1 (defaulting to $XDG_CACHE_HOME/flexmesa/derived/v1 or ~/.cache/flexmesa/derived/v1) wrapped in an FMCENV01 envelope recording schema version, builder version, payload tag, source SHA-256, and payload SHA-256. Set FLEXMESA_DISABLE_RUNTIME_CACHE=1 to disable runtime cache I/O, or run flexmesa data clean-cache (--purge-legacy-in-data) to remove derived caches.