Skip to content

I/O, Schemas, Plotting & Benchmarks (schema, data, testing, plotting, bench)

This reference page documents the configuration schema and Fortran &namelist parser (flexmesa.schema), the .safetensors memory-mapped data loader and SHA-256 manifest verifier (flexmesa.data), the upstream test_output reference and MESA 26.4.1 trajectory comparators (flexmesa.testing), the publication-styled diagnostic plotting suite (flexmesa.plotting), and the 4-stage benchmark harness (flexmesa.bench).

For hands-on guides, see Inlists, Models & Data Caches, Diagnostic Plotting, Backends & CPU/GPU Performance, and Which Instrument for Which Symptom.


Quick Usage Example

from flexmesa.schema import namelist
from flexmesa.testing import golden

# Parse an inline Fortran &namelist block into typed NamelistBlock structures
blocks = namelist.parse_namelist_text(
    """
&star_job
  create_pre_main_sequence_model = .false.
/
&controls
  initial_mass = 1.0d0
  initial_z = 0.02d0
  mixing_length_alpha = 2.0d0
/
"""
)
val = golden.parse_fortran_float("1.98840987D+33")
print(
    f"block={blocks[1].name}, {blocks[1].assignments[0].name}={blocks[1].assignments[0].value}, "
    f"parsed float={val:.6e}"
)

Declarative .defaults & Fortran inlist Schemas (flexmesa.schema)

flexmesa.schema parses upstream MESA <pkg>/defaults/*.defaults and *_columns.list files into typed control registries and validates Fortran &namelist (inlist) files (including 1.0d0 exponents, .true./.false. booleans, array subscripts xa_central_lower_limit_species(1), and recursive read_extra_*_inlist chains).

flexmesa.schema.defaults

Parser for MESA <pkg>/defaults/*.defaults and *_columns.list files.

Extracts parameter names, Fortran control types (LOGICAL, INTEGER, FLOAT, STRING), scalar and array default values, indexed element overrides, section headings, and inline documentation from MESA .defaults and *_columns.list files by delegating to the canonical Safe Rust flexmesa_schema implementation in flexmesa._rust.

ControlType

Bases: StrEnum

Fortran scalar type for a MESA .defaults control parameter.

ControlDefault dataclass

Single control parameter definition parsed from a .defaults file.

Attributes:

Name Type Description
name str

Canonical control identifier (for example, use_PC or initial_mass).

control_type ControlType

Parsed ControlType (LOGICAL, INTEGER, FLOAT, or STRING).

default_value ControlValue

Scalar or broadcast default value (in the physical CGS or solar units documented by the MESA control).

is_array bool

Whether the control is an array parameter (declared with (:) or an explicit subscript in .defaults).

element_overrides tuple[tuple[str, ControlValue], ...]

Tuple of (subscript, value) pairs for per-index defaults (such as ("13", "_CO") on suffix_for_FreeEOS_Z).

section str

Active underlined section header preceding this control.

doc str

Cleaned documentation comment block preceding the control.

line_number int

1-based line number of the initial declaration.

ColumnEntry dataclass

Single active column or directive from a MESA *_columns.list file.

Attributes:

Name Type Description
name str

Column identifier or directive (for example, model_number, star_age, or add_abundances).

section str

Active !# or !## section heading preceding this column.

comment str

Inline trailing comment describing units or meaning.

line_number int

1-based line number in the *_columns.list file.

find_unquoted_char

find_unquoted_char(text, target)

Return index of first target character outside quotes, or None.

Parameters:

Name Type Description Default
text str

Input Fortran source or configuration line.

required
target str

Single-character delimiter (such as '!' or '/').

required

Returns:

Type Description
int | None

0-based character index of the first unquoted target, or None.

strip_fortran_comment

strip_fortran_comment(line)

Split a Fortran line into (code_part, comment_part) outside quotes.

Parameters:

Name Type Description Default
line str

Raw single line of Fortran source or .defaults text.

required

Returns:

Type Description
tuple[str, str]

Tuple (code, comment) with outer whitespace stripped.

parse_control_value

parse_control_value(raw)

Parse a Fortran .defaults or namelist literal into type and value.

Delegates to flexmesa_schema::parse_control_value via flexmesa._rust.

Parameters:

Name Type Description Default
raw str

Stripped right-hand-side literal string (for example, .false., 1d-4, 'undefined', or 170).

required

Returns:

Type Description
tuple[ControlType, ControlValue]

Tuple (control_type, parsed_value).

Raises:

Type Description
ValueError

If raw is not a valid Fortran logical, string, 64-bit integer, or finite floating-point literal.

Examples:

>>> from flexmesa.schema import defaults
>>> defaults.parse_control_value(".true.")
(<ControlType.LOGICAL: 'logical'>, True)
>>> defaults.parse_control_value("1d-4")
(<ControlType.FLOAT: 'float'>, 0.0001)

parse_assignment_clause

parse_assignment_clause(clause, line_idx)

Parse a name[(subscript)] = value clause into its typed components.

Parameters:

Name Type Description Default
clause str

Single assignment expression without trailing comments.

required
line_idx int

1-based line number for error reporting.

required

Returns:

Type Description
tuple[str, str | None, ControlType, ControlValue]

Tuple (name, subscript, control_type, value).

Raises:

Type Description
ValueError

If clause does not match name[(subscript)] = value.

parse_defaults_text

parse_defaults_text(text)

Parse the text of a MESA <pkg>/defaults/*.defaults file.

Delegates to flexmesa_schema::parse_defaults_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Full UTF-8 contents of a MESA .defaults file.

required

Returns:

Type Description
dict[str, ControlDefault]

Ordered dictionary mapping lowercase control names to ControlDefault

dict[str, ControlDefault]

entries.

Raises:

Type Description
ValueError

If any non-comment line contains a malformed assignment or invalid literal.

Examples:

>>> from flexmesa.schema import defaults
>>> sample = "! EOS\n! ---\n  use_PC = .false.\n  logT1 = 7.6d0\n"
>>> schema = defaults.parse_defaults_text(sample)
>>> schema["use_pc"].default_value, schema["logt1"].section
(False, 'EOS')

parse_defaults_file

parse_defaults_file(path)

Read and parse a MESA <pkg>/defaults/*.defaults file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the .defaults file.

required

Returns:

Type Description
dict[str, ControlDefault]

Ordered dictionary mapping lowercase control names to ControlDefault

dict[str, ControlDefault]

objects.

parse_columns_text

parse_columns_text(text)

Parse active column declarations from a MESA *_columns.list file.

Delegates to flexmesa_schema::parse_columns_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Full UTF-8 contents of a history_columns.list or profile_columns.list file.

required

Returns:

Type Description
list[ColumnEntry]

Ordered list of active ColumnEntry declarations (preserving first

list[ColumnEntry]

occurrence order when duplicates appear, matching MESA's rule).

Examples:

>>> from flexmesa.schema import defaults
>>> sample = "!# general\n  model_number ! count\n  !star_age_sec\n"
>>> cols = defaults.parse_columns_text(sample)
>>> len(cols), cols[0].name, cols[0].section
(1, 'model_number', 'general')

parse_columns_file

parse_columns_file(path)

Read and parse a MESA *_columns.list file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the *_columns.list file.

required

Returns:

Type Description
list[ColumnEntry]

Ordered list of active ColumnEntry declarations.

flexmesa.schema.namelist

Parser and schema validator for legacy MESA Fortran &namelist blocks.

Parses Fortran &namelist ... / blocks (&eos, &kap, &star_job, &controls) into structured NamelistBlock objects by delegating to the canonical Safe Rust flexmesa_schema::parse_namelist_text implementation in flexmesa._rust, and validates every control assignment against a parsed ControlDefault schema.

NamelistAssignment dataclass

Single name[(subscript)] = value assignment inside a namelist block.

Attributes:

Name Type Description
name str

Control parameter name as written in the inlist.

subscript str | None

Optional array subscript string (for example, "1" or "13"), or None for scalar assignments.

value_type ControlType

Parsed ControlType of the assigned literal.

value ControlValue

Parsed Python scalar value (bool | int | float | str).

line_number int

1-based line number in the inlist source.

NamelistBlock dataclass

Parsed Fortran &namelist ... / block from a MESA inlist file.

Attributes:

Name Type Description
name str

Namelist group name without leading & (for example, "eos", "controls", or "star_job").

assignments tuple[NamelistAssignment, ...]

Ordered tuple of NamelistAssignment entries.

parse_namelist_text

parse_namelist_text(text)

Parse one or more Fortran &namelist ... / blocks from text.

Delegates directly to flexmesa_schema::parse_namelist_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Full UTF-8 contents of a MESA inlist file.

required

Returns:

Type Description
list[NamelistBlock]

Ordered list of NamelistBlock objects.

Raises:

Type Description
ValueError

If namelist headers, assignments, or terminators (/) are malformed or unclosed.

Examples:

>>> from flexmesa.schema import namelist
>>> src = "&eos\n  use_PC = .true.\n/\n"
>>> blocks = namelist.parse_namelist_text(src)
>>> blocks[0].name, blocks[0].assignments[0].value
('eos', True)

parse_namelist_file

parse_namelist_file(path)

Read and parse a MESA Fortran inlist file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the inlist file.

required

Returns:

Type Description
list[NamelistBlock]

Ordered list of NamelistBlock objects.

validate_namelist_block

validate_namelist_block(
    block, schema, *, strict_numeric_types=False
)

Validate a NamelistBlock against a .defaults schema.

Parameters:

Name Type Description Default
block NamelistBlock

Parsed NamelistBlock to validate.

required
schema Mapping[str, ControlDefault]

Mapping of lowercase control names to ControlDefault entries (as returned by defaults.parse_defaults_text).

required
strict_numeric_types bool

If True, reject FLOAT literals on controls whose default literal in .defaults was parsed as INTEGER. Defaults to False because MESA .defaults files frequently write -1 or 1 for real(dp) controls (Zbase = -1, initial_mass = 1).

False

Returns:

Type Description
dict[str, ControlValue | dict[str, ControlValue]]

Dictionary of validated control overrides keyed by canonical control

dict[str, ControlValue | dict[str, ControlValue]]

name (mapping scalar controls to ControlValue and subscripted array

dict[str, ControlValue | dict[str, ControlValue]]

controls to {subscript: ControlValue}).

Raises:

Type Description
KeyError

If an assigned control name does not exist in schema.

TypeError

If an assigned value's type or subscript is incompatible with the schema definition.


.safetensors Data Loader, Manifest, Release Bundles & Converters (flexmesa.data)

flexmesa.data validates archive and per-file SHA-256 checksums against manifest.toml, bundles.toml, and bundle_hashes/*.sha256.tsv (flexmesa data fetch, flexmesa data verify, rejecting unexpected files inside read-only $FLEXMESA_DATA_DIR), isolates versioned runtime-derived caches under $FLEXMESA_CACHE_DIR/v1 (resolve_cache_dir, FLEXMESA_DISABLE_RUNTIME_CACHE, flexmesa data clean-cache), memory-maps 64-byte-aligned .safetensors physics tables directly from the OS page cache, and converts built-in ASCII MESA tables (lodders03.data, isotopes.data, and helm_table.dat) into .safetensors (while full-grid data-v1 binary bundles are built offline via make data-bundles).

flexmesa.data.manifest

SHA-256 manifest parser and file integrity verifier for physics tables.

Parses manifest.toml declarations ([[tables]]) into typed TableArtifact records and verifies .safetensors files against their recorded SHA-256 digests via flexmesa._rust prior to memory-mapping.

TableArtifact dataclass

Metadata and integrity record for a .safetensors physics table.

Attributes:

Name Type Description
name str

Logical table identifier (e.g., 'lodders03', 'isotopes', 'helm_table').

filename str

Canonical .safetensors filename (e.g., 'lodders03.safetensors').

sha256 str

Lowercase 64-character hexadecimal SHA-256 digest of the uncompressed .safetensors file.

size_bytes int

Uncompressed .safetensors file size in bytes (>= 0).

tensors tuple[str, ...]

Ordered tuple of tensor names required in the bundle.

description str

Human-readable summary of the physical data and source.

is_valid_sha256_hex

is_valid_sha256_hex(digest)

Return True if digest is a 64-character hexadecimal string.

Delegates to flexmesa_data::sha256::is_valid_sha256_hex via flexmesa._rust.

Parameters:

Name Type Description Default
digest str

Candidate SHA-256 hexadecimal digest string.

required

Returns:

Type Description
bool

True if digest has length 64 and contains only ASCII hex digits.

Examples:

>>> is_valid_sha256_hex("0" * 64)
True
>>> is_valid_sha256_hex("not-a-digest")
False

compute_sha256_bytes

compute_sha256_bytes(data)

Compute the lowercase 64-character SHA-256 hex digest of data.

Delegates to flexmesa_data::sha256::compute_sha256_bytes via flexmesa._rust.

Parameters:

Name Type Description Default
data bytes

Raw byte buffer to hash.

required

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest.

Examples:

>>> compute_sha256_bytes(b"")
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

compute_sha256_file

compute_sha256_file(path)

Compute the lowercase 64-character SHA-256 hex digest of a file.

Delegates to flexmesa_data::sha256::compute_sha256_file via flexmesa._rust.

Parameters:

Name Type Description Default
path str | Path

Path to the file on disk.

required

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest.

Raises:

Type Description
FileNotFoundError

If path does not exist.

verify_file_sha256

verify_file_sha256(path, expected_sha256)

Verify that path matches expected_sha256.

Parameters:

Name Type Description Default
path str | Path

Path to the file on disk.

required
expected_sha256 str

Expected 64-character hexadecimal SHA-256 digest.

required

Returns:

Type Description
str

Verified lowercase 64-character hexadecimal SHA-256 digest.

Raises:

Type Description
ValueError

If expected_sha256 is not a valid 64-character hex string or if the computed file digest does not match expected_sha256.

parse_manifest_text

parse_manifest_text(text)

Parse manifest.toml text into a dict of TableArtifact entries.

Parameters:

Name Type Description Default
text str

Raw TOML content containing a [[tables]] array of tables.

required

Returns:

Type Description
dict[str, TableArtifact]

Dictionary mapping logical table name to its TableArtifact.

Raises:

Type Description
ValueError

If the TOML syntax is invalid, [[tables]] is missing, duplicate table names appear, or any field fails validation.

parse_manifest_file

parse_manifest_file(path)

Read and parse a manifest.toml file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the manifest.toml file.

required

Returns:

Type Description
dict[str, TableArtifact]

Dictionary mapping logical table name to its TableArtifact.

load_default_manifest

load_default_manifest()

Load the bundled src/flexmesa/data/manifest.toml table manifest.

Returns:

Type Description
dict[str, TableArtifact]

Dictionary mapping logical table name to its TableArtifact.

flexmesa.data.fetch

Download, SHA-256-verify, and unpack data-v1 physics and test bundles.

Can run either through the installed flexmesa data CLI or directly via python3 src/flexmesa/data/fetch.py in clean Rust-only CI jobs prior to building flexmesa._rust.

UpstreamReference dataclass

Machine-readable provenance record for the pinned MESA release.

summary_line

summary_line()

Return a concise single-line provenance summary.

ReleaseBundle dataclass

Metadata and checksum record for one data-v1 release archive.

EmbeddedIonizationAsset dataclass

Provenance and grid metadata for embedded ion_tables_full.bin.

is_runtime_cache_disabled

is_runtime_cache_disabled()

Return True when FLEXMESA_DISABLE_RUNTIME_CACHE is enabled.

resolve_cache_dir

resolve_cache_dir(explicit=None)

Resolve the separate, versioned runtime derived-cache directory.

Returns None when FLEXMESA_DISABLE_RUNTIME_CACHE is enabled, and raises ValueError if FLEXMESA_CACHE_DIR (or explicit) overlaps resolve_data_dir() (N1-11).

resolve_data_dir

resolve_data_dir(explicit=None)

Resolve the canonical FlexMESA physics table directory.

Precedence: 1. explicit argument if provided. 2. $FLEXMESA_DATA_DIR if set and non-empty. 3. $XDG_CACHE_HOME/flexmesa/data if XDG_CACHE_HOME is set. 4. ~/.cache/flexmesa/data.

Parameters:

Name Type Description Default
explicit str | Path | None

Optional directory override.

None

Returns:

Type Description
Path

Resolved pathlib.Path to the physics data directory.

resolve_mesa_test_inputs_dir

resolve_mesa_test_inputs_dir(explicit=None, data_dir=None)

Resolve the extraction root for mesa-test-inputs-v2.tar.zst.

resolve_mesa_histories_dir

resolve_mesa_histories_dir(explicit=None, data_dir=None)

Resolve the extraction root for mesa-histories-v3.tar.zst.

resolve_mesa_module_hex_dir

resolve_mesa_module_hex_dir(explicit=None, data_dir=None)

Resolve the extraction root for mesa-module-hex-v1.tar.zst.

load_upstream_reference

load_upstream_reference(manifest_path=None)

Load [upstream_reference] metadata from bundles.toml.

load_bundles_manifest

load_bundles_manifest(manifest_path=None)

Parse bundles.toml into (repo, tag, bundles).

load_embedded_ionization_asset

load_embedded_ionization_asset(manifest_path=None)

Load [embedded_ionization] provenance from bundles.toml.

resolve_mesa_astero_tracks_dir

resolve_mesa_astero_tracks_dir(data_dir=None)

Resolve the unpacked mesa-astero-tracks-v1.tar.zst root (#430).

Parameters:

Name Type Description Default
data_dir Path | None

Optional physics data directory; defaults to :func:resolve_data_dir.

None

Returns:

Type Description
Path

<data_dir>/mesa_astero_tracks, holding

Path

astero/<case>/track_NNNN.data.

bundle_environment

bundle_environment(data_dir=None, manifest_path=None)

Environment variables that point upstream's data controls at bundles.

Some upstream data is not shipped with MESA and is located through an environment variable read when the control is blank, such as $MESA_OP_MONO_DATA_PATH for op_mono_data_path (star/job/run_star_support.f90:407-417). A bundle that declares environment_variable maps it to environment_relpath inside its install root once the bundle is installed.

Parameters:

Name Type Description Default
data_dir str | Path | None

Physics data directory (defaults to :func:resolve_data_dir).

None
manifest_path Path | None

Optional bundles.toml path.

None

Returns:

Type Description
dict[str, str]

{variable: absolute path} for every installed bundle that

dict[str, str]

declares an environment variable.

select_bundles

select_bundles(
    bundles, *, include_test_inputs=False, names=None
)

Choose the bundles an operation acts on.

Parameters:

Name Type Description Default
bundles Sequence[ReleaseBundle]

Every declared bundle.

required
include_test_inputs bool

Include test_only bundles. Ignored when names is given.

False
names Sequence[str] | None

Explicit bundle names. Only these are selected, whether or not they are test_only or on_demand.

None

Returns:

Type Description
ReleaseBundle

The selected bundles in declaration order. Without names,

...

on_demand bundles are never selected.

Raises:

Type Description
ValueError

If a name in names is not a declared bundle.

clean_runtime_cache

clean_runtime_cache(
    *,
    cache_dir=None,
    data_dir=None,
    purge_legacy_in_data=False,
    quiet=False,
)

Remove versioned runtime caches and optional legacy data-dir caches.

is_bundle_ready

is_bundle_ready(root, bundle)

Return True when bundle is already unpacked and stamped.

verify_bundles

verify_bundles(
    *,
    dest=None,
    include_test_inputs=False,
    mesa_test_dest=None,
    manifest_path=None,
    quiet=False,
    names=None,
)

Verify unpacked data-v1 bundles and per-file SHA-256 manifests.

With names, only those bundles are verified (see :func:select_bundles) and the scan for unexpected files is skipped, since the other bundles' files share the directory. Without it, files of an installed on_demand bundle are expected, not reported.

fetch_bundles

fetch_bundles(
    *,
    dest=None,
    include_test_inputs=False,
    mesa_test_dest=None,
    source_dir=None,
    base_url=None,
    quiet=False,
    names=None,
)

Ensure all required data-v1 bundles are verified and unpacked.

Parameters:

Name Type Description Default
dest str | Path | None

Physics table destination directory (defaults to resolve_data_dir()).

None
include_test_inputs bool

Also fetch MESA 26.4.1 test-input, history, and module-hex verification bundles.

False
mesa_test_dest str | Path | None

Destination directory for mesa_test_inputs.

None
source_dir str | Path | None

Optional local directory containing pre-downloaded archives (.zst, or .xz for verbatim upstream archives) for offline/staging installation.

None
base_url str | None

Optional override for the GitHub Release download base URL.

None
quiet bool

Suppress progress lines when True.

False
names Sequence[str] | None

Explicit bundle names to fetch instead of the default selection. This is the only way to fetch an on_demand bundle (see :func:select_bundles).

None

Returns:

Type Description
Path

Resolved physics data directory pathlib.Path.

build_parser

build_parser(prog='flexmesa data')

Construct the argparse.ArgumentParser for flexmesa data.

main

main(argv=None)

CLI entry point for python -m flexmesa.data.

flexmesa.data.loader

Memory-mapped .safetensors bundle reader and writer for physics tables.

Enforces row-major (C-contiguous) float64 (F64) and int64 (I64) tensor layouts, finite IEEE-754 floating-point checks, and optional SHA-256 digest verification prior to memory-mapping .safetensors files.

LoadedTableBundle dataclass

Loaded .safetensors physics table bundle.

Attributes:

Name Type Description
tensors dict[str, TableTensor]

Dictionary mapping tensor name to its row-major float64 or int64 NumPy array.

metadata dict[str, str]

Dictionary of string key-value metadata recorded in the .safetensors header (__metadata__).

encode_safetensors_bytes

encode_safetensors_bytes(
    tensors, metadata=None, *, require_finite=True
)

Serialize tensors and metadata into deterministic .safetensors.

Orders both "__metadata__" keys and tensor keys lexicographically so the resulting byte buffer and SHA-256 digest are 100% deterministic across runs and byte-for-byte identical to Safe Rust encode_safetensors_bytes.

Parameters:

Name Type Description Default
tensors Mapping[str, TableTensor]

Mapping from tensor name to float64 or int64 NumPy array.

required
metadata Mapping[str, str] | None

Optional string-to-string header metadata dictionary.

None
require_finite bool

If True (default), reject NaN or Inf values in any float64 tensor.

True

Returns:

Type Description
bytes

Raw .safetensors binary byte buffer.

Raises:

Type Description
ValueError

If tensors is empty, a tensor name is invalid, or any float64 tensor contains non-finite values.

TypeError

If any tensor has a dtype other than float64 or int64.

save_safetensors_bundle

save_safetensors_bundle(
    path, tensors, metadata=None, *, require_finite=True
)

Write a .safetensors physics table bundle and return its SHA-256.

Parameters:

Name Type Description Default
path str | Path

Destination .safetensors file path.

required
tensors Mapping[str, TableTensor]

Mapping from tensor name to float64 or int64 NumPy array.

required
metadata Mapping[str, str] | None

Optional string-to-string header metadata dictionary.

None
require_finite bool

If True (default), reject NaN or Inf values in any float64 tensor.

True

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest of the written file.

Raises:

Type Description
ValueError

If tensors is empty or any float64 tensor contains non-finite values when require_finite=True.

TypeError

If any tensor has a dtype other than float64 or int64.

load_safetensors_bundle

load_safetensors_bundle(
    path,
    *,
    expected_sha256=None,
    required_tensors=None,
    require_finite=True,
)

Memory-map and validate a .safetensors physics table bundle from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the .safetensors file on disk.

required
expected_sha256 str | None

Optional 64-character SHA-256 hex digest to verify prior to opening the file.

None
required_tensors Sequence[str] | None

Optional sequence of tensor names that must exist in the loaded bundle.

None
require_finite bool

If True (default), verify that all float64 tensors contain only finite IEEE-754 values.

True

Returns:

Type Description
LoadedTableBundle

LoadedTableBundle containing the memory-mapped float64/int64

LoadedTableBundle

arrays and string metadata dictionary.

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If the SHA-256 checksum mismatches, the bundle is empty, or non-finite values are encountered when require_finite=True.

KeyError

If any tensor listed in required_tensors is missing.

TypeError

If any stored tensor has a dtype other than float64 or int64.

flexmesa.data.converters

ASCII-to-.safetensors converters for MESA nuclear and EOS tables.

Converts MESA's ASCII tables (chem/data/lodders03.data, chem/data/isotopes.data, and eos/helm_table.dat) into row-major float64 and int64 .safetensors bundles obeying the Mandatory Index & Memory-Order Contract (docs/design/wave-0-spec.md §2.2) by delegating text parsing to the canonical Safe Rust flexmesa_data::converters implementation in flexmesa._rust.

parse_lodders03_text

parse_lodders03_text(text)

Parse chem/data/lodders03.data text into a LoadedTableBundle.

Delegates directly to flexmesa_data::converters::parse_lodders03_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Raw ASCII content of lodders03.data (or lodders09.data).

required

Returns:

Type Description
LoadedTableBundle

LoadedTableBundle with 1D arrays 'atomic_number_z' (int64,

LoadedTableBundle

shape (N,), dimensionless proton number \(Z\)), 'mass_number_a'

LoadedTableBundle

(int64, shape (N,), dimensionless nucleon number \(A\)),

LoadedTableBundle

'isotopic_percent' (float64, shape (N,), atom %), and

LoadedTableBundle

'number_abundance_si' (float64, shape (N,), solar number

LoadedTableBundle

abundance normalized to \(N(\text{Si}) = 10^6\)), plus metadata

LoadedTableBundle

'isotopes' (comma-separated lowercase names such as

LoadedTableBundle

'h1,h2,he3').

Raises:

Type Description
ValueError

If no entries are found or any row fails to parse.

parse_isotopes_text

parse_isotopes_text(text)

Parse MESA chem/data/isotopes.data text into a LoadedTableBundle.

Delegates directly to flexmesa_data::converters::parse_isotopes_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Raw ASCII content of isotopes.data (4 non-empty lines per nuclide consisting of a name W Z N spin mass_excess header followed by 24 partition-function values across 3 lines of 8 values).

required

Returns:

Type Description
LoadedTableBundle

LoadedTableBundle containing 'atomic_number_z' (int64,

LoadedTableBundle

(N,)), 'neutron_number_n' (int64, (N,)),

LoadedTableBundle

'isomeric_state' (int64, (N,)), 'atomic_mass_w'

LoadedTableBundle

(float64, (N,), atomic mass units \(\text{u}\)), 'spin'

LoadedTableBundle

(float64, (N,), ground-state spin in \(\hbar\)),

LoadedTableBundle

'mass_excess_mev' (float64, (N,), \(\text{MeV}\)), and

LoadedTableBundle

'partition_function' (float64, (N, 24), dimensionless),

LoadedTableBundle

plus metadata 'nuclide_names'.

Raises:

Type Description
ValueError

If the non-empty line count is zero or not a multiple of 4, or if any record is malformed.

parse_helm_table_text

parse_helm_table_text(
    text,
    *,
    imax=2701,
    jmax=1001,
    logdlo=-12.0,
    logdhi=15.0,
    logtlo=3.0,
    logthi=13.0,
)

Parse MESA eos/helm_table.dat text into a LoadedTableBundle.

Delegates directly to flexmesa_data::converters::parse_helm_table_text via flexmesa._rust. Follows MESA's read_helm_table loop order (j = 0..jmax outer temperature loop, i = 0..imax inner density loop) and stores FlexMESA's canonical row-major (imax, jmax) layout where [i_rho, j_temp] matches Fortran h% f(i_rho + 1, j_temp + 1).

Parameters:

Name Type Description Default
text str

Raw ASCII content of helm_table.dat.

required
imax int

Number of density grid points (>= 2, default 2701).

2701
jmax int

Number of temperature grid points (>= 2, default 1001).

1001
logdlo float

Minimum \(\log_{10}(\rho / Y_e)\) (default -12.0).

-12.0
logdhi float

Maximum \(\log_{10}(\rho / Y_e)\) (default 15.0).

15.0
logtlo float

Minimum \(\log_{10} T\) in \(\text{K}\) (default 3.0).

3.0
logthi float

Maximum \(\log_{10} T\) in \(\text{K}\) (default 13.0).

13.0

Returns:

Type Description
LoadedTableBundle

LoadedTableBundle with 1D grids ('log_d_grid', 'd_grid' of

LoadedTableBundle

shape (imax,) in \(\text{g cm}^{-3}\); 'log_t_grid', 't_grid'

LoadedTableBundle

of shape (jmax,) in \(\text{K}\)), the 21 (imax, jmax) CGS

LoadedTableBundle

tables, and the 4 packed jet tensors ('f_jet' (imax, jmax, 9),

LoadedTableBundle

'dpdf_jet', 'ef_jet', 'xf_jet' (imax, jmax, 4)).

Raises:

Type Description
ValueError

If imax < 2, jmax < 2, grid bounds are inverted, or the line count does not equal 4 * imax * jmax.

convert_lodders03_file

convert_lodders03_file(input_path, output_path)

Convert lodders03.data on disk to .safetensors (SHA-256).

Parameters:

Name Type Description Default
input_path str | Path

Path to the source lodders03.data ASCII file.

required
output_path str | Path

Destination .safetensors path.

required

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest of output file.

convert_isotopes_file

convert_isotopes_file(input_path, output_path)

Convert isotopes.data on disk to .safetensors and return SHA-256.

Parameters:

Name Type Description Default
input_path str | Path

Path to the source isotopes.data ASCII file.

required
output_path str | Path

Destination .safetensors path.

required

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest of output file.

convert_helm_table_file

convert_helm_table_file(
    input_path,
    output_path,
    *,
    imax=2701,
    jmax=1001,
    logdlo=-12.0,
    logdhi=15.0,
    logtlo=3.0,
    logthi=13.0,
)

Convert helm_table.dat on disk to .safetensors (SHA-256).

Parameters:

Name Type Description Default
input_path str | Path

Path to the source helm_table.dat ASCII file.

required
output_path str | Path

Destination .safetensors path.

required
imax int

Number of density grid points (default 2701).

2701
jmax int

Number of temperature grid points (default 1001).

1001
logdlo float

Minimum \(\log_{10}(\rho / Y_e)\) (default -12.0).

-12.0
logdhi float

Maximum \(\log_{10}(\rho / Y_e)\) (default 15.0).

15.0
logtlo float

Minimum \(\log_{10} T\) in \(\text{K}\) (default 3.0).

3.0
logthi float

Maximum \(\log_{10} T\) in \(\text{K}\) (default 13.0).

13.0

Returns:

Type Description
str

Lowercase 64-character hexadecimal SHA-256 digest of output file.


Upstream test_output Reference & Trajectory Harness (flexmesa.testing)

flexmesa.testing parses upstream MESA <pkg>/test/test_output reference files (including Fortran 1pe24.16 and missing-E three-digit exponents like 1.2345-102), validates the 106-case MESA 26.4.1 trajectory manifest and declared known-gaps registry (case_manifest.toml, known_gaps.toml), compares LOGS/history.data and binary_history.data tracks on a shared float64 coordinate grid, and drives flexmesa trace and flexmesa harness (supporting --numerics-mode {strict,fast}, with --gate restricted to strict, and defaulting to strict rejection of unsupported controls unless --allow-unsupported-controls is explicitly given).

flexmesa.testing.golden

Parser and numerical parity comparator for MESA golden test_output files.

MESA's standalone module unit-test suites (<pkg>/test/test_output*) emit 16-digit formatted floating-point reference values (1pe24.16) organized into section headers, key-value scalar lines, indexed multi-column records, and dense numeric tables. This module routes golden text and Fortran float parsing through the canonical Safe Rust flexmesa_testing implementation in flexmesa._rust and verifies elementwise relative and absolute numerical parity (<= 1e-12 relative error by default).

GoldenRecord dataclass

Single numeric record parsed from a MESA test_output file.

Attributes:

Name Type Description
line_number int

1-based line number in the source golden file.

section str

Active section header preceding this record (empty string if none).

label str

Text label preceding the integer indices and floating-point values on the line (empty string for unlabeled table rows).

indices tuple[int, ...]

Tuple of integer indices preceding the floating-point values on the line (for example, (1, 2) in test2D_db 1 2 ...).

values NDArray[float64]

1D float64 NumPy array of shape (n_values,) containing the parsed IEEE-754 double-precision reference values (dimensionless or in the physical CGS/solar units of the corresponding MESA test).

GoldenComparisonSummary dataclass

Summary metrics from comparing two sequences of golden records.

Attributes:

Name Type Description
num_records int

Total number of GoldenRecord entries compared.

num_values int

Total number of scalar float64 values compared across all records.

max_abs_error float

Maximum elementwise absolute error |actual - expected| across all compared values.

max_rel_error float

Maximum elementwise relative error |actual - expected| / max(|expected|, atol) across all values.

is_fortran_float_token

is_fortran_float_token(token)

Return whether token is a Fortran floating-point literal.

Delegates to flexmesa_testing::is_fortran_float_token via flexmesa._rust.

Parameters:

Name Type Description Default
token str

Whitespace-delimited string token from a MESA output line.

required

Returns:

Type Description
bool

True if token contains a decimal point or exponent in standard

bool

or Fortran (D/d or bare 3-digit signed exponent) notation.

Examples:

>>> from flexmesa.testing import golden
>>> golden.is_fortran_float_token("8.2630874248383526D-04")
True
>>> golden.is_fortran_float_token("42")
False

parse_fortran_float

parse_fortran_float(token)

Parse a Fortran or IEEE-754 floating-point string into a float64.

Delegates to flexmesa_testing::parse_fortran_float via flexmesa._rust.

Parameters:

Name Type Description Default
token str

String representation of a floating-point number.

required

Returns:

Type Description
float

Parsed Python float (IEEE-754 binary64).

Raises:

Type Description
ValueError

If token cannot be parsed as a finite floating-point number.

Examples:

>>> from flexmesa.testing import golden
>>> golden.parse_fortran_float("2.3025850929940455D+00")
2.3025850929940455
>>> golden.parse_fortran_float("-1.5000000000000000-100")
-1.5e-100

parse_golden_text

parse_golden_text(text)

Parse the text of a MESA <pkg>/test/test_output file into records.

Delegates to flexmesa_testing::parse_golden_text via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Full UTF-8 contents of a MESA test_output file.

required

Returns:

Type Description
list[GoldenRecord]

Ordered list of GoldenRecord entries extracted from text.

Raises:

Type Description
ValueError

If a trailing numeric token is non-finite (NaN, Inf, or exponent overflow).

Examples:

>>> from flexmesa.testing import golden
>>> sample = " test1 T\n  f(2, 1)  8.2630874248383526D-04\n"
>>> records = golden.parse_golden_text(sample)
>>> len(records)
1
>>> records[0].section, records[0].label
('test1 T', 'f(2, 1)')

parse_golden_file

parse_golden_file(path)

Read and parse a MESA <pkg>/test/test_output file from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the golden test_output file.

required

Returns:

Type Description
list[GoldenRecord]

Ordered list of GoldenRecord entries extracted from path.

extract_golden_table

extract_golden_table(records)

Stack uniform-width GoldenRecord entries into a 2D float64 array.

Parameters:

Name Type Description Default
records Sequence[GoldenRecord]

Non-empty sequence of GoldenRecord objects whose values vectors all have the same length n_cols.

required

Returns:

Type Description
NDArray[float64]

2D C-contiguous float64 array of shape (n_records, n_cols).

Raises:

Type Description
ValueError

If records is empty or records have differing column counts.

assert_values_match

assert_values_match(
    actual, expected, *, rtol=1e-12, atol=1e-15, context=""
)

Assert elementwise parity between two float64 arrays or scalars.

For each element pair (a, e), checks |a - e| <= atol + rtol * |e| and reports the maximum absolute and relative errors.

Parameters:

Name Type Description Default
actual ArrayLike

Computed array or scalar of shape (*shape,).

required
expected ArrayLike

Reference golden array or scalar of shape (*shape,).

required
rtol float

Maximum permitted relative error (default 1e-12).

1e-12
atol float

Absolute error floor for near-zero values (default 1e-15).

1e-15
context str

Optional diagnostic label included in failure messages.

''

Returns:

Type Description
tuple[float, float]

Tuple (max_abs_error, max_rel_error) in float64.

Raises:

Type Description
ValueError

If rtol < 0, atol <= 0, non-finite tolerances, or shape mismatch.

AssertionError

If any element contains NaN/Inf or exceeds the tolerance bound.

assert_golden_records_match

assert_golden_records_match(
    actual, expected, *, rtol=1e-12, atol=1e-15
)

Compare two sequences of GoldenRecord objects for numerical parity.

Parameters:

Name Type Description Default
actual Sequence[GoldenRecord]

Computed sequence of GoldenRecord entries.

required
expected Sequence[GoldenRecord]

Reference sequence of GoldenRecord entries.

required
rtol float

Maximum permitted relative error (default 1e-12).

1e-12
atol float

Absolute error floor for near-zero values (default 1e-15).

1e-15

Returns:

Type Description
GoldenComparisonSummary

GoldenComparisonSummary reporting record/value counts and peak

GoldenComparisonSummary

errors.

Raises:

Type Description
AssertionError

If record counts, labels, indices, value vector lengths, or numeric tolerances fail to match.

flexmesa.testing.case_manifest

TOML case manifest and declared known-gaps loader for history comparisons.

Defines the schema for benchmarks/history_harness/case_manifest.toml and benchmarks/history_harness/known_gaps.toml, covering the 106 upstream test cases of MESA release 26.4.1 (90 star, 8 binary, 8 astero).

DepartureSpec dataclass

Documented intentional or pending departure attached to a case.

Attributes:

Name Type Description
issue str

Linked GitHub issue reference formatted as #<number>.

rationale str

Brief explanation of the departure and upstream mechanism.

KnownGapSpec dataclass

Declared known gap for a failing or incomplete upstream case.

Attributes:

Name Type Description
suite SuiteName

Upstream test suite ("star", "binary", or "astero").

case str

Upstream test-case directory name.

issue str

Linked open GitHub issue formatted as #<number>.

reason str

Concise statement of missing physics or divergence mechanism.

CaseManifestEntry dataclass

Manifest specification for a single upstream MESA 26.4.1 case.

Attributes:

Name Type Description
suite SuiteName

Upstream test suite ("star", "binary", or "astero").

case str

Upstream test-case directory name.

reference_status ReferenceStatus

Availability and provenance of stored reference data ("no_reference_yet", "interim_0b2e6bb", or "mesa_26_4_1", or "mesa_26_4_1_artifact" for a case that takes zero steps and is judged by its artifact table, #606).

reference_path str

Repository-relative path to the stored reference file (empty string when reference_status == "no_reference_yet").

required_termination str

Expected upstream termination code string (may contain |-separated accepted alternatives when upstream sets required_termination_code_string(1..N)).

independent_var str

Monotonic coordinate column name for track comparison (for example "star_age" in yr, "age" in yr, or "model_number").

final_tolerances dict[str, float]

Mapping from column name (or "rel_<xcol>") to maximum allowed absolute (or relative) difference at termination.

track_tolerances dict[str, float]

Mapping from column name to maximum allowed absolute deviation across the interpolated common track overlap.

pr_ci bool

Whether the case belongs to the fast per-pull-request CI subset.

uses_pulsation_scaffolding bool

True when the case currently relies on the in-house pulsation solver rather than ported GYRE or ADIPLS; such cases cannot count as passing under notes/SCOPE.md.

scaffolding_issue str

Linked #<number> issue when uses_pulsation_scaffolding is True.

uses_library_extras bool

True if a case dispatches per-case test hooks inside library crates rather than test-side extras_factory callbacks (deprecated gate retained for manifest schema stability; False for all cases after #148).

library_extras_issue str

Optional #<number> issue when uses_library_extras is True.

extras_status str

Status of the case's upstream extras logic from extras_status.toml ("ported", "stock", "unported", or "" when no ledger sits next to the manifest). An "unported" case runs without its upstream extras logic and never counts as passing.

extras_issue str

#<number> issue owning the port when extras_status is "unported".

extras_factory str

Optional "module:callable" path returning test-side extras handlers for the case.

departures tuple[DepartureSpec, ...]

Tuple of documented DepartureSpec items.

track_reference_dir str

Directory of the mesa-astero-tracks-v1 data bundle holding one MESA 26.4.1 history per search track (track_0001.data, track_0002.data, ...) for astero search cases, whose LOGS/history.data keeps only the last track (#430). Empty when the case is compared against reference_path alone.

artifact ArtifactSpec | None

Optional [cases.artifact] declaration for a case with no history (#606). It is judged in place of the history comparison when reference_status is "mesa_26_4_1_artifact"; with "no_reference_yet" the comparison is reported but the verdict does not use it.

regenerated_inputs tuple[RegeneratedInput, ...]

Upstream case files replaced by models regenerated with MESA 26.4.1 ([[cases.regenerated_inputs]], DECISIONS #93); empty for the shipped inputs.

data_bundles tuple[str, ...]

Names of the on-demand data bundles (src/flexmesa/data/bundles.toml) the case reads, such as the OP monochromatic opacity data that upstream locates through an environment variable; empty for a case that needs only the default bundles.

max_rss_gb float | None

Resident-memory ceiling (GB) the case needs when it is above a run's --max-rss-gb. Under --case-rss-ceilings such a case runs with that ceiling and with no other case at the same time; otherwise, and when None, it keeps the run's.

key property

key

Return the (suite, case) lookup key.

component_spec

component_spec(component_name, reference_path='')

Build the stellar tolerance spec for a binary LOGS{1,2} track.

HarnessManifest dataclass

Validated collection of upstream MESA 26.4.1 case specifications.

Attributes:

Name Type Description
mesa_release str

Pinned upstream MESA release tag ("26.4.1").

zenodo_record str

Zenodo archive identifier for the pinned release.

cases tuple[CaseManifestEntry, ...]

Tuple of CaseManifestEntry records in canonical order.

extras_factory str

Optional default "module:callable" spec resolving test-side extras handlers.

by_key

by_key()

Return a dictionary mapping (suite, case) to its entry.

Returns:

Type Description
dict[tuple[str, str], CaseManifestEntry]

Dictionary keyed by (suite, case).

repo_root

repo_root()

Return the repository root directory relative to this module.

Returns:

Type Description
Path

Resolved repository root pathlib.Path when running from a source

Path

checkout, or the current working directory otherwise.

default_manifest_path

default_manifest_path()

Return the default case_manifest.toml path.

Returns:

Type Description
Path

Path to benchmarks/history_harness/case_manifest.toml.

default_known_gaps_path

default_known_gaps_path()

Return the default known_gaps.toml path.

Returns:

Type Description
Path

Path to benchmarks/history_harness/known_gaps.toml.

load_case_manifest

load_case_manifest(path=None)

Load and validate case_manifest.toml.

Parameters:

Name Type Description Default
path Path | str | None

Optional path to case_manifest.toml. Defaults to default_manifest_path().

None

Returns:

Type Description
HarnessManifest

Validated HarnessManifest instance.

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If any suite, status, tolerance, issue link, data bundle name, memory ceiling, or duplicate case entry is invalid.

load_known_gaps

load_known_gaps(path=None)

Load and validate known_gaps.toml.

Parameters:

Name Type Description Default
path Path | str | None

Optional path to known_gaps.toml. Defaults to default_known_gaps_path().

None

Returns:

Type Description
dict[tuple[str, str], KnownGapSpec]

Dictionary mapping (suite, case) to its KnownGapSpec.

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If any gap lacks a valid #<number> issue link or reason.

termination_matches

termination_matches(required, observed)

Check whether observed termination satisfies required.

Supports |-delimited multi-code specifications (corresponding to MESA required_termination_code_string(1..N)), species-parameterized codes such as xa_central_lower_limit(he4), and astero summary suffixes ending in _term=<code> while keeping extras_finish_step and extras_check_model distinct.

Parameters:

Name Type Description Default
required str

Expected upstream termination code(s) from the manifest.

required
observed str

Observed termination code returned by the tracer.

required

Returns:

Type Description
bool

True if observed matches at least one alternative in required

bool

and is not "max_steps_cap".

Cases whose upstream starting model MESA 26.4.1 itself cannot complete from (DECISIONS #93) declare a replacement in [[cases.regenerated_inputs]]; the harness stages a copy of the case directory with that model in place and refuses a missing file or a SHA-256 mismatch:

flexmesa.testing.regenerated_inputs

Upstream test inputs replaced by models regenerated with MESA 26.4.1.

A few upstream test cases ship a saved model (standard_*.mod) that was written by an older MESA. With MESA_SKIP_OPTIONAL set, ./rn copies it over the stage input and runs only the final stage from it. When MESA 26.4.1 itself cannot complete that stage from the shipped model, the case's reference is the final stage of a full-chain MESA 26.4.1 run, and the test starts that stage from the model the chain wrote instead (DECISIONS #93). The case manifest declares each replacement in a [[cases.regenerated_inputs]] table: the case file it replaces, the committed regenerated model, its SHA-256, and the issue recording why.

:func:stage_case_dir builds a copy of the upstream case directory with the declared files replaced, under a directory named mesa_test_inputs so the Rust tracer treats it as read-only input and stages its own writable copy (crates/flexmesa-star/src/case_staging.rs). The copy is keyed by the contents of every input, so concurrent runs share it safely and a changed input builds a new one. A missing file, a SHA-256 mismatch, or a target the case does not ship is an error, never a silent fallback (#147).

RegeneratedInput dataclass

One upstream case file replaced by a regenerated MESA model.

Attributes:

Name Type Description
file str

Name of the file in the upstream case directory that is replaced (for example "standard_after_si_burn.mod").

path str

Repository-relative path of the committed regenerated model.

sha256 str

Lower-case hexadecimal SHA-256 of the regenerated model.

issue str

#<number> issue recording why the shipped file is not used.

parse_regenerated_inputs

parse_regenerated_inputs(raw, ctx)

Validate the [[cases.regenerated_inputs]] tables of one case.

Parameters:

Name Type Description Default
raw Any

Parsed TOML value (a list of tables), or None.

required
ctx str

suite/case label for error messages.

required

Returns:

Type Description
tuple[RegeneratedInput, ...]

The validated replacements in manifest order (empty for None).

Raises:

Type Description
ValueError

On a missing key, a file name with a directory part, a malformed SHA-256 or issue, or a file replaced twice.

stage_case_dir

stage_case_dir(
    suite,
    case_dir,
    replacements,
    repo_root,
    cache_root=None,
)

Return a case directory with the declared files replaced.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case_dir Path

Upstream case directory from the test-inputs bundle.

required
replacements tuple[RegeneratedInput, ...]

Validated replacements of the case (may be empty).

required
repo_root Path

Repository root that RegeneratedInput.path is relative to.

required
cache_root Path | None

Directory holding the staged copies (default: <system temp>/flexmesa-regenerated-inputs).

None

Returns:

Type Description
Path

case_dir itself when there is nothing to replace, otherwise

Path

<cache_root>/<digest>/mesa_test_inputs/<suite>/test_suite/<case>

Path

holding the upstream files with the replacements in place.

Raises:

Type Description
FileNotFoundError

If a regenerated model is missing, or the case does not ship the file it replaces.

ValueError

If a regenerated model's SHA-256 differs from the manifest.

flexmesa.testing.history_compare

Upstream MESA trajectory loader and float64 history track comparator.

Loads raw 6-line MESA LOGS/history.data or binary_history.data files as well as thinned tab-separated reference histories, scrubs restart backups, interpolates onto a shared monotonic grid uniting uniform samples and interior track nodes, evaluates final-state and along-track tolerances with strict finiteness and sentinel checks, and identifies the first step at which a trajectory exceeds tolerance.

HistoryRunStats dataclass

Step, retry, and Newton iteration statistics extracted from a history.

Attributes:

Name Type Description
steps int | None

Evolutionary steps spanned by the final stage, or None if model_number is absent.

retries int | None

Cumulative num_retries at the final logged step, or None if num_retries is absent.

iters_sum int | None

Sum of per-step num_iters across all logged rows, or None if num_iters is absent. Equals cumulative Newton iterations across the stage when iters_rows == steps.

mean_iters float | None

Mean per-step num_iters across logged rows, or None if num_iters is absent.

iters_rows int

Number of logged rows averaged in mean_iters and summed in iters_sum (0 when num_iters is absent).

HistoryTable dataclass

Columnar float64 representation of a stellar or binary history file.

Attributes:

Name Type Description
columns dict[str, ndarray]

Mapping from canonical column name to a 1D float64 array of shape (n_models,) in MESA output units (ages in yr, masses in M_sun, logarithmic quantities in dex).

num_rows int

Number of stored evolutionary rows n_models.

provenance_comment str

Leading # ... provenance note when loaded from a thinned TSV file, or empty string for raw 6-line MESA logs.

mesa_version_number str

version_number token from a 6-line MESA header (such as "r26.4.1"), or empty string for TSV files.

TrackDeviation dataclass

Summary of differences along the common independent-variable interval.

Attributes:

Name Type Description
column str

History column name.

max_abs_diff float

Maximum absolute difference max |run - ref| on the interior common grid.

median_abs_diff float

Median absolute difference on the interior common grid.

x_at_max float

Value of the independent coordinate where max_abs_diff occurs (in yr for star_age/age or dimensionless step).

tolerance float | None

Configured track tolerance if constrained, else None.

within_tolerance bool

True when tolerance is None or all compared samples are finite, non-sentinel, and within the configured absolute (<col>) or relative (rel_<col>) tolerance.

max_rel_diff float | None

Maximum relative difference max |run - ref| / |ref| on the interior common grid when |ref| > 0 everywhere on the grid, else None.

HistoryComparison dataclass

Quantitative comparison between a reference history and a run history.

Attributes:

Name Type Description
independent_var str

Coordinate column name used for alignment.

ref_rows int

Number of rows in the reference table.

run_rows int

Number of rows in the candidate run table.

overlap_min float

Lower bound of the shared coordinate range.

overlap_max float

Upper bound of the shared coordinate range.

final_diffs dict[str, float]

Mapping from column name (plus rel_<xcol>) to run[-1] - ref[-1] (or signed relative error).

within_final_tolerances bool

True when every configured final tolerance holds on finite non-sentinel values.

failed_final_columns tuple[str, ...]

Tuple of column names exceeding final tolerance.

track_deviations tuple[TrackDeviation, ...]

Tuple of TrackDeviation records across shared continuous columns.

within_track_tolerances bool

True when every configured track tolerance holds across adequate coordinate-span coverage.

failed_track_columns tuple[str, ...]

Tuple of column names exceeding track tolerance.

first_diverging_step int | None

Earliest model_number (or 1-based row index) in run at which any tracked column exceeds its track tolerance, or None if no column diverges.

first_diverging_x float | None

Coordinate value at first_diverging_step, or None.

ref_span float

Independent-variable span of the reference history.

final_run_values dict[str, float]

Selected final candidate run values (such as log_rel_run_E_err) captured for mechanical reporting.

final_ref_values dict[str, float]

Selected final reference values (such as log_rel_run_E_err) captured alongside final_run_values.

extract_history_run_stats

extract_history_run_stats(tbl, suite)

Extract final-stage step, retry, and iteration counts from tbl.

Parameters:

Name Type Description Default
tbl HistoryTable

Loaded HistoryTable for a single evolutionary stage.

required
suite str

Upstream suite name ("star", "binary", or "astero").

required

Returns:

Type Description
HistoryRunStats

HistoryRunStats populated from model_number, num_retries,

HistoryRunStats

and num_iters where present.

load_history_file

load_history_file(path)

Load a MESA 6-line history.data file or a thinned TSV history file.

Filters multi-stage TSV logs to the final stage and scrubs superseded model_number backup rows (where an earlier row has model_number >= a subsequent restarted row).

Parameters:

Name Type Description Default
path Path | str

Path to a raw MESA 6-line ASCII log or #-prefixed TSV file.

required

Returns:

Type Description
HistoryTable

HistoryTable containing 1D float64 arrays of shape

HistoryTable

(n_models,).

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If the file contains no header or zero data rows.

join_history_tables

join_history_tables(tables)

Join the history tables one MESA run wrote to several files, in order.

Same rule as scripts/data/build_mesa_histories.py (DECISIONS #78). RSP runs with RSP_write_map switch star_history_name to the map history when the map period starts (MESA star/private/rsp.f90:534-535). The files are concatenated in the given order, the columns must be identical, and the model numbers must increase across each boundary.

Parameters:

Name Type Description Default
tables list[HistoryTable]

Non-empty tables in file order, columns of shape (n_models,).

required

Returns:

Type Description
HistoryTable

One table; tables[0] itself when there is only one.

Raises:

Type Description
ValueError

If the columns differ or a later file's first model does not follow the last model of the rows before it.

load_run_history

load_run_history(path)

Load a run's history.data, joined with a sibling map history.

RSP runs with RSP_write_map write later models to map_history.data beside history.data; the MESA reference joins both, so the run side must too. Other history files load unchanged.

Parameters:

Name Type Description Default
path Path | str

Path to the run's history file.

required

Returns:

Type Description
HistoryTable

The joined table, see join_history_tables.

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If a file is malformed or the two files do not join.

compare_histories

compare_histories(ref, run, spec, num_grid=400)

Compare a FlexMESA history table against an upstream MESA reference.

Parameters:

Name Type Description Default
ref HistoryTable

Reference HistoryTable with arrays of shape (n_ref,).

required
run HistoryTable

Candidate HistoryTable with arrays of shape (n_run,).

required
spec CaseManifestEntry

CaseManifestEntry providing independent_var and tolerance dictionaries.

required
num_grid int

Number of uniform interior grid samples combined with interior sample coordinates (default 400). Unused when the reference skips models (history_interval > 1): every along-track column is then compared only at the reference rows, with the run interpolated there (#459), as num_zones always is.

400

Returns:

Type Description
HistoryComparison

Populated HistoryComparison with final differences, track

HistoryComparison

deviations, tolerance outcomes, and first_diverging_step.

Raises:

Type Description
KeyError

If spec.independent_var is absent from ref or run.

ValueError

If coordinate arrays contain NaN, Inf, -1e99 sentinels, or non-monotonic reversals.

re_evaluate_comparison

re_evaluate_comparison(comp, spec)

Re-evaluate comp against spec's current tolerances.

comparison_to_dict

comparison_to_dict(comp)

Serialize a HistoryComparison into a strict JSON-safe dictionary.

comparison_from_dict

comparison_from_dict(raw)

Deserialize a HistoryComparison from comparison_to_dict.

The full-history bit-identity comparator compares parsed IEEE-754 float64 values across every row, column, and part (exact_row_match=True by default, requiring identical row counts and model_number ordering with zero extra run files or asymmetric stage_logs), and checks every non-ignored MESA header scalar bit-for-bit (excluding only build/run provenance keys date, compiler, build, MESA_SDK_version, and math_backend unless --strict-headers is passed). Raw header text and column order are reported separately via byte_identical, and partial/subset modes (--prefix-only, --no-exact-row-match, --no-astero-tracks) exit with distinct code 3:

flexmesa.testing.full_history_compare

Full-history bit-identity comparator against MESA 26.4.1 runs/.

Compares parsed IEEE-754 float64 data values across every row, column, and part of a FlexMESA run's MESA-format history logs (LOGS*/history.data, map_history.data, binary_history.data, LOGS1//LOGS2/, and astero search tracks) against stored reference outputs without column aliasing or duplicate-row dropping. By default exact_row_match=True enforces identical row counts and model_number ordering (with zero extra run history files or asymmetric stage_logs), while raw ASCII header text and column ordering are tracked separately via byte_identical.

FullHistoryTable dataclass

Lossless positional representation of a 6-line MESA history file.

Preserves raw column names (disambiguating repeated column names with #2, #3, ...) and all rows without scrubbing equal model_number rows from multi-star runs such as twin_studies.

Attributes:

Name Type Description
header dict[str, str | int | float]

Scalar header metadata from lines 2 and 3 of the MESA file.

column_names tuple[str, ...]

Positional canonical column labels of length n_cols.

column_values tuple[ndarray, ...]

Tuple of 1D float64 arrays of shape (n_models,) in MESA output units (ages in yr, masses in M_sun, logarithmic quantities in dex), aligned 1-to-1 with column_names.

num_rows int

Number of data rows n_models.

mesa_version_number str

version_number token from the header.

column_index

column_index()

Return a mapping from canonical column label to positional index.

FirstDiff dataclass

Earliest difference found between a reference history and a run history.

Attributes:

Name Type Description
part str

History part label (for example "LOGS/history.data" or "binary_history.data").

kind str

Category of mismatch ("value", "header_mismatch", "missing_run_row", "extra_run_rows", "row_count_mismatch", "row_order_mismatch", "missing_column", "extra_column", "missing_run_file", "missing_ref_file", "missing_run_dir", "extra_run_file", "asymmetric_stage_logs", "empty_history", "non_finite", "no_overlap", or "parse_error").

model_number int | None

Evolutionary model_number at the divergence, or None for file-level or column-header mismatches.

row_index int

0-based reference row index, or -1 if not tied to a reference row.

run_row_index int | None

0-based run row index, or None if absent.

column str

Differing column or header label, or empty string for row/file diffs.

ref_value float | int | str | None

Reference scalar value (or descriptor string), else None.

run_value float | int | str | None

Candidate run scalar value (or descriptor), else None.

abs_diff float | None

Absolute difference |run_value - ref_value|, else None.

rel_diff float | None

Relative difference abs_diff / |ref_value| when ref_value != 0, 0.0 when both are zero, else None.

ulp_diff int | None

IEEE-754 binary64 ULP distance when both values are finite, else None.

HeaderDiff dataclass

Mismatch on a single non-ignored MESA history header scalar.

Attributes:

Name Type Description
part str

History part label.

key str

Header scalar name (for example "msun" or "version_number").

kind HeaderDiffKind

Mismatch category ("value", "missing_in_run", "missing_in_ref", "type_mismatch", or "non_finite").

ref_value float | int | str | None

Reference header value, or None when absent.

run_value float | int | str | None

Candidate run header value, or None when absent.

abs_diff float | None

Absolute difference for numeric values, else None.

rel_diff float | None

Relative difference for numeric values, else None.

ulp_diff int | None

IEEE-754 binary64 ULP distance for finite floats, else None.

PartComparison dataclass

Bit-identity comparison summary for one history part.

Attributes:

Name Type Description
part str

Relative part label (for example "LOGS/history.data").

ref_path str | None

Reference file path string, or None for in-memory tables.

run_path str | None

Candidate run file path string, or None when absent.

reference_kind ReferenceKind

"full" for full-column references or "thinned_track" for thinned astero search track files.

status PartStatusType

"bit_identical", "prefix_identical", "subset_identical", "diverged", "error", or "no_history".

bit_identical bool

True iff all reference columns, rows, and values match bit-for-bit across all parsed IEEE-754 float64 cells under prefix_only=False and exact_row_match=True (header text and column ordering are tracked separately by byte_identical).

byte_identical bool

True iff the underlying reference and run ASCII files are byte-for-byte identical (including headers and column order).

ref_rows int

Total data rows in the reference table.

run_rows int

Total data rows in the candidate run table.

compared_rows int

Number of reference rows aligned against the run.

identical_rows int

Number of aligned reference rows where every reference column is present and bit-identical.

ref_columns tuple[str, ...]

Ordered canonical column labels in the reference table.

run_columns tuple[str, ...]

Ordered canonical column labels in the run table.

columns_only_in_ref tuple[str, ...]

Columns present in reference only.

columns_only_in_run tuple[str, ...]

Columns present in run only.

shared_cols int

Count of aligned columns present on both sides.

identical_cols int

Count of shared columns identical on all compared rows.

first_diff FirstDiff | None

Earliest discrepancy in this part, or None.

max_abs_diff_per_col dict[str, float]

Maximum absolute difference per shared column.

max_rel_diff_per_col dict[str, float | None]

Maximum relative difference per shared column, or None when a non-identical cell occurs at ref_value == 0.

max_ulp_diff_per_col dict[str, int | None]

Maximum IEEE-754 ULP distance per shared column, or None when a differing value is non-finite.

differing_columns tuple[str, ...]

Ordered shared columns with at least one difference.

error str

Diagnostic error message when status == "error".

header_diffs tuple[HeaderDiff, ...]

Non-ignored MESA header scalar discrepancies.

ignored_header_keys tuple[str, ...]

Sorted tuple of excluded header metadata keys (default excludes date, compiler, build, MESA_SDK_version, math_backend).

total_ref_cols property

total_ref_cols

Total column count in the reference table.

total_run_cols property

total_run_cols

Total column count in the candidate run table.

FullHistoryComparison dataclass

Case-level full-history bit-identity result across all parts.

Attributes:

Name Type Description
suite str

Suite name ("star", "binary", or "astero").

case str

Case directory name.

status StatusType

"bit_identical", "prefix_identical", "subset_identical", "diverged", "error", or "no_history".

bit_identical bool

True iff parts is non-empty, prefix_only=False, exact_row_match=True, zero extra_run_files, zero asymmetric stage_logs, and every part has bit_identical == True. Header text and column order are tracked separately via byte_identical.

byte_identical bool

True iff parts is non-empty and every part file is byte-for-byte identical on disk (header, order, and rows).

judged_part str | None

Primary/final part label, or None if no history parts.

identical_rows int

Sum of identical_rows across parts.

total_ref_rows int

Sum of ref_rows across parts.

total_run_rows int

Sum of run_rows across parts.

compared_rows int

Sum of compared_rows across parts.

identical_cols int

Sum of identical_cols across parts.

total_ref_cols int

Sum of total_ref_cols across parts.

total_run_cols int

Sum of total_run_cols across parts.

columns_only_in_ref tuple[str, ...]

Columns present in reference only (bare column names when len(parts) == 1, else "<part>:<col>").

columns_only_in_run tuple[str, ...]

Columns present in run only (same naming rule).

first_diff FirstDiff | None

Earliest discrepancy across parts, or None.

max_abs_diff_per_col dict[str, float]

Max absolute difference per column (same naming).

max_rel_diff_per_col dict[str, float | None]

Max relative difference per column (same naming).

max_ulp_diff_per_col dict[str, int | None]

Max ULP difference per column (same naming).

differing_columns tuple[str, ...]

Differing shared column keys across parts.

parts tuple[PartComparison, ...]

Ordered tuple of PartComparison results.

error str

Diagnostic error summary if any part errored.

prefix_only bool

Whether prefix/windowed comparison mode was enabled.

exact_row_match bool

Whether strict 1-to-1 row count and ordering held.

extra_run_files tuple[str, ...]

Relative run-side history files absent from reference.

header_diffs tuple[HeaderDiff, ...]

Aggregated non-ignored header scalar discrepancies.

ignored_header_keys tuple[str, ...]

Sorted tuple of excluded build/run metadata keys.

include_astero_tracks bool

Whether per-track astero search files were included in the comparison.

load_full_history_file

load_full_history_file(path)

Load one 6-line MESA ASCII or synthetic TSV history file losslessly.

Uses _rust.mesa_read_log_file for standard 6-line MESA logs and falls back to lossless TSV parsing for synthetic #-prefixed or .tsv fixtures, without column aliasing or multi-star row scrubbing.

Parameters:

Name Type Description Default
path Path | str

Path to a MESA history.data, map_history.data, binary_history.data, search track file, or synthetic .tsv.

required

Returns:

Type Description
FullHistoryTable

FullHistoryTable with 1D float64 arrays of shape

FullHistoryTable

(n_models,) in MESA output units.

Raises:

Type Description
FileNotFoundError

If path does not exist.

ValueError

If the file is malformed or lacks column headers.

join_full_history_tables

join_full_history_tables(tables)

Concatenate ordered FullHistoryTable chunks from one run.

Parameters:

Name Type Description Default
tables Sequence[FullHistoryTable]

Non-empty sequence of FullHistoryTable objects with identical positional column labels and shape (n_models,) columns.

required

Returns:

Type Description
FullHistoryTable

Single combined FullHistoryTable preserving all columns and rows.

Raises:

Type Description
ValueError

If tables is empty, columns differ across files, or a continuation file's first model_number does not follow the previous file's final model_number.

load_full_run_history

load_full_run_history(path, *, join_map_history=True)

Load a run history file, joining sibling map_history.data if present.

Parameters:

Name Type Description Default
path Path | str

Path to history.data or binary_history.data.

required
join_map_history bool

When True and path is named history.data, appends sibling map_history.data if present on disk.

True

Returns:

Type Description
FullHistoryTable

Combined FullHistoryTable with shape (n_models,) arrays.

compare_history_tables

compare_history_tables(
    ref,
    run,
    *,
    part="history.data",
    ref_path=None,
    run_path=None,
    reference_kind="full",
    byte_identical=False,
    prefix_only=False,
    exact_row_match=True,
    ignored_header_keys=DEFAULT_IGNORED_HEADER_KEYS,
)

Compare two loaded FullHistoryTable objects bit-for-bit.

Parameters:

Name Type Description Default
ref FullHistoryTable

Reference FullHistoryTable with shape (n_ref,) columns.

required
run FullHistoryTable

Candidate run FullHistoryTable with shape (n_run,) cols.

required
part str

Relative part name for reporting.

'history.data'
ref_path str | None

Optional reference path string stored on the result.

None
run_path str | None

Optional run path string stored on the result.

None
reference_kind ReferenceKind

"full" or "thinned_track".

'full'
byte_identical bool

Precomputed raw-file byte-equality flag (covering headers and column ordering in addition to data cells).

False
prefix_only bool

When True, compare only reference rows whose model_number lies inside the run's covered range (for partial or windowed trace --compare runs; emits "prefix_identical" with bit_identical=False when matching).

False
exact_row_match bool

When True (default), require 1-to-1 row counts and model_number ordering without extra or reordered run rows. When False, emits "subset_identical" with bit_identical=False.

True
ignored_header_keys Collection[str]

Header metadata keys excluded from scalar comparison. Defaults to DEFAULT_IGNORED_HEADER_KEYS (date, compiler, build, MESA_SDK_version, math_backend).

DEFAULT_IGNORED_HEADER_KEYS

Returns:

Type Description
PartComparison

Populated PartComparison dataclass.

compare_history_files

compare_history_files(
    ref_path,
    run_path,
    *,
    part="history.data",
    join_map_history=True,
    reference_kind="full",
    prefix_only=False,
    exact_row_match=True,
    ignored_header_keys=DEFAULT_IGNORED_HEADER_KEYS,
)

Load and compare a reference history file against a run history file.

Parameters:

Name Type Description Default
ref_path Path | str

Reference MESA history file path.

required
run_path Path | str

Candidate FlexMESA history file path.

required
part str

Relative part label reported in outputs.

'history.data'
join_map_history bool

Join sibling map_history.data when present.

True
reference_kind ReferenceKind

"full" or "thinned_track".

'full'
prefix_only bool

Compare only the model range covered by the run.

False
exact_row_match bool

Require 1-to-1 row counts and model numbers.

True
ignored_header_keys Collection[str]

Header metadata keys excluded from scalar checks (default excludes date, compiler, build, MESA_SDK_version, math_backend).

DEFAULT_IGNORED_HEADER_KEYS

Returns:

Type Description
PartComparison

PartComparison describing bit-identity and differences.

resolve_case_reference_parts

resolve_case_reference_parts(
    suite,
    case,
    *,
    ref_dir=None,
    astero_tracks_dir=None,
    include_astero_tracks=True,
)

Resolve ordered reference parts for a MESA 26.4.1 case directory.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case str

Case directory name.

required
ref_dir Path | str | None

Explicit reference directory or file; defaults to <mesa_histories>/runs/<suite>/<case>.

None
astero_tracks_dir Path | str | None

Optional directory containing track_NNNN.data files for astero search cases.

None
include_astero_tracks bool

Include per-track astero references when present.

True

Returns:

Type Description
list[_ResolvedPart]

(parts, has_history) where has_history is False for

bool

zero-step artifact cases such as star/rsp_check_2nd_crossing.

compare_case_runs

compare_case_runs(
    ref_dir,
    run_dir,
    *,
    suite="",
    case="",
    part_pairs=None,
    astero_tracks_dir=None,
    include_astero_tracks=True,
    prefix_only=False,
    exact_row_match=True,
    ignored_header_keys=DEFAULT_IGNORED_HEADER_KEYS,
)

Compare all history parts of a FlexMESA run against MESA 26.4.1.

Parameters:

Name Type Description Default
ref_dir Path | str | None

Reference case directory (or single history file). When None and part_pairs is None, resolves <mesa_histories>/runs/<suite>/<case>.

required
run_dir Path | str

Candidate FlexMESA output directory (or single history file).

required
suite str

Suite name ("star", "binary", or "astero").

''
case str

Case name.

''
part_pairs Sequence[tuple[str, Path | str, Path | str]] | None

Optional explicit sequence of (part_label, ref_path, run_path) tuples overriding automatic part discovery.

None
astero_tracks_dir Path | str | None

Optional directory holding track_NNNN.data.

None
include_astero_tracks bool

Whether to compare per-track astero search files when available. When False, emits "subset_identical" (never "bit_identical").

True
prefix_only bool

When True, compare covered model_number ranges and reached parts only (for partial/windowed trace runs; emits "prefix_identical" with bit_identical=False when matching).

False
exact_row_match bool

When True (default), enforce 1-to-1 row counts and model_number ordering (for --respect-intervals runs). When False, emits "subset_identical" with bit_identical=False.

True
ignored_header_keys Collection[str]

Header metadata keys excluded from bit-for-bit scalar comparison. Defaults to DEFAULT_IGNORED_HEADER_KEYS (date, compiler, build, MESA_SDK_version, math_backend).

DEFAULT_IGNORED_HEADER_KEYS

Returns:

Type Description
FullHistoryComparison

Aggregated FullHistoryComparison covering every resolved part.

part_comparison_to_dict

part_comparison_to_dict(part)

Serialize a PartComparison into a strict JSON-safe dictionary.

part_comparison_from_dict

part_comparison_from_dict(raw)

Deserialize a PartComparison from part_comparison_to_dict.

comparison_to_dict

comparison_to_dict(comp)

Serialize a FullHistoryComparison into a strict JSON-safe dict.

comparison_from_dict

comparison_from_dict(raw)

Deserialize a FullHistoryComparison from comparison_to_dict.

format_report

format_report(comp)

Format a human-readable summary of a FullHistoryComparison.

main

main(argv=None)

CLI entry point for full_history_compare.

Parameters:

Name Type Description Default
argv list[str] | None

Optional CLI argument list.

None

Returns:

Type Description
int

Exit code: 0 only when full bit_identical; 3

int

(EXIT_PARTIAL_IDENTICAL) when prefix_identical or

int

subset_identical; 2 on divergence or no_history; 1 on

int

error or invalid CLI usage.

flexmesa.testing.harness_runner

Guarded execution and verdict evaluation for upstream MESA trajectories.

Executes star, binary, and astero test-suite cases with optional wall-clock and resident-memory limits while preserving incrementally flushed LOGS/history.data and binary_history.data files on disk, then evaluates verdicts against case_manifest.toml and known_gaps.toml.

CaseHarnessRecord dataclass

Manifest, execution, and trajectory-comparison record for one case.

stage_counter_pairs property

stage_counter_pairs

Return each stage's counters with MESA's testhub.yml block.

stage_step_deltas property

stage_step_deltas

Return the aligned per-stage step counts of the run and MESA.

step_count_differs property

step_count_differs

Return whether any aligned stage ends at another model than MESA.

A run that reports fewer stages than MESA, or that was cut short (status other than ok), is not compared.

is_within_tolerances property

is_within_tolerances

Return whether primary and component comparisons meet tolerances.

is_diagnostic property

is_diagnostic

Return whether the run did not do what upstream's case does.

A run is diagnostic when it continued past unsupported controls (DECISIONS #26) or ran without its upstream extras logic (extras_status = "unported", DECISIONS #32). A diagnostic run is never counted as strict and never passes.

run_mode property

run_mode

Label of how the reported run was made.

Returns:

Name Type Description
str

"-" when the case was not run, "strict" for a run that

str

passed strict control validation and executed its upstream

str

extras logic, and otherwise "diagnostic (...)" naming each

reason str

"N controls ignored" for a rerun that continued past

str

unsupported controls and "extras unported: #NNN" for a case

str

whose upstream extras logic FlexMESA does not execute.

TraceRunOutcome dataclass

Execution telemetry from a star, binary, or astero run.

Attributes:

Name Type Description
suite str

Suite name ("star", "binary", or "astero").

case str

Case directory name.

status str

Execution status ("ok", "error", "timeout", "oom_killed", "diverged" for a case stopped by --early-stop-on-divergence, DECISIONS #69, or "step_overrun" for a case stopped by the step cap, DECISIONS #90).

termination_code str

Observed termination code (or empty string on crash).

steps int

Total evolutionary steps completed before exit.

retries int

Total step retries recorded.

wall_time_sec float

Elapsed wall-clock time in seconds (s).

peak_rss_gb float

Peak resident memory of the worker in gigabytes (GB).

history_path Path | None

Path to the emitted history.data or binary_history.data file if present on disk, else None.

error_message str

Diagnostic error string when status != "ok".

controls_ignored bool

True when the run used the #147 opt-out and continued past unsupported controls. Such a run is diagnostic only and can never produce a pass verdict.

n_controls_ignored int

Number of unsupported controls and sections the strict run named before stopping (0 when unknown).

strict_rejection str

Message of the strict run that stopped on unsupported controls, when this outcome is its diagnostic rerun.

iters int | None

Cumulative Newton solver iterations across logged final-stage steps, or None when num_iters is unavailable.

mean_iters float | None

Mean Newton solver iterations per logged final-stage step, or None when num_iters is unavailable.

track_history_paths tuple[Path, ...]

Per-track astero search histories (sample_NNNN_history.data) ordered by track number, the last one possibly cut short when the run did not finish (#430).

stage_steps tuple[int, ...]

Model number at the end of each star stage the run completed (empty when not reported), compared with MESA's stage by stage (DECISIONS #69).

stages_total int

Number of do_one stages the rn script runs under the harness (0 when not a multi-stage star run).

stage_reached int | None

1-based stage the run ended in, or None when the run does not establish it (stages_total > 1 only).

star1_final_model_number int | None

Final model number of star 1 of a binary run, when the run report provides it.

star1_retries int | None

Retry count of star 1 of a binary run, when the run report provides it.

stage_counters tuple[StageCounters, ...]

Run counters at the end of each star stage the run completed, for comparison with MESA's testhub.yml counters (:mod:flexmesa.testing.testhub_counters).

stdout_text str | None

The worker's standard output, compared with a declared artifact stdout_reference (#925); None when the run did not capture it.

final_stage_reached property

final_stage_reached

Return whether the history is that of the final stage.

A multi-stage run that ended earlier, or that does not establish the stage it ended in, holds the partial history of another stage, which must not be scored against the reference of the final stage.

count_unsupported_controls

count_unsupported_controls(message)

Count the unsupported controls and sections named in message.

Parameters:

Name Type Description Default
message str

Error text of a strict #147 control rejection.

required

Returns:

Type Description
int

Number of unsupported controls plus unsupported namelist sections in

int

the stage inlist that stopped the run (later stages are not scanned).

evaluate_case_record

evaluate_case_record(
    spec,
    known_gaps,
    outcome,
    *,
    max_steps=None,
    root_dir=None,
    precomputed_comparison=None,
    precomputed_component_comparisons=None,
    precomputed_has_component_error=False,
    precomputed_mesa_stats=None,
    enforce_step_counts=False,
    artifact_comparison=None,
)

Combine manifest metadata, run outcome, and comparison into a verdict.

With enforce_step_counts a run that would pass but ends a stage at another model number than MESA, reports another number of stages, or has no per-stage counts on either side is fail (step count) (DECISIONS #70, :func:enforced_step_difference). Without it the difference is only reported (DECISIONS #69).

An astero search case with a manifest track_reference_dir is compared track by track (:func:compare_search_tracks, #430): the per-track comparisons go to component_comparisons and the first track's comparison is the record's primary comparison.

A case with reference_status = "mesa_26_4_1_artifact" (#606) takes no evolution steps. It passes only when artifact_comparison (the run's file against the committed MESA file) is within every declared tolerance, the run took exactly artifact.required_steps steps, and it ended with the required termination. Failures use the ordinary wording and the first field out of tolerance goes in the error message. For other statuses the comparison is only attached to the record.

extract_reference_run_stats

extract_reference_run_stats(
    spec, *, root_dir=None, ref_tbl=None
)

Extract MESA 26.4.1 step, retry, and iteration counts for spec.

For binary cases whose binary_history.data omits num_retries or num_iters, supplements missing fields from LOGS1/history.data when available.

is_unsupported_controls_rejection

is_unsupported_controls_rejection(message)

Return whether message is a strict #147 control rejection.

Only rejections that the opt-out can continue past qualify. Unknown or misspelled controls and sections fail with or without the opt-out.

Parameters:

Name Type Description Default
message str

Error text of a failed run.

required

Returns:

Type Description
bool

True when the run stopped only on unsupported upstream controls or

bool

namelist sections.

load_full_reference_history

load_full_reference_history(paths)

Load and concatenate the history files of one MESA run in order.

Parameters:

Name Type Description Default
paths list[Path]

Non-empty ordered paths from resolve_full_reference_history_paths.

required

Returns:

Type Description
HistoryTable

One table with float64 columns of shape (n_models,).

Raises:

Type Description
ValueError

If the files do not share one column set.

resolve_binary_component_reference_paths

resolve_binary_component_reference_paths(
    case, root_dir=None
)

Locate stored LOGS1/LOGS2 component reference tracks.

resolve_full_reference_history_path

resolve_full_reference_history_path(
    suite, case, *, root_dir=None
)

Return the first full MESA history file of a case, if available.

Parameters:

Name Type Description Default
suite str

Suite name.

required
case str

Upstream test-case directory name.

required
root_dir Path | None

Optional root directory override.

None

Returns:

Type Description
Path | None

The first path of resolve_full_reference_history_paths, else

Path | None

None. Use that function for a run whose history spans files.

resolve_full_reference_history_paths

resolve_full_reference_history_paths(
    suite, case, root_dir=None
)

Locate the un-thinned MESA 26.4.1 history file in runs/.

Only consults the host mesa_histories cache when root_dir is None or matches the repository root so hermetic tests under temporary directories remain isolated.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case str

Upstream test-case directory name.

required
root_dir Path | None

Optional root directory override.

None

Returns:

Type Description
list[Path]

Paths of the full MESA history files of the final stage in model

list[Path]

order (history.data then map_history.data where MESA switched

list[Path]

files, DECISIONS #78), or binary_history.data; [] if none

list[Path]

is available.

resolve_reference_history_path

resolve_reference_history_path(
    reference_path, root_dir=None
)

Resolve reference_path against root_dir, repo root, or cache.

resolve_effective_numerics_mode

resolve_effective_numerics_mode(numerics_mode=None)

Resolve effective "strict"/"fast" mode from arg, env, or process.

Parameters:

Name Type Description Default
numerics_mode str | None

Optional explicit mode override ("strict" or "fast"). When None, inspects FLEXMESA_NUMERICS_MODE and falls back to :func:flexmesa.get_numerics_mode.

None

Returns:

Type Description
str

Canonical lowercase mode string ("strict" or "fast").

Raises:

Type Description
ValueError

If numerics_mode or FLEXMESA_NUMERICS_MODE is not "strict" or "fast".

resolve_mesa_test_root

resolve_mesa_test_root(mesa_dir=None)

Locate and validate the unpacked MESA test-suite root directory.

Parameters:

Name Type Description Default
mesa_dir Path | str | None

Optional explicit root directory path.

None

Returns:

Type Description
Path

Resolved pathlib.Path containing star/test_suite.

Raises:

Type Description
FileNotFoundError

If the resolved directory does not contain star/test_suite.

resolve_case_dir

resolve_case_dir(suite, case_or_path, mesa_dir=None)

Resolve a case name or filesystem path to an existing directory.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case_or_path str

Case directory name (such as "1.3M_ms_high_Z") or explicit directory path.

required
mesa_dir Path | str | None

Optional MESA test-inputs root override.

None

Returns:

Type Description
Path

Resolved pathlib.Path to the case directory. For a case name whose

Path

manifest entry declares [[cases.regenerated_inputs]], a staged

Path

copy with those files replaced (DECISIONS #93); an explicit

Path

directory path is returned as given.

Raises:

Type Description
FileNotFoundError

If the target case directory does not exist, the case manifest is not found, or a declared regenerated input is missing.

ValueError

If a regenerated input's SHA-256 differs from the manifest.

proc_rss_gb

proc_rss_gb(pid)

Return the resident set size of pid in gigabytes (GB).

Parameters:

Name Type Description Default
pid int

Operating-system process identifier.

required

Returns:

Type Description
float

Resident memory in GB (0.0 if the process has exited).

stage_model_numbers

stage_model_numbers(rep)

Return the model number at the end of each stage of a trace report.

Parameters:

Name Type Description Default
rep dict[str, Any]

Report of a star trace (stages[*].model_number).

required

Returns:

Type Description
tuple[int, ...]

The per-stage model numbers; empty for reports without stages.

stage_progress

stage_progress(
    suite, case_dir, skip_optional, started_ns, completed
)

Return the stages of a star case and the stage a run ended in.

A run that returned its report names its stages itself. A run cut off by a budget or an error did not, so the stage is read from the stage output models of the rn script: stage k is complete when its .mod was written after the run started (within a 2 s timestamp slack), and the run ended in the first stage whose declared .mod is missing or older.

Parameters:

Name Type Description Default
suite str

Suite name; only "star" has stages.

required
case_dir Path

Upstream case directory holding the stage output models.

required
skip_optional bool

Whether the run skipped the optional stages.

required
started_ns int

Wall-clock start of the run (time.time_ns()).

required
completed tuple[int, ...] | None

Model number at the end of each completed stage from the run report, or None when the run returned no report.

required

Returns:

Type Description
int

(stages_total, stage_reached). stages_total is 0 for a

int | None

case with at most one stage, and stage_reached is the 1-based

tuple[int, int | None]

stage the run ended in, or None when the run does not establish

tuple[int, int | None]

it (a stage without a declared output model decides nothing).

history_model_span

history_model_span(path)

Return the first and last model_number of a history file.

Reads only the column-name line (line 6 of MESA's six-line header), the first data row and the end of the file, so polling a long history stays cheap. A row still being written (no trailing newline) is ignored.

Parameters:

Name Type Description Default
path Path

A history.data or binary_history.data file.

required

Returns:

Type Description
tuple[int, int] | None

(first, last) model numbers, or None when the file has no

tuple[int, int] | None

model_number column or no complete data row yet.

history_steps

history_steps(path)

Return the steps a history records: last minus first model, plus one.

A stage that starts from a loaded model writes its first row at the loaded model number plus one, so this counts the steps of that stage alone (DECISIONS #90).

Parameters:

Name Type Description Default
path Path

A history.data or binary_history.data file.

required

Returns:

Type Description
int | None

The step count, or None when the file has no complete row.

locate_track_histories

locate_track_histories(out_target, is_logs_dir)

Locate the per-track histories of an astero search run (#430).

The astero driver writes every track it evolves to <astero_results_directory>/sample_NNNN_history.data, numbering tracks from 1 in evaluation order whether or not the search accepted them, while MESA keeps only the last track in LOGS/history.data.

Parameters:

Name Type Description Default
out_target Path

Output file or root directory passed to the tracer.

required
is_logs_dir bool

True when out_target is a directory root.

required

Returns:

Type Description
tuple[Path, ...]

Track histories ordered by track number; empty when there are none.

Raises:

Type Description
ValueError

If track histories sit in more than one directory or their numbers are not exactly 1..N.

locate_written_history

locate_written_history(suite, out_target, is_logs_dir)

Locate the emitted history file, including partial interrupted tracks.

Selects the most recently modified history file under out_target so multi-stage cases whose final stage uses a custom log_directory win over preliminary stages.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
out_target Path

Output file or root directory passed to the tracer.

required
is_logs_dir bool

True when out_target is a directory root.

required

Returns:

Type Description
Path | None

Path to the non-empty history file if present, else None.

load_extras_factory

load_extras_factory(spec)

Resolve an 'module.path:callable' test-side extras factory spec.

run_trace_inprocess

run_trace_inprocess(
    suite,
    case_dir,
    out_target,
    *,
    max_steps=None,
    skip_optional=True,
    respect_intervals=False,
    write_profiles=False,
    is_logs_dir=True,
    numerics_mode=None,
    allow_unsupported_controls=False,
    extras_factory=None,
    extras=None,
)

Invoke the compiled Safe Rust tracer directly in the current process.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case_dir Path

Path to the upstream case directory.

required
out_target Path

Output directory or explicit history file path.

required
max_steps int | None

Optional non-negative per-stage step cap.

None
skip_optional bool

Skip optional multi-stage setup stages when True.

True
respect_intervals bool

Honor history_interval instead of every step.

False
write_profiles bool

Enable writing radial profileN.data files.

False
is_logs_dir bool

Treat out_target as a root directory when True.

True
numerics_mode str | None

Arithmetic mode ("strict" or "fast"; defaults to active FLEXMESA_NUMERICS_MODE / process mode).

None
allow_unsupported_controls bool

Bypass strict namelist rejection of unread, unused, or unimplemented MESA controls when True.

False
extras_factory str | None

Optional 'module:callable' specification returning test-side extras handlers from (suite, case_dir).

None
extras Any

Explicit pre-built test-side extras callback object; overrides extras_factory when provided.

None

Returns:

Type Description
dict[str, Any]

Raw telemetry dictionary returned by flexmesa._rust.

Raises:

Type Description
ValueError

If max_steps < 0, numerics_mode is invalid, suite is unknown, or "astero" extras lack set_param or set_constraint_value.

run_traced_case

run_traced_case(
    suite,
    case_dir,
    out_target,
    *,
    max_steps=None,
    skip_optional=True,
    respect_intervals=False,
    write_profiles=False,
    is_logs_dir=True,
    numerics_mode=None,
    allow_unsupported_controls=False,
    extras_factory=None,
    timeout_sec=None,
    max_rss_gb=None,
    monitor=None,
    monitor_interval_sec=MONITOR_INTERVAL_SEC,
    step_cap=None,
)

Execute one upstream case with optional wall-time and RSS guards.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case_dir Path

Path to the upstream case directory.

required
out_target Path

Output directory or explicit history file path.

required
max_steps int | None

Optional non-negative per-stage step cap.

None
skip_optional bool

Skip optional setup stages when True.

True
respect_intervals bool

Honor history_interval instead of every step.

False
write_profiles bool

Enable writing radial profileN.data files.

False
is_logs_dir bool

Treat out_target as a root directory when True.

True
numerics_mode str | None

Arithmetic mode ("strict" or "fast"; defaults to active FLEXMESA_NUMERICS_MODE / process mode).

None
allow_unsupported_controls bool

Bypass strict namelist rejection of unread, unused, or unimplemented MESA controls when True.

False
extras_factory str | None

Optional 'module:callable' specification returning test-side extras handlers from (suite, case_dir).

None
timeout_sec float | None

Optional wall-clock timeout in seconds (s).

None
max_rss_gb float | None

Optional resident-memory ceiling in gigabytes (GB).

None
monitor RunMonitor | None

Optional polling hook (early_stop.EarlyStopMonitor) called with the partial history every monitor_interval_sec while the case runs. A StopRequest stops the case with its status ("timeout" for a step bound, "diverged" for an early divergence stop). Used only with a time or memory guard.

None
monitor_interval_sec float

Seconds between polls.

MONITOR_INTERVAL_SEC
step_cap int | None

Optional step cap: the case is stopped with status "step_overrun" once the newest history it has written records more steps than this (last minus first model number, plus one; DECISIONS #90). Polled every monitor_interval_sec and only in a worker process.

None

Returns:

Type Description
TraceRunOutcome

TraceRunOutcome summarizing execution status, termination, resource

TraceRunOutcome

usage, emitted history path, and (for astero) the per-track

TraceRunOutcome

search histories.

Raises:

Type Description
ValueError

If max_steps < 0 or numerics_mode is invalid.

run_case_with_diagnostic

run_case_with_diagnostic(
    suite,
    case_dir,
    out_target,
    *,
    max_steps=None,
    numerics_mode=None,
    allow_unsupported_controls=False,
    extras_factory=None,
    timeout_sec=None,
    max_rss_gb=None,
    monitor=None,
    monitor_interval_sec=MONITOR_INTERVAL_SEC,
    step_cap=None,
    deadline=None,
)

Run one case strictly, then diagnostically if strict rejects it.

The case is first run under strict #147 control validation. If that run stops because the inlists set upstream controls FlexMESA does not support, the case is run a second time with those controls ignored, so the table still reports steps, termination and deviations. The returned outcome of such a rerun has controls_ignored set, which bars it from a pass verdict in evaluate_case_record.

Parameters:

Name Type Description Default
suite str

Suite name ("star", "binary", or "astero").

required
case_dir Path

Path to the upstream case directory.

required
out_target Path

Output root directory for the run.

required
max_steps int | None

Optional non-negative per-stage step cap.

None
numerics_mode str | None

Arithmetic mode ("strict" or "fast").

None
allow_unsupported_controls bool

Skip the strict run and go straight to the diagnostic run when True.

False
extras_factory str | None

Optional 'module:callable' specification returning test-side extras handlers from (suite, case_dir).

None
timeout_sec float | None

Optional wall-clock timeout in seconds (s), applied to each of the two runs separately.

None
max_rss_gb float | None

Optional resident-memory ceiling in gigabytes (GB).

None
monitor RunMonitor | None

Optional polling hook applied to each of the two runs (see run_traced_case).

None
monitor_interval_sec float

Seconds between polls.

MONITOR_INTERVAL_SEC
step_cap int | None

Optional step cap applied to each of the two runs (see run_traced_case).

None
deadline float | None

Optional end of the whole harness run (time.monotonic seconds). The diagnostic rerun gets at most the time left before it; when none is left the strict outcome is returned as a "timeout" (inconclusive, DECISIONS #90).

None

Returns:

Type Description
TraceRunOutcome

The strict TraceRunOutcome when strict validation accepted the

TraceRunOutcome

inlists (whatever happened afterwards), otherwise the outcome of the

TraceRunOutcome

diagnostic rerun.

flexmesa.testing.case_report

Script-generated Markdown and JSON case-table builder for #143.

Produces deterministic, non-hand-typed case tables and headline summaries from case_manifest.toml, known_gaps.toml, and optional trajectory runs.

summarize_records

summarize_records(
    manifest,
    records,
    known_gaps=None,
    *,
    numerics_mode="strict",
)

Compute manifest-wide and run-level headline counts across records.

Parameters:

Name Type Description Default
manifest HarnessManifest

Loaded HarnessManifest.

required
records list[CaseHarnessRecord]

Evaluated CaseHarnessRecord sequence.

required
known_gaps dict[tuple[str, str], KnownGapSpec] | None

Optional known_gaps.toml mapping for total gap count.

None
numerics_mode str

Arithmetic mode used for the run ("strict" or "fast").

'strict'

Returns:

Type Description
dict[str, Any]

Dictionary of headline counts and gate violation lists.

record_to_dict

record_to_dict(rec)

Convert a CaseHarnessRecord into a JSON-serializable dictionary.

Parameters:

Name Type Description Default
rec CaseHarnessRecord

CaseHarnessRecord instance.

required

Returns:

Type Description
dict[str, Any]

JSON-serializable dictionary.

build_report_payload

build_report_payload(
    manifest,
    records,
    known_gaps=None,
    *,
    numerics_mode="strict",
)

Assemble the complete JSON report dictionary.

Parameters:

Name Type Description Default
manifest HarnessManifest

HarnessManifest instance.

required
records list[CaseHarnessRecord]

Sequence of CaseHarnessRecord entries.

required
known_gaps dict[tuple[str, str], KnownGapSpec] | None

Optional known_gaps.toml mapping.

None
numerics_mode str

Arithmetic mode used for the run ("strict" or "fast").

'strict'

Returns:

Type Description
dict[str, Any]

Structured dictionary with summary and cases keys.

default_baseline_json_path

default_baseline_json_path()

Return the committed MESA 26.4.1 baseline harness JSON path.

build_deterministic_baseline_payload

build_deterministic_baseline_payload(
    manifest,
    records,
    known_gaps=None,
    *,
    numerics_mode="strict",
)

Build a deterministic baseline JSON payload omitting volatile timings.

Parameters:

Name Type Description Default
manifest HarnessManifest

HarnessManifest instance.

required
records list[CaseHarnessRecord]

Evaluated CaseHarnessRecord entries.

required
known_gaps dict[tuple[str, str], KnownGapSpec] | None

Optional known_gaps.toml mapping.

None
numerics_mode str

Arithmetic mode used for the run ("strict" or "fast").

'strict'

Returns:

Type Description
dict[str, Any]

JSON-serializable dictionary with wall_time_sec and peak_rss_gb

dict[str, Any]

normalized to 0.0, and max_rss_gb omitted, for deterministic

dict[str, Any]

git diffs.

render_case_table_markdown

render_case_table_markdown(
    manifest,
    records,
    *,
    summary=None,
    known_gaps=None,
    figure_links=None,
    title="Upstream MESA Trajectory Case Table",
)

Render a deterministic Markdown table from records.

Parameters:

Name Type Description Default
manifest HarnessManifest

HarnessManifest instance.

required
records list[CaseHarnessRecord]

Sequence of CaseHarnessRecord entries.

required
summary dict[str, Any] | None

Optional precomputed summary dictionary.

None
known_gaps dict[tuple[str, str], KnownGapSpec] | None

Optional known_gaps.toml mapping.

None
figure_links dict[tuple[str, str], str] | None

Optional mapping from (suite, case) to comparison figure link targets included as a trailing column when given.

None
title str

Top-level Markdown heading text.

'Upstream MESA Trajectory Case Table'

Returns:

Type Description
str

Formatted Markdown document ending with a newline.

build_manifest_inventory_records

build_manifest_inventory_records(
    manifest_path=None,
    known_gaps_path=None,
    baseline_json_path=None,
)

Build CaseHarnessRecord entries from manifest and baseline JSON.

Re-evaluates verdicts dynamically against case_manifest.toml and known_gaps.toml using stored MESA 26.4.1 baseline measurements when present, judging stage step counts as DECISIONS #70 requires (the committed baseline is a step-count-enforced snapshot).

Parameters:

Name Type Description Default
manifest_path Path | str | None

Optional path to case_manifest.toml.

None
known_gaps_path Path | str | None

Optional path to known_gaps.toml.

None
baseline_json_path Path | str | None

Optional path to baseline_run_26_4_1.json.

None

Returns:

Type Description
tuple[HarnessManifest, dict[tuple[str, str], KnownGapSpec], list[CaseHarnessRecord]]

Tuple (manifest, known_gaps, records) across all manifest entries.

records_from_stored_rows

records_from_stored_rows(
    manifest,
    gaps,
    stored_by_key,
    base_dir=None,
    *,
    max_steps=None,
    enforce_step_counts=False,
)

Rebuild CaseHarnessRecord entries from stored JSON case rows.

Verdicts are re-evaluated against manifest and gaps from the stored measurements and comparisons; no history file is read.

Parameters:

Name Type Description Default
manifest HarnessManifest

Loaded HarnessManifest.

required
gaps dict[tuple[str, str], KnownGapSpec]

Loaded known_gaps.toml mapping.

required
stored_by_key dict[tuple[str, str], dict[str, Any]]

Executed case rows (as written by :func:record_to_dict) keyed by (suite, case).

required
base_dir Path | None

Directory against which manifest reference paths resolve.

None
max_steps int | None

Step cap the stored runs used, or None when uncapped.

None
enforce_step_counts bool

Judge stored stage step counts as ``DECISIONS

70requires (seeevaluate_case_record``).

False

Returns:

Type Description
list[CaseHarnessRecord]

One record per manifest entry, in manifest order; entries without a

list[CaseHarnessRecord]

stored row are not-executed records.

flexmesa.testing.baseline_regression

Regression check of a harness run against the committed baseline run.

While a case is a declared known gap its verdict cannot get worse, so the known-gaps gate alone cannot see a case that used to evolve and now stops. This module compares each executed case with the same case in the committed baseline run (a FlexMESA regression snapshot, not a MESA reference) and reports the cases whose measured state got worse (DECISIONS #27).

A campaign may run the cases whose baseline row ended on the time budget with a shorter budget than the rest (the short-budget tier). Strict mode is bit-identical across machines, so such a run reproduces a prefix of the baseline trajectory unless the engine changed; the comparison for those cases is restricted to what a prefix can show.

BaselineRegression dataclass

One case whose measured state is worse than in the baseline run.

Attributes:

Name Type Description
suite str

Upstream suite (star, binary or astero).

case str

Upstream case name.

kind str

One of "stopped taking steps", "lost upstream termination" or "left tolerance".

detail str

Baseline and current values, for the report.

label property

label

Return "<suite>/<case>: <kind> (<detail>)".

budget_limited_keys

budget_limited_keys(baseline_records)

Return the cases whose baseline run ended on the time budget.

Parameters:

Name Type Description Default
baseline_records list[CaseHarnessRecord]

Records rebuilt from the committed baseline run.

required

Returns:

Type Description
frozenset[tuple[str, str]]

(suite, case) keys of executed baseline rows whose run status is

frozenset[tuple[str, str]]

"timeout".

find_baseline_regressions

find_baseline_regressions(
    records, baseline_records, *, short_budget=frozenset()
)

List executed cases whose state is worse than in the baseline run.

A case regresses when the baseline run took steps and this run takes none, when the baseline run reached upstream's termination condition and this run does not, or when the baseline history was within the manifest tolerances and this one is not. A run cut off by its time or memory budget is inconclusive on its own; when the baseline run completed, it is checked as a prefix of that row (it takes steps and does not leave a track tolerance at an earlier model; DECISIONS #59). The check must not be used on step-capped runs, whose outcome differs from the baseline by design.

A case in short_budget whose baseline row ended on the time budget was run with a shorter budget and is compared as a prefix of that row instead: it regresses when it takes no steps, when it ends (other than on upstream's termination) before the baseline's step count, or when it first leaves a track tolerance at an earlier model than the baseline.

Parameters:

Name Type Description Default
records list[CaseHarnessRecord]

Records of the cases executed in this run.

required
baseline_records list[CaseHarnessRecord]

Records rebuilt from the committed baseline run.

required
short_budget frozenset[tuple[str, str]]

(suite, case) keys run with the short budget.

frozenset()

Returns:

Type Description
list[BaselineRegression]

Regressions in the order of records, at most one per case (the

list[BaselineRegression]

earliest kind that applies).

merge_records_into_baseline

merge_records_into_baseline(
    records, baseline_records, *, short_budget=frozenset()
)

Replace the executed cases of a run inside the full baseline list.

A case run with the short budget that ended on that budget keeps its baseline row, which records a longer run of the same trajectory. A short-budget case that ended before the budget (on a termination condition or an error) is replaced like any other case.

Parameters:

Name Type Description Default
records list[CaseHarnessRecord]

Records of the cases executed in this run.

required
baseline_records list[CaseHarnessRecord]

Records for every manifest case, rebuilt from the committed baseline run.

required
short_budget frozenset[tuple[str, str]]

(suite, case) keys run with the short budget.

frozenset()

Returns:

Type Description
list[CaseHarnessRecord]

A list in the order of baseline_records in which every case

list[CaseHarnessRecord]

executed in this run carries this run's record, except short-budget

list[CaseHarnessRecord]

cases cut off by that budget.

flexmesa.testing.harness_shards splits a harness campaign into disjoint shards (flexmesa harness run --shard I/N) and combines their reports for flexmesa harness merge (#389). Without --case-budgets the shards are packed by MESA 26.4.1's own wall time on each case, read by flexmesa.testing.case_timings from benchmarks/history_harness/case_timings.toml, and a case over one hour gets a shard of its own. The cases of a shard that sent no report are reported as untested and the gate judges the rest (DECISIONS #90).

flexmesa.testing.harness_shards

Split a harness campaign into shards and merge the shard reports.

A full strict campaign runs every manifest case once. Strict mode is bit-identical across machines and thread counts, so the cases can run on several machines at once and the per-case results can be combined into one case table and one baseline candidate afterwards. Only the outcomes cut off by a time or memory budget depend on the machine.

Each shard writes the usual --json-out report with a run block that records the shard, the run settings and the plan of every shard; :func:merge_shard_payloads checks that the shards agree on the settings and reports the cases of a shard that sent no report, or of cases a shard never started, as untested (DECISIONS #90).

MergedShards dataclass

Case rows and run settings combined from shard reports.

Attributes:

Name Type Description
rows dict[tuple[str, str], dict[str, Any]]

Executed case rows keyed by (suite, case).

settings dict[str, Any]

The run settings shared by every shard.

short_budget_cases frozenset[tuple[str, str]]

(suite, case) keys run with the short budget.

budgeted_cases frozenset[tuple[str, str]]

(suite, case) keys that ran with a wall-time budget derived from the baseline (--budget-from-baseline).

untested frozenset[tuple[str, str]]

(suite, case) keys that no shard measured: the cases of a shard that sent no report (from the shard plan the other shards recorded) and the cases a shard did not start before its deadline.

missing_shards tuple[int, ...]

1-based indices of the shards that sent no report.

per_shard dict[str, dict[int, Any]]

{key: {shard index: value}} for each key of :data:PER_SHARD_KEYS.

problems tuple[str, ...]

Reasons the shards do not form one campaign (repeated shards or cases, or a missing shard whose cases are unknown because the reports carry no shard plan); empty when they do.

parse_shard

parse_shard(raw)

Parse a "I/N" shard specification.

Parameters:

Name Type Description Default
raw str

Shard text, with 1 <= I <= N.

required

Returns:

Type Description
tuple[int, int]

(index, count) with a 1-based index.

Raises:

Type Description
ValueError

If raw is not of the form I/N with 1 <= I <= N.

plan_shards

plan_shards(
    entries,
    count,
    costly=frozenset(),
    weights=None,
    solo_sec=None,
)

Assign every entry to a shard.

With weights the entries are packed by weight. When solo_sec is given, each entry heavier than it gets a shard of its own, heaviest first on the lowest shard indices. The remaining entries are packed heaviest first, each onto the remaining shard with the smallest total so far (lowest index on a tie), which keeps the heaviest shard close to the mean. An entry without a weight counts as the largest weight of the entries that share shards, so an unlisted case is never assumed cheap.

Without weights the entries are ordered with the costly cases (those expected to run to their time or memory budget) first, each group in its input order, and dealt round-robin to the shards, so every shard gets a near-equal share of the costly cases. Either way the assignment depends only on the inputs.

Parameters:

Name Type Description Default
entries list[CaseManifestEntry]

Selected entries in manifest order.

required
count int

Number of shards.

required
costly frozenset[tuple[str, str]]

(suite, case) keys dealt out first (ignored when weights is given).

frozenset()
weights Mapping[tuple[str, str], float] | None

Optional cost per (suite, case), such as MESA's wall time in seconds (s).

None
solo_sec float | None

Weight above which an entry runs alone (needs weights).

None

Returns:

Type Description
list[list[CaseManifestEntry]]

count lists, the entries of shards 1..count in manifest

list[list[CaseManifestEntry]]

order.

Raises:

Type Description
ValueError

If count < 1 or the solo entries leave no shard for the others.

shard_entries

shard_entries(
    entries,
    index,
    count,
    costly=frozenset(),
    weights=None,
    solo_sec=None,
)

Select the entries one shard runs (see :func:plan_shards).

Parameters:

Name Type Description Default
entries list[CaseManifestEntry]

Selected entries in manifest order.

required
index int

1-based shard index.

required
count int

Number of shards.

required
costly frozenset[tuple[str, str]]

(suite, case) keys dealt out first (without weights).

frozenset()
weights Mapping[tuple[str, str], float] | None

Optional cost per (suite, case) in seconds (s).

None
solo_sec float | None

Weight above which an entry runs alone.

None

Returns:

Type Description
list[CaseManifestEntry]

The entries of shard index, in manifest order.

merge_shard_payloads

merge_shard_payloads(payloads)

Combine the --json-out reports of the shards of one campaign.

Parameters:

Name Type Description Default
payloads list[dict[str, Any]]

Parsed shard reports, each with a run block.

required

A missing shard, or a selected case that a shard did not run, no longer makes the campaign incomplete: those cases are untested and the rest are judged (DECISIONS #90).

Returns:

Type Description
MergedShards

The combined rows and settings, the untested cases and any problems.

Raises:

Type Description
ValueError

If there are no payloads, a payload has no run block or shard, or the shards disagree on a run setting or on the shard count.

flexmesa.testing.case_timings

Committed wall-time measurements of the harness cases.

benchmarks/history_harness/case_timings.toml is generated by scripts/audit/case_timings.py (see the header of that file for its sources, thread counts and machines). The campaign packs its shards by MESA 26.4.1's own wall time on each case (DECISIONS #90), which does not move when FlexMESA gets faster or slower, and the runtime tracker compares the measured order with upstream's do1_test_source (DECISIONS #92).

The module has no package dependencies, so scripts can load it by path without the compiled extension.

default_path

default_path()

Return the committed timing table of a source checkout.

load_mesa_wall_times

load_mesa_wall_times(path=None)

Read MESA 26.4.1's wall time on each case.

Parameters:

Name Type Description Default
path Path | str | None

A case_timings.toml file (default: the committed table).

None

Returns:

Type Description
dict[tuple[str, str], float]

{(suite, case): mesa_wall_sec} in seconds (s) for every row

dict[tuple[str, str], float]

with a positive MESA wall time.

Raises:

Type Description
ValueError

If the file has no cases list, a row is malformed, or a case appears twice.

flexmesa.testing.testhub_counters pairs FlexMESA's run counters at the end of each star stage with the block MESA 26.4.1 wrote to testhub.yml for the same inlist, and says for each counter whether the two definitions agree; flexmesa.testing.photo_restart reads upstream's restart directives from do1_test_source and defines the restart comparison (flexmesa harness run --photo-restart-check); flexmesa.testing.case_status_history reads each case's verdict at each rebaseline from the git history of the committed baseline (DECISIONS #94).

flexmesa.testing.testhub_counters

FlexMESA's per-stage run counters beside MESA's testhub.yml counters.

MESA's test suite writes one counter block per inlist to testhub.yml (star/job/test_suite_extras.inc:16-57): model_number, star_age, num_retries and log_rel_run_E_err from the star, then the per-part counters steps, retries, redos, solver_calls_made, solver_calls_failed and solver_iterations. DECISIONS #91 commits them, as benchmarks/history_harness/mesa_testhub_26_4_1.json.

FlexMESA reports, for each star stage it runs, the counters it keeps with the same definition (:data:SHARED_COUNTERS). They are of two kinds on both sides:

  • Carried in the saved model (test_suite_extras.inc:37-41: "these quantities can be cumulative as they are stored in saved models"):

  • model_number: the model number at the end of the stage (s% model_number). A stage that loads a .mod continues its model number (star/private/read_model.f90:281-288; FlexMESA model_io.rs:348-353, 578) unless set_initial_model_number (default .false.) resets it (star/job/run_star_support.f90: 2003-2007; FlexMESA star_job_init.rs:844).

  • num_retries: s% num_retries. It is read from the .mod (read_model.f90:288; FlexMESA model_io.rs:425-430) and then reset to initial_number_retries (0) by set_initial_number_retries, which defaults to .true. (run_star_support.f90:2009-2012; FlexMESA model_io.rs:570-578, star_job_init.rs:850), so it counts the stage's own retries unless the stage sets it .false. and continues the loaded count. A relax saves and restores it (star/private/relax.f90:4030, 4244).

  • Not in the saved model, so counted from zero for each stage: MESA runs each do_one in a new process (alloc_star_data -> set_starting_star_data, star/private/init.f90:407, 489-500) and FlexMESA builds each stage's model anew (run_test_suite_case_with_extras):

  • solver_iterations: s% total_num_solver_iterations, one per Newton iteration of the structure solve (star/private/star_solver.f90:339, added up in struct_burn_mix.f90:55-56, 175-176), relax steps included; for RSP the iterations the RSP step reports. MESA does not count an iteration that leaves on a failed solver_test_partials (star_solver.f90:333-337, before the increment at :339); FlexMESA has no such exit. solver_test_partials is a debugging aid that fails only with its own debug controls set, so the difference does not arise in a test-suite run.

  • solver_calls_made: s% total_num_solver_calls_made, one per call of do_struct_burn_mix that reaches the solver (struct_burn_mix.f90:177). FlexMESA counts one per solve_henyey_step call, which do_struct_burn_mix makes once. One case differs: a call with dt <= 0 is counted by MESA, whose do_solver_converge then returns without solving (struct_burn_mix.f90:377-379), and is not counted by FlexMESA, whose solve_henyey_step returns before counting. Not reported for an RSP stage: MESA counts each RSP step as a solver call (struct_burn_mix.f90:57), FlexMESA's RSP step does not.

The counters MESA writes that FlexMESA does not report (:data:MESA_ONLY_COUNTERS) are shown from MESA's side only:

  • steps (total_steps_finished), retries (total_step_retries) and redos (total_step_redos) count the results of do_evolve_step_part1 and do_evolve_step_part2 (star/private/evolve.f90:71-82, 483-493): steps counts relax steps and a step whose timestep pick then retries, and retries does not count a retry asked by the timestep pick. FlexMESA's step does not follow MESA's two-part split, and it keeps no counter with these definitions; its stage step and retry totals count other things.
  • solver_calls_failed needs a count of converged solver calls (total_num_solver_calls_converged), which FlexMESA does not keep.
  • runtime_minutes is a wall time (case_timings.toml records wall times), star_age and log_rel_run_E_err are not in the committed table, and the extra_testhub values are written by each case's own run_star_extras.f90, which FlexMESA does not call.

Only star cases report counters. A FlexMESA stage is paired with MESA's first unused inlist line of the same inlist name; an inlist line with more than one block (a multi-star run's copies) is not compared.

StageCounters dataclass

FlexMESA's counters at the end of one stage.

Attributes:

Name Type Description
inlist str

Inlist file the stage ran (the do_one argument).

model_number int

Model number at the end of the stage.

num_retries int

num_retries at the end of the stage.

solver_iterations int

Newton iterations of the stage.

solver_calls_made int | None

Structure-solver calls of the stage, or None for an RSP stage.

as_dict

as_dict()

Return the counters keyed by their testhub.yml names.

StageCounterPair dataclass

One FlexMESA stage and the MESA testhub.yml block it pairs with.

Attributes:

Name Type Description
run StageCounters

FlexMESA's counters.

mesa Mapping[str, Any] | None

MESA's block (mesa_testhub_26_4_1.json fields), or None.

note str

Why no MESA block is paired, when mesa is None.

differences

differences()

Return the shared counters whose values differ from MESA's.

A counter either side does not have is not compared.

to_dict

to_dict()

Return the JSON form written to case_result rows.

counters_from_report

counters_from_report(rep)

Read the per-stage counters of a star trace report.

Parameters:

Name Type Description Default
rep Mapping[str, Any]

Report of trace_star_case (stages[*]).

required

Returns:

Type Description
StageCounters

One entry per stage that ran its evolve loop (a stage stopped in

...

its setup reports no counters and is skipped).

counters_to_report

counters_to_report(counters)

Return counters as the stages entries of a trace report.

The trace worker writes them to its result file, which the harness reads back with counters_from_report({"stages": ...}).

counters_to_dicts

counters_to_dicts(counters)

Return counters as JSON objects (see :func:counters_from_dicts).

counters_from_dicts

counters_from_dicts(rows)

Rebuild counters from :func:counters_to_dicts or stored row output.

Parameters:

Name Type Description Default
rows Sequence[Mapping[str, Any]]

Objects with inlist and the shared counters, either flat or under a flexmesa key (StageCounterPair.to_dict).

required

Returns:

Type Description
tuple[StageCounters, ...]

The counters, in order.

load_mesa_testhub

load_mesa_testhub(path=None)

Read MESA's counter blocks grouped by inlist line.

Parameters:

Name Type Description Default
path Path | None

Optional path of mesa_testhub_26_4_1.json (default: the committed file).

None

Returns:

Type Description
MesaTesthubTable

{(suite, case): inlist lines}, each line the blocks MESA wrote

MesaTesthubTable

under it (block 1, 2, ...); empty when the file is absent.

pair_stages

pair_stages(counters, mesa_lines)

Pair each FlexMESA stage with MESA's block of the same inlist.

Parameters:

Name Type Description Default
counters Sequence[StageCounters]

FlexMESA's stages, in run order.

required
mesa_lines Sequence[Sequence[Mapping[str, Any]]]

MESA's inlist lines (:func:load_mesa_testhub).

required

Returns:

Type Description
StageCounterPair

One pair per FlexMESA stage. A stage is paired with the first MESA

...

inlist line after the previous pairing whose inlist name is the

tuple[StageCounterPair, ...]

same; a line with more than one block, or a block MESA did not

tuple[StageCounterPair, ...]

finish writing, is not paired.

flexmesa.testing.photo_restart

Upstream's photo-restart check and its status for each harness case.

MESA's test suite runs each case twice (star/test_suite/each_test_run, the same script for binary and astero). check_run (lines 208-278) runs ./rn and records md5sum of the final model named by the third do_one argument of do1_test_source in checks.md5. check_restart (lines 131-205) then reads the fourth argument, the restart photo:

  • skip: no restart;
  • auto: the antepenultimate photo, the third newest file in photos/ by modification time (antepenultimate_photo, lines 118-129; for binary the third newest b_* file without its b_ prefix);
  • any other value (for example x150): that photo.

It deletes the final model, runs ./re <photo>, which restarts the last do_one inlist (the inlist the last stage copied) from the photo, and runs ./ck, which requires md5sum -c checks.md5 to pass (star/test_suite/test_suite_helpers, check_one): the restarted run's final model must be byte for byte the uninterrupted run's.

FlexMESA's check (:func:compare_restart) is that comparison plus one on the histories: the restarted run's final model file must equal the uninterrupted run's byte for byte, and its history rows must be, line for line and byte for byte, the uninterrupted run's rows after the photo's model number.

FlexMESA writes photos during a run (photo_interval, save_photo_when_terminate) and reads them (flexmesa_star::photo_io::read_photo_bytes), but its stage runner has no restart path: every stage starts from its inlist's model, with restart = false (crates/flexmesa-star/src/star_job_init.rs), so there is no counterpart of ./re. The verify_restart option of star.run_test_suite_case is not one either: after the first stage that ends normally it serializes the in-memory model, reloads it, takes one star_evolve_step with each copy (no stage loop, extras or termination checks) and compares the two serialized states (verify_photo_restart_parity); it never reads a photo the run wrote. Until a restart runner exists, every case upstream restarts is reported unsupported (:data:UNSUPPORTED_REASON), and nothing is run.

RestartDirective dataclass

One do_one line of a suite's do1_test_source.

Attributes:

Name Type Description
case str

Case directory name.

final_model str

Model whose checksum the restart must reproduce, or "skip".

photo str

Restart photo: "auto", "skip", a photo name, or "" when the line gives none (upstream then prints a warning and does not restart).

restarts property

restarts

Return whether upstream restarts this case from a photo.

RestartCheck dataclass

Result of the photo-restart check of one case.

Attributes:

Name Type Description
status str

"unknown", "not restarted upstream", "unsupported", "pass" or "fail".

photo str

The photo upstream restarts from (do1_test_source).

reason str

Why the check did not pass, or did not run.

to_dict

to_dict()

Return the JSON form written to case_result rows.

parse_do1_test_source

parse_do1_test_source(text)

Parse the do_one lines of a do1_test_source file.

Parameters:

Name Type Description Default
text str

File contents. Comment lines and lines other than do_one calls are ignored.

required

Returns:

Type Description
dict[str, RestartDirective]

{case: directive}.

load_restart_directives

load_restart_directives(mesa_dir, suite)

Read <mesa_dir>/<suite>/test_suite/do1_test_source.

Returns:

Type Description
dict[str, RestartDirective]

{case: directive}.

Raises:

Type Description
FileNotFoundError

The suite has no do1_test_source, so which cases upstream restarts is not known.

antepenultimate_photo

antepenultimate_photo(photo_dir, *, binary=False)

Return the photo upstream's auto restarts from.

Parameters:

Name Type Description Default
photo_dir Path

The case's photos/ directory.

required
binary bool

Pick among b_* files and drop the prefix, as upstream does for the binary suite.

False

Returns:

Type Description
str | None

The third newest file by modification time (``ls -t * | head -3 |

str | None

tail -1``), the oldest one when there are fewer than three, or

str | None

None when there is none.

compare_restart

compare_restart(
    full_model,
    restart_model,
    full_history,
    restart_history,
    photo_model_number,
)

Compare a restarted run with the uninterrupted run.

Parameters:

Name Type Description Default
full_model Path

Final model of the uninterrupted run.

required
restart_model Path

Final model of the restarted run.

required
full_history Path

history.data of the uninterrupted run's last stage.

required
restart_history Path

history.data the restarted run wrote.

required
photo_model_number int

Model number of the photo the run restarted from.

required

Returns:

Type Description
RestartCheck

pass when the two final models are identical bytes and the

RestartCheck

restarted run's data rows are exactly the uninterrupted run's rows

RestartCheck

whose model number exceeds photo_model_number, in order and

RestartCheck

byte for byte; otherwise fail with the first difference.

check_status

check_status(directive)

Return the restart-check result FlexMESA can give a case today.

Parameters:

Name Type Description Default
directive RestartDirective | None

The case's do1_test_source line, or None when the file does not list the case.

required

Returns:

Type Description
RestartCheck

unknown when the case has no line (upstream's choice is not

RestartCheck

known), not restarted upstream for a skip or empty photo,

RestartCheck

else unsupported with :data:UNSUPPORTED_REASON.

flexmesa.testing.case_status_history

Each harness case's verdict over the committed baseline's history.

The committed baseline benchmarks/history_harness/baseline_run_26_4_1.json is rewritten by every rebaseline, so its git history holds each case's verdict at each rebaseline. :func:build_history reads that history, keeping only the commits that changed at least one verdict, and :func:render_markdown turns it and the runtime tracker case_timings.toml into docs/benchmarks/case-status-history.md.

Nothing is stored besides the page: the history is read from git each time, so it needs a clone with the baseline's full history, and a shallow clone is refused (:class:ShallowCloneError). The dashboard refresh on main (.github/workflows/dashboard.yml, a full-history checkout) regenerates and commits the page after every merge, so no rebaseline has a manual step.

ShallowCloneError

Bases: RuntimeError

The clone lacks the history the page is built from.

verdict_symbol

verdict_symbol(verdict)

Return the one-letter timeline symbol of verdict.

Parameters:

Name Type Description Default
verdict str | None

A baseline row's verdict, or None when the case had no row in that baseline.

required

Returns:

Type Description
str

The symbol of the first verdict class whose name starts the verdict,

str

"?" for an unknown verdict, "." for no row.

baseline_verdicts

baseline_verdicts(payload)

Return {"suite/case": verdict} of a baseline payload.

build_history

build_history(repo_root)

Read the verdict history of the committed baseline from git.

Parameters:

Name Type Description Default
repo_root Path

Repository root, a clone with full history.

required

Returns:

Type Description
dict[str, Any]

{"baseline": path, "entries": [...]}, oldest entry first. Each

dict[str, Any]

entry has commit (12-character hash), date (author date,

dict[str, Any]

YYYY-MM-DD), ref (the (#N) issue or pull request the

dict[str, Any]

commit's subject ends with, or None) and changes, the

dict[str, Any]

verdicts that differ from the previous entry's

dict[str, Any]

(every verdict for the first entry; None for a case that lost

dict[str, Any]

its row). A

dict[str, Any]

commit is kept only when it changed at least one verdict.

Raises:

Type Description
ShallowCloneError

repo_root is a shallow clone, whose history of the baseline is cut short.

ValueError

A commit's baseline is not valid JSON with suite, case and verdict in every row.

CalledProcessError

git failed (no repository, or a commit that deleted the baseline).

entry_verdicts

entry_verdicts(history)

Return the full verdict map after each history entry, oldest first.

render_markdown

render_markdown(history, timings_path, *, banner, blob_url)

Render the per-case status history page.

Parameters:

Name Type Description Default
history Mapping[str, Any]

History from :func:build_history.

required
timings_path Path

case_timings.toml (runtime tracker).

required
banner str

Generated-file comment for the first line.

required
blob_url str

URL prefix of repository files (.../blob/main).

required

Returns:

Type Description
str

The Markdown page, ending with a newline.

flexmesa.testing.harness_budgets derives per-case wall-time and step budgets for a campaign from recorded wall times and the MESA step counts (flexmesa harness run --budget-from-baseline, --mesa-step-factor), and flexmesa.testing.early_stop stops a running star case once its partial history is out of an along-track tolerance (--early-stop-on-divergence, #554, DECISIONS #69). flexmesa.testing.stage_steps pairs FlexMESA's per-stage step counts with those of the stored MESA runs (--enforce-step-counts, --stop-on-excess-steps) and gives the step cap of --step-cap-factor, which stops a case as fail (step overrun) once the history it is writing records more than that multiple of MESA's steps over the case, counted from MESA's own testhub.yml counters (DECISIONS #90).

flexmesa.testing.harness_budgets

Per-case budgets for harness campaigns, derived from the baseline run.

A uniform time budget makes a campaign wait the full budget for every case that is slow or has stopped making progress. --budget-from-baseline gives each case a wall-time budget of max(K x its recorded wall time, floor) capped at --timeout-sec, and --mesa-step-factor bounds its steps at a multiple of the step count of the MESA reference run. A case stopped by either bound is inconclusive and is compared as a prefix of its baseline row (DECISIONS #59, DECISIONS #69).

The committed baseline records wall times as zero so that it diffs deterministically (DECISIONS #58), so the wall times come from a previous harness --json-out report of the same machine class.

CaseBudget dataclass

Wall-time and step budget of one case.

Attributes:

Name Type Description
timeout_sec float

Wall-clock budget in seconds (s).

mesa_steps int | None

Step count of the MESA reference run, or None.

step_factor float | None

Step bound as a multiple of mesa_steps, or None.

from_baseline bool

True when timeout_sec was derived from a recorded wall time rather than being the plain --timeout-sec cap.

load_wall_times

load_wall_times(path)

Read the wall time of each executed case from a harness report.

Parameters:

Name Type Description Default
path Path | str

A harness --json-out report (or any JSON with a cases list whose rows carry suite, case, executed and wall_time_sec).

required

Returns:

Type Description
dict[tuple[str, str], float]

{(suite, case): wall_time_sec} for rows that ran to completion

dict[tuple[str, str], float]

(not cut off by a budget) and recorded a positive wall time.

Raises:

Type Description
ValueError

If the file has no cases list.

passing_keys

passing_keys(baseline_records)

Return the cases whose baseline verdict is pass.

Parameters:

Name Type Description Default
baseline_records list[CaseHarnessRecord]

Records rebuilt from the committed baseline run.

required

Returns:

Type Description
frozenset[tuple[str, str]]

(suite, case) keys of the cases for the passes preset.

derive_budgets

derive_budgets(
    entries,
    baseline_records,
    wall_times,
    *,
    timeout_sec,
    factor,
    floor_sec,
    step_factor,
)

Derive the budget of every selected case.

A case with a recorded wall time w gets min(timeout_sec, max(factor * w, floor_sec)). A case without one (not in wall_times, or its baseline row ended on a budget) keeps the full timeout_sec. The step bound applies to every case whose baseline row records the MESA step count.

Parameters:

Name Type Description Default
entries list[CaseManifestEntry]

Selected manifest entries.

required
baseline_records list[CaseHarnessRecord]

Records rebuilt from the committed baseline run.

required
wall_times dict[tuple[str, str], float]

Recorded wall times from :func:load_wall_times.

required
timeout_sec float

The scheduled budget (--timeout-sec), the cap.

required
factor float

Multiple K of the recorded wall time.

required
floor_sec float

Smallest derived budget.

required
step_factor float | None

Multiple M of the MESA step count, or None.

required

Returns:

Type Description
dict[tuple[str, str], CaseBudget]

A budget per selected (suite, case).

Raises:

Type Description
ValueError

If a numeric argument is not positive.

flexmesa.testing.case_budgets reads the committed per-case wall-time budgets, generated from measured campaign and MESA wall times by scripts/audit/case_budgets.py (flexmesa harness run --case-budgets, #640).

flexmesa.testing.case_budgets

Committed per-case wall-time budgets for strict harness campaigns.

benchmarks/history_harness/case_budgets.toml is generated by scripts/audit/case_budgets.py from measured wall times (see the header of that file for the recipe, the floor and the safety factors). A campaign or a single-case run reads it with flexmesa harness run --case-budgets so that a case that needs seconds does not hold a budget sized for the slowest case, and a case that needs hours is not cut off by a budget sized for the typical one. A case that stops on its budget is inconclusive, as with any time budget (DECISIONS #59).

default_path

default_path()

Return the committed budget table of a source checkout.

load_case_budgets

load_case_budgets(path)

Read the wall-time budget of each case from a budget table.

Parameters:

Name Type Description Default
path Path | str

A case_budgets.toml file with [[cases]] rows carrying suite, case and budget_sec.

required

Returns:

Type Description
dict[tuple[str, str], float]

{(suite, case): budget_sec} with every budget positive, in

dict[tuple[str, str], float]

seconds (s).

Raises:

Type Description
ValueError

If the file has no cases list, a row is malformed, a budget is not positive, or a case appears twice.

load_projected_times

load_projected_times(path)

Read each case's projected wall time from a budget table.

Parameters:

Name Type Description Default
path Path | str

A case_budgets.toml file whose [[cases]] rows carry projected_sec.

required

Returns:

Type Description
dict[tuple[str, str], float]

{(suite, case): projected_sec} in seconds (s).

Raises:

Type Description
ValueError

If the file has no cases list or a row is malformed.

flexmesa.testing.early_stop

Stop a harness case early when its partial history has left tolerance.

The history harness judges a finished run by comparing its history with the stored MESA reference along the independent coordinate (DECISIONS #27, compare_histories). A case whose partial history already violates an along-track tolerance cannot pass, so a fast loop may stop it instead of waiting for upstream's termination condition (DECISIONS #69).

The along-track check of the final comparison evaluates, on a grid that contains every interior row of the run, the distance between the run and the reference interpolated to the same coordinate. :func:find_early_divergence evaluates the same distance with the same tolerance and bad-value rules at a subset of those points: the interior rows of the run that are already complete (every row except the last collapsed one, whose value can still change). For a sparse reference or a discrete column, which the final comparison evaluates only at the reference rows, the points are the reference rows that those complete run rows span, and only once at least two of them lie in the run. A point that fails is therefore also checked, and fails, in the final comparison of any longer run that contains the same rows, so the check can never stop a case that the final comparison would pass. Final-value tolerances are only defined at termination and are never used here.

EarlyDivergence dataclass

The first along-track point at which a partial run is out of tolerance.

Attributes:

Name Type Description
column str

Tolerance key that failed (<col> or rel_<col>).

x_name str

Independent coordinate name (such as star_age).

x float

Coordinate value of the failing point (yr for ages).

model int | None

model_number of the first run row at or after x, or None when the run has no model_number column.

run_value float

Run value of the column at the point.

ref_value float

Reference value of the column interpolated to the point.

tolerance float

The configured tolerance that was exceeded.

message

message()

Return the one-line report of the early stop.

StopRequest dataclass

A request from a monitor to stop a running case.

Attributes:

Name Type Description
status str

Run status to report: "timeout" for a step bound (an inconclusive budget cut-off, DECISIONS #59) or "diverged" for an early divergence stop.

message str

Report line for the case table.

EarlyStopMonitor dataclass

Polling hook that applies the step bound and the divergence check.

Attributes:

Name Type Description
spec CaseManifestEntry

Manifest entry of the case.

ref HistoryTable | None

Augmented reference table, or None when the divergence check does not apply to this case.

step_limit int | None

Stop once the run's last model_number reaches this value, or None for no step bound.

step_message str

Report line used when the step bound stops the case.

excess_limit int | None

Stop once the run's last model_number exceeds this (MESA's step count of the stage plus a margin), or None.

mesa_stage_steps int

MESA's step count of that stage, for the report.

__call__

__call__(path)

Check the partial history at path (see class docstring).

find_early_divergence

find_early_divergence(ref, run, spec)

Return the first point of a partial run that is out of tolerance.

Parameters:

Name Type Description Default
ref HistoryTable

Reference table (augmented as for the final comparison), arrays of shape (n_ref,).

required
run HistoryTable

Partial run table, arrays of shape (n_run,). Its last row may be an incomplete step; it is never used to decide.

required
spec CaseManifestEntry

Case manifest entry giving independent_var and track_tolerances.

required

Returns:

Type Description
EarlyDivergence | None

The earliest failing point over all tracked columns, or None

EarlyDivergence | None

when no complete point of the partial run is out of tolerance, or

EarlyDivergence | None

when the comparison cannot be decided yet (too few rows, a missing

EarlyDivergence | None

coordinate, or a reference of zero span).

read_partial_history

read_partial_history(path)

Load the complete lines of a history file that is still being written.

Parameters:

Name Type Description Default
path Path

Path of the history file of a running case.

required

Returns:

Type Description
HistoryTable | None

The table of the complete rows, or None when the file cannot be

HistoryTable | None

read or has no complete data row yet.

single_stage_star_case

single_stage_star_case(case_dir)

Return whether case_dir runs exactly one stage under the harness.

A case with several stages writes a history for each; the history that the final comparison sees is the last one, so a partial history of an earlier stage says nothing about the verdict.

Parameters:

Name Type Description Default
case_dir Path

Upstream star test-suite case directory.

required

Returns:

Type Description
bool

True when the rn script runs exactly one do_one stage with

bool

the optional inlists skipped, as the harness runs it (file copies

bool

between stages do not write a history).

build_monitor

build_monitor(
    spec,
    case_dir,
    *,
    early_stop,
    mesa_steps,
    step_factor,
    root_dir=None,
    stop_on_excess_steps=False,
    mesa_stage_steps=(),
    margin_abs=5,
    margin_frac=0.02,
)

Build the polling hook of one case, or None when none applies.

The divergence check is enabled only for single-stage star cases with a MESA 26.4.1 history reference and no per-track reference; every other case runs without it.

Parameters:

Name Type Description Default
spec CaseManifestEntry

Manifest entry of the case.

required
case_dir Path

Upstream case directory.

required
early_stop bool

Enable the divergence check.

required
mesa_steps int | None

Step count of the MESA reference run, for the step bound.

required
step_factor float | None

Stop at step_factor * mesa_steps steps, or None.

required
root_dir Path | None

Manifest directory against which reference paths resolve.

None
stop_on_excess_steps bool

Stop a single-stage star case that passes MESA's step count of its stage by more than the margin.

False
mesa_stage_steps tuple[int, ...]

MESA's per-stage step counts (the last stage is the one a single-stage case runs).

()
margin_abs int

Smallest margin of the excess-step stop, in steps.

5
margin_frac float

Margin as a fraction of MESA's step count.

0.02

Returns:

Type Description
EarlyStopMonitor | None

The monitor, or None when neither check applies to the case.

flexmesa.testing.stage_steps

Per-stage step counts of MESA 26.4.1 and FlexMESA, and their difference.

A faithful port takes the same steps as MESA, stage by stage, so the step count of each stage is a fidelity signal in its own right (``DECISIONS

69``). MESA prints, at the end of every stage, the model number reached

(runtime (minutes), retries, steps). For a stage that starts at model 0 that is the number of steps; for a stage that continues a loaded model it includes the earlier models. FlexMESA reports the model number at the end of each stage the same way, so the two are compared directly.

The MESA counts are read from benchmarks/history_harness/mesa_stage_steps.json, written by scripts/mesa_reference/extract_stage_steps.py from the stored real-MESA runs. The harness runs a case with its optional stages skipped, so FlexMESA may report fewer stages than a full MESA run; the stages are aligned from the end.

StageDelta dataclass

Step counts of one aligned stage.

Attributes:

Name Type Description
stage int

1-based stage index in FlexMESA's run.

run int

FlexMESA's model number at the end of the stage.

mesa int | None

MESA's model number at the end of the stage, or None when MESA reports no such stage.

delta property

delta

Return run - mesa, or None when MESA has no such stage.

load_mesa_stage_steps

load_mesa_stage_steps(path=None)

Read the MESA per-stage step counts.

Parameters:

Name Type Description Default
path Path | None

Optional path of mesa_stage_steps.json (default: the committed file).

None

Returns:

Type Description
dict[tuple[str, str], tuple[int, ...]]

{(suite, case): stage steps}; empty when the file is absent.

stage_retries_taken

stage_retries_taken(retries, continued)

Return the retries MESA took within each stage.

MESA prints num_retries at the end of each stage. A stage that does not reset the counter (set_initial_number_retries = .false., star/job/run_star_support.f90:2009-2012) starts from the count saved in the model it loads (star/private/read_model.f90:280-288), which is the previous stage's final count, so its own retries are the difference.

Parameters:

Name Type Description Default
retries tuple[int, ...]

num_retries at the end of each stage.

required
continued tuple[bool, ...]

Whether each stage carried on the previous stage's count (False for the first stage).

required

Returns:

Type Description
int

One value per stage: retries[k] - retries[k - 1] for a continued

...

stage k >= 1, else retries[k].

Raises:

Type Description
ValueError

The two tuples differ in length, or the first stage is marked continued.

load_mesa_stage_retries

load_mesa_stage_retries(path=None)

Read the retries MESA took within each stage.

The table records num_retries at the end of each stage and whether each stage carried on the previous stage's count (stage_retries_continued); :func:stage_retries_taken turns the two into per-stage retries, so their sum counts each retry once. A row without the flags is read as resetting at every stage.

Parameters:

Name Type Description Default
path Path | None

Optional path of mesa_stage_steps.json (default: the committed file).

None

Returns:

Type Description
dict[tuple[str, str], tuple[int, ...]]

{(suite, case): retries taken per stage} for cases that list one

dict[tuple[str, str], tuple[int, ...]]

value per stage; empty when the file is absent.

stage_deltas

stage_deltas(run, mesa)

Align FlexMESA's stages with MESA's from the end and pair them.

Parameters:

Name Type Description Default
run tuple[int, ...]

FlexMESA's model number at the end of each stage.

required
mesa tuple[int, ...]

MESA's model number at the end of each stage.

required

Returns:

Type Description
StageDelta

One pair per FlexMESA stage. A run with more stages than MESA gets

...

mesa=None for the extra leading stages.

step_bound

step_bound(mesa_steps, margin_abs, margin_frac)

Return the largest stage step count tolerated before a stop.

Parameters:

Name Type Description Default
mesa_steps int

MESA's model number at the end of the stage.

required
margin_abs int

Smallest margin, in steps.

required
margin_frac float

Margin as a fraction of mesa_steps.

required

Returns:

Type Description
int

mesa_steps + max(margin_abs, ceil(margin_frac * mesa_steps)).

mesa_case_steps

mesa_case_steps(testhub_row, stage_steps)

Return the number of steps MESA 26.4.1 took over a whole case.

The count comes from MESA's own testhub.yml counters (mesa_testhub_26_4_1.json): the steps (total_steps_finished) of each inlist, summed over the inlists. Where MESA wrote several blocks under one inlist line (one per astero search track, whose steps keep counting, or a multi-star run's trailing copy) the largest block counts. A case whose testhub file has no counters but whose single stage ended at a known model number (star/custom_colors, a run from model 0) uses that model number.

Parameters:

Name Type Description Default
testhub_row Mapping[str, Any] | None

The case's row of mesa_testhub_26_4_1.json, or None.

required
stage_steps tuple[int, ...]

MESA's end-of-stage model numbers.

required

Returns:

Type Description
int | None

The step count, or None when MESA has none for the case.

load_mesa_case_steps

load_mesa_case_steps(path=None)

Return :func:mesa_case_steps for every case that has a count.

Parameters:

Name Type Description Default
path Path | None

Optional path of mesa_testhub_26_4_1.json (default: the committed file).

None

Returns:

Type Description
dict[tuple[str, str], int]

{(suite, case): steps}; empty when the file is absent.

step_cap

step_cap(mesa_steps, factor)

Return the step count past which a run counts as a step overrun.

The harness counts the steps of the history a case is writing now, as its newest model number minus its first plus one, so a stage that starts from a loaded model with a high model number is not credited with the models before it. Which stage is running is not known while the case runs, so the cap is ceil(factor * S) with S MESA's steps over the whole case (:func:mesa_case_steps); for a case with several stages it is therefore more lenient than a per-stage cap, never stricter (DECISIONS #90).

Parameters:

Name Type Description Default
mesa_steps int | None

MESA's step count of the case, or None.

required
factor float

Multiple of S allowed, greater than 1.

required

Returns:

Type Description
int | None

The cap, or None when MESA has no step count for the case.

Raises:

Type Description
ValueError

If factor is not greater than 1.

flexmesa.testing.port_manifest

Port manifest schema, loader, serializer, and CI validator (#174).

Every upstream source file in MESA release 26.4.1 (plus bundled GYRE, ADIPLS, STELLA, and pgstar/pgbinary plotting) has one entry recording its exact upstream line count, SHA-256 digest, implementing FlexMESA files, status tier, public-routine mapping, and verification evidence links.

PortStatus

Bases: StrEnum

Ordered port and verification status tiers for an upstream file.

rank property

rank

Integer promotion rank (0 = absent .. 5 = case).

is_ported property

is_ported

Whether status is at least ported_unverified.

is_verified property

is_verified

Whether status is backed by committed MESA 26.4.1 evidence.

label property

label

Human-readable dashboard label for this status.

PortManifestEntry dataclass

Single upstream MESA 26.4.1 source-file port record.

Attributes:

Name Type Description
upstream_path str

Relative POSIX path inside MESA 26.4.1.

module str

Canonical dashboard module name in MODULE_ORDER.

upstream_lines int

Exact line count in MESA 26.4.1.

upstream_sha256 str

Lowercase hexadecimal SHA-256 of the upstream file.

status PortStatus

Port and verification status tier.

flexmesa_files tuple[str, ...]

Implementing repository-relative source paths.

routine_map tuple[tuple[str, str], ...]

Mapping from upstream public Fortran routine name to <flexmesa_file>::<symbol>[+<symbol>...].

routine_map_partial tuple[str, ...]

routine_map keys whose Rust counterpart is known to implement only part of the upstream routine.

evidence_artifacts tuple[str, ...]

Committed generated reference/comparison artifacts.

evidence_tests tuple[str, ...]

Test files exercising evidence_artifacts.

harness_cases tuple[str, ...]

Passing <suite>/<case> IDs for case-level evidence.

notes str

Provenance note (e.g. coverage-map.md or audit finding ID).

routine_dict

routine_dict()

Return routine_map as a dictionary.

PortManifest dataclass

Complete upstream MESA 26.4.1 port manifest.

Attributes:

Name Type Description
schema_version int

Manifest schema version integer.

upstream_version str

Pinned MESA release string (r26.4.1).

upstream_commit str

Pinned MESA git commit hash.

archive_md5 str

MD5 checksum of mesa-26.04.1.zip.

entries tuple[PortManifestEntry, ...]

Tuple of per-file PortManifestEntry records.

by_upstream_path

by_upstream_path()

Index entries by upstream_path.

parse_port_manifest_text

parse_port_manifest_text(text, source_name='<memory>')

Parse port_manifest.toml TOML text into a PortManifest.

Parameters:

Name Type Description Default
text str

UTF-8 TOML text of a port manifest.

required
source_name str

Label included in validation error messages.

'<memory>'

Returns:

Type Description
PortManifest

Parsed PortManifest instance.

Raises:

Type Description
ValueError

If required schema fields or status values are invalid.

load_port_manifest

load_port_manifest(path)

Load and parse port_manifest.toml from path.

Parameters:

Name Type Description Default
path Path

Path to a TOML port manifest file.

required

Returns:

Type Description
PortManifest

Parsed PortManifest instance.

dump_port_manifest

dump_port_manifest(manifest)

Serialize manifest into deterministic canonical TOML text.

Parameters:

Name Type Description Default
manifest PortManifest

PortManifest instance to format.

required

Returns:

Type Description
str

Canonical UTF-8 TOML string.

verify_port_manifest

verify_port_manifest(
    manifest,
    repo_root,
    mesa_dir=None,
    baseline_harness_json=None,
    base_manifest=None,
    changed_paths=None,
)

Validate manifest schema, line counts, routines, evidence, and diffs.

Parameters:

Name Type Description Default
manifest PortManifest

Loaded PortManifest under check.

required
repo_root Path

Repository checkout root directory.

required
mesa_dir Path | None

Optional MESA 26.4.1 source/test-inputs directory for live line-count, SHA-256, and Fortran public-routine verification.

None
baseline_harness_json Path | None

Optional path to baseline_run_26_4_1.json used to verify case_level_evidence passing cases.

None
base_manifest PortManifest | None

Optional base-branch PortManifest for PR promotion and upstream-digest immutability checks.

None
changed_paths frozenset[str] | None

Repository-relative paths changed in base...HEAD.

None

Returns:

Type Description
list[str]

List of human-readable validation error strings (empty when valid).

flexmesa.testing.dashboard

Progress dashboard generator, freshness gate, and CLI (#174).

Orchestrates collection across benchmarks/dashboard/port_manifest.toml, repository source counts, benchmarks/history_harness/, control defaults, cargo llvm-cov and pytest --cov summaries, #[ignore]/xfail annotations, GitHub issue/PR snapshots, and merge history, and renders the marked blocks in README.md, docs/benchmarks/progress-dashboard.md, docs/index.md, and benchmarks/dashboard/dashboard.json.

load_history_tsv

load_history_tsv(history_path)

Read merge-by-merge headline rows from history.tsv.

Parameters:

Name Type Description Default
history_path Path

Path to benchmarks/dashboard/history.tsv.

required

Returns:

Type Description
list[dict[str, str]]

Ordered list of row dictionaries keyed by HISTORY_HEADER columns.

build_dashboard_data

build_dashboard_data(
    repo_root, mesa_dir=None, manifest=None
)

Assemble the complete dashboard data dictionary from repository files.

Parameters:

Name Type Description Default
repo_root Path

Root directory of the FlexMESA repository checkout.

required
mesa_dir Path | None

Optional MESA 26.4.1 mesa_test_inputs directory.

None
manifest PortManifest | None

Optional pre-loaded PortManifest instance.

None

Returns:

Type Description
dict[str, Any]

JSON-serializable dictionary backing all Markdown and JSON outputs.

render_expected_files

render_expected_files(repo_root, mesa_dir=None, data=None)

Compute the expected UTF-8 contents of all four dashboard target files.

Parameters:

Name Type Description Default
repo_root Path

Repository checkout root directory.

required
mesa_dir Path | None

Optional MESA 26.4.1 mesa_test_inputs directory.

None
data dict[str, Any] | None

Optional pre-computed build_dashboard_data dictionary.

None

Returns:

Type Description
dict[Path, str]

Mapping from target pathlib.Path to expected file contents.

verify_all_dashboard_invariants

verify_all_dashboard_invariants(
    repo_root,
    mesa_dir=None,
    base_ref=None,
    check_outputs=True,
)

Run manifest, skip-link, and byte-exact freshness checks.

Parameters:

Name Type Description Default
repo_root Path

Repository checkout root directory.

required
mesa_dir Path | None

Optional MESA 26.4.1 mesa_test_inputs directory.

None
base_ref str | None

Optional git base ref (e.g. origin/main) for PR status promotion checks.

None
check_outputs bool

When False, the dashboard is still rendered, so a rendering failure is reported, but the rendered text is not compared with the committed files. Pull requests use this: main regenerates the files after each merge (DECISIONS #47).

True

Returns:

Type Description
list[str]

List of validation error messages (empty when all checks pass).

record_history_entry

record_history_entry(
    repo_root, mesa_dir, date_utc, commit_short, event_label
)

Append or update one merge headline line in history.tsv.

Parameters:

Name Type Description Default
repo_root Path

Repository checkout root directory.

required
mesa_dir Path | None

Optional MESA 26.4.1 mesa_test_inputs directory.

required
date_utc str

ISO date YYYY-MM-DD in UTC.

required
commit_short str

Short git commit SHA.

required
event_label str

Short merge event label (e.g. PR #200 (#174)).

required

dashboard_main

dashboard_main(argv=None)

CLI entry point for flexmesa dashboard subcommands.

Parameters:

Name Type Description Default
argv list[str] | None

Optional list of CLI arguments following dashboard.

None

Returns:

Type Description
int

Process exit code (0 on success, 1 on check failure).

flexmesa.testing.trace_cli

Command-line interface for flexmesa trace and flexmesa harness.

trace_main

trace_main(argv=None)

Execute flexmesa trace star|binary|astero <case>.

Parameters:

Name Type Description Default
argv list[str] | None

CLI arguments following flexmesa trace.

None

Returns:

Type Description
int

Exit status (0 on success, 1 on run failure/timeout/OOM; with

int

--compare, 2 when the step dumps differ). bisect as the

int

first argument runs :func:flexmesa.testing.trace_bisect.main.

gate_status

gate_status(
    summary,
    *,
    has_regressions,
    has_problems,
    stale_gap_status=1,
)

Return the gate's exit status for one run or merged campaign.

The nightly campaign reports a run whose only finding is improvement (declared gaps that now pass) with its own status, so it asks for a rebaseline instead of raising the regression alert (DECISIONS #81). Undeclared failures, regressions against the baseline and incomplete shard sets are always status 1.

Parameters:

Name Type Description Default
summary Mapping[str, Any]

The report payload's summary block.

required
has_regressions bool

Whether any case regressed against the baseline.

required
has_problems bool

Whether the shard reports are not one campaign.

required
stale_gap_status int

Status for a stale-gaps-only result.

1

Returns:

Type Description
int

0 (clean), stale_gap_status or 1.

harness_main

harness_main(argv=None)

Execute flexmesa harness table|run|merge.

Parameters:

Name Type Description Default
argv list[str] | None

CLI arguments following flexmesa harness.

None

Returns:

Type Description
int

Exit status (0 on success, 1 on check mismatch or gate failure).

flexmesa.testing.stepdump_compare compares a FlexMESA step dump with a MESA 26.4.1 step dump record by record for both the Henyey solver (star_solver, #372) and the nonlinear radial pulsation solver (RSP HYD, covering RSPAUX, RSP_TRY, RSP_RESID, RSP_SOLVE, and RSP_CORR, #963), and reports the first difference: the step, solver record, zone and variable, with its ULP distance (flexmesa trace <suite> <case> --compare <dump>).

flexmesa.testing.stepdump_compare

First-divergence comparison of MESA and FlexMESA step dumps (#372).

Both sides write the record layout of benchmarks/fortran_mesa/stepdumps/stepdump_patch.py: per star, the solver records of the first few models (CALL, CORR, NEWTON, FOLD, TRY, RESID for star_solver, and CALL, RSP_TRY, RSP_RESID, RSP_SOLVE, RSP_CORR for RSP #963) and, at the first solver call of each model, the per-zone state (STATE), cell mass (DM), auxiliary fields (AUX or RSPAUX), and residuals (EQU). Values are IEEE-754 binary64 bit patterns in hexadecimal, so equality here is bitwise.

Models are aligned per star by order of appearance, not by model number, so that an offset in model numbering (#359) does not hide every later difference; both model numbers are reported. Within a model the solver records are compared in order. The first record whose type differs marks a change of control flow (for example a retry on one side only); the first record whose values differ marks a numerical divergence.

Record dataclass

One parsed record.

Attributes:

Name Type Description
tag str

Record type.

star int

Star id (MESA s% id).

model int

Model number as written.

ints tuple[int, ...]

Leading integer fields (iteration counters or zone).

bits tuple[int, ...]

IEEE-754 bit patterns of the values.

tail tuple[int, ...]

Trailing integer fields (argmax zone and index, 1-based).

ModelBlock dataclass

Records of one model of one star, in file order.

Attributes:

Name Type Description
model int

Model number as written.

solver list[Record]

Solver records in order.

zones dict[tuple[str, int], tuple[int, ...]]

(tag, zone) -> bits for STATE, DM and EQU.

StepDump dataclass

A parsed step dump.

Attributes:

Name Type Description
header list[str]

# lines without the leading #.

names dict[int, list[str]]

Star id -> solver variable names (hydro then species).

eqnames dict[int, list[str]]

Star id -> equation names.

nvar_hydro dict[int, int]

Star id -> hydro variables per zone.

blocks dict[int, list[ModelBlock]]

Star id -> model blocks in order of appearance.

skipped dict[str, int]

Record type -> count of lines of a type this parser does not know (diagnostic records added by a patched solver, for example). They are left out of every comparison.

Divergence dataclass

The first difference between two dumps.

Attributes:

Name Type Description
star int

Star id.

model_index int

0-based position of the model in the star's sequence.

mesa_model int

MESA's model number.

flex_model int

FlexMESA's model number.

kind str

"control" (record types differ), "value", "location" (argmax zone or index differs), "zone" (STATE/EQU differ) or "missing" (one side ends).

record str

Record type, or STATE/EQU.

position int | None

0-based position among the model's solver records.

zone int | None

1-based zone for zone records, else None.

field str

Name of the differing field or column.

mesa str

MESA's value (or record type for "control").

flex str

FlexMESA's value.

ulps int | None

ULP distance for a value difference, else None.

ColumnSummary dataclass

Per-column difference count of one zone record type in one model.

Attributes:

Name Type Description
record str

STATE or EQU.

column str

Column name.

n_diff int

Zones whose bits differ.

first_zone int

First differing zone (1-based).

max_rel float

Largest relative difference.

bits_to_float

bits_to_float(bits)

Returns the binary64 value of a 64-bit pattern.

ulp_distance

ulp_distance(a, b)

Returns the number of representable doubles between two patterns.

Parameters:

Name Type Description Default
a int

First bit pattern.

required
b int

Second bit pattern.

required

Returns:

Type Description
int

The distance on the ordered integer line of IEEE-754 doubles.

parse_record

parse_record(line)

Parses one record line.

Parameters:

Name Type Description Default
line str

A solver or zone record.

required

Returns:

Type Description
Record

The record.

Raises:

Type Description
ValueError

If the line does not match its record layout.

parse_dump

parse_dump(text)

Parses a step dump.

Parameters:

Name Type Description Default
text str

Contents of a .stepdump file.

required

Returns:

Type Description
StepDump

The parsed dump.

compare_zones

compare_zones(mesa, flex, star, index)

Summarises STATE and EQU differences of one model.

Parameters:

Name Type Description Default
mesa StepDump

MESA dump.

required
flex StepDump

FlexMESA dump.

required
star int

Star id.

required
index int

0-based model position.

required

Returns:

Type Description
list[ColumnSummary]

One summary per column with at least one differing zone.

first_divergence

first_divergence(mesa, flex, ignore=frozenset())

Returns the first difference between two dumps, or None.

Within each model, the zone records (the state at the first solver call) are checked before the solver records, since they come first in the step.

Parameters:

Name Type Description Default
mesa StepDump

MESA dump.

required
flex StepDump

FlexMESA dump.

required
ignore frozenset[str]

Record types (EQU, DM, TRY, ...), column names (h1, lnd, ...) or xa (every species column) left out of the comparison, so that a known difference does not hide the next one.

frozenset()

Returns:

Type Description
Divergence | None

The first divergence in star, model, then record order.

format_report

format_report(mesa, flex, div)

Returns a human-readable report of a comparison.

Parameters:

Name Type Description Default
mesa StepDump

MESA dump.

required
flex StepDump

FlexMESA dump.

required
div Divergence | None

Result of :func:first_divergence.

required

Returns:

Type Description
str

The report text.

compare_files

compare_files(mesa_path, flex_path, ignore=frozenset())

Compares two dump files.

Parameters:

Name Type Description Default
mesa_path Path

MESA .stepdump file.

required
flex_path Path

FlexMESA dump file.

required
ignore frozenset[str]

See :func:first_divergence.

frozenset()

Returns:

Type Description
str

The report text and the first divergence (None when the records

Divergence | None

are bit-identical).

flexmesa.testing.phase_tap_compare parses and compares structured FLEXMESA_PHASE_TAP captures from stellar relaxations, standard remeshing, and split-merge AMR against a matching MESA 26.4.1 overlay (phase_tap_patch.py), aligning stage sequences and checking scalar and array digest bit patterns. Exit codes distinguish full bit-identical streams (0), --prefix-only matches (3, prefix_identical), value or digest mismatches (2), and I/O or CLI errors (1). Fortran emits REMESH_ENTER before planning (including planner error paths), whereas Rust emits REMESH_ENTER after planning succeeds; XOR digests summarize active arrays without localizing individual zones and can collide, and solver iterations, error paths without *_EXIT, intermediate state between taps, and unhashed solver/microphysics caches are outside tap visibility.

flexmesa.testing.phase_tap_compare

Parser and bitwise comparator for FlexMESA and MESA 26.4.1 phase taps.

Reads FLEXMESA_PHASE_TAP records from phase_tap.rs and the matching MESA 26.4.1 overlay (stepdumps/phase_tap_patch.py), aligns events in sequence order per RUN stage and star, and reports the first structural, integer, digest, or scalar IEEE-754 bitwise difference.

PhaseTapRecord dataclass

One parsed phase-tap record from FlexMESA or a MESA overlay.

TapDivergence dataclass

First differing record or field between reference and run phase taps.

PhaseTapComparison dataclass

Summary of comparing two phase-tap streams.

parse_phase_tap_text

parse_phase_tap_text(text)

Parse phase-tap records from text.

parse_phase_tap

parse_phase_tap(source)

Parse phase-tap records from a file path or raw text.

compare_phase_taps

compare_phase_taps(
    ref,
    run,
    *,
    phases=None,
    ignore_fields=None,
    allow_signed_zero=False,
    prefix_only=False,
)

Compare two phase-tap streams event by event in IEEE-754 hex.

When prefix_only is True and the leading prefix matches, returns status="prefix_identical" with identical=False so partial traces are distinguished from full bit-identical runs.

comparison_to_dict

comparison_to_dict(cmp)

Serialize a :class:PhaseTapComparison into JSON-safe primitives.

format_report

format_report(cmp)

Format a human-readable phase-tap comparison report.

main

main(argv=None)

CLI entry point for comparing two .phasetap files.

Returns 0 on full bit-identical streams, 3 (EXIT_PARTIAL_IDENTICAL) when --prefix-only matches, 2 on any value, digest, count, or identity mismatch, and 1 on I/O, parse, or argument errors.

flexmesa.testing.trace_bisect finds the first model whose step dump differs from MESA's below the harness's first diverging history row, comparing windows of step dumps and making at most the MESA windows the dumps on disk do not cover (flexmesa trace bisect <suite>/<case> --work-dir <dir>).

flexmesa.testing.trace_bisect

flexmesa trace bisect: the first model whose step dump differs.

The history harness reports the first model at which a tracked history column leaves its tolerance (first_diverging_step). The step dumps (benchmarks/fortran_mesa/stepdumps) hold the solver records of a window of models bit for bit, and the first bit-level difference usually comes many models earlier. This module narrows the interval between the last model known to agree and the first model known (or, from the harness, assumed) to differ:

  1. The upper bound is the harness's first diverging model D plus one (the history row of model D is written after its step, so a difference in the timestep it chooses first appears in the dt of model D + 1).
  2. MESA dumps already on disk are probed first, nearest the middle of the interval first: the start-of-run dump of the mesa_stepdumps bundle, the windows of the mesa_stepdump_windows bundle, and the windows an earlier bisect wrote to its work directory. Each probe runs FlexMESA with flexmesa trace --compare over the same window.
  3. When no dump on disk falls in the interval, one MESA window is made: a window covering the whole interval when it holds at most max_window models (one MESA run gives the answer), else a short window at its midpoint.

A probe whose window agrees moves the lower bound to its last model. A probe that differs moves the upper bound to the first differing model, and the lower bound to the model before it when an earlier model of the same window agrees. The search ends when the two bounds are adjacent, or the differing model is the first model of the run. It assumes a difference, once present, persists into later models (a later window cannot agree after an earlier one differed); a difference that disappears again is reported where it was found, not necessarily where it began. For a binary the first differing model is the earliest over both stars.

Windows open at the first crossing of their first model, which is exact only while a stage's model numbers never restart. A case whose numbering restarts in-process (a relax phase, then the evolve phase) is refused: FlexMESA's dump records each drop as a RESTART record, the harness run (or one scan run) carries a dump that records them for the whole run, and a drop inside any window's dump also refuses. A FlexMESA run that was stopped or failed (timeout, memory limit, worker error) ends the bisect without recording that window; a run the engine ended early compares as a missing model.

Every command is printed before it runs. The work directory keeps the harness report, the MESA windows, the FlexMESA dumps and a state.json of finished probes, so an interrupted or stopped bisect resumes where it left off, and the same inputs probe the same windows in the same order.

Bounds dataclass

The bisection interval.

Attributes:

Name Type Description
lo int

Last model known to agree (run_first - 1 or 0 at the start).

hi int

First model known or assumed to differ.

hi_probe Probe | None

The probe that showed the difference at hi, or None while hi is the harness's bound.

run_first int | None

First model of the run, when a start-of-run dump says.

found

found()

Returns whether the first differing model is pinned down.

update

update(probe)

Narrows the interval with one probe.

Parameters:

Name Type Description Default
probe Probe

A finished probe.

required

Probe dataclass

The outcome of comparing one window.

Attributes:

Name Type Description
window_id str

:attr:Window.window_id.

first int

First MESA model number in the window.

last int

Last MESA model number in the window.

div_model int | None

Model of the first difference (MESA's number, FlexMESA's when MESA has no model there), or None when the window agrees.

div_index int | None

0-based position of that model in the window.

report str

The comparison report.

Window dataclass

A MESA step-dump window of one case.

Attributes:

Name Type Description
first_model int | None

FLEXMESA_STEPDUMP_FIRST, or None for a dump of the first models of the run.

steps int

Models per star.

stage int

1-based stage (./rn process that reaches the solver).

occurrence int

Crossing of first_model that opens the window.

path Path | None

The MESA dump, or None for a window not made yet.

source str

Where the dump comes from (bundle name or work).

window_id property

window_id

Returns s<stage>_k<occurrence>_m<first>_n<steps>.

The start-of-run window has m0.

BisectStop

Bases: Exception

Ends a bisect early with an exit status and a message.

Attributes:

Name Type Description
code

Exit status.

message

Printed reason.

Bisect dataclass

One bisect of one case, with its work directory.

Attributes:

Name Type Description
suite str

Suite of the case.

case str

Case name.

stage int

Stage to bisect. Windows open at the first crossing of their first model, which is exact only without in-process restarts; a case with restarts is refused (see :meth:probe).

work Path

Work directory.

flex_cmd list[str]

Command prefix running flexmesa (python -m flexmesa.cli); trace and harness arguments are added.

flex_env dict[str, str]

Environment additions for FlexMESA (PYTHONPATH).

trace_args list[str]

Extra flexmesa trace arguments.

run_prefix list[str]

Command prefix for the harness and trace runs (a scheduler wrapper).

assume_no_restarts bool

Skip the whole-run restart scan and accept FlexMESA dumps without the # restarts: recorded header (a build from before RESTART records), trusting that the case has no in-process restarts. RESTART records and drops seen in a window's dumps still refuse the case.

mesa_cmd list[str] | None

Command prefix running run_stepdumps.py with its directory options, or None when MESA windows are not made here (the bisect stops and prints the command).

roots list[tuple[Path, str]]

Directories searched for MESA dumps, besides the work one.

max_window int

See :func:plan_window.

probe_steps int

See :func:plan_window.

ignore frozenset[str]

Record types or columns left out of the comparison.

run Runner

Command runner (prints and runs).

harness_bound

harness_bound(harness_args)

Returns the harness's first diverging model, running it if needed.

Parameters:

Name Type Description Default
harness_args Sequence[str]

Extra flexmesa harness run arguments.

required

Returns:

Type Description
int | None

The model, or None when the harness run failed.

scan_restarts

scan_restarts()

Refuses the case when FlexMESA's run restarts the stage's numbering.

The scan comes from the harness run the bisect made, or else from one flexmesa trace run of the case with the scan on (a full run).

Raises:

Type Description
BisectStop

When the scan run did not finish, the build does not record restarts, or the stage restarts.

mesa_command

mesa_command(w)

Returns the run_stepdumps.py arguments that make window w.

Parameters:

Name Type Description Default
w Window

A planned window.

required

Returns:

Type Description
list[str]

The window arguments, after :attr:mesa_cmd when it is set.

probe

probe(w)

Runs FlexMESA over window w and compares.

Parameters:

Name Type Description Default
w Window

A window with a MESA dump.

required

Returns:

Type Description
Probe

The probe. A FlexMESA run that the engine ended early (a

Probe

termination before the window's last model) compares as a

Probe

missing difference.

Raises:

Type Description
BisectStop

When the run was stopped or failed (timeout, memory limit, worker error: its dump may be cut short and decides nothing), wrote no dump, or the case restarts its model numbers in-process.

check_restarts

check_restarts(path, who, flex_side=False)

Refuses a case whose model numbers restart in-process.

A window opens at the first crossing of its first model; with a restart (a relax phase, then the evolve phase) that crossing can lie in another phase than the harness compares, so the bisect does not handle such cases.

Parameters:

Name Type Description Default
path Path

A step dump.

required
who str

MESA or FlexMESA, for the message.

required
flex_side bool

The dump is FlexMESA's, which records every restart of the stage (RESTART) before and inside the window.

False

Raises:

Type Description
BisectStop

With :data:EXIT_UNSUPPORTED on a restart, or when a FlexMESA dump does not record restarts and :attr:assume_no_restarts is not set.

bisect

bisect(upper)

Runs the bisection below the harness's first diverging model.

Parameters:

Name Type Description Default
upper int

First model assumed to differ (harness model plus one).

required

Returns:

Type Description
int

data:EXIT_FOUND, :data:EXIT_FAILED,

int

data:EXIT_NEEDS_MESA or :data:EXIT_NO_DIFFERENCE.

trace_status

trace_status(stdout)

Returns the status= field of flexmesa trace's summary line.

Parameters:

Name Type Description Default
stdout str

Output of one flexmesa trace run.

required

Returns:

Type Description
str | None

ok, timeout, oom_killed, error (or another status),

str | None

or None when no summary line was printed.

build_parser

build_parser()

Returns the flexmesa trace bisect argument parser.

main

main(argv)

Runs flexmesa trace bisect.

Parameters:

Name Type Description Default
argv list[str]

Arguments after flexmesa trace bisect.

required

Returns:

Type Description
int

Exit status (see :func:build_parser).

flexmesa.testing.mod_compare compares two MESA or FlexMESA ASCII .mod files at exact file-byte level (byte_identical, exit 0) and IEEE-754 binary64 bit precision (values_bit_identical), reporting value/structural diffs, inline ! computed core values, swapped column orders, and text/formatting differences (text_differences, exit 2; usage/parse/I/O errors exit 1) via flexmesa diff mod <a.mod> <b.mod>.

flexmesa.testing.mod_compare

Bit-for-bit and byte-level comparator for MESA and FlexMESA .mod files.

Promotes and hardens the cell-by-cell modcmp comparison utility into flexmesa.testing:

  • Distinguishes exact file byte equality (byte_identical) from IEEE-754 binary64 value/structure equality (values_bit_identical), reporting formatting-only and metadata differences in text_differences (including file_type description text, standalone and inline ! comments, header key ordering, quoting style, D vs E exponents, 3.77D+02 vs 377 spelling, whitespace, and line endings).
  • Extracts and compares MESA's computed scalar values inside inline ! comments on xmstar, R_center, and L_center header lines (star/private/write_model.f90:131-149).
  • Parses file_type bitfields (star/private/read_model.f90:27-43), multi-pair scalar header lines (write_model.f90:170-174), duplicate header keys, arbitrary zone column orderings without assuming a leading lnd column, structural zone mismatches (such as deleted cells or rows leaving n_shells unchanged), and structured previous model blocks.
  • Exit codes follow CLI convention: 0 when byte_identical, 2 when differences are detected (value, structural, or text-only), and 1 on usage, missing-input, parse, or I/O errors.

ModParseError

Bases: ValueError

Parse error for invalid or malformed MESA .mod files.

ModScalar dataclass

Typed scalar value parsed from a .mod header or previous block.

Attributes:

Name Type Description
kind ScalarKind

Value category ("int", "float", or "str").

raw str

Raw trimmed string token (quotes removed for string literals).

int_val int | None

Parsed integer value when kind == "int".

float_val float | None

Parsed IEEE-754 double when kind == "float" (in the header field's own units, such as Msun, yr, s, g, or cm).

bits int | None

Unsigned 64-bit IEEE-754 representation when kind == "float".

str_val str | None

String content when kind == "str".

quoted bool

Whether the original token was quoted in the source file.

quote_char str | None

Enclosing quote character ("'" or '"') if quoted.

raw_token property

raw_token

Exact lexical token text including enclosing quotes if present.

ZoneTable dataclass

Per-zone arrays parsed from a .mod table section.

Attributes:

Name Type Description
columns tuple[str, ...]

Ordered zone column names (for example ("lnd", "lnT", "lnR", "L", "dq", "h1", ...)).

nz int

Number of parsed zone rows stored in each column array.

bits dict[str, NDArray[uint64]]

Mapping from column name to 1D uint64 array of shape (nz,) storing exact IEEE-754 binary64 bit patterns.

values dict[str, NDArray[float64]]

Mapping from column name to 1D float64 array of shape (nz,) in the file's native units (typically CGS).

raw_tokens dict[str, tuple[str, ...]]

Mapping from column name to raw trimmed cell strings of length nz ("<missing>" when a truncated row lacks cells).

declared_nz int | None

Header n_shells value if present, else None.

zone_indices tuple[int, ...]

Parsed 1-based leading zone indices for each row.

structural_issues tuple[str, ...]

Structural anomalies encountered while reading the table (for example nz != declared_nz, gaps in zone numbering, or rows with fewer/more values than len(columns)).

PreviousModel dataclass

Structured previous model block (write_model.f90:218-231).

Attributes:

Name Type Description
properties dict[str, ModScalar]

Scalar key-value pairs inside previous model (such as previous n_shells, previous mass (grams), timestep (seconds), dt_next (seconds)).

property_order tuple[str, ...]

Ordered list of scalar keys as encountered.

duplicate_keys tuple[str, ...]

Any repeated property keys within previous model.

comment_properties dict[str, ModScalar]

Numeric scalars parsed from inline ! comments inside previous model.

inline_comments dict[str, str]

Mapping from property key to inline ! comment text.

comment_lines tuple[str, ...]

Standalone ! comment lines inside the block.

zones ZoneTable | None

Optional prior-step zone table present in archived models, or None when only scalar properties are stored.

trailing_lines tuple[str, ...]

Any unparsed non-blank, non-comment lines following the previous model section.

ModFile dataclass

Complete structured representation of a MESA ASCII .mod file.

Attributes:

Name Type Description
comments tuple[str, ...]

Leading ! comment lines stripped of ! for inspection.

comment_lines tuple[str, ...]

All standalone ! comment lines in the main section before previous model.

file_type int

Integer bitmask header (read_model.f90:27-43).

file_type_description str

Trailing description text on the file_type line.

properties dict[str, ModScalar]

Scalar key-value properties preceding the zone table.

property_order tuple[str, ...]

Ordered scalar keys as encountered in the header.

duplicate_keys tuple[str, ...]

Any scalar keys appearing more than once in the header.

comment_properties dict[str, ModScalar]

Numeric scalars extracted from inline ! comments (such as xmstar core mass, R_center core radius / density, and L_center core luminosity / eps).

inline_comments dict[str, str]

Mapping from header key to raw inline ! text.

zones ZoneTable

Primary stellar structure and composition zone table.

previous PreviousModel | None

Parsed previous model block if present, else None.

trailing_lines tuple[str, ...]

Non-blank, non-comment lines outside previous.

raw_bytes bytes

Exact raw bytes of the file (or UTF-8 encoding in memory).

raw_lines tuple[str, ...]

Lines from splitlines() before comment stripping.

line_ending_style str

Line ending signature ("LF", "CRLF", "mixed", or "none").

ScalarDiff dataclass

Single differing scalar property between two .mod sections.

HeaderDiff dataclass

Comparison summary for two scalar property dictionaries.

ColumnDiffSummary dataclass

Per-column cell difference summary across common zones.

Attributes:

Name Type Description
section str

Section label ("main" or "previous").

column str

Column name in both tables.

n_diff int

Number of differing cells over 1..min(nz_a, nz_b).

signed_zero_matches int

Cells differing only in +0.0 vs -0.0 sign bit that were waived when allow_signed_zero=True.

first_zone int

Earliest 1-based zone index where this column differs.

first_a float

Value in file A at first_zone (file units).

first_b float

Value in file B at first_zone (file units).

first_bits_a int

IEEE-754 uint64 bits of first_a.

first_bits_b int

IEEE-754 uint64 bits of first_b.

first_ulps int | None

Signed-magnitude ULP distance at first_zone, or None when either value is NaN.

max_ulps int | None

Maximum ULP distance among non-NaN differing cells, or None if all diffs involve NaN.

max_abs_diff float | None

Maximum finite absolute difference, or None.

max_rel_diff float | None

Maximum finite relative difference |a - b| / max(|a|, 1e-300), or None.

has_nan bool

True if any differing cell involves NaN.

FirstZoneCellDiff dataclass

Earliest cell diff in row-major (zone, column_order_a) order.

ZoneTableDiff dataclass

Comparison summary between two ZoneTable structures.

PreviousModelDiff dataclass

Comparison summary for optional previous model blocks.

TextDiffEntry dataclass

Single formatting, metadata, or raw-text discrepancy entry.

TextDiffSummary dataclass

Summary of byte-level, formatting, comment, and ordering diffs.

ModComparison dataclass

Byte-level and binary64 bitwise comparison between two .mod files.

bits_to_float

bits_to_float(bits)

Convert an unsigned 64-bit integer to an IEEE-754 float64.

float_to_bits

float_to_bits(value)

Convert a Python float to its IEEE-754 binary64 bit pattern.

ulp_distance

ulp_distance(bits_a, bits_b)

Return signed-magnitude ULP distance between two IEEE-754 bit patterns.

Uses the same signed-magnitude ordering as crates/flexmesa-replay (compare.rs:12-30): +0.0 and -0.0 are 1 ULP apart, while identical bit patterns return 0 and asymmetric NaN pairs return None.

Parameters:

Name Type Description Default
bits_a int

Unsigned 64-bit IEEE-754 representation of the first value.

required
bits_b int

Unsigned 64-bit IEEE-754 representation of the second value.

required

Returns:

Type Description
int | None

Non-negative integer ULP distance, or None if one or both inputs are

int | None

non-identical NaN patterns.

decode_file_type_bits

decode_file_type_bits(file_type)

Decode a MESA .mod file_type bitmask into named flag labels.

Parameters:

Name Type Description Default
file_type int

Integer bitmask from the header line of a .mod file (star/private/read_model.f90:27-43).

required

Returns:

Type Description
str

Ordered tuple of active flag names (with unknown bits formatted as

...

"bit_<k>").

parse_fortran_mod_float

parse_fortran_mod_float(token)

Parse a Fortran or IEEE-754 float literal into (value, uint64_bits).

Supports D/E exponents, Fortran missing-E exponents such as -1.5-102, -0.0, NaN, and Inf.

Parameters:

Name Type Description Default
token str

Scalar numeric token from a MESA .mod file.

required

Returns:

Type Description
float

Tuple (value, bits) where value is the binary64 float and

int

bits is its unsigned 64-bit IEEE-754 integer pattern.

Raises:

Type Description
ModParseError

If token is not a valid floating-point token.

parse_mod

parse_mod(text, *, raw_bytes=None)

Parse a MESA or FlexMESA ASCII .mod file into structured sections.

Mirrors star/private/read_model.f90:240-518 without assuming a leading lnd column name, preserves formatting/comment metadata for byte-exact checks, parses computed scalars inside ! comments on xmstar, R_center, and L_center lines (write_model.f90:131-149), handles multi-pair property lines, detects duplicate header keys, captures structural zone anomalies as data rather than fatal parse errors, and separates previous model metadata from trailing lines.

Parameters:

Name Type Description Default
text str

Full UTF-8 contents of a .mod file.

required
raw_bytes bytes | None

Optional raw byte buffer read from disk (defaults to UTF-8 encoding of text).

None

Returns:

Name Type Description
Structured ModFile

class:ModFile.

Raises:

Type Description
ModParseError

If the file lacks a valid file_type header, lacks a zone column header, has unclosed quotes or unparseable float tokens, or has negative n_shells.

load_mod

load_mod(path)

Load and parse a MESA or FlexMESA .mod file from disk.

Parameters:

Name Type Description Default
path Path | str

Filesystem path to the .mod file.

required

Returns:

Name Type Description
Parsed ModFile

class:ModFile.

Raises:

Type Description
OSError

If the file cannot be read.

UnicodeDecodeError

If the file is not valid UTF-8.

ModParseError

If the file contents cannot be parsed.

compare_mods

compare_mods(
    model_a,
    model_b,
    *,
    allow_signed_zero=False,
    path_a=None,
    path_b=None,
)

Compare two parsed .mod models at byte and binary64 bit precision.

Parameters:

Name Type Description Default
model_a ModFile

First parsed :class:ModFile (conventionally the reference).

required
model_b ModFile

Second parsed :class:ModFile (conventionally the candidate).

required
allow_signed_zero bool

If True, treat -0.0 and +0.0 as equal for values_bit_identical while keeping byte_identical exact.

False
path_a str | None

Optional display path for model A.

None
path_b str | None

Optional display path for model B.

None

Returns:

Name Type Description
Structured ModComparison

class:ModComparison separating byte_identical,

ModComparison

values_bit_identical, and text_differences.

comparison_verdict

comparison_verdict(cmp)

Return canonical verdict string for a :class:ModComparison.

comparison_to_dict

comparison_to_dict(cmp)

Serialize a :class:ModComparison into an RFC-8259-safe dictionary.

format_report

format_report(cmp)

Format a concise human-readable report for a ModComparison.

Parameters:

Name Type Description Default
cmp ModComparison

Comparison result produced by :func:compare_mods.

required

Returns:

Type Description
str

Multi-line human-readable summary ending with a newline.

compare_files

compare_files(path_a, path_b, *, allow_signed_zero=False)

Load, compare, and format a report for two .mod files on disk.

Parameters:

Name Type Description Default
path_a Path | str

Path to the first .mod file.

required
path_b Path | str

Path to the second .mod file.

required
allow_signed_zero bool

Whether -0.0 and +0.0 should be waived in values_bit_identical (tracked in signed_zero_waived_total).

False

Returns:

Type Description
tuple[str, ModComparison]

Tuple (report_text, comparison).

Raises:

Type Description
OSError

If either input file cannot be read.

UnicodeDecodeError

If either file is not valid UTF-8.

ModParseError

If either file violates .mod syntax.

build_parser

build_parser(prog='flexmesa diff mod')

Build the CLI argument parser for flexmesa diff mod.

main

main(argv=None, *, prog='flexmesa diff mod')

Execute the mod_compare CLI entry point.

Parameters:

Name Type Description Default
argv Sequence[str] | None

Argument list excluding the program name (default sys.argv[1:]).

None
prog str

Program label shown in --help and usage messages.

'flexmesa diff mod'

Returns:

Type Description
int

0 when byte_identical, 2 when differences are detected

int

(value, structural, or text-only), and 1 on invalid arguments,

int

missing input, parse failure, or I/O error.

flexmesa.testing.known_gaps_gate

Bijective known-gaps verification gate for tests and skips.

Enforces bidirectional correspondence between code-level suppression markers (Rust #[ignore] and Python @pytest.mark.{xfail,skip,skipif}) and the [[test_gaps]] section of benchmarks/history_harness/known_gaps.toml. Every declared gap must cite an open GitHub issue, and --ignored campaign runs fail if a test passes unexpectedly (stale_known_gap) or fails unexpectedly.

DeclaredTestGap dataclass

Single declared test-suppression record from known_gaps.toml.

Attributes:

Name Type Description
kind GapKind

Marker type (rust_ignore, python_xfail, or python_skip).

file str

Repository-relative POSIX path to the test source file.

test_name str

Function or class name carrying the marker.

issue str

Primary owning open issue tag (#<number>).

crate str | None

Cargo package name for Rust tests, or None for Python.

role GapRole

Functional category (physics_gap, campaign, or benchmark).

expect_fail_when_run bool

Whether passing under cargo test -- --ignored must fail the gate as a stale gap; if False, failing under --ignored triggers an unexpected failure violation.

reason str

Human-readable explanation anchored to open work.

key property

key

Unique (kind, file, test_name) identifier.

DiscoveredMarker dataclass

Test suppression marker extracted from Rust or Python source.

Attributes:

Name Type Description
kind GapKind

Marker type (rust_ignore, python_xfail, or python_skip).

file str

Repository-relative POSIX path to the source file.

line int

1-based source line number of the attribute or decorator.

test_name str

Annotated Rust function or Python function/class name.

issues tuple[str, ...]

Issue tags (#<number>) parsed from the marker metadata.

reason str

Extracted attribute or decorator text.

key property

key

Unique (kind, file, test_name) identifier.

KnownGapsAuditResult dataclass

Outcome summary of the bijective known-gaps verification gate.

only_unexpected_passes property

only_unexpected_passes

Whether the gate's only finding is ignored tests that now pass.

The nightly campaign reports this improvement with its own exit status so that it asks for the ledger to be updated instead of raising the regression alert (DECISIONS #81).

ok property

ok

Whether all bijective, issue, and execution checks pass.

to_dict

to_dict()

Serialize audit findings into a JSON-compatible dictionary.

require_zero_skips_enabled

require_zero_skips_enabled()

Return whether strict non-vacuous zero-skip enforcement is active.

Defaults to True unless FLEXMESA_REQUIRE_ZERO_SKIPS is explicitly set to 0, false, no, or off for local partial runs.

require_upstream_file

require_upstream_file(path, *, label='upstream test input')

Verify an upstream MESA test file exists under zero-skip enforcement.

Parameters:

Name Type Description Default
path Path

Filesystem path expected from MESA_DIR or bundled inputs.

required
label str

Descriptive label included in the assertion message.

'upstream test input'

Returns:

Type Description
bool

True if path exists on disk, or False only when

bool

FLEXMESA_REQUIRE_ZERO_SKIPS is explicitly opted out and MESA_DIR

bool

is unset.

Raises:

Type Description
AssertionError

If path is missing while MESA_DIR is set or zero-skip enforcement is enabled.

require_mesa_test_inputs_dir

require_mesa_test_inputs_dir()

Resolve MESA_DIR or cached mesa_test_inputs without skipping.

Returns:

Type Description
Path | None

Resolved directory containing star/test_suite, or None only

Path | None

when FLEXMESA_REQUIRE_ZERO_SKIPS is explicitly opted out and the

Path | None

directory is absent on disk.

Raises:

Type Description
AssertionError

If star/test_suite is missing while MESA_DIR is set or zero-skip enforcement is enabled.

extract_rust_test_ignores

extract_rust_test_ignores(raw_text, rel_path)

Extract #[ignore] markers and their test function names from Rust.

extract_python_test_markers

extract_python_test_markers(source, rel_path)

Extract @pytest.mark.{xfail,skip,skipif} decorators via AST.

scan_imperative_python_skips

scan_imperative_python_skips(root)

Return file:line for runtime skip, xfail and importorskip calls.

discover_repo_test_markers

discover_repo_test_markers(root)

Scan all Rust crates and Python sources for test suppression markers.

load_declared_test_gaps

load_declared_test_gaps(toml_path)

Parse [[test_gaps]] from known_gaps.toml and validate fields.

Parameters:

Name Type Description Default
toml_path Path

Path to the TOML declaration file.

required

Returns:

Type Description
tuple[list[DeclaredTestGap], list[str]]

Tuple (gaps, duplicate_keys).

Raises:

Type Description
FileNotFoundError

If toml_path does not exist.

ValueError

If any record violates required schema constraints.

load_issue_states

load_issue_states(
    root,
    *,
    extra_issue_numbers=(),
    fetch_github_api=False,
    repo_slug=DEFAULT_REPO_SLUG,
)

Load issue open/closed states from snapshot and optionally GitHub API.

parse_cargo_test_outcomes

parse_cargo_test_outcomes(log_text)

Parse test <name> ... ok|FAILED|ignored lines from Cargo logs.

Returns:

Type Description
dict[str, str]

Mapping from short test function name (stripping module path prefix) to

dict[str, str]

its reported outcome (ok, FAILED, or ignored).

verify_known_gaps_gate

verify_known_gaps_gate(
    root,
    *,
    test_gaps_path=None,
    history_gaps_path=None,
    cargo_ignored_logs=(),
    require_all_rust_ignores_executed=False,
    fail_on_imperative_skips=False,
    fetch_github_api=False,
)

Run bijective, issue-status, and ignored-outcome verification gates.

Parameters:

Name Type Description Default
root Path

Repository root directory.

required
test_gaps_path Path | None

Override TOML path for [[test_gaps]].

None
history_gaps_path Path | None

Override path to known_gaps.toml.

None
cargo_ignored_logs Sequence[Path]

Optional Cargo --ignored output files to enforce unexpected_passes, unexpected_failures, and undeclared runs.

()
require_all_rust_ignores_executed bool

Require every rust_ignore entry to appear with a non-ignored outcome in the Cargo logs.

False
fail_on_imperative_skips bool

Include runtime pytest.skip() sites in the pass/fail evaluation of :attr:KnownGapsAuditResult.ok.

False
fetch_github_api bool

Whether to query GitHub's REST API for live open/ closed verification of every cited issue.

False

Returns:

Name Type Description
Structured KnownGapsAuditResult

class:KnownGapsAuditResult.

render_markdown_summary

render_markdown_summary(result)

Format a Markdown summary of the known-gaps bijective audit.

main

main(argv=None)

CLI entrypoint returning 0 on clean gate pass, 1 on failure.

flexmesa.testing.module_hex_gate

Level-2 IEEE-754 module hex verification gate (mesa_module_hex).

Compares FlexMESA double-precision computations in strict arithmetic mode against upstream MESA 26.4.1 raw_bits_hex captures across module test suites while accounting bijectively for all 26 upstream MESA packages in summary.json against benchmarks/module_hex/known_module_gaps.toml.

DeclaredModuleGap dataclass

Single declared module hex gap from known_module_gaps.toml.

ModuleProbeResult dataclass

Measured IEEE-754 ULP audit outcome for one MESA package.

to_dict

to_dict()

Serialize module probe result to JSON-safe dict.

ModuleHexAuditResult dataclass

Complete Level-2 module-hex gate outcome across all 26 MESA packages.

ok property

ok

Whether all module-hex checks and declarations pass.

to_summary_dict

to_summary_dict()

Build deterministic JSON matching module_hex_summary.json.

resolve_hex_root

resolve_hex_root(explicit_dir=None)

Locate mesa_module_hex directory or fail cleanly when missing.

load_declared_module_gaps

load_declared_module_gaps(toml_path)

Parse known_module_gaps.toml into (by_module, duplicates).

verify_module_hex_gate

verify_module_hex_gate(
    repo_root,
    *,
    hex_dir=None,
    gaps_toml_path=None,
    fetch_github_api=False,
)

Execute Level-2 IEEE-754 bit-exact checks across mesa_module_hex.

render_markdown_summary

render_markdown_summary(result)

Format a Markdown table and violations for the Level-2 hex gate.

main

main(argv=None)

CLI entrypoint returning 0 on clean gate pass, 1 on failure.

flexmesa.testing.test_taxonomy

W4 test-suite classification and per-routine MESA oracle mapping (#563).

Classifies every Rust integration test and Python test file into one of three mutually exclusive categories per DECISIONS #67 and DECISIONS #72:

  • oracle: compares FlexMESA outputs against MESA 26.4.1 reference data (hex dumps, test_output fixtures, Fortran oracle TSVs, MESA 26.4.1 histories, or unmodified *.defaults tables).
  • invariant: checks algebraic properties, conservation laws, AD consistency, error handling, input validation, or Rust-vs-JAX parity.
  • regression: checks against self-generated FlexMESA regression snapshots or determinism without an external MESA oracle.

TestFileRecord dataclass

Single classified test file entry in test_taxonomy.toml.

oracle_routines property

oracle_routines

Routine ids claimed by this record's [[tests.oracles]].

TestTaxonomy dataclass

Parsed test_taxonomy.toml catalog.

by_path

by_path()

Return a mapping from repository-relative path to record.

discover_test_files

discover_test_files(repo_root)

Discover all Rust integration and Python test files deterministically.

Parameters:

Name Type Description Default
repo_root Path

Repository root directory (follows top-level symlinks).

required

Returns:

Type Description
list[str]

Sorted list of POSIX paths relative to repo_root.

count_tests_in_file

count_tests_in_file(path)

Count declared test functions in a Rust or Python test file.

Parameters:

Name Type Description Default
path Path

Absolute path to a .rs or .py test file.

required

Returns:

Type Description
int

Number of test functions found (#[test] or proptest! fns in

int

Rust; top-level and class test_* functions in Python).

detect_inline_test_kind

detect_inline_test_kind(path)

Detect optional file-level taxonomy marker inside a Rust or Python file.

Parameters:

Name Type Description Default
path Path

Path to a test file.

required

Returns:

Type Description
TestKind | None

Pair (kind, error). kind is None if no file-level marker is

str | None

present or on conflict; error describes conflicting markers if any.

file_has_oracle_evidence

file_has_oracle_evidence(path)

Return True when code cites MESA oracle artifacts or hex tables.

validate_oracle_provenance

validate_oracle_provenance(repo_root, rec, full_path)

Validate MESA-origin provenance artifact, existence, and code linkage.

load_test_taxonomy

load_test_taxonomy(path)

Parse test_taxonomy.toml into typed immutable records.

dump_test_taxonomy

dump_test_taxonomy(taxonomy)

Render a TestTaxonomy in deterministic sorted TOML form.

verify_test_taxonomy

verify_test_taxonomy(
    repo_root, taxonomy_path=None, manifest_path=None
)

Verify bijection, provenance, mislabel tracking, and routine symbols.

Parameters:

Name Type Description Default
repo_root Path

Repository root path.

required
taxonomy_path Path | None

Override path to test_taxonomy.toml.

None
manifest_path Path | None

Override path to port_manifest.toml.

None

Returns:

Type Description
list[str]

List of human-readable verification errors (empty when clean).

summarize_test_taxonomy

summarize_test_taxonomy(repo_root, taxonomy, manifest=None)

Compute file-level classification and listed routine oracle counts.

main

main(argv=None)

CLI entry point for W4 test-taxonomy verification and reporting.


Publication-Styled Diagnostic Plotting (flexmesa.plotting)

flexmesa.plotting replaces Fortran MESA's legacy X11/PGPLOT PGSTAR and PGBINARY subsystems with composable, colorblind-safe (Okabe-Ito) Matplotlib figure builders for Hertzsprung-Russell (plot_hr_diagram), \(T_c\) versus \(\rho_c\) (plot_tc_rhoc_diagram), Kippenhahn convective/burning history (plot_kippenhahn), asteroseismic propagation diagrams (plot_propagation_diagram), binary RLOF evolution (plot_binary_evolution), and asteroseismic échelle and separation-ratio diagrams (plot_echelle_diagram, plot_separation_ratios).

flexmesa.plotting.style

Publication matplotlib figure styling for FlexMESA.

Configures AASTeX column and text widths (3.352 in and 7.100 in), Computer Modern serif typography at 9/10/12 pt, inward ticks on all four sides, frameless legends, and colorblind-safe Okabe-Ito semantic palettes.

figsize

figsize(layout='single', aspect=0.78)

Returns publication figure dimensions (width_in, height_in).

Parameters:

Name Type Description Default
layout str

Either "single" (AASTeX column width 3.352 in) or "double" / "wide" (AASTeX text width 7.100 in).

'single'
aspect float

Height-to-width ratio (height / width).

0.78

Returns:

Type Description
tuple[float, float]

Tuple (width_in, height_in) in inches.

mesa_rc_params

mesa_rc_params()

Returns the canonical matplotlib rcParams dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary of matplotlib style parameters.

use_mesa_plot_style

use_mesa_plot_style()

Applies the canonical FlexMESA publication style to mpl.rcParams.

init_ax

init_ax(ax, layout='single', aspect=0.85)

Applies use_mesa_plot_style and returns (fig, ax).

finalize_fig

finalize_fig(fig, ax, save_path=None)

Optionally saves fig at 300 dpi and returns (fig, ax).

flexmesa.plotting.stellar_plots

Stellar structure and evolution diagnostic plots (pgstar replacements).

Provides Hertzsprung-Russell (plot_hr_diagram), central temperature-density (plot_tc_rhoc_diagram), Kippenhahn (plot_kippenhahn), and asteroseismic propagation (plot_propagation_diagram) figures styled to journal standards.

plot_hr_diagram

plot_hr_diagram(
    log_teff,
    log_l,
    *,
    color_val=None,
    color_label="Center Hydrogen Fraction [$X_c$]",
    vmin=None,
    vmax=None,
    ax=None,
    save_path=None,
)

Plots a Hertzsprung-Russell diagram.

Parameters:

Name Type Description Default
log_teff Any

Sequence of \(\log_{10}(T_{\mathrm{eff}} / \mathrm{K})\) ((N_t,)).

required
log_l Any

Sequence of \(\log_{10}(L / L_\odot)\) ((N_t,)).

required
color_val Any | None

Optional scalar sequence ((N_t,)) coloring the track.

None
color_label str

Colorbar label when color_val is provided.

'Center Hydrogen Fraction [$X_c$]'
vmin float | None

Explicit minimum colorbar limit.

None
vmax float | None

Explicit maximum colorbar limit.

None
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

plot_tc_rhoc_diagram

plot_tc_rhoc_diagram(
    log_rhoc,
    log_tc,
    *,
    label="Core Trajectory",
    show_burn_lines=True,
    ax=None,
    save_path=None,
)

Plots the central temperature-density trajectory.

Parameters:

Name Type Description Default
log_rhoc Any

Sequence of \(\log_{10}(\rho_c / \mathrm{g\,cm^{-3}})\) ((N_t,)).

required
log_tc Any

Sequence of \(\log_{10}(T_c / \mathrm{K})\) ((N_t,)).

required
label str

Legend label for the core trajectory.

'Core Trajectory'
show_burn_lines bool

Whether to draw approximate H/He/C ignition thresholds.

True
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

plot_kippenhahn

plot_kippenhahn(
    age_myr,
    mass_grid_msun,
    mix_type_grid,
    eps_nuc_grid=None,
    total_mass_msun=None,
    *,
    vmin=0.0,
    vmax=6.0,
    ax=None,
    save_path=None,
)

Plots a Kippenhahn convective/burning structure diagram.

Parameters:

Name Type Description Default
age_myr Any

Stellar ages ((N_t,)) [Myr].

required
mass_grid_msun Any

Enclosed mass coordinates ((N_m,)) [M_sun].

required
mix_type_grid Any

Mixing type integer grid ((N_m, N_t), 1 = convective).

required
eps_nuc_grid Any | None

Optional nuclear energy generation grid ((N_m, N_t)).

None
total_mass_msun Any | None

Optional total stellar mass curve ((N_t,)) [M_sun].

None
vmin float

Minimum colorbar limit for \(\log_{10} \epsilon_{\mathrm{nuc}}\).

0.0
vmax float

Maximum colorbar limit for \(\log_{10} \epsilon_{\mathrm{nuc}}\).

6.0
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

plot_propagation_diagram

plot_propagation_diagram(
    r_over_rstar,
    brunt_n2,
    csound,
    r_cm,
    *,
    ell_values=(1, 2),
    nu_max_uhz=None,
    ax=None,
    save_path=None,
)

Plots an asteroseismic propagation diagram (\(N/2\pi\) and \(S_l/2\pi\)).

Parameters:

Name Type Description Default
r_over_rstar Any

Normalized radial coordinate \(r / R_*\) ((N,)).

required
brunt_n2 Any

Squared Brunt-Vaisala frequency \(N^2\) ((N,)) [s^-2].

required
csound Any

Adiabatic sound speed \(c_s\) ((N,)) [cm s^-1].

required
r_cm Any

Radial coordinate \(r\) ((N,)) [cm].

required
ell_values tuple[int, ...]

Spherical degrees \(l\) for Lamb frequencies \(S_l\).

(1, 2)
nu_max_uhz float | None

Optional \(\nu_{\max}\) reference line [uHz].

None
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

flexmesa.plotting.astero_binary_plots

Asteroseismic and binary evolution diagnostic plots.

Provides echelle diagrams (plot_echelle_diagram), frequency separation ratio plots (plot_separation_ratios), and binary orbital/RLOF evolution multi-panel plots (plot_binary_evolution).

plot_echelle_diagram

plot_echelle_diagram(
    obs_freqs,
    obs_sigmas,
    delta_nu,
    *,
    model_freqs_uncorr=None,
    model_freqs_corr=None,
    degrees=None,
    ax=None,
    save_path=None,
)

Plots an asteroseismic echelle diagram.

Parameters:

Name Type Description Default
obs_freqs Any

Observed frequencies ((M,)) [uHz].

required
obs_sigmas Any

Observed frequency uncertainties ((M,)) [uHz].

required
delta_nu float

Large frequency separation \(\Delta\nu\) [uHz].

required
model_freqs_uncorr Any | None

Optional uncorrected model frequencies ((M,)) [uHz].

None
model_freqs_corr Any | None

Optional surface-corrected model frequencies ((M,)) [uHz].

None
degrees Any | None

Optional spherical degrees \(l_i \in \{0, 1, 2, 3\}\) ((M,)).

None
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

plot_separation_ratios

plot_separation_ratios(
    freqs_r010,
    r010_obs,
    r010_sigmas,
    r010_model=None,
    *,
    freqs_r02=None,
    r02_obs=None,
    r02_sigmas=None,
    r02_model=None,
    ax=None,
    save_path=None,
)

Plots Roxburgh & Vorontsov (2003) separation ratios (\(r_{010}, r_{02}\)).

Parameters:

Name Type Description Default
freqs_r010 Any

Reference frequencies for \(r_{010}\) ((K,)) [uHz].

required
r010_obs Any

Observed \(r_{010}\) ratios ((K,)).

required
r010_sigmas Any

Observed \(r_{010}\) uncertainties ((K,)).

required
r010_model Any | None

Optional model \(r_{010}\) ratios ((K,)).

None
freqs_r02 Any | None

Optional reference frequencies for \(r_{02}\) ((K_2,)) [uHz].

None
r02_obs Any | None

Optional observed \(r_{02}\) ratios ((K_2,)).

None
r02_sigmas Any | None

Optional observed \(r_{02}\) uncertainties ((K_2,)).

None
r02_model Any | None

Optional model \(r_{02}\) ratios ((K_2,)).

None
ax Any | None

Optional pre-existing matplotlib.axes.Axes.

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, ax) of matplotlib Figure and Axes.

plot_binary_evolution

plot_binary_evolution(
    age_myr,
    period_days,
    lg_mtransfer_rate,
    eccentricity=None,
    *,
    save_path=None,
)

Plots a multi-panel binary orbital and RLOF evolution summary.

Parameters:

Name Type Description Default
age_myr Any

Binary system ages ((N_t,)) [Myr].

required
period_days Any

Orbital periods ((N_t,)) [days].

required
lg_mtransfer_rate Any

Log mass-transfer rate \(\log_{10}(|\dot{M}| / M_\odot\,\mathrm{yr}^{-1})\) ((N_t,)).

required
eccentricity Any | None

Optional orbital eccentricity ((N_t,)).

None
save_path str | None

Optional output path (300 dpi).

None

Returns:

Type Description
tuple[Any, Any]

Tuple (fig, axes) of matplotlib Figure and array of Axes.

flexmesa.plotting.compare

MESA 26.4.1 comparison and radial profile plots built solely from outputs.

Every figure in this module reads stored ASCII outputs (history.data, binary_history.data, and profileN.data) directly via flexmesa.testing and flexmesa._rust. No physics quantities are recomputed or synthesized inside plotting code.

ProfileTable dataclass

Columnar float64 representation of a MESA profileN.data file.

Attributes:

Name Type Description
header dict[str, Any]

Scalar header metadata extracted from lines 2 and 3 (for example model_number, star_age [yr], num_zones, version_number, and math_backend).

columns dict[str, ndarray]

Mapping from canonical column name to a 1D float64 array of shape (num_zones,) in MESA output units.

num_zones int

Number of radial zones stored in the profile table.

load_profile_file

load_profile_file(path)

Load a 6-line-header MESA ASCII profileN.data file.

Parameters:

Name Type Description Default
path Path | str

Filesystem path to profileN.data.

required

Returns:

Type Description
ProfileTable

Populated ProfileTable containing header metadata and 1D

ProfileTable

float64 zone arrays of shape (num_zones,).

Raises:

Type Description
FileNotFoundError

If path does not exist on disk.

ValueError

If the parsed table has zero zones.

resolve_case_entry

resolve_case_entry(case, suite=None, manifest_path=None)

Look up a CaseManifestEntry by case and optional suite.

Supports "<suite>/<case>" notation in case as well as bare case names unique across star, binary, and astero.

Parameters:

Name Type Description Default
case str

Case directory name or "<suite>/<case>" specifier.

required
suite str | None

Optional suite override ("star", "binary", or "astero").

None
manifest_path Path | str | None

Optional override path to case_manifest.toml.

None

Returns:

Type Description
CaseManifestEntry

Matching CaseManifestEntry.

Raises:

Type Description
ValueError

If case does not exist in the manifest or matches more than one suite without disambiguation.

plot_case_comparison

plot_case_comparison(
    case,
    *,
    suite=None,
    flexmesa_history=None,
    flexmesa_dir=None,
    mesa_history=None,
    manifest_path=None,
    save_path=None,
    termination_code="",
    numerics_mode="",
    controls_ignored=False,
    max_steps=None,
    n_controls_ignored=0,
    case_entry=None,
    comparison=None,
)

Overplot a FlexMESA run against a stored MESA 26.4.1 reference history.

Reads solely from stored ASCII tables on disk and evaluates residuals with :func:flexmesa.testing.history_compare.compare_histories. Never computes or synthesizes physics values inside plotting code.

Parameters:

Name Type Description Default
case str

Manifest case name or "<suite>/<case>" identifier.

required
suite str | None

Optional suite name ("star", "binary", or "astero").

None
flexmesa_history Path | str | None

Direct path to FlexMESA history.data or binary_history.data.

None
flexmesa_dir Path | str | None

Output root directory containing FlexMESA LOGS/ or binary_history.data (ignored if flexmesa_history is set).

None
mesa_history Path | str | None

Optional explicit path overriding the manifest's stored MESA reference file.

None
manifest_path Path | str | None

Optional override path to case_manifest.toml.

None
save_path Path | str | None

Optional output path for saving a 300 dpi figure.

None
termination_code str

Optional termination label for title provenance.

''
numerics_mode str

Optional arithmetic mode label ("strict"/"fast").

''
controls_ignored bool

Whether the run skipped unsupported controls.

False
max_steps int | None

Optional per-stage step cap used during a smoke trace.

None
n_controls_ignored int

Number of unsupported controls the run ignored, shown in the diagnostic label when positive.

0
case_entry CaseManifestEntry | None

Optional pre-resolved CaseManifestEntry to avoid re-parsing case_manifest.toml.

None
comparison HistoryComparison | None

Optional precomputed HistoryComparison from a harness run.

None

Returns:

Type Description
tuple[Figure, ndarray]

Tuple (fig, axes) with shape (3, 2) of subplots.

Raises:

Type Description
FileNotFoundError

If the FlexMESA history or MESA reference cannot be located.

ValueError

If the manifest entry is unknown, lacks a stored reference, or cannot be parsed cleanly.

plot_profile_panels

plot_profile_panels(
    profile_path, *, ref_profile_path=None, save_path=None
)

Plot radial structure panels from stored profileN.data output.

Displays mass-fraction abundances, thermodynamic logT / logRho, nuclear burning or luminosity, and log_D_mix shaded by integer mixing_type (convective boundaries), optionally overlaying a stored MESA 26.4.1 reference profile.

Parameters:

Name Type Description Default
profile_path Path | str

Path to FlexMESA profileN.data.

required
ref_profile_path Path | str | None

Optional path to reference MESA profileN.data.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, ndarray]

Tuple (fig, axes) with shape (2, 2).

Raises:

Type Description
FileNotFoundError

If either profile path is missing.

ValueError

If the profile file contains zero rows.

plot_profile_kippenhahn

plot_profile_kippenhahn(
    profile_paths,
    *,
    mass_grid_points=120,
    xaxis="star_age",
    yaxis="mass",
    history_path=None,
    save_path=None,
)

Assemble a Kippenhahn diagram strictly from stored profileN.datas.

Parameters:

Name Type Description Default
profile_paths list[Path | str]

Ordered sequence of at least two stored profileN.data files spanning time.

required
mass_grid_points int

Uniform vertical grid size across yaxis (default 120).

120
xaxis Literal['model_number', 'star_age']

Horizontal coordinate ("star_age" or "model_number").

'star_age'
yaxis Literal['mass', 'q', 'radius']

Vertical coordinate ("mass", "q", or "radius").

'mass'
history_path Path | str | None

Optional history.data providing core mass boundaries.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
Figure

Tuple (fig, ax) produced by

Axes

func:flexmesa.plotting.stellar_plots.plot_kippenhahn or

tuple[Figure, Axes]

func:flexmesa.plotting.kippenhahn.plot_history_kippenhahn.

Raises:

Type Description
ValueError

If fewer than two profiles are given or required columns are absent.

flexmesa.plotting.kippenhahn

Kippenhahn convective, mixing, and burning diagrams (#173).

Ports the static diagnostic content of star/private/pgstar_kipp.f90:59-814 (star/defaults/pgstar.defaults:1200-1327) strictly from saved history.data region columns (mix_type_*, mix_qtop_*, mix_relr_type_*, mix_relr_top_*, burn_type_*, burn_qtop_*, burn_relr_type_*, burn_relr_top_*, core mass boundaries, and luminosities) and/or sequences of profileN.data files.

plot_history_kippenhahn

plot_history_kippenhahn(
    history_path=None,
    *,
    profile_paths=None,
    xaxis="model_number",
    yaxis="mass",
    age_units="auto",
    log_xaxis=False,
    time_from_present=False,
    xaxis_reversed=None,
    show_mixing=True,
    show_burn=True,
    show_mass_boundaries=True,
    show_luminosities=False,
    burn_type_cutoff=0.0,
    mass_grid_points=140,
    ax=None,
    save_path=None,
)

Plot a MESA 26.4.1 Kippenhahn diagram from history or profiles.

Implements do_Kipp_Plot from star/private/pgstar_kipp.f90:59-814 strictly from saved run outputs without computing physics inside plotting code.

Parameters:

Name Type Description Default
history_path Path | str | None

Optional path to history.data providing region columns (mix_type_*, burn_type_*), core mass boundaries, and luminosities.

None
profile_paths Sequence[Path | str] | None

Optional sequence of at least two profileN.data files used to assemble radial mixing and burning grids when history region columns are absent or radial detail is preferred.

None
xaxis Literal['model_number', 'star_age']

Horizontal coordinate ("model_number" default per star/defaults/pgstar.defaults:1226, or "star_age").

'model_number'
yaxis Literal['mass', 'q', 'radius']

Vertical coordinate ("mass" [\(M_r / M_\odot\)], "q" [\(m / M\)], or "radius" [\(R_r / R_\odot\)]).

'mass'
age_units Literal['auto', 'yr', 'Myr']

Age unit when xaxis="star_age" ("auto", "yr", or "Myr").

'auto'
log_xaxis bool

Apply \(\log_{10}|x|\) scaling (pgstar_kipp.f90:193-197).

False
time_from_present bool

Shift star_age to \(t - t_{\mathrm{final}}\) (pgstar_kipp.f90:186-191).

False
xaxis_reversed bool | None

Optional override reversing horizontal axis direction (pgstar.defaults:1232). Defaults to True when xaxis == "star_age", time_from_present=True, and log_xaxis=True so evolution advances left-to-right toward the final model, and False otherwise.

None
show_mixing bool

Render convective, overshoot, semiconvective, thermohaline, and RTI regions (pgstar_kipp.f90:724-796).

True
show_burn bool

Shade nuclear burning and cooling zones (pgstar_kipp.f90:399-512).

True
show_mass_boundaries bool

Draw surface mass/radius and core boundaries (he_core_mass, co_core_mass, c_core_mass, o_core_mass, si_core_mass, fe_core_mass, pgstar_kipp.f90:589-645).

True
show_luminosities bool

Overlay log_L, log_LH, log_LHe, and log_Lneu on a twin right axis (pgstar_kipp.f90:515-586).

False
burn_type_cutoff float

Minimum \(|\log_{10}|\epsilon||\) threshold shown when rendering burn_type_* regions (pgstar.defaults:1287).

0.0
mass_grid_points int

Vertical interpolation grid length when rendering from profile_paths (default 140).

140
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax) of Figure and primary left Axes.

Raises:

Type Description
ValueError

If neither history_path nor profile_paths is given, or required coordinate columns are missing.

flexmesa.plotting.pgstar_panels

Upstream pgstar TRho_Profile, Power, Abundance, Mixing.

Ports TRho_Profile (star/private/pgstar_trho_profile.f90:56-445), Power (star/private/pgstar_power.f90:73-278), Abundance (star/private/pgstar_abundance.f90:74-403), and Mixing (star/private/pgstar_mixing_ds.f90:106-480) strictly from saved profileN.data outputs and bundled MESA 26.4.1 plot_info/*.data.

safe_log10_pos

safe_log10_pos(arr)

Compute log10(x) on positive finite values and NaN elsewhere.

plot_trho_profile

plot_trho_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="logRho",
    show_degeneracy_line=True,
    show_pgas_prad_line=True,
    show_burn_lines=True,
    show_gamma1_4_3rd=False,
    show_kap_lines=False,
    show_mix_types=True,
    full_trho_bounds=False,
    mesa_dir=None,
    ax=None,
    save_path=None,
)

Plot radial TRho_Profile with MESA 26.4.1 regime guide lines.

Implements do_TRho_Profile_plot from star/private/pgstar_trho_profile.f90:56-445 paired with bundled data/star_data/plot_info/*.data curves read via star/private/pgstar_support.f90:276-395.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis Literal['logRho', 'column_depth', 'logxm']

Horizontal coordinate ("logRho" default, "column_depth", or "logxm", pgstar_trho_profile.f90:82-95).

'logRho'
show_degeneracy_line bool

Draw \(\epsilon_{\mathrm{F}}/k_{\mathrm{B}}T=4\) from psi4.data (pgstar_trho_profile.f90:174, 229-240).

True
show_pgas_prad_line bool

Draw \(P_{\mathrm{rad}} \approx P_{\mathrm{gas}}\) (pgstar_trho_profile.f90:72, 175, 417-431).

True
show_burn_lines bool

Draw H/He/C/O ignition curves from *_burn.data (pgstar_trho_profile.f90:176, 434-445).

True
show_gamma1_4_3rd bool

Draw \(\Gamma_1 < 4/3\) locus from gamma_4_thirds.data (pgstar_trho_profile.f90:173, 397-407).

False
show_kap_lines bool

Draw \(\kappa_{\mathrm{rad}} = \kappa_{\mathrm{cond}}\) and \(e^-e^+\) curves from kap_rad_cond_eq.data and elect.data (pgstar_trho_profile.f90:313-321).

False
show_mix_types bool

Highlight convective and non-convective mixing zones along the profile locus.

True
full_trho_bounds bool

Use wide pgstar.defaults:326-329 plane limits [-11.1, 10.2] x [2.6, 10.2] instead of framing the star.

False
mesa_dir Path | str | None

Optional MESA 26.4.1 root directory.

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_power_profile

plot_power_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    ymin=None,
    ymax=None,
    max_categories=10,
    ax=None,
    save_path=None,
)

Plot nuclear reaction category Power profile (pgstar_power.f90).

Implements do_power_panel from star/private/pgstar_power.f90:73-278 across all nuclear categories stored in profileN.data, ranked by peak specific energy generation rate.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial coordinate name (default "mass").

'mass'
ymin float | None

Optional lower \(\log_{10}(\epsilon)\) bound overriding pgstar_power.f90:161-170.

None
ymax float | None

Optional upper \(\log_{10}(\epsilon)\) bound.

None
max_categories int

Maximum number of active categories drawn in legend.

10
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_abundance_profile

plot_abundance_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    isos=None,
    num_isos_to_show=10,
    log_mass_frac_min=-5.1,
    log_mass_frac_max=0.25,
    ax=None,
    save_path=None,
)

Plot radial logarithmic Abundance profiles (pgstar_abundance.f90).

Implements do_abundance_panel from star/private/pgstar_abundance.f90:74-403.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial coordinate name (default "mass").

'mass'
isos Sequence[str] | None

Optional explicit list of isotope column names to display.

None
num_isos_to_show int

Maximum number of ranked species plotted when isos is None (pgstar_abundance.f90:277-296).

10
log_mass_frac_min float

Lower \(\log_{10} X_i\) (pgstar_abundance.f90:155).

-5.1
log_mass_frac_max float

Upper \(\log_{10} X_i\) (pgstar_abundance.f90:163).

0.25
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_mixing_profile

plot_mixing_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    show_rotation_details=True,
    ymin=None,
    ymax=None,
    ax=None,
    save_path=None,
)

Plot radial Mixing diffusivity (pgstar_mixing_ds.f90).

Implements MixDs_plot (star/private/pgstar_mixing_ds.f90:106-480), including non-rotational mixing regimes and rotational diffusion curves (D_ST, D_visc, D_DSI, D_SH, D_SSI, D_ES, D_GSF, and D_mix_rotation / log_D_omega per star/private/pgstar_mixing_ds.f90:342-441) whenever those profile columns are present.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial coordinate name (default "mass").

'mass'
show_rotation_details bool

Plot individual rotational diffusivity curves (D_ST, D_visc, D_DSI, D_SH, D_SSI, D_ES, D_GSF) when present; if False and no aggregate rotation column exists, plot their sum matching star/private/pgstar_mixing_ds.f90:354-368.

True
ymin float | None

Optional lower \(\log_{10}(D / \mathrm{cm^2\,s^{-1}})\) bound.

None
ymax float | None

Optional upper \(\log_{10}(D / \mathrm{cm^2\,s^{-1}})\) bound.

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

flexmesa.plotting.pgstar_summary

Upstream pgstar summary and custom radial profile panels (#173).

Ports Summary_Profile (star/private/pgstar_summary_profile.f90:72-307), Summary_Burn (star/private/pgstar_summary_burn.f90:54-299), and customizable Profile_Panels<N> (star/private/pgstar_profile_panels.f90:31-220) strictly from saved profileN.data files (#173).

plot_summary_profile

plot_summary_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    columns=None,
    ax=None,
    save_path=None,
)

Plot normalized [0, 1] Summary_Profile (pgstar).

Implements do_summary_profile_panel from star/private/pgstar_summary_profile.f90:72-307 (star/defaults/pgstar.defaults:985-1042).

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial coordinate name (default "mass").

'mass'
columns Sequence[tuple[str, str, bool]] | None

Optional (col_name, legend_label, scale_minmax) triples overriding upstream Summary_Profile defaults.

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_summary_burn_profile

plot_summary_burn_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    ax=None,
    save_path=None,
)

Plot radial Summary_Burn panel (pgstar_summary_burn.f90).

Implements do_summary_burn_plot from star/private/pgstar_summary_burn.f90:54-299 (logRho, \(\log|\epsilon_{\mathrm{nuc}}|\), neutrino losses, and logT).

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial coordinate name (default "mass").

'mass'
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax) (primary left Axes).

plot_profile_custom_panels

plot_profile_custom_panels(
    profile_path,
    panels,
    *,
    ref_profile_path=None,
    xaxis="mass",
    axes=None,
    save_path=None,
)

Plot stacked Profile_Panels<N> from arbitrary profile columns.

Implements Profile_Panels from star/private/pgstar_profile_panels.f90:31-220.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
panels Sequence[str | tuple[str, str | None]]

Non-empty sequence of column names y_col or pairs (y_col, other_y_col) plotted on shared xaxis.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Shared horizontal profile coordinate (default "mass").

'mass'
axes Sequence[Axes] | None

Optional pre-created stack of len(panels) Axes (for embedding inside Grid<N> or Star<N> cells).

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
Figure

Tuple (fig, axes) where axes is a 1D array of length

ndarray

len(panels).

flexmesa.plotting.pgstar_text

Upstream pgstar and pgbinary Text_Summary<N> table renderer.

Ports Summary_plot from star/private/pgstar_summary.f90:337-447 and binary/private/pgbinary_summary.f90:338-445 together with upstream default Text_Summary1 grids (star/defaults/pgstar.defaults:6401-6447, binary/defaults/pgbinary.defaults:1915-1925) strictly from saved history.data or binary_history.data tables (#173).

TextSummarySpec dataclass

Parsed Text_Summary<N> table specification from an inlist.

Attributes:

Name Type Description
num_rows int

Number of rows in the text summary grid.

num_cols int

Number of columns in the text summary grid.

title str

Optional title string from Text_Summary<N>_title.

layout tuple[tuple[str, ...], ...]

Tuple of num_rows tuples, each of length num_cols, giving the requested history column names ("" for blank cells).

parse_inlist_text_summary_spec

parse_inlist_text_summary_spec(
    inlist_path, *, summary_index=1, namelist_name=None
)

Parse Text_Summary<N>_* layout controls from an inlist file.

Mirrors Text_Summary<N>_num_rows, Text_Summary<N>_num_cols, Text_Summary<N>_title, and Text_Summary<N>_name(row, col) in star/defaults/pgstar.defaults:6401-6447 and binary/defaults/pgbinary.defaults:1915-1925.

Parameters:

Name Type Description Default
inlist_path Path | str

Path to an inlist or .defaults file containing a &pgstar or &pgbinary namelist block.

required
summary_index int

1-based Text_Summary<N> index (1..9).

1
namelist_name str | None

Optional filter restricting parsing to "pgstar" or "pgbinary".

None

Returns:

Name Type Description
Populated TextSummarySpec

class:TextSummarySpec.

Raises:

Type Description
ValueError

If summary_index is outside 1..9 or no rows/cols are configured.

format_summary_value

format_summary_value(name, value)

Format a scalar summary value matching pgstar_summary.f90:420-442.

Integer columns and exact integer values render as integers; finite floats with 1e-3 < |v| < 1e3 render in fixed-point; other non-zero magnitudes render in scientific notation (1pe10.3).

plot_text_summary

plot_text_summary(
    history_path,
    *,
    layout=None,
    inlist_path=None,
    summary_index=1,
    is_binary=False,
    model_number=None,
    row_index=-1,
    ref_history_path=None,
    title="",
    ax=None,
    save_path=None,
)

Render a Text_Summary<N> key-value table from saved history output.

Implements Summary_plot from star/private/pgstar_summary.f90:337-447 and binary/private/pgbinary_summary.f90:338-445 strictly from saved history.data or binary_history.data files.

Parameters:

Name Type Description Default
history_path Path | str

Path to history.data or binary_history.data.

required
layout Sequence[Sequence[str]] | None

Optional 2D sequence rows x cols of history column names overriding upstream Text_Summary1 defaults.

None
inlist_path Path | str | None

Optional inlist or .defaults file defining Text_Summary<N>_* controls.

None
summary_index int

1-based Text_Summary<N> index (1..9) used when parsing inlist_path.

1
is_binary bool

When True and neither layout nor inlist_path is supplied, use pgbinary Text_Summary1 defaults (binary/defaults/pgbinary.defaults:1915-1925).

False
model_number int | None

Optional model_number selecting the displayed row.

None
row_index int

0-based (or negative) row index when model_number is None (default -1, terminal model).

-1
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history recorded in the panel title for provenance.

None
title str

Optional panel title overriding Text_Summary<N>_title.

''
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

Raises:

Type Description
KeyError

If none of the requested columns exist in history_path.

ValueError

If layout is empty.

plot_pgbinary_text_summary

plot_pgbinary_text_summary(
    binary_history,
    *,
    layout=None,
    inlist_path=None,
    summary_index=1,
    model_number=None,
    row_index=-1,
    mesa_binary_history=None,
    title="",
    ax=None,
    save_path=None,
)

Render a pgbinary Text_Summary<N> table from binary history.

Implements Summary_plot from binary/private/pgbinary_summary.f90:338-445 using upstream default rows from binary/defaults/pgbinary.defaults:1915-1925.

Parameters:

Name Type Description Default
binary_history Path | str

Path to binary_history.data.

required
layout Sequence[Sequence[str]] | None

Optional 2D sequence rows x cols overriding defaults.

None
inlist_path Path | str | None

Optional inlist defining Text_Summary<N>_*.

None
summary_index int

1-based Text_Summary<N> index (1..9).

1
model_number int | None

Optional model_number selecting the displayed row.

None
row_index int

Row index when model_number is None (default -1).

-1
mesa_binary_history Path | str | None

Optional MESA 26.4.1 reference binary history.

None
title str

Optional panel title.

''
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

flexmesa.plotting.pgstar_extra

Upstream pgstar Dynamo, dPg_dnu, rti, and CMD panels.

Ports Dyn_plot (star/private/pgstar_dynamo.f90:57-315), do_dPg_dnu_Plot (star/private/pgstar_dpg_dnu.f90:55-84), do_rti_Plot (star/private/pgstar_rti.f90:55-481), and do_Color_Magnitude_plot (star/private/pgstar_color_magnitude.f90:589-923) strictly from saved MESA profileN.data and history.data files (#173).

ColorMagnitudeSpec dataclass

Parsed Color_magnitude<N> namelist specification.

plot_dynamo_profile

plot_dynamo_profile(
    profile_path,
    *,
    ref_profile_path=None,
    xaxis="mass",
    ymin_left=None,
    ymax_left=None,
    ymin_right=None,
    ymax_right=None,
    ax=None,
    save_path=None,
)

Plot radial Dynamo magnetic/rotation profiles (pgstar_dynamo.f90).

Implements Dyn_plot (star/private/pgstar_dynamo.f90:99-312), drawing \(\log_{10}(B_\phi/\mathrm{G})\) and \(\log_{10}(B_r/\mathrm{G})\) on the left axis and \(\log_{10}(\Omega/\mathrm{rad\,s^{-1}})\) plus \(\log_{10}(j_{\mathrm{rot}} / 10^{20}\,\mathrm{cm^2\,s^{-1}})\) on the right axis, paired with the bottom mixing-region bar.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
xaxis str

Radial profile coordinate (default "mass").

'mass'
ymin_left float | None

Optional lower left-axis bound (\(\log_{10}(B / \mathrm{G})\)).

None
ymax_left float | None

Optional upper left-axis bound.

None
ymin_right float | None

Optional lower right-axis bound.

None
ymax_right float | None

Optional upper right-axis bound.

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax) (primary left Axes).

Raises:

Type Description
KeyError

If no magnetic-field columns (dynamo_log_B_phi / dynamo_B_phi or dynamo_log_B_r / dynamo_B_r) exist in profileN.data.

plot_dpg_dnu

plot_dpg_dnu(
    history_path,
    *,
    ref_history_path=None,
    xmin=None,
    xmax=None,
    ymin=None,
    ymax=None,
    ax=None,
    save_path=None,
)

Plot gravity-mode period spacing dPg_dnu (pgstar_dpg_dnu.f90).

Implements do_dPg_dnu_Plot (star/private/pgstar_dpg_dnu.f90:55-84), plotting delta_Pg (\(\Delta\Pi_1\) in seconds) against delta_nu (\(\Delta\nu\) in \(\mu\mathrm{Hz}\)) strictly from saved history.data.

Parameters:

Name Type Description Default
history_path Path | str

Path to history.data.

required
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history overlay.

None
xmin float | None

Optional lower \(\Delta\nu\) limit (\(\mu\mathrm{Hz}\)).

None
xmax float | None

Optional upper \(\Delta\nu\) limit (\(\mu\mathrm{Hz}\)).

None
ymin float | None

Optional lower \(\Delta\Pi_g\) limit (\(\mathrm{s}\)).

None
ymax float | None

Optional upper \(\Delta\Pi_g\) limit (\(\mathrm{s}\)).

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_rti_history

plot_rti_history(
    history_path=None,
    *,
    profile_paths=None,
    ref_history_path=None,
    xaxis="model_number",
    age_units="yr",
    log_xaxis=False,
    time_from_present=False,
    xaxis_reversed=None,
    ymin=None,
    ymax=None,
    rti_interval=1,
    ax=None,
    save_path=None,
)

Plot Rayleigh-Taylor Instability (rti) evolution (pgstar_rti.f90).

Implements do_rti_Plot from star/private/pgstar_rti.f90:55-481 (star/defaults/pgstar.defaults:1346-1439), rendering vertical RTI regions from rti_type_*/rti_qtop_* (or mix_type_* == 6 / profile mixing_type == 6 / alpha_RTI) alongside total, core, and shock mass boundaries.

Parameters:

Name Type Description Default
history_path Path | str | None

Path to history.data containing star_mass and rti_type_*/rti_qtop_* (or mix_type_*/mix_qtop_*).

None
profile_paths Sequence[Path | str] | None

Optional sequence of profileN.data files supplying RTI zones when history region columns are absent.

None
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history overlay.

None
xaxis Literal['model_number', 'star_age']

Horizontal coordinate ("model_number" or "star_age").

'model_number'
age_units Literal['yr', 'Myr', 's']

Units when xaxis == "star_age" ("yr", "Myr", "s").

'yr'
log_xaxis bool

Apply \(\log_{10}\) to star_age.

False
time_from_present bool

Plot time relative to the terminal model.

False
xaxis_reversed bool | None

Optional axis-reversal override.

None
ymin float | None

Optional lower mass bound (\(M_\odot\)).

None
ymax float | None

Optional upper mass bound (\(M_\odot\)).

None
rti_interval int

Model stride between drawn vertical RTI segments.

1
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

format_cmd_label

format_cmd_label(col1, col2='')

Format photometric axis label (pgstar_color_magnitude.f90:887-920).

parse_inlist_cmd_spec

parse_inlist_cmd_spec(inlist_path, *, panel_index=1)

Parse Color_magnitude<N>_* controls from an inlist file.

plot_color_magnitude

plot_color_magnitude(
    history_path,
    xaxis1=None,
    xaxis2=None,
    panels=None,
    *,
    ref_history_path=None,
    inlist_path=None,
    panel_index=1,
    xaxis_reversed=None,
    yaxis_reversed=True,
    xmin=None,
    xmax=None,
    axes=None,
    ax=None,
    save_path=None,
)

Plot photometric Color_magnitude<N> diagrams.

Implements do_Color_Magnitude_plot from star/private/pgstar_color_magnitude.f90:589-923 (star/defaults/pgstar.defaults:5264-5380), supporting arbitrary color differences xaxis1 - xaxis2 and stacked single- or dual-axis magnitude or color panels read strictly from saved history.data columns.

Parameters:

Name Type Description Default
history_path Path | str

Path to history.data.

required
xaxis1 str | None

Primary horizontal column (for example "abs_mag_B" or "bc_B").

None
xaxis2 str | None

Optional second horizontal column subtracted from xaxis1 to form a color index (for example "abs_mag_V").

None
panels Sequence[str | tuple[str, str | None] | tuple[str, str | None, str | None, str | None]] | None

Sequence of panel specs: "y1", ("y1", "y2"), or ("y1", "y2", "other_y1", "other_y2").

None
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history overlay.

None
inlist_path Path | str | None

Optional &pgstar inlist defining Color_magnitude<N>_*.

None
panel_index int

1-based Color_magnitude<N> index (1..9).

1
xaxis_reversed bool | None

Optional x-axis inversion override.

None
yaxis_reversed bool

Invert magnitude y-axes by default (brighter upward).

True
xmin float | None

Optional lower horizontal bound.

None
xmax float | None

Optional upper horizontal bound.

None
axes Sequence[Axes] | None

Optional pre-allocated axes sequence matching len(panels).

None
ax Axes | None

Optional single target Axes when rendering a 1-panel CMD.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, ndarray]

Tuple (fig, axes_arr) where axes_arr is a 1D Axes array.

flexmesa.plotting.pgstar_nucleosyn

Upstream pgstar Network and Production nucleosynthesis panels.

Ports do_network_panel (star/private/pgstar_network.f90:74-284) and do_production_panel (star/private/pgstar_production.f90:71-350) strictly from saved profileN.data isotope columns and MESA 26.4.1 nuclide tables via flexmesa.chem (#173).

plot_network_chart

plot_network_chart(
    profile_path,
    *,
    nmin=None,
    nmax=None,
    zmin=None,
    zmax=None,
    log_mass_frac_min=-5.0,
    log_mass_frac_max=0.0,
    show_mass_fraction=True,
    show_element_names=True,
    show_colorbar=True,
    min_mass=None,
    max_mass=None,
    ax=None,
    save_path=None,
)

Plot Network chart of nuclides (\(N\) vs. \(Z\), pgstar_network.f90).

Implements do_network_panel from star/private/pgstar_network.f90:74-284 (star/defaults/pgstar.defaults:2626-2670), drawing one unit cell per nuclide present in profileN.data, shaded by mass-averaged \(\log_{10} \bar{X}_i\).

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
nmin int | None

Optional lower neutron-number bound \(N_{\min}\).

None
nmax int | None

Optional upper neutron-number bound \(N_{\max}\).

None
zmin int | None

Optional lower proton-number bound \(Z_{\min}\).

None
zmax int | None

Optional upper proton-number bound \(Z_{\max}\).

None
log_mass_frac_min float

Lower colorbar bound for \(\log_{10} \bar{X}_i\) (default -5.0, pgstar.defaults:2661).

-5.0
log_mass_frac_max float

Upper colorbar bound for \(\log_{10} \bar{X}_i\) (default 0.0, pgstar.defaults:2662).

0.0
show_mass_fraction bool

Fill cells colored by \(\log_{10} \bar{X}_i\).

True
show_element_names bool

Annotate element symbols along the left side.

True
show_colorbar bool

Attach a colorbar with explicit vmin/vmax.

True
min_mass float | None

Optional lower enclosed mass cut (\(M_\odot\)).

None
max_mass float | None

Optional upper enclosed mass cut (\(M_\odot\)).

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_production_profile

plot_production_profile(
    profile_path,
    *,
    init_profile_path=None,
    ref_profile_path=None,
    amin=None,
    amax=None,
    ymin=None,
    ymax=None,
    min_mass=None,
    max_mass=None,
    min_mass_frac=-5.0,
    show_element_names=True,
    ax=None,
    save_path=None,
)

Plot Production factors vs. mass number \(A\).

Implements do_production_panel from star/private/pgstar_production.f90:71-350 (star/defaults/pgstar.defaults:2697-2745), mapping network species onto the 286 stable isotopes via :func:flexmesa.chem.get_stable_mass_frac.

Parameters:

Name Type Description Default
profile_path Path | str

Path to profileN.data.

required
init_profile_path Path | str | None

Optional initial profileN.data providing the reference composition (defaults to AG89 solar scaled by header initial_z/initial_y when present).

None
ref_profile_path Path | str | None

Optional MESA 26.4.1 profileN.data overlay.

None
amin int | None

Optional lower mass-number bound \(A_{\min}\).

None
amax int | None

Optional upper mass-number bound \(A_{\max}\).

None
ymin float | None

Optional lower log production-factor limit.

None
ymax float | None

Optional upper log production-factor limit.

None
min_mass float | None

Optional lower enclosed mass cut (\(M_\odot\)).

None
max_mass float | None

Optional upper enclosed mass cut (\(M_\odot\)).

None
min_mass_frac float

Minimum \(\log_{10} X\) filter for both star and reference (default -5.0, pgstar.defaults:2735).

-5.0
show_element_names bool

Annotate staggered element symbols above curves.

True
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

flexmesa.plotting.pgbinary_panels

Binary pgbinary diagnostic and MESA 26.4.1 panels (#173).

Ports the static content of binary/private/pgbinary_orbit.f90:63-296, binary/private/pgbinary_summary_history.f90:55-282, and binary/private/pgbinary_star.f90:93-221 strictly from saved binary_history.data and component LOGS1/LOGS2 history.data files, with optional MESA 26.4.1 reference overplotting and provenance subtitles.

plot_pgbinary_orbit

plot_pgbinary_orbit(
    binary_history,
    *,
    model_number=None,
    row_index=-1,
    eccentricity=None,
    mesa_binary_history=None,
    show_roche_lobes=True,
    show_stars=True,
    ax=None,
    save_path=None,
)

Plot 2D binary orbital paths and Roche geometry (pgbinary_orbit.f90).

Implements orbit_panel from binary/private/pgbinary_orbit.f90:63-296 strictly from saved binary_history.data rows. When eccentricity is omitted from binary_history_columns.list, recovers exact Keplerian eccentricity from J_orb, star_1_mass, star_2_mass, and binary_separation (binary/private/binary_utils.f90:190-191).

Parameters:

Name Type Description Default
binary_history Path | str

Path to binary_history.data.

required
model_number int | None

Optional model_number selecting the snapshot row.

None
row_index int

Row index used when model_number is None (default -1, terminal model).

-1
eccentricity float | None

Optional explicit orbital eccentricity override in [0, 1).

None
mesa_binary_history Path | str | None

Optional MESA 26.4.1 binary_history.data for dashed reference overlay.

None
show_roche_lobes bool

Draw critical Roche-lobe equipotential contours.

True
show_stars bool

Draw hatched stellar equipotential surfaces (or compact markers when point_mass_index marks a point mass).

True
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax) of Figure and equal-aspect Axes.

plot_pgbinary_summary_history

plot_pgbinary_summary_history(
    binary_history,
    *,
    mesa_binary_history=None,
    columns=None,
    xaxis="model_number",
    ax=None,
    save_path=None,
)

Plot min-max normalized Summary_History binary traces (pgbinary).

Implements do_summary_history_plot from binary/private/pgbinary_summary_history.f90:55-282 (binary/defaults/pgbinary.defaults:309-335).

Parameters:

Name Type Description Default
binary_history Path | str

Path to binary_history.data.

required
mesa_binary_history Path | str | None

Optional MESA 26.4.1 binary_history.data reference to overplot using identical normalization bounds.

None
columns Sequence[str] | None

Optional sequence of column names overriding upstream defaults.

None
xaxis Literal['model_number', 'age']

Horizontal coordinate ("model_number" or "age").

'model_number'
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax) with normalized trajectories in [0, 1].

plot_pgbinary_panels

plot_pgbinary_panels(
    binary_history=None,
    *,
    case=None,
    flexmesa_dir=None,
    mesa_binary_history=None,
    star1_history=None,
    star2_history=None,
    mesa_star1_history=None,
    mesa_star2_history=None,
    manifest_path=None,
    orbit_model_number=None,
    numerics_mode="",
    termination_code="",
    controls_ignored=False,
    n_controls_ignored=0,
    max_steps=None,
    save_path=None,
)

Plot the 6-panel pgbinary diagnostic and MESA 26.4.1 figure.

Combines 2D Orbit Roche geometry, Donor + Accretor HR tracks, Roche-lobe filling factor \(R / R_{\mathrm{RL}}\), lg_mtransfer_rate, orbital period and separation, and component masses / residuals strictly from stored outputs.

Parameters:

Name Type Description Default
binary_history Path | str | None

Direct path to binary_history.data.

None
case str | None

Optional manifest binary case name for resolving stored MESA 26.4.1 reference history and tolerances.

None
flexmesa_dir Path | str | None

Optional run directory containing binary_history.data and optional LOGS1/, LOGS2/ component histories.

None
mesa_binary_history Path | str | None

Optional reference MESA binary_history.data.

None
star1_history Path | str | None

Optional path to Star 1 history.data.

None
star2_history Path | str | None

Optional path to Star 2 history.data.

None
mesa_star1_history Path | str | None

Optional reference Star 1 history.data.

None
mesa_star2_history Path | str | None

Optional reference Star 2 history.data.

None
manifest_path Path | str | None

Optional override path to case_manifest.toml.

None
orbit_model_number int | None

Optional model_number for the (0, 0) orbit snapshot (defaults to terminal model).

None
numerics_mode str

Optional arithmetic mode label for provenance banner.

''
termination_code str

Optional termination code for provenance banner.

''
controls_ignored bool

Whether unsupported controls were bypassed.

False
n_controls_ignored int

Count of bypassed controls.

0
max_steps int | None

Optional step cap used during a smoke trace.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, ndarray]

Tuple (fig, axes) with axes of shape (3, 2).

plot_pgbinary_star

plot_pgbinary_star(
    star_number,
    panel_name="HR",
    *,
    binary_history=None,
    star_history=None,
    star_profile=None,
    star_profile_paths=None,
    inlist_path=None,
    mesa_dir=None,
    title="",
    ax=None,
    save_path=None,
)

Embed any supported pgstar window for binary component Star<N>.

Implements do_star_plot (binary/private/pgbinary_star.f90:93-615), showing component donor/accretor/detached status when binary_history is provided and rendering upstream's point-mass notice when point_mass_index == star_number.

Parameters:

Name Type Description Default
star_number Literal[1, 2]

Binary component index (1 or 2).

required
panel_name str

Any pgstar window identifier supported by :func:flexmesa.plotting.plot_pgstar_grid (for example "HR", "TRho_Profile", "Kipp", "Dynamo", "Network", "Text_Summary1", "Profile_Panels1", or "Grid1").

'HR'
binary_history Path | str | None

Optional binary_history.data providing component donor/accretor status and point_mass_index.

None
star_history Path | str | None

Optional component LOGS<N>/history.data.

None
star_profile Path | str | None

Optional component LOGS<N>/profile*.data.

None
star_profile_paths Sequence[Path | str] | None

Optional sequence of component profiles (for profile Kippenhahn or rti panels).

None
inlist_path Path | str | None

Optional &pgstar inlist configuring custom panels.

None
mesa_dir Path | str | None

Optional MESA 26.4.1 root for plot_info/*.data.

None
title str

Optional custom title prefix overriding Star <N>.

''
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, list[Axes]]

Tuple (fig, axes) where axes lists the rendered Axes.

flexmesa.plotting.pgstar_grid

Upstream pgstar/pgbinary track, history, and Grid builders.

Ports History_Track<N> and all named two-column evolutionary track windows (star/private/pgstar_hist_track.f90:53-280, pgstar_tmaxrho.f90:57-105, pgstar_logg_teff.f90:55-88, pgstar_logg_logt.f90:58-88, pgstar_logl_r.f90:55-96, pgstar_logl_v.f90:55-93, pgstar_l_teff.f90:57-87, pgstar_l_r.f90:57-87, pgstar_l_v.f90:57-87, pgstar_r_teff.f90:57-87, pgstar_r_l.f90:57-87), Summary_History (star/private/pgstar_summary_history.f90:54-265), History_Panels<N> (star/private/pgstar_history_panels.f90:31-240), and the Grid<N> multi-window layout composer (star/private/pgstar_grid.f90:50-260, binary/private/pgbinary_grid.f90:32-260).

TrackPreset dataclass

Column and axis specification for an upstream pgstar track window.

GridPanelSpec dataclass

Zero-based GridSpec cell placement for plot_pgstar_grid.

Attributes:

Name Type Description
name str

Panel identifier (such as "HR", "Kipp", "TRho_Profile", "Power", "Abundance", "Orbit", "Star1:HR", or "History_Track:star_age:log_L").

row int

Zero-based top row index.

col int

Zero-based left column index.

rowspan int

Vertical span in grid rows (default 1).

colspan int

Horizontal span in grid columns (default 1).

plot_history_track

plot_history_track(
    history_path,
    x_col=None,
    y_col=None,
    *,
    preset=None,
    ref_history_path=None,
    reverse_xaxis=None,
    reverse_yaxis=None,
    show_degeneracy_line=None,
    mesa_dir=None,
    ax=None,
    save_path=None,
)

Plot a 2D evolutionary History_Track or named pgstar track.

Implements do_Hist_Track (star/private/pgstar_hist_track.f90:53-280) and named pgstar track presets (HR, TRho, TmaxRho, logg_Teff, logg_logT, logL_R, logL_v, L_Teff, L_R, L_v, R_Teff, R_L, dPg_dnu).

Parameters:

Name Type Description Default
history_path Path | str

Path to history.data or binary_history.data.

required
x_col str | None

Horizontal column name when preset is None.

None
y_col str | None

Vertical column name when preset is None.

None
preset str | None

Case-insensitive pgstar preset name overriding x_col and y_col.

None
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history overlay.

None
reverse_xaxis bool | None

Optional axis-inversion override.

None
reverse_yaxis bool | None

Optional axis-inversion override.

None
show_degeneracy_line bool | None

Draw psi4.data degeneracy guide line (star/private/pgstar_tmaxrho.f90:90-105).

None
mesa_dir Path | str | None

Optional MESA 26.4.1 root for psi4.data.

None
ax Axes | None

Optional target matplotlib.axes.Axes.

None
save_path Path | str | None

Optional output image path (300 dpi).

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple (fig, ax).

plot_summary_history

plot_summary_history(
    history_path,
    *,
    ref_history_path=None,
    xaxis="model_number",
    ax=None,
    save_path=None,
)

Plot normalized [0, 1] Summary_History (pgstar).

Implements do_summary_history_plot from star/private/pgstar_summary_history.f90:54-265.

plot_history_panels

plot_history_panels(
    history_path,
    panels,
    *,
    ref_history_path=None,
    xaxis="model_number",
    axes=None,
    save_path=None,
)

Plot stacked History_Panels<N> from arbitrary history columns.

Implements History_Panels from star/private/pgstar_history_panels.f90:31-240 and binary/private/pgbinary_history_panels.f90:31-240.

parse_inlist_grid_spec

parse_inlist_grid_spec(
    inlist_path, *, grid_index=1, namelist_name=None
)

Parse Grid<N>_* layout controls from an inlist file.

Mirrors Grid_plot arguments in star/private/pgstar_grid.f90:50-79 and binary/private/pgbinary_grid.f90:32-56.

plot_pgstar_grid

plot_pgstar_grid(
    panels=None,
    *,
    num_rows=None,
    num_cols=None,
    inlist_path=None,
    grid_index=1,
    namelist_name=None,
    history_path=None,
    ref_history_path=None,
    profile_path=None,
    ref_profile_path=None,
    profile_paths=None,
    binary_history_path=None,
    ref_binary_history_path=None,
    star1_history_path=None,
    star2_history_path=None,
    star1_profile_path=None,
    star2_profile_path=None,
    star1_profile_paths=None,
    star2_profile_paths=None,
    star1_inlist_path=None,
    star2_inlist_path=None,
    mesa_dir=None,
    title="",
    save_path=None,
)

Compose a multi-panel Grid<N> dashboard (pgstar / pgbinary).

Implements Grid_plot from star/private/pgstar_grid.f90:504-1018 and binary/private/pgbinary_grid.f90:275-572 via matplotlib.gridspec, supporting Text_Summary<N>, Profile_Panels<N>, History_Panels<N>, Star1/Star2, and nested Grid<N> cells.

flexmesa.plotting.live

Live-evolution plotting hooks and log watchers (#173).

Provides headless, non-leaking live frame rendering during FlexMESA single-star and binary evolutions via :class:LiveEvolutionPlotter (compatible with StarExtras and BinaryExtras step hooks) and :func:watch_logs for watching incrementally written LOGS/ directories.

Mirrors the upstream pgstar/pgbinary *_file_cnt frame-emission cadence (star/defaults/pgstar.defaults:17-58, binary/defaults/pgbinary.defaults:17-48) while writing each frame atomically and always closing every matplotlib figure.

LiveFrameRecord dataclass

Metadata for a frame written by :class:LiveEvolutionPlotter.

Attributes:

Name Type Description
model_number int

Model index associated with the rendered frame.

path Path

Numbered output frame path on disk.

latest_path Path | None

Optional atomically updated latest frame path.

profile_path Path | None

Latest profileN.data used when rendering (if any).

num_rows int

Number of history rows present when the frame was rendered.

LiveEvolutionPlotter

Headless live-evolution frame renderer and Extras step hook.

Compatible with flexmesa.star.run_test_suite_case(..., extras=...), flexmesa.binary.run_binary_test_suite_case(..., extras=...), and custom Python evolution loops. Every file_cnt steps it renders the configured pgstar/pgbinary panels from incrementally written history.data/profileN.data files, writes frames atomically, and closes the matplotlib figure immediately to prevent memory leaks.

frames property

frames

Chronological tuple of frames emitted by this plotter.

logs_dir property

logs_dir

Resolved log directory currently watched by this plotter.

__init__

__init__(
    out_dir,
    *,
    logs_dir=None,
    panels=("HR", "TRho"),
    inlist_path=None,
    grid_index=1,
    namelist_name=None,
    file_cnt=5,
    file_prefix="frame_",
    file_format="png",
    dpi=150,
    write_latest=True,
    render_on_finish=True,
    is_binary=False,
    ref_history_path=None,
    ref_profile_path=None,
    ref_binary_history_path=None,
    mesa_dir=None,
    title="",
    on_frame=None,
)

Configure live-evolution plotting parameters.

Parameters:

Name Type Description Default
out_dir Path | str

Directory receiving rendered frame images.

required
logs_dir Path | str | None

Directory containing history.data (or LOGS/ and binary_history.data). When omitted, inferred from state["case_dir"] during extras_startup.

None
panels Sequence[GridPanelSpec | str] | None

Panel sequence passed to :func:plot_pgstar_grid when inlist_path is None.

('HR', 'TRho')
inlist_path Path | str | None

Optional &pgstar/&pgbinary namelist defining Grid<N>_*.

None
grid_index int

1-based Grid<N> index when inlist_path is set.

1
namelist_name str | None

Optional "pgstar" or "pgbinary" override.

None
file_cnt int

Emit one frame every file_cnt model steps (matching upstream *_file_cnt, must be >= 1).

5
file_prefix str

Filename prefix for emitted frames.

'frame_'
file_format str

Output image extension without leading dot (default "png").

'png'
dpi int

Raster resolution for saved frames (default 150 for fast live iteration).

150
write_latest bool

Also atomically update <file_prefix>latest.<ext>.

True
render_on_finish bool

Emit a terminal frame in extras_after_evolve if the final model was not already rendered.

True
is_binary bool

Set True when plotting pgbinary evolution logs.

False
ref_history_path Path | str | None

Optional MESA 26.4.1 star history overlay.

None
ref_profile_path Path | str | None

Optional MESA 26.4.1 star profile overlay.

None
ref_binary_history_path Path | str | None

Optional MESA binary history overlay.

None
mesa_dir Path | str | None

Optional MESA root for psi4.data / reference tracks.

None
title str

Optional figure super-title.

''
on_frame Callable[[LiveFrameRecord], None] | None

Optional callback invoked with each :class:LiveFrameRecord after atomic save.

None

extras_startup

extras_startup(state, restart)

StarExtras startup hook capturing case_dir if needed.

extras_binary_startup

extras_binary_startup(state, restart)

BinaryExtras startup hook capturing case_dir if needed.

extras_finish_step

extras_finish_step(state)

StarExtras step hook emitting frames every file_cnt steps.

finish_step

finish_step(state)

BinaryExtras hook emitting frames every file_cnt steps.

extras_after_evolve

extras_after_evolve(state)

StarExtras end-of-evolution hook ensuring a final frame.

extras_binary_after_evolve

extras_binary_after_evolve(state)

BinaryExtras end-of-evolution hook ensuring a final frame.

render_now

render_now(*, model_number=None)

Render one frame immediately from currently saved log files.

Returns None if no non-empty history or profile log is present yet. Always closes the allocated matplotlib figure before returning.

watch_logs

watch_logs(
    logs_dir,
    out_dir,
    *,
    panels=("HR", "TRho"),
    inlist_path=None,
    grid_index=1,
    namelist_name=None,
    is_binary=False,
    poll_interval_sec=0.5,
    max_frames=None,
    max_wait_sec=None,
    stop_event=None,
    file_prefix="frame_",
    file_format="png",
    dpi=150,
    write_latest=True,
    ref_history_path=None,
    ref_profile_path=None,
    ref_binary_history_path=None,
    mesa_dir=None,
    title="",
    on_frame=None,
)

Watch logs_dir and render frames whenever new evolution data lands.

Polls logs_dir at poll_interval_sec until stop_event is set, max_frames frames have been written, or max_wait_sec elapses.

Parameters:

Name Type Description Default
logs_dir Path | str

Run or LOGS/ directory written by a running evolution.

required
out_dir Path | str

Output directory for rendered frames.

required
panels Sequence[GridPanelSpec | str] | None

Panel names or GridPanelSpec cells when inlist_path is None.

('HR', 'TRho')
inlist_path Path | str | None

Optional &pgstar/&pgbinary inlist defining Grid<N>_*.

None
grid_index int

1-based Grid<N> index when inlist_path is set.

1
namelist_name str | None

Optional "pgstar" or "pgbinary" override.

None
is_binary bool

Set True to watch binary_history.data and LOGS1/LOGS2.

False
poll_interval_sec float

Polling sleep interval in seconds (must be > 0).

0.5
max_frames int | None

Optional cap on emitted frames before returning.

None
max_wait_sec float | None

Optional wall-clock timeout in seconds before returning.

None
stop_event Event | None

Optional threading.Event signalling clean shutdown.

None
file_prefix str

Filename prefix for emitted frames.

'frame_'
file_format str

Image extension without leading dot (default "png").

'png'
dpi int

Raster resolution for saved frames.

150
write_latest bool

Atomically maintain <file_prefix>latest.<ext>.

True
ref_history_path Path | str | None

Optional MESA 26.4.1 reference history overlay.

None
ref_profile_path Path | str | None

Optional MESA 26.4.1 reference profile overlay.

None
ref_binary_history_path Path | str | None

Optional MESA reference binary history overlay.

None
mesa_dir Path | str | None

Optional MESA root directory.

None
title str

Optional figure super-title.

''
on_frame Callable[[LiveFrameRecord], None] | None

Optional callback invoked after each emitted frame.

None

Returns:

Type Description
list[LiveFrameRecord]

List of emitted :class:LiveFrameRecord instances.

flexmesa.plotting.pgstar_case

Render the panels a MESA case's inlists enable (#173).

enabled_panels reads the &pgstar / &pgbinary settings of a case's inlist files and lists every panel whose <Panel>_win_flag or <Panel>_file_flag is .true.. render_case_panels draws each one from a run's history and profile files with the existing flexmesa.plotting builders and returns one PanelResult per panel. A panel that cannot be drawn (missing history or profile file, missing column, or a panel family without a builder yet) is reported with its reason and, when a figure is produced, carries a visible note. Nothing is skipped silently, and strict=True raises instead.

Layout and styling are approximate: panels are drawn one per figure with the flexmesa.plotting style, except Grid<N>, which keeps its row/column layout through plot_pgstar_grid.

PanelUnavailableError

Bases: RuntimeError

Raised in strict mode when an enabled panel cannot be drawn.

EnabledPanel dataclass

One panel enabled by a case's inlists.

Attributes:

Name Type Description
name str

Panel name as written upstream, without the flag suffix (for example "Grid1", "HR", or "Profile_Panels2").

namelist str

Source block, "pgstar" or "pgbinary".

outputs tuple[str, ...]

Enabled outputs, a sorted subset of ("file", "win").

inlist Path

Last inlist file (in the order given) that sets any control of this panel, used to read its layout and column lists.

PanelResult dataclass

Outcome of drawing one enabled panel.

Attributes:

Name Type Description
panel EnabledPanel

The enabled panel.

status str

"rendered", "partial" (a Grid<N> whose other cells drew but some carry a note), "unavailable" (data or column missing), or "unsupported" (no builder for this family yet).

reason str

Empty when rendered, otherwise the explicit reason.

figure Figure | None

The figure, or None when nothing could be drawn at all.

path Path | None

Saved image path when an output directory was given.

case_inlist_paths

case_inlist_paths(case_dir)

List the top-level inlist* files of a test-suite case, sorted.

Parameters:

Name Type Description Default
case_dir Path | str

Case directory.

required

Returns:

Type Description
list[Path]

Sorted inlist paths. Later files override earlier ones.

enabled_panels

enabled_panels(inlist_paths)

Find the panels whose window or file output is enabled.

Parameters:

Name Type Description Default
inlist_paths Iterable[Path | str]

Inlist files. Within one file the last assignment of a flag wins; a panel is enabled when any file enables it. Files without a &pgstar or &pgbinary block are ignored.

required

Returns:

Type Description
list[EnabledPanel]

Panels in first-seen order.

Raises:

Type Description
ValueError

If an inlist file cannot be parsed.

render_case_panels

render_case_panels(
    inlist_paths,
    *,
    history_path=None,
    profile_path=None,
    profile_paths=None,
    binary_history_path=None,
    star1_history_path=None,
    star2_history_path=None,
    out_dir=None,
    strict=False,
)

Draw every panel the inlists enable from a run's output files.

Parameters:

Name Type Description Default
inlist_paths Iterable[Path | str]

Inlist files in override order (see enabled_panels).

required
history_path Path | str | None

Star history.data.

None
profile_path Path | str | None

One profile<N>.data for single-profile panels.

None
profile_paths Sequence[Path | str] | None

Profile files for panels that need a time series of profiles, such as Kipp.

None
binary_history_path Path | str | None

binary_history.data for pgbinary panels.

None
star1_history_path Path | str | None

Star 1 history inside a binary run.

None
star2_history_path Path | str | None

Star 2 history inside a binary run.

None
out_dir Path | str | None

When given, each figure is saved there as <namelist>_<panel>.png (created if missing).

None
strict bool

Raise PanelUnavailableError on the first panel that cannot be drawn instead of recording it.

False

Returns:

Type Description
list[PanelResult]

One PanelResult per enabled panel, in inlist order. Callers own

list[PanelResult]

the figures and should close them.

Raises:

Type Description
PanelUnavailableError

In strict mode, when a panel cannot be drawn.

flexmesa.plotting.pgstar_coverage

Upstream pgstar / pgbinary / astero_pgstar coverage catalog.

Parses MESA 26.4.1 plotting *.defaults schemas and maps each upstream *_win_flag panel family onto flexmesa.plotting builders (#173).

PgstarPanelStatus dataclass

Coverage status for one upstream PGSTAR/PGBINARY panel family.

Attributes:

Name Type Description
namelist str

Source namelist ("pgstar", "pgbinary", or "astero_pgstar").

family str

Canonical panel family identifier (for example "HR" or "History_Panels<N>").

window_count int

Number of distinct *_win_flag instances in upstream .defaults.

status str

Implementation tier: "approximate" (draws the intended quantities; controls not compared against the upstream pgstar_*.f90 or pgbinary_*.f90 definition), "partial" (known gaps stated in notes), or "absent".

flexmesa_builders str

Comma-separated flexmesa.plotting entry points covering this panel family (or "-" when absent).

issue str

Tracking GitHub issue reference ("#173", etc.).

notes str

Concise scope note distinguishing implemented panels from pending interactive or multi-panel options.

PgstarCoverageReport dataclass

Aggregated panel and control-key coverage across MESA plotting files.

Attributes:

Name Type Description
source_counts dict[str, int]

Mapping from defaults filename to parsed control count.

total_windows int

Total *_win_flag window definitions across all three plotting .defaults files.

panels tuple[PgstarPanelStatus, ...]

Ordered tuple of PgstarPanelStatus records.

build_pgstar_coverage_report

build_pgstar_coverage_report(mesa_dir)

Parse upstream MESA plotting .defaults and summarize panel coverage.

Parameters:

Name Type Description Default
mesa_dir Path

Path to extracted MESA 26.4.1 source/test-inputs root.

required

Returns:

Type Description
PgstarCoverageReport

Populated PgstarCoverageReport.

Raises:

Type Description
FileNotFoundError

If any plotting .defaults file is missing.

ValueError

If upstream .defaults contains an uncatalogued *_win_flag panel family, or a catalogued row names a builder that flexmesa.plotting does not export.

flexmesa.plotting.cli

Command-line interface for flexmesa plot diagnostic figures (#173).

main

main(argv=None)

Execute flexmesa plot CLI subcommands.

Parameters:

Name Type Description Default
argv list[str] | None

Arguments following flexmesa plot (default sys.argv[1:]).

None

Returns:

Type Description
int

Exit status code (0 on success, non-zero on missing inputs/error).


Four-Stage Performance Benchmark Harness (flexmesa.bench)

flexmesa.bench executes the 4-stage optimization staircase (Stage 0 Sequential Baseline, Stage 1 Multi-Core FFI / SoA, Stage 2 @jax.jit, Stage 3 @jax.jit(vmap)) and reports regression summary checksums across standalone kernels (post-audit MESA 26.4.1 comparator re-runs and timing provenance are tracked under #146).

flexmesa.bench.harness

Shared timing harness and deterministic stellar fixtures for Wave 1F.

Provides LatencyStats, BenchRecord, ThermoGrid, BicubTable, measure_us, measure_and_capture, and make_block_tridiag_fixture matching crates/flexmesa-bench.

LatencyStats dataclass

Summary latency statistics in microseconds for an optimization stage.

Attributes:

Name Type Description
median_us float

Median wall-clock execution time in microseconds (\(\mu\)s).

iqr_us float

Interquartile range (\(Q_{75} - Q_{25}\)) in microseconds (\(\mu\)s).

compile_us float

First-call XLA compilation latency in microseconds (\(0.0\) for non-JIT stages).

BenchRecord dataclass

Four-stage benchmark record for a single workload and zone count.

Attributes:

Name Type Description
workload str

Workload identifier ("auto_diff", "interp_2d", "mtx_tridiag", "neu", "turb_mlt", or "turb_tdc").

n_zones int

Number of stellar zones (\(N_{\mathrm{zones}}\)).

stage0 LatencyStats

Stage 0 (sequential 1-thread flexmesa._rust PyO3) latency.

stage1 LatencyStats

Stage 1 (parallel 4-thread rayon flexmesa._rust) latency.

stage2 LatencyStats

Stage 2 (XLA @jax.jit fused kernel) latency.

stage3 LatencyStats

Stage 3 (batched jax.vmap ensemble, per-profile) latency.

max_rel_err float

Maximum relative discrepancy across Stages 0..3.

checksum float

Scalar float64 checksum matching the Rust benchmark suite.

ThermoGrid dataclass

Deterministic stellar thermodynamic profile across \(N_{\mathrm{zones}}\).

Attributes:

Name Type Description
n_zones int

Number of stellar zones (\(N_{\mathrm{zones}}\)).

log10_t NDArray[float64]

Base-10 log temperature \(\log_{10}(T/\mathrm{K})\), shape (n_zones,).

t NDArray[float64]

Temperature \(T\) in \(\mathrm{K}\), shape (n_zones,).

log10_rho NDArray[float64]

Base-10 log density in \(\mathrm{g\,cm^{-3}}\), shape (n_zones,).

rho NDArray[float64]

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape (n_zones,).

abar NDArray[float64]

Mean atomic weight \(\bar{A}\) in \(\mathrm{amu}\), shape (n_zones,).

zbar NDArray[float64]

Mean ionic charge \(\bar{Z}\) in \(e\), shape (n_zones,).

create classmethod

create(n_zones)

Constructs the deterministic stellar profile for n_zones shells.

Parameters:

Name Type Description Default
n_zones int

Number of radial zones (\(N_{\mathrm{zones}} \ge 1\)).

required

Returns:

Type Description
ThermoGrid

Initialized ThermoGrid instance with float64 NumPy arrays.

BicubTable dataclass

Precomputed \(64 \times 64\) 2D bicubic spline table over \((\rho, T)\).

Attributes:

Name Type Description
x NDArray[float64]

Strictly ascending x grid of shape (64,) in \([3.5, 9.5]\).

y NDArray[float64]

Strictly ascending y grid of shape (64,) in \([7.0, 10.0]\).

coeffs NDArray[float64]

Bicubic spline coefficients [f, f_xx, f_yy, f_xxyy] of shape (64, 64, 4).

x_jax Array

Device-resident JAX float64 x grid of shape (64,).

y_jax Array

Device-resident JAX float64 y grid of shape (64,).

coeffs_jax Array

Device-resident JAX float64 coefficients (64, 64, 4).

ilinx bool

Uniform-spacing flag along x.

iliny bool

Uniform-spacing flag along y.

create classmethod

create()

Builds the deterministic \(64 \times 64\) bicubic spline table.

Returns:

Type Description
BicubTable

Initialized BicubTable matching crates/flexmesa-bench.

measure_us

measure_us(
    n_warmup, n_repeats, op, record_first_as_compile=False
)

Measures median and IQR latency (in microseconds) of callable op.

Parameters:

Name Type Description Default
n_warmup int

Number of untimed warmup iterations (\(\ge 1\) when record_first_as_compile is True).

required
n_repeats int

Number of timed iterations (\(\ge 3\)).

required
op Callable[[], object]

Zero-argument callable to benchmark.

required
record_first_as_compile bool

Whether to time the very first warmup call as compile_us (including XLA trace + compilation).

False

Returns:

Type Description
LatencyStats

LatencyStats containing (median_us, iqr_us, compile_us).

measure_and_capture

measure_and_capture(
    n_warmup, n_repeats, op, record_first_as_compile=False
)

Measures latency of op and returns (LatencyStats, last_result).

Parameters:

Name Type Description Default
n_warmup int

Number of untimed warmup iterations.

required
n_repeats int

Number of timed iterations.

required
op Callable[[], T]

Zero-argument callable returning a result of type T.

required
record_first_as_compile bool

Whether to record first-call compile time.

False

Returns:

Type Description
tuple[LatencyStats, T]

Tuple (stats, result) where result is the output of the final call.

measure_stage3_batch

measure_stage3_batch(n_warmup, n_repeats, op_batch)

Measures a batched Stage 3 call and amortizes latency per profile.

Parameters:

Name Type Description Default
n_warmup int

Number of untimed warmup iterations.

required
n_repeats int

Number of timed iterations.

required
op_batch Callable[[], T]

Zero-argument callable executing a batch of STAGE3_BATCH_SIZE stellar profiles.

required

Returns:

Type Description
LatencyStats

Two-tuple (amortized_stats, batch_result) where median_us and

T

iqr_us are divided by STAGE3_BATCH_SIZE.

max_rel_diff

max_rel_diff(reference, candidate)

Computes maximum elementwise relative difference between two arrays.

Parameters:

Name Type Description Default
reference ArrayLike

Reference array-like input in float64.

required
candidate ArrayLike

Candidate array-like input in float64 of matching shape (or batched shape (B, *reference.shape)).

required

Returns:

Type Description
float

Maximum relative discrepancy across all elements, or NaN if any

float

entry is non-finite.

Raises:

Type Description
ValueError

If candidate is not broadcast-compatible with reference.

max_err3

max_err3(d1, d2, d3)

Combines three stage relative errors while propagating NaN.

Parameters:

Name Type Description Default
d1 float

Stage 1 relative discrepancy.

required
d2 float

Stage 2 relative discrepancy.

required
d3 float

Stage 3 relative discrepancy.

required

Returns:

Type Description
float

Maximum of (d1, d2, d3), or NaN if any input is NaN.

make_block_tridiag_fixture

make_block_tridiag_fixture(nz)

Constructs the \(5 \times 5\) block-tridiagonal system across nz shells.

Parameters:

Name Type Description Default
nz int

Number of stellar shells (\(N_{\mathrm{zones}}\)).

required

Returns:

Type Description
NDArray[float64]

4-tuple (lblk, dblk, ublk, rhs) with block arrays of shape

NDArray[float64]

(nz, 5, 5) and right-hand side of shape (nz, 5) in float64.

flexmesa.bench.kernels_micro

Four-stage microphysics and utility kernel benchmarks (flexmesa.bench).

Evaluates the Three-Tier Hybrid Architecture across Stages 0..3 for: 1. bench_autodiff: Two-variable second-order forward-mode hyperdual via zero-copy flexmesa._rust (parallel=False Stage 0, parallel=True 4-thread rayon Stage 1) vs. XLA @jax.jit (Stage 2) and @jax.jit(vmap) (Stage 3). 2. bench_interp2d: 2D bicubic spline evaluation (interp_2d) across flexmesa._rust.interp_evbicub_batch (1-thread Stage 0, 4-thread rayon Stage 1) and @jax.jit / @jax.jit(vmap) (Stages 2..3). 3. bench_neu: Thermal neutrino energy-loss rate and 4-variable Jacobian evaluation (neu) across flexmesa._rust.neu_get_batch (Stages 0..1) and @jax.jit / @jax.jit(vmap) (Stages 2..3).

bench_autodiff

bench_autodiff(grid, n_warmup=2, n_repeats=7)

Benchmarks two-variable 2nd-order automatic differentiation.

Parameters:

Name Type Description Default
grid ThermoGrid

Stellar thermodynamic profile across n_zones shells.

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_interp2d

bench_interp2d(grid, table, n_warmup=2, n_repeats=7)

Benchmarks 2D bicubic spline evaluation (interp_2d) across Stages 0..3.

Parameters:

Name Type Description Default
grid ThermoGrid

Stellar thermodynamic profile across n_zones shells.

required
table BicubTable

Precomputed \(64 \times 64\) bicubic spline table.

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_neu

bench_neu(grid, n_warmup=2, n_repeats=7)

Benchmarks thermal neutrino loss (neu) across Stages 0..3.

Parameters:

Name Type Description Default
grid ThermoGrid

Stellar thermodynamic profile across n_zones shells.

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

flexmesa.bench.kernels_solver

Four-stage solver and convective transport benchmarks (flexmesa.bench).

Evaluates the Three-Tier Hybrid Architecture across Stages 0..3 for: 1. bench_mtx_block_tridiag: \(5 \times 5\) block-tridiagonal Henyey system factorization and solve (mtx) across flexmesa._rust (sequential Thomas Stage 0, 4-thread rayon Hirshman bcyclic Stage 1) and JAX solve_block_tridiag_pcr (@jax.jit Stage 2, @jax.jit(vmap) Stage 3). 2. bench_turb_mlt: Cox Mixing-Length Theory (set_mlt / set_mlt_jax) with first-order sensitivities across flexmesa._rust.set_mlt_batch (1-thread Stage 0, 4-thread rayon Stage 1) and @jax.jit / @jax.jit(vmap) (Stages 2..3). 3. bench_turb_tdc: Kuhfuss 1D Time-Dependent Convection (set_tdc) with Newton-iteration sensitivities matching upstream auto_diff_real_tdc across flexmesa._rust.set_tdc_batch (Stages 0..1) and @jax.jit / @jax.jit(vmap) (Stages 2..3).

bench_turb_mlt

bench_turb_mlt(grid, n_warmup=2, n_repeats=7)

Benchmarks Cox Mixing-Length Theory (set_mlt) across Stages 0..3.

Parameters:

Name Type Description Default
grid ThermoGrid

Stellar thermodynamic profile across n_zones shells.

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_turb_tdc

bench_turb_tdc(grid, n_warmup=2, n_repeats=7)

Benchmarks Kuhfuss 1D Time-Dependent Convection (set_tdc) Stages 0..3.

Parameters:

Name Type Description Default
grid ThermoGrid

Stellar thermodynamic profile across n_zones shells.

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

run_all_wave1_benchmarks

run_all_wave1_benchmarks(
    zone_counts=(128, 1024, 4096), n_warmup=2, n_repeats=7
)

Runs all six Wave 1 benchmark workloads across zone_counts.

Parameters:

Name Type Description Default
zone_counts Sequence[int]

Sequence of stellar zone counts \(N_{\mathrm{zones}}\).

(128, 1024, 4096)
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
list[BenchRecord]

List of BenchRecord instances across all workloads and zone counts.

flexmesa.bench.kernels_wave2

Wave 2 four-stage microphysics benchmarks (flexmesa.bench.kernels_wave2).

Evaluates the Three-Tier Hybrid Architecture across Stages 0..3 for the four Wave 2 atomic and photometric microphysics workloads: 1. bench_chem_comp: 8-isotope stellar composition moments (xh, xhe, xz, abar, zbar, z2bar, z53bar, ye, mass_correction, sumx) across a core-to-surface composition gradient (get_composition_info_zones). 2. bench_ion_fe56: Potekhin \({}^{56}\mathrm{Fe}\)-in-\({}^4\mathrm{He}\) effective charge and partial derivatives ([z, dz_dlog10_ne, dz_dlog10_t]) on the \(105 \times 30\) Thomas-Fermi-Dirac-Hubbard bicubic spline grid. 3. bench_ion_4d: 4D (Z, X, log10_rho, log10_T) trilinear-over-bicubic mean ionic charge and partial pressure interpolation across all 28 eval_ionization channels. 4. bench_colors_sed: 3D (Teff, log_g, [M/H]) Kurucz2003all cubic Hermite SED synthesis (1199 wavelengths) plus bolometric integration and 7-band Generic/Johnson (B, I, J, M, R, U, V) Vega synthetic photometry.

make_wave2_composition_profile

make_wave2_composition_profile(nz)

Build the deterministic (nz, 8) stellar abundance profile xa.

Matches make_wave2_composition_profile in flexmesa-bench and benchmarks/fortran_mesa/bench_kernels_wave2.f90.

Parameters:

Name Type Description Default
nz int

Number of radial stellar shells (\(N_{\mathrm{zones}}\)).

required

Returns:

Type Description
NDArray[float64]

2D C-contiguous float64 array of shape (nz, 8).

bench_chem_comp

bench_chem_comp(nz, n_warmup=2, n_repeats=7)

Benchmark 8-isotope stellar composition moments (chem_comp).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_ion_fe56

bench_ion_fe56(nz, n_warmup=2, n_repeats=7)

Benchmark Fe56-in-He4 bicubic spline (ion_fe56).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_ion_4d

bench_ion_4d(nz, n_warmup=2, n_repeats=7)

Benchmark 4D (Z, X, log10_rho, log10_T) ionization (ion_4d).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_colors_sed

bench_colors_sed(nz, n_warmup=2, n_repeats=7)

Benchmark 3D Kurucz Hermite SED + Johnson photometry (colors_sed).

Parameters:

Name Type Description Default
nz int

Number of stellar models (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

run_all_wave2_benchmarks

run_all_wave2_benchmarks(
    zone_counts=(128, 1024, 4096), n_warmup=2, n_repeats=7
)

Run all four Wave 2 benchmarks across zone_counts.

flexmesa.bench.kernels_wave3a

Wave 3a four-stage EOS benchmarks (flexmesa.bench.kernels_wave3a).

Evaluates the Three-Tier Hybrid Architecture across Stages 0..3 for the four Wave 3a stellar equation-of-state (eos) workloads: 1. bench_eos_ideal: Neutral ideal-gas plus Planckian radiation EOS (eval_ideal_eos_zones) over the 8-isotope WAVE2_ISO_NAMES composition profile at \(\log_{10}\rho \in [-6, -2]\) and \(\log_{10}T \in [3.5, 4.5]\). 2. bench_eos_helm: Timmes & Swesty (2000) biquintic/bicubic Helmholtz electron-positron + Hull & Lewis (1956) Coulomb + ideal-ion + radiation EOS (eval_helm_eos_zones) for a 50/50 \({}^{12}\mathrm{C}/{}^{16}\mathrm{O}\) mixture at \(\log_{10}\rho \in [1.0, 6.0]\) and \(\log_{10}T \in [8.0, 8.008]\). 3. bench_eos_pc: Potekhin & Chabrier (2010, 2013) non-ideal Coulomb liquid and bcc crystal EOS (eval_pc_eos_zones) for a 50/50 \({}^{12}\mathrm{C}/{}^{16}\mathrm{O}\) white dwarf interior crossing the liquid-to-crystal phase transition (\(\log_{10}\rho \in [4.5, 7.5]\), \(\log_{10}T \in [6.2, 7.4]\)). 4. bench_eos_skye: Jermyn et al. (2021) third-order Helmholtz free-energy minimization EOS (eval_skye_eos_zones) for a 50/50 \({}^{12}\mathrm{C}/{}^{16}\mathrm{O}\) plasma at \(\log_{10}\rho \in [1.0, 6.0]\) and \(\log_{10}T \in [8.0, 8.008]\).

bench_eos_ideal

bench_eos_ideal(nz, n_warmup=2, n_repeats=7)

Benchmark neutral ideal-gas + radiation EOS (eos_ideal).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_eos_helm

bench_eos_helm(nz, n_warmup=2, n_repeats=7)

Benchmark Timmes & Swesty (2000) HELM EOS (eos_helm).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_eos_pc

bench_eos_pc(nz, n_warmup=2, n_repeats=7)

Benchmark Potekhin & Chabrier (2010, 2013) PC EOS (eos_pc).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_eos_skye

bench_eos_skye(nz, n_warmup=2, n_repeats=7)

Benchmark Jermyn et al. (2021) third-order Skye EOS (eos_skye).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

run_all_wave3a_benchmarks

run_all_wave3a_benchmarks(
    zone_counts=(128, 1024, 4096), n_warmup=2, n_repeats=7
)

Run all four Wave 3a EOS benchmarks across zone_counts.

Parameters:

Name Type Description Default
zone_counts Sequence[int]

Sequence of radial zone counts (\(N_{\mathrm{zones}}\)).

(128, 1024, 4096)
n_warmup int

Number of untimed warmup iterations per stage.

2
n_repeats int

Number of timed iterations per stage.

7

Returns:

Type Description
list[BenchRecord]

List of [BenchRecord] objects (4 * len(zone_counts) total).

flexmesa.bench.kernels_wave3b

Wave 3b four-stage microphysics benchmarks (flexmesa.bench.kernels_wave3b).

Evaluates the Three-Tier Hybrid Architecture across Stages 0..3 for the five Wave 3b stellar microphysics workloads (eos_4d, kap_fixed, rates_screen, net_eval, and atm_table).

bench_eos_4d

bench_eos_4d(nz, n_warmup=2, n_repeats=7)

Benchmark 4D tabulated OPAL/SCVH EOS (eos_4d).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_kap_fixed

bench_kap_fixed(nz, n_warmup=2, n_repeats=7)

Benchmark Type 1 fixed-metal + conductive opacity (kap_fixed).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_rates_screen

bench_rates_screen(nz, n_warmup=2, n_repeats=7)

Benchmark r_c12_ag_o16 REACLIB + extended screening (rates_screen).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_net_eval

bench_net_eval(nz, n_warmup=2, n_repeats=7)

Benchmark 8-isotope basic.net RHS + Jacobian (net_eval).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

bench_atm_table

bench_atm_table(nz, n_warmup=2, n_repeats=7)

Benchmark ATM_TABLE_PHOTOSPHERE model atmosphere (atm_table).

Parameters:

Name Type Description Default
nz int

Number of radial zones (\(N_{\mathrm{zones}}\)).

required
n_warmup int

Number of untimed warmup iterations.

2
n_repeats int

Number of timed iterations.

7

Returns:

Type Description
BenchRecord

BenchRecord with Stages 0..3 latencies and cross-stage error.

run_all_wave3b_benchmarks

run_all_wave3b_benchmarks(
    zone_counts=(128, 1024, 4096), n_warmup=2, n_repeats=7
)

Run all five Wave 3b microphysics benchmarks across zone_counts.

Parameters:

Name Type Description Default
zone_counts Sequence[int]

Sequence of radial zone counts (\(N_{\mathrm{zones}}\)).

(128, 1024, 4096)
n_warmup int

Number of untimed warmup iterations per stage.

2
n_repeats int

Number of timed iterations per stage.

7

Returns:

Type Description
list[BenchRecord]

List of [BenchRecord] objects (5 * len(zone_counts) total).

flexmesa.bench.kernels_wave4

Wave 4 four-stage stellar structure and evolution benchmarks.

Evaluates the Three-Tier Hybrid Architecture (flexmesa._rust + JAX float64) across Stages 0..3 for the five Wave 4 1D stellar engine workloads: 1. star_micro_vars: Zone EOS/opacity/neutrino/nuclear network + face MLT and Brunt-Väisälä evaluation (eval_hydro_vars vs. @jax.jit face kernels). 2. star_hydro_eqns: Coupled 1D Lagrangian hydrostatic/thermal residuals and block-tridiagonal Jacobian assembly (eval_equations vs. @jax.jit eval_hydro_residuals_jax). 3. star_newton_step: Single Henyey linearize-and-solve step comparing sequential solve_block_tridiagonal, 4-thread Hirshman bcyclic, @jax.jit Parallel Cyclic Reduction (solver_mode="pcr"), and custom_vjp Safe Rust bcyclic FFI (solver_mode="rust_ffi"). 4. star_remesh: Dimensionless mesh spacing function \(g_k\) (eval_mesh_gval) and adaptive split/merge planning. 5. star_evolve_step: Full structure + nuclear burning + convective mixing evolutionary step (step_struct_burn_mix + Söderlind & Wang 2006 H211 digital timestep controller).

MIN_EVOLVE_STEP_ZONES module-attribute

MIN_EVOLVE_STEP_ZONES = 64

Smallest grid on which bench_star_evolve_step runs (mirrors the Rust constant of the same name in crates/flexmesa-bench/src/kernels_wave4.rs).

make_wave4_zams_model

make_wave4_zams_model(nz)

Construct a resampled \(4.0\,M_\odot, Z = 0.02\) ZAMS StarModel.

Matches flexmesa_bench::make_wave4_zams_model(nz) so cross-language benchmarks operate on identical initial stellar profiles.

Parameters:

Name Type Description Default
nz int

Target number of Lagrangian zones (\(N_{\mathrm{zones}} \ge 4\)).

required

Returns:

Type Description
StarModel

Initialized StarModel with nz zones.

bench_star_micro_vars

bench_star_micro_vars(nz, n_warmup=2, n_repeats=7)

Benchmark zone/face stellar microphysics (star_micro_vars).

bench_star_hydro_eqns

bench_star_hydro_eqns(nz, n_warmup=2, n_repeats=7)

Benchmark coupled 1D Henyey residual & Jacobian (star_hydro_eqns).

bench_star_newton_step

bench_star_newton_step(nz, n_warmup=2, n_repeats=7)

Benchmark Henyey linearize-and-solve step (star_newton_step).

bench_star_remesh

bench_star_remesh(nz, n_warmup=2, n_repeats=7)

Benchmark adaptive mesh spacing evaluation (star_remesh).

bench_star_evolve_step

bench_star_evolve_step(nz, n_warmup=2, n_repeats=7)

Benchmark full structure + burn + mix step (star_evolve_step).

The kernel runs on at least MIN_EVOLVE_STEP_ZONES zones: the resampled ZAMS fixture is too far from equilibrium on coarser grids to take a step at the model's own timestep.

run_all_wave4_benchmarks

run_all_wave4_benchmarks(
    zone_counts=(128, 512, 1024), n_warmup=2, n_repeats=7
)

Run all five Wave 4 1D stellar engine benchmarks across zone_counts.

flexmesa.bench.kernels_wave5

Wave 5 four-stage advanced stellar physics, interacting binary, and asteroseismology benchmarks (flexmesa.bench.kernels_wave5).

Evaluates the Three-Tier Hybrid Architecture (flexmesa._rust + JAX float64) across Stages 0..3 for the three Wave 5 workloads: 1. w5_riemann_rsp2: Well-balanced 1D spherical Lagrangian HLLC Riemann hydrodynamics, momentum residual assembly, Kuhfuss (1986) / Smolec & Moskalik (2008) RSP2 turbulent convection equations, and Dziembowski dimensionless pulsation variables \((V, V_g, A^*, U, c_1)\). 2. w5_binary_rlof: Eggleton (1983) Roche-lobe radius, Keplerian orbital mechanics, Ritter (1988) optically thin RLOF mass transfer, Bardeen (1972) / King & Kolb (1999) / Podsiadlowski (2003) Kerr black hole ISCO spin and Eddington accretion, Peters (1964) + Rappaport, Verbunt & Joss (1983) orbital \(\dot{J}\), and Hut (1981) tidal eccentricity evolution. 3. w5_astero_seism: Cumulative acoustic radius/depth integrals, asymptotic and solar-scaled \(\Delta\nu, \nu_{\max}, \nu_{\mathrm{ac}}, \Delta\Pi_1\), Ball & Gizon (2014) 1-term cubic and 2-term combined surface-effect frequency corrections, and Roxburgh & Vorontsov (2003) 5-point separation ratios \((r_{01}, r_{10})\).

bench_w5_riemann_rsp2

bench_w5_riemann_rsp2(nz, n_warmup=3, n_repeats=9)

Benchmark Wave 5.2 HLLC Riemann and RSP2 (w5_riemann_rsp2).

bench_w5_binary_rlof

bench_w5_binary_rlof(nz, n_warmup=3, n_repeats=9)

Benchmark Wave 5.3 interacting binary physics (w5_binary_rlof).

bench_w5_astero_seism

bench_w5_astero_seism(nz, n_warmup=3, n_repeats=9)

Benchmark Wave 5.4 asteroseismic diagnostics (w5_astero_seism).

run_all_wave5_benchmarks

run_all_wave5_benchmarks(
    zone_counts=(128, 512, 1024), n_warmup=3, n_repeats=9
)

Run all three Wave 5 benchmarks across zone_counts.

flexmesa.testing.routine_inventory reads the committed list of every subroutine and function in the upstream MESA 26.4.1 Fortran files with its line span (benchmarks/dashboard/routine_inventory.json, generated from the MESA source by scripts/dashboard/build_routine_inventory.py, #611). flexmesa.testing.routine_gate checks that every routine_map key in the port manifest is a routine of that upstream file and that every mapped target is an existing Rust fn item. flexmesa.testing.routine_table derives the per-module and per-file counts of routines and own lines mapped in full, mapped in part (routine_map_partial in the port manifest), declared not applicable (flexmesa.testing.routine_na, benchmarks/dashboard/port_status_na.toml), and unmapped (notes/audit/routine_table.md). flexmesa.testing.routine_backlog attributes unmapped routines to the declared-gap cases whose reasons name them.

flexmesa.testing.routine_inventory

Routine inventory of upstream MESA 26.4.1 Fortran sources (#611).

The committed inventory benchmarks/dashboard/routine_inventory.json lists, for every Fortran file in port_manifest.toml, each routine with its line span and the number of lines outside any routine. It is generated by scripts/dashboard/build_routine_inventory.py from the upstream source and checked here without the source by internal-consistency rules.

Covered suffixes are those that hold Fortran text: .f90, .F90, .f, .inc, .incl, .dek, .fpp, and .fypp (GYRE templates, scanned unexpanded). Skipped suffixes are .c and .h (C sources) and .trf (STELLA sources in a transformed Fortran dialect with ; terminators and -- comments that the routine scanner cannot read).

is_covered

is_covered(upstream_path)

Return True when the inventory scans upstream_path.

build_inventory

build_inventory(manifest, mesa_dir)

Parse every covered upstream file and build the inventory payload.

Parameters:

Name Type Description Default
manifest PortManifest

Loaded port manifest (provides paths and SHA-256 digests).

required
mesa_dir Path

Root of the MESA 26.4.1 source tree.

required

Returns:

Type Description
dict[str, Any]

JSON-serializable inventory with a provenance header and per-file

dict[str, Any]

routine lists.

Raises:

Type Description
ValueError

If a source digest or line count disagrees with the manifest, or the parser reports a diagnostic for a file.

render_inventory

render_inventory(payload)

Render the inventory deterministically, one routine per line.

load_inventory

load_inventory(path)

Load a committed inventory file.

validate_inventory

validate_inventory(payload, manifest)

Check an inventory against the manifest and its own spans.

Needs no MESA source. Verifies the provenance header, that the covered file set equals the manifest's Fortran files with matching digests and line counts, that every span lies in the file and is correctly ordered, and that each file's outside count equals the lines outside the union of its routine spans.

Parameters:

Name Type Description Default
payload dict[str, Any]

Loaded inventory.

required
manifest PortManifest

Loaded port manifest.

required

Returns:

Type Description
list[str]

Error messages (empty when consistent).

flexmesa.testing.routine_gate

Gate on routine_map entries against the routine inventory (#611).

Two checks run over every routine_map entry of port_manifest.toml:

  • routine_key: the key names exactly one routine of that upstream file in benchmarks/dashboard/routine_inventory.json (Fortran names are matched without regard to case). A key is either a bare name or parent::name for a contained procedure. A bare name that matches more than one routine of the file (for example three contained check procedures) is a violation, and the qualified form must be used;
  • fn_item: every symbol of the mapped target <path>::<sym>[+<sym>...] exists as a function item (fn in Rust, def in Python) in that file. A struct, constant, or enum with the right name does not satisfy it. A symbol is a bare name or a type-qualified method Type::name. A qualified symbol requires an impl block for Type in the file (an inherent impl, a generic impl, or impl Trait for Type) that holds fn name. A bare Rust name is a violation when the file defines more than one fn of that name (free functions and methods together), because it cannot say which one is meant; use Type::name.

Two structural checks run without an allow-list:

  • every name in a file's routine_map_partial is a key of that file's routine_map;
  • every routine declared not applicable in port_status_na.toml (read by routine_na, when that file exists) names exactly one routine of the inventory and is not also a routine_map key naming the same routine.

Violations present when the gate was introduced are listed in benchmarks/dashboard/routine_map_allowlist.toml with per-check counts. The gate fails on any violation outside the allow-list and on any allow-list entry that no longer violates, so the allow-list can only shrink.

Run python -m flexmesa.testing.routine_gate to check, --report to print counts, and --write-allowlist to regenerate the allow-list after a deliberate change.

Violation dataclass

One routine_map entry that fails a gate check.

Attributes:

Name Type Description
check str

routine_key or fn_item.

upstream_path str

Manifest upstream_path of the entry.

routine str

The routine_map key.

target str

The mapped <path>::<sym>[+<sym>...] value.

detail str

What is missing (the file, or the offending symbol).

ident

ident()

Return the identity used to match allow-list entries.

match_routines

match_routines(key, routines)

Return the inventory routines that a routine_map key names.

Parameters:

Name Type Description Default
key str

name or parent::name (case-insensitive). The parent is the enclosing routine recorded in the inventory.

required
routines list[list[Any]]

Inventory rows [name, kind, parent, first, last].

required

Returns:

Type Description
list[list[Any]]

Matching rows. A usable key matches exactly one; none means the key

list[list[Any]]

is unknown and several mean it is ambiguous.

structural_errors

structural_errors(manifest, inventory, na_entries)

Return errors for partial markers and N/A declarations.

Parameters:

Name Type Description Default
manifest PortManifest

Loaded port manifest.

required
inventory dict[str, Any]

Loaded routine inventory.

required
na_entries list[Any]

routine_na.NotApplicable declarations.

required

Returns:

Type Description
list[str]

Error messages, empty when every marker and declaration is valid.

na_rows

na_rows(na, routines)

Return inventory rows named by an N/A entry (name, parent, span).

collect_violations

collect_violations(manifest, inventory, repo_root)

Return every routine_map entry failing a gate check, sorted.

load_allowlist

load_allowlist(path)

Load (declared counts, allowed violations) from the allow-list.

render_allowlist

render_allowlist(violations)

Render the allow-list for violations deterministically.

verify_routine_map

verify_routine_map(repo_root, manifest=None, mesa_dir=None)

Run the inventory consistency and routine_map gate checks.

Parameters:

Name Type Description Default
repo_root Path

Repository checkout root.

required
manifest PortManifest | None

Loaded manifest (loaded from the repository when omitted).

None
mesa_dir Path | None

Optional MESA 26.4.1 source tree. When it holds the manifest's Fortran files (a partial tree is ignored), the inventory is also regenerated and compared; otherwise only internal consistency is checked.

None

Returns:

Type Description
list[str]

Error messages (empty when the gate passes).

main

main(argv=None)

Command-line entry point.

flexmesa.testing.routine_backlog

Failing-case attribution for the unmapped-routine backlog (#611).

The backlog lists routines of core-engine files with status stub, partial, or absent that no gate-checked routine_map entry names. This module attaches to each routine the non-passing harness cases that plausibly need it, using one mechanical signal only: the free-text reason of each declared gap in benchmarks/history_harness/known_gaps.toml.

A routine is attributed to a case when the case's reason

  • names the routine (an identifier equal to the Fortran name, compared without regard to case, of at least eight characters or containing an underscore, so that short common words never match), basis routine; or
  • names the routine's upstream file, by full path or by file name of at least six characters, basis file (every unmapped routine of the file is then attributed, because the reason does not say which one is needed).

A routine name that occurs in several backlog files is attributed only when the same reason also names one of those files; otherwise it is left unattributed. Neither the unsupported-controls report nor extras_status.toml names a routine, so they cannot attribute anything and are not used. Routines that no reason names stay unattributed, which does not mean that no case needs them.

load_gap_cases

load_gap_cases(repo_root)

Return (case_id, reason) for every declared harness gap.

Parameters:

Name Type Description Default
repo_root Path

Repository root.

required

Returns:

Type Description
list[tuple[str, str]]

Pairs of "<suite>/<case>" and the gap's reason text.

attribute

attribute(backlog, gaps)

Fill cases and basis on each backlog row, in place.

Parameters:

Name Type Description Default
backlog list[dict[str, Any]]

Rows with upstream_path and routine keys.

required
gaps list[tuple[str, str]]

Output of :func:load_gap_cases.

required

flexmesa.testing.routine_table

Derived routine-level port table from the routine inventory (#611).

Combines routine_inventory.json (what upstream contains) with the routine_map entries of port_manifest.toml (what the port claims) to give routines and upstream lines per file, per module, and for the core engine modules together. Every routine is at exactly one of four levels:

  • full: the file's routine_map names it, the mapped target passes the routine_map gate (the key is an inventory routine and every symbol is a function item), and it is not listed in routine_map_partial;
  • partial: mapped as above and listed in the file's routine_map_partial (the Rust counterpart implements only part of it);
  • na: declared not applicable to a Rust port in port_status_na.toml (see routine_na). It is never counted as mapped and stays in every denominator; fractions are given both with and without those lines;
  • unmapped: none of the above.

Lines are credited to a routine for its own lines only: its span minus the spans of the procedures contained in it. A contained procedure is credited only when it is itself mapped (by bare name where that is unambiguous, or as parent::name). The own lines of all routines of a file plus its lines outside any routine therefore equal the file's line count.

The oracle levels count a fully mapped routine only through a verified [[tests.oracles]] entry of a test classified oracle in test_taxonomy.toml, whose expected values trace to a committed MESA 26.4.1 artifact (_oracle_provenance, DECISIONS #80): oracle_exact when some verified entry compares at 0 ULP, otherwise oracle_print when a verified entry compares within a stated tolerance against printed MESA values. The exercised level needs the coverage job and is not computed. No status in the manifest is read as evidence of a routine.

Each file also gets a derived status ceiling (see status_ceiling) from full mappings only, and the table reports where the hand-set status exceeds it or sits below it. The ceiling is reported only; nothing gates on it and no status is changed. The backlog of unmapped routines carries failing-case attribution from routine_backlog.

Outputs are notes/audit/routine_table.md and notes/audit/routine_table.json, regenerated by scripts/dashboard/build_routine_table.py and compared byte for byte by its --check mode.

own_lines

own_lines(routines)

Return each routine's own line count (span minus contained spans).

Parameters:

Name Type Description Default
routines list[list[Any]]

Inventory rows [name, kind, parent, first, last] sorted by span, as the inventory stores them.

required

Returns:

Type Description
list[int]

One count per row: its span length less the union of the spans of the

list[int]

rows contained in it. Rows with an identical span are nested in

list[int]

inventory order.

status_ceiling

status_ceiling(routines, mapped, oracle, partial=0)

Return the highest status the routine evidence supports, or None.

The rule, applied to the applicable routines of one inventory file (those not declared not applicable) with mapped counting full mappings only:

  • no routines, or none mapped in full or in part: None;
  • any routine partial or unmapped: partial;
  • all routines mapped in full: ported_unverified;
  • all routines mapped in full and each also has exact (0-ULP) oracle evidence: kernel_reference_vectors. Print-precision oracles do not count toward this ceiling.

case_level_evidence is never a ceiling because the exercised level is not derived. Contained procedures count as routines, so a file is eligible only when they are mapped too.

Parameters:

Name Type Description Default
routines int

Number of applicable inventory routines in the file.

required
mapped int

How many of them are mapped in full.

required
oracle int

How many of them have exact (0-ULP) oracle evidence.

required
partial int

How many of them are mapped in part.

0

Returns:

Type Description
PortStatus | None

The ceiling status, or None when the evidence makes no claim.

oracle_claims

oracle_claims(repo_root, manifest)

Evaluate every [[tests.oracles]] claim of the test taxonomy.

oracle_routine_ids

oracle_routine_ids(repo_root, manifest)

Return (exact ids, print-only ids) of verified oracle routines.

build_table

build_table(
    manifest,
    inventory,
    repo_root,
    *,
    oracle_ids=None,
    gaps=None,
    na_entries=None,
)

Derive the per-file, per-module, and engine routine table.

Parameters:

Name Type Description Default
manifest PortManifest

Loaded port manifest.

required
inventory dict[str, Any]

Loaded routine inventory.

required
repo_root Path

Repository root (to resolve mapped Rust and Python files).

required
oracle_ids tuple[set[str], set[str]] | None

(exact, print-only) sets of verified <upstream path>::<routine> ids; evaluated from test_taxonomy.toml when None.

None
gaps list[tuple[str, str]] | None

(case id, reason) pairs for backlog attribution; read from known_gaps.toml when None.

None
na_entries list[NotApplicable] | None

Routines declared not applicable; read from port_status_na.toml (none when absent) when None.

None

Returns:

Type Description
dict[str, Any]

JSON-serializable table with files, modules, engine and

dict[str, Any]

backlog sections.

render_json

render_json(table)

Render the table as deterministic JSON, one file row per line.

render_markdown

render_markdown(table)

Render the table as Markdown for notes/audit/.

render_outputs

render_outputs(repo_root)

Return the expected content of the table files for repo_root.

flexmesa.testing.routine_na

Upstream routines declared not applicable to a Rust port (#611).

benchmarks/dashboard/port_status_na.toml lists upstream routines that have no counterpart by design, such as Fortran memory management, module-global callback adapters, debug helpers, empty stubs, and pgstar plotting. Each [[na]] entry carries upstream_path, routine, category and reason, and may carry parent, first and last to pin the inventory row. The routine table reports these routines as their own level. They are never counted as mapped and never removed from the denominators.

NotApplicable dataclass

One routine declared not applicable to the Rust port.

Attributes:

Name Type Description
upstream_path str

Manifest path of the upstream file.

routine str

Fortran routine name.

category str

Reason category, for example fortran_mem or stub.

reason str

Free-text justification.

parent str

Enclosing routine name, empty for a top-level routine.

first int | None

First line of the routine in the inventory, or None.

last int | None

Last line of the routine in the inventory, or None.

key

key()

Return the name or parent::name key of the routine.

load_na

load_na(path)

Load the N/A declarations (empty when the file does not exist).

Raises:

Type Description
ValueError

If an entry lacks a required field.

na_row_ids

na_row_ids(entries, path, routines)

Return id() of the inventory rows of path declared N/A.

flexmesa.testing.artifact_compare judges a case that takes zero steps and writes a result file (star/rsp_check_2nd_crossing): it parses the file and compares every field with the committed MESA 26.4.1 copy at the precision of the upstream format statement (DECISIONS #76, #606).

flexmesa.testing.artifact_compare

Artifact comparison for cases that take zero evolution steps (#606).

Some upstream test cases never start the evolution loop. Their MESA 26.4.1 run ends inside a hook (for example other_rsp_build_model of star/rsp_check_2nd_crossing) after writing a result file, so there is no history.data to compare. For such a case the manifest declares an [cases.artifact] table: the file MESA wrote, a committed reference copy of it, a parser kind, and one tolerance per field group. This module parses both files, compares every declared field, and reports the first field out of tolerance and the field furthest out (in tolerance units).

Tolerances are the print precision of the upstream format statement, not fitted values. A tolerance is either {abs = x} or {sig_digits = n}: the latter allows one unit in the last printed significant digit of the reference value (for 1pd20.10, n = 11; for E-format with five digits, n = 5). Integers (model numbers, offsets) must be equal.

Only one parser kind exists, rsp_instability_strip, for the output of star/test_suite/rsp_check_2nd_crossing/src/run_star_extras.f90:135-348.

ArtifactSpec dataclass

Manifest declaration of an artifact comparison.

Attributes:

Name Type Description
file str

Name of the file MESA writes (and FlexMESA's hook writes next to the case inputs).

reference str

Repository-relative path of the committed MESA copy.

parser str

Parser kind (see :data:VALID_PARSERS).

tolerances dict[str, dict[str, float]]

Mapping from field group to {"abs": x} or {"sig_digits": n}.

required_steps int

Evolution steps both runs take (0 for the cases this exists for); a different count fails the case.

stdout_reference str

Optional repository-relative path of the per-model lines extracted from MESA's terminal output.

StripScan dataclass

Parsed instability-strip scan file.

Attributes:

Name Type Description
header dict[str, float]

Model parameters (RSP_mass, ...), by label.

models list[tuple[int, float, float, float, float, float]]

One (model_number, period_d, growth, Teff, L, age) row per scanned model; period_d in days, Teff in K, L in Lsun, age in yr.

edges dict[str, float]

Teff_red_edge and Teff_blue_edge in K, by label.

table list[tuple[int, float, float]]

(offset, Teff, L) rows (K, K, Lsun).

StdoutModel dataclass

One per-model block of MESA's terminal output.

Attributes:

Name Type Description
model_number int

Model number of the track point.

teff float

Effective temperature (K) printed with list-directed output.

lum float

Luminosity (Lsun) printed with list-directed output.

period_d float

Period (days), five significant digits.

growth float

Growth rate (per period), five significant digits.

FieldDiff dataclass

One compared field.

Attributes:

Name Type Description
label str

Field name, such as model_growth[3] or edge[Teff_red].

reference float

Value in the MESA reference.

run float

Value in the FlexMESA file (nan when absent).

tolerance float

Allowed absolute difference.

excess float

|run - reference| / tolerance (inf for a nonzero difference against a zero tolerance, 0 for equal values).

out_of_tolerance property

out_of_tolerance

Return whether the field is outside its tolerance.

ArtifactComparison dataclass

Result of comparing one run artifact with its MESA reference.

Attributes:

Name Type Description
status str

"ok" (every field within tolerance), "differs", "missing" (no run file), or "unparsable".

n_fields int

Number of fields compared.

n_out int

Number of fields outside tolerance (or absent).

first_failure FieldDiff | None

First field out of tolerance, in comparison order.

largest FieldDiff | None

Field with the largest excess (None when empty).

stdout_checked bool

Whether per-model standard-output lines were compared.

message str

One-line description for the case table.

ok property

ok

Return whether the artifact agrees within every tolerance.

parse_spec

parse_spec(raw, ctx)

Validate a [cases.artifact] TOML table.

Parameters:

Name Type Description Default
raw dict[str, Any]

Parsed TOML table.

required
ctx str

suite/case label for error messages.

required

Returns:

Type Description
ArtifactSpec

The validated :class:ArtifactSpec.

Raises:

Type Description
ValueError

On a missing key, unknown parser, absent tolerance group, or malformed tolerance.

parse_instability_strip

parse_instability_strip(text)

Parse the file written by rsp_check_2nd_crossing.

Parameters:

Name Type Description Default
text str

File contents.

required

Returns:

Type Description
StripScan

The parsed :class:StripScan.

Raises:

Type Description
ValueError

On a line the format does not allow.

parse_stdout_models

parse_stdout_models(text)

Parse the per-model blocks of MESA's terminal output.

Each block is the line call star_do1_rsp_build model Teff L <n> <Teff> <L>, a P(days) growth header, and one line <mode> <P> <growth>. A block followed by failed in star_do1_rsp_build has no values and is skipped.

Parameters:

Name Type Description Default
text str

Terminal output (or the extract kept as the reference).

required

Returns:

Name Type Description
One list[StdoutModel]

class:StdoutModel per block, in order.

Raises:

Type Description
ValueError

If a block is incomplete or malformed.

compare_artifact

compare_artifact(
    spec,
    reference_text,
    run_text,
    *,
    reference_stdout=None,
    run_stdout=None,
)

Compare a run's artifact with the committed MESA reference.

Parameters:

Name Type Description Default
spec ArtifactSpec

Manifest declaration.

required
reference_text str

Contents of the committed MESA file.

required
run_text str | None

Contents of the file FlexMESA wrote, or None when it wrote none.

required
reference_stdout str | None

Committed per-model terminal lines, when declared.

None
run_stdout str | None

Captured terminal output of the run. When the spec declares a stdout reference and the run's output is None, the comparison is missing rather than a check of the data file alone (#925).

None

Returns:

Name Type Description
The ArtifactComparison

class:ArtifactComparison.

compare_files

compare_files(spec, root_dir, run_dirs, *, run_stdout=None)

Locate the run's artifact in run_dirs and compare it.

Parameters:

Name Type Description Default
spec ArtifactSpec

Manifest declaration.

required
root_dir Path

Directory against which the reference paths resolve.

required
run_dirs list[Path]

Directories to search, in order, for spec.file.

required
run_stdout str | None

Captured per-model terminal lines, if any.

None

Returns:

Name Type Description
The ArtifactComparison

class:ArtifactComparison.

Raises:

Type Description
FileNotFoundError

If a committed reference file is absent.

comparison_to_dict

comparison_to_dict(c)

Convert a comparison to a JSON-serializable dictionary.

comparison_from_dict

comparison_from_dict(d)

Rebuild a comparison from :func:comparison_to_dict output.


Compiled Rust Extension Bridge (flexmesa._rust)

Low-level Safe Rust PyO3 bindings exposed via flexmesa._rust for tracing, log reading, and benchmark kernels (_ArrF64 denotes a float64 NumPy ndarray).

trace_py

  • mesa_read_log_file ((path: str) -> dict[str, Any]): Reads a 6-line-header MESA ASCII table (history.data, profileN.data, or binary_history.data) into a dictionary of headers and 1D float64 arrays.
  • trace_astero_case ((case_dir: str, out_target: str, max_steps_per_stage: int | None = None, skip_optional: bool = True, respect_intervals: bool = False, write_profiles: bool = False, is_logs_dir: bool = True, numerics_mode: str | None = None, allow_unsupported_controls: bool = False, extras: Any = None) -> dict[str, Any]): Runs an upstream astero/test_suite/<case> directory while streaming incremental MESA-format LOGS/history.data and asteroseismic tables.
  • trace_binary_case ((case_dir: str, out_target: str, max_steps: int | None = None, respect_intervals: bool = False, is_logs_dir: bool = True, numerics_mode: str | None = None, allow_unsupported_controls: bool = False, extras: Any = None) -> dict[str, Any]): Runs an upstream binary/test_suite/<case> directory while streaming incremental MESA-format binary_history.data and component LOGS1//LOGS2/.
  • trace_star_case ((case_dir: str, out_target: str, max_steps_per_stage: int | None = None, skip_optional: bool = True, respect_intervals: bool = False, write_profiles: bool = False, is_logs_dir: bool = True, numerics_mode: str | None = None, allow_unsupported_controls: bool = False, extras: Any = None) -> dict[str, Any]): Runs an upstream star/test_suite/<case> directory while streaming incremental MESA-format LOGS/history.data (and optional profiles).

wave5_bench_py

  • w5_eval_astero_seism ((nz: int) -> float): Evaluates the w5_astero_seism benchmark scalar digest for nz zones.
  • w5_eval_binary_rlof_batch ((nz: int, parallel: bool = False) -> _ArrF64): Evaluates the w5_binary_rlof benchmark profile across nz binary configurations (shape (nz,)), dispatching across the persistent 4-thread worker team when parallel is True.
  • w5_eval_diff_rot_batch ((nz: int, parallel: bool = False) -> _ArrF64): Evaluates the w5_diff_rot benchmark profile across nz zones (shape (nz,)), dispatching across the persistent 4-thread worker team when parallel is True.
  • w5_eval_riemann_rsp2_batch ((nz: int, parallel: bool = False) -> _ArrF64): Evaluates the w5_riemann_rsp2 benchmark profile across nz zones (shape (nz,)), dispatching across the persistent 4-thread worker team when parallel is True.