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, |
control_type |
ControlType
|
Parsed |
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
|
element_overrides |
tuple[tuple[str, ControlValue], ...]
|
Tuple of |
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, |
section |
str
|
Active |
comment |
str
|
Inline trailing comment describing units or meaning. |
line_number |
int
|
1-based line number in the |
find_unquoted_char
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
0-based character index of the first unquoted |
strip_fortran_comment
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
Tuple |
parse_control_value
¶
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, |
required |
Returns:
| Type | Description |
|---|---|
tuple[ControlType, ControlValue]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
parse_assignment_clause
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
parse_defaults_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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ControlDefault]
|
Ordered dictionary mapping lowercase control names to |
dict[str, ControlDefault]
|
entries. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any non-comment line contains a malformed assignment or invalid literal. |
Examples:
parse_defaults_file
¶
Read and parse a MESA <pkg>/defaults/*.defaults file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ControlDefault]
|
Ordered dictionary mapping lowercase control names to |
dict[str, ControlDefault]
|
objects. |
parse_columns_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 |
required |
Returns:
| Type | Description |
|---|---|
list[ColumnEntry]
|
Ordered list of active |
list[ColumnEntry]
|
occurrence order when duplicates appear, matching MESA's rule). |
Examples:
parse_columns_file
¶
Read and parse a MESA *_columns.list file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
list[ColumnEntry]
|
Ordered list of active |
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 |
subscript |
str | None
|
Optional array subscript string (for example, |
value_type |
ControlType
|
Parsed |
value |
ControlValue
|
Parsed Python scalar value ( |
line_number |
int
|
1-based line number in the |
NamelistBlock
dataclass
¶
Parsed Fortran &namelist ... / block from a MESA inlist file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Namelist group name without leading |
assignments |
tuple[NamelistAssignment, ...]
|
Ordered tuple of |
parse_namelist_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 |
required |
Returns:
| Type | Description |
|---|---|
list[NamelistBlock]
|
Ordered list of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If namelist headers, assignments, or terminators ( |
Examples:
parse_namelist_file
¶
Read and parse a MESA Fortran inlist file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
list[NamelistBlock]
|
Ordered list of |
validate_namelist_block
¶
Validate a NamelistBlock against a .defaults schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
NamelistBlock
|
Parsed |
required |
schema
|
Mapping[str, ControlDefault]
|
Mapping of lowercase control names to |
required |
strict_numeric_types
|
bool
|
If |
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 |
dict[str, ControlValue | dict[str, ControlValue]]
|
controls to |
Raises:
| Type | Description |
|---|---|
KeyError
|
If an assigned control name does not exist in |
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., |
filename |
str
|
Canonical |
sha256 |
str
|
Lowercase 64-character hexadecimal |
size_bytes |
int
|
Uncompressed |
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
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
compute_sha256_bytes
¶
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 |
Examples:
compute_sha256_file
¶
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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
verify_file_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 |
required |
Returns:
| Type | Description |
|---|---|
str
|
Verified lowercase 64-character hexadecimal |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
parse_manifest_text
¶
Parse manifest.toml text into a dict of TableArtifact entries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Raw TOML content containing a |
required |
Returns:
| Type | Description |
|---|---|
dict[str, TableArtifact]
|
Dictionary mapping logical table |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the TOML syntax is invalid, |
parse_manifest_file
¶
Read and parse a manifest.toml file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
dict[str, TableArtifact]
|
Dictionary mapping logical table |
load_default_manifest
¶
Load the bundled src/flexmesa/data/manifest.toml table manifest.
Returns:
| Type | Description |
|---|---|
dict[str, TableArtifact]
|
Dictionary mapping logical table |
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.
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
¶
Return True when FLEXMESA_DISABLE_RUNTIME_CACHE is enabled.
resolve_cache_dir
¶
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 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 |
resolve_mesa_test_inputs_dir
¶
Resolve the extraction root for mesa-test-inputs-v2.tar.zst.
resolve_mesa_histories_dir
¶
Resolve the extraction root for mesa-histories-v3.tar.zst.
resolve_mesa_module_hex_dir
¶
Resolve the extraction root for mesa-module-hex-v1.tar.zst.
load_upstream_reference
¶
Load [upstream_reference] metadata from bundles.toml.
load_bundles_manifest
¶
Parse bundles.toml into (repo, tag, bundles).
load_embedded_ionization_asset
¶
Load [embedded_ionization] provenance from bundles.toml.
resolve_mesa_astero_tracks_dir
¶
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: |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
|
Path
|
|
bundle_environment
¶
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: |
None
|
manifest_path
|
Path | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
dict[str, str]
|
declares an environment variable. |
select_bundles
¶
Choose the bundles an operation acts on.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bundles
|
Sequence[ReleaseBundle]
|
Every declared bundle. |
required |
include_test_inputs
|
bool
|
Include |
False
|
names
|
Sequence[str] | None
|
Explicit bundle names. Only these are selected, whether or
not they are |
None
|
Returns:
| Type | Description |
|---|---|
ReleaseBundle
|
The selected bundles in declaration order. Without |
...
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name in |
clean_runtime_cache
¶
Remove versioned runtime caches and optional legacy data-dir caches.
is_bundle_ready
¶
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
|
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 |
None
|
source_dir
|
str | Path | None
|
Optional local directory containing pre-downloaded
archives ( |
None
|
base_url
|
str | None
|
Optional override for the GitHub Release download base URL. |
None
|
quiet
|
bool
|
Suppress progress lines when |
False
|
names
|
Sequence[str] | None
|
Explicit bundle names to fetch instead of the default
selection. This is the only way to fetch an |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Resolved physics data directory |
build_parser
¶
Construct the argparse.ArgumentParser for 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 |
metadata |
dict[str, str]
|
Dictionary of string key-value metadata recorded in the
|
encode_safetensors_bytes
¶
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 |
required |
metadata
|
Mapping[str, str] | None
|
Optional string-to-string header metadata dictionary. |
None
|
require_finite
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
bytes
|
Raw |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If any tensor has a dtype other than |
save_safetensors_bundle
¶
Write a .safetensors physics table bundle and return its SHA-256.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination |
required |
tensors
|
Mapping[str, TableTensor]
|
Mapping from tensor name to |
required |
metadata
|
Mapping[str, str] | None
|
Optional string-to-string header metadata dictionary. |
None
|
require_finite
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Lowercase 64-character hexadecimal |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If any tensor has a dtype other than |
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 |
required |
expected_sha256
|
str | None
|
Optional 64-character |
None
|
required_tensors
|
Sequence[str] | None
|
Optional sequence of tensor names that must exist in the loaded bundle. |
None
|
require_finite
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
LoadedTableBundle
|
|
LoadedTableBundle
|
arrays and string metadata dictionary. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the |
KeyError
|
If any tensor listed in |
TypeError
|
If any stored tensor has a dtype other than |
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 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 |
required |
Returns:
| Type | Description |
|---|---|
LoadedTableBundle
|
|
LoadedTableBundle
|
shape |
LoadedTableBundle
|
( |
LoadedTableBundle
|
|
LoadedTableBundle
|
|
LoadedTableBundle
|
abundance normalized to \(N(\text{Si}) = 10^6\)), plus metadata |
LoadedTableBundle
|
|
LoadedTableBundle
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no entries are found or any row fails to parse. |
parse_isotopes_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 |
required |
Returns:
| Type | Description |
|---|---|
LoadedTableBundle
|
|
LoadedTableBundle
|
|
LoadedTableBundle
|
|
LoadedTableBundle
|
( |
LoadedTableBundle
|
( |
LoadedTableBundle
|
|
LoadedTableBundle
|
|
LoadedTableBundle
|
plus metadata |
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 |
required |
imax
|
int
|
Number of density grid points ( |
2701
|
jmax
|
int
|
Number of temperature grid points ( |
1001
|
logdlo
|
float
|
Minimum \(\log_{10}(\rho / Y_e)\) (default |
-12.0
|
logdhi
|
float
|
Maximum \(\log_{10}(\rho / Y_e)\) (default |
15.0
|
logtlo
|
float
|
Minimum \(\log_{10} T\) in \(\text{K}\) (default |
3.0
|
logthi
|
float
|
Maximum \(\log_{10} T\) in \(\text{K}\) (default |
13.0
|
Returns:
| Type | Description |
|---|---|
LoadedTableBundle
|
|
LoadedTableBundle
|
shape |
LoadedTableBundle
|
of shape |
LoadedTableBundle
|
tables, and the 4 packed jet tensors ( |
LoadedTableBundle
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
convert_lodders03_file
¶
Convert lodders03.data on disk to .safetensors (SHA-256).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Path to the source |
required |
output_path
|
str | Path
|
Destination |
required |
Returns:
| Type | Description |
|---|---|
str
|
Lowercase 64-character hexadecimal |
convert_isotopes_file
¶
Convert isotopes.data on disk to .safetensors and return SHA-256.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str | Path
|
Path to the source |
required |
output_path
|
str | Path
|
Destination |
required |
Returns:
| Type | Description |
|---|---|
str
|
Lowercase 64-character hexadecimal |
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 |
required |
output_path
|
str | Path
|
Destination |
required |
imax
|
int
|
Number of density grid points (default |
2701
|
jmax
|
int
|
Number of temperature grid points (default |
1001
|
logdlo
|
float
|
Minimum \(\log_{10}(\rho / Y_e)\) (default |
-12.0
|
logdhi
|
float
|
Maximum \(\log_{10}(\rho / Y_e)\) (default |
15.0
|
logtlo
|
float
|
Minimum \(\log_{10} T\) in \(\text{K}\) (default |
3.0
|
logthi
|
float
|
Maximum \(\log_{10} T\) in \(\text{K}\) (default |
13.0
|
Returns:
| Type | Description |
|---|---|
str
|
Lowercase 64-character hexadecimal |
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, |
values |
NDArray[float64]
|
1D |
GoldenComparisonSummary
dataclass
¶
Summary metrics from comparing two sequences of golden records.
Attributes:
| Name | Type | Description |
|---|---|---|
num_records |
int
|
Total number of |
num_values |
int
|
Total number of scalar |
max_abs_error |
float
|
Maximum elementwise absolute error
|
max_rel_error |
float
|
Maximum elementwise relative error
|
is_fortran_float_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
|
|
bool
|
or Fortran ( |
Examples:
parse_fortran_float
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
parse_golden_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 |
required |
Returns:
| Type | Description |
|---|---|
list[GoldenRecord]
|
Ordered list of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a trailing numeric token is non-finite ( |
Examples:
parse_golden_file
¶
Read and parse a MESA <pkg>/test/test_output file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the golden |
required |
Returns:
| Type | Description |
|---|---|
list[GoldenRecord]
|
Ordered list of |
extract_golden_table
¶
Stack uniform-width GoldenRecord entries into a 2D float64 array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
Sequence[GoldenRecord]
|
Non-empty sequence of |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
2D C-contiguous |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
assert_values_match
¶
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 |
required |
expected
|
ArrayLike
|
Reference golden array or scalar of shape |
required |
rtol
|
float
|
Maximum permitted relative error (default |
1e-12
|
atol
|
float
|
Absolute error floor for near-zero values (default |
1e-15
|
context
|
str
|
Optional diagnostic label included in failure messages. |
''
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
AssertionError
|
If any element contains |
assert_golden_records_match
¶
Compare two sequences of GoldenRecord objects for numerical parity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual
|
Sequence[GoldenRecord]
|
Computed sequence of |
required |
expected
|
Sequence[GoldenRecord]
|
Reference sequence of |
required |
rtol
|
float
|
Maximum permitted relative error (default |
1e-12
|
atol
|
float
|
Absolute error floor for near-zero values (default |
1e-15
|
Returns:
| Type | Description |
|---|---|
GoldenComparisonSummary
|
|
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 |
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 ( |
case |
str
|
Upstream test-case directory name. |
issue |
str
|
Linked open GitHub issue formatted as |
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 ( |
case |
str
|
Upstream test-case directory name. |
reference_status |
ReferenceStatus
|
Availability and provenance of stored reference data
( |
reference_path |
str
|
Repository-relative path to the stored reference file
(empty string when |
required_termination |
str
|
Expected upstream termination code string (may
contain |
independent_var |
str
|
Monotonic coordinate column name for track comparison
(for example |
final_tolerances |
dict[str, float]
|
Mapping from column name (or |
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 |
scaffolding_issue |
str
|
Linked |
uses_library_extras |
bool
|
True if a case dispatches per-case test hooks
inside library crates rather than test-side |
library_extras_issue |
str
|
Optional |
extras_status |
str
|
Status of the case's upstream extras logic from
|
extras_issue |
str
|
|
extras_factory |
str
|
Optional |
departures |
tuple[DepartureSpec, ...]
|
Tuple of documented |
track_reference_dir |
str
|
Directory of the |
artifact |
ArtifactSpec | None
|
Optional |
regenerated_inputs |
tuple[RegeneratedInput, ...]
|
Upstream case files replaced by models
regenerated with MESA |
data_bundles |
tuple[str, ...]
|
Names of the on-demand data bundles
( |
max_rss_gb |
float | None
|
Resident-memory ceiling ( |
HarnessManifest
dataclass
¶
Validated collection of upstream MESA 26.4.1 case specifications.
Attributes:
| Name | Type | Description |
|---|---|---|
mesa_release |
str
|
Pinned upstream MESA release tag ( |
zenodo_record |
str
|
Zenodo archive identifier for the pinned release. |
cases |
tuple[CaseManifestEntry, ...]
|
Tuple of |
extras_factory |
str
|
Optional default |
by_key
¶
Return a dictionary mapping (suite, case) to its entry.
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], CaseManifestEntry]
|
Dictionary keyed by |
repo_root
¶
Return the repository root directory relative to this module.
Returns:
| Type | Description |
|---|---|
Path
|
Resolved repository root |
Path
|
checkout, or the current working directory otherwise. |
default_manifest_path
¶
Return the default case_manifest.toml path.
Returns:
| Type | Description |
|---|---|
Path
|
Path to |
default_known_gaps_path
¶
Return the default known_gaps.toml path.
Returns:
| Type | Description |
|---|---|
Path
|
Path to |
load_case_manifest
¶
Load and validate case_manifest.toml.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
Optional path to |
None
|
Returns:
| Type | Description |
|---|---|
HarnessManifest
|
Validated |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If any suite, status, tolerance, issue link, data bundle name, memory ceiling, or duplicate case entry is invalid. |
load_known_gaps
¶
Load and validate known_gaps.toml.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
Optional path to |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], KnownGapSpec]
|
Dictionary mapping |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If any gap lacks a valid |
termination_matches
¶
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 |
bool
|
and is not |
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 |
path |
str
|
Repository-relative path of the committed regenerated model. |
sha256 |
str
|
Lower-case hexadecimal SHA-256 of the regenerated model. |
issue |
str
|
|
parse_regenerated_inputs
¶
Validate the [[cases.regenerated_inputs]] tables of one case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
Any
|
Parsed TOML value (a list of tables), or |
required |
ctx
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[RegeneratedInput, ...]
|
The validated replacements in manifest order (empty for |
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
¶
Return a case directory with the declared files replaced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suite
|
str
|
Suite name ( |
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 |
required |
cache_root
|
Path | None
|
Directory holding the staged copies (default:
|
None
|
Returns:
| Type | Description |
|---|---|
Path
|
|
Path
|
|
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 |
retries |
int | None
|
Cumulative |
iters_sum |
int | None
|
Sum of per-step |
mean_iters |
float | None
|
Mean per-step |
iters_rows |
int
|
Number of logged rows averaged in |
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 |
num_rows |
int
|
Number of stored evolutionary rows |
provenance_comment |
str
|
Leading |
mesa_version_number |
str
|
|
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 |
median_abs_diff |
float
|
Median absolute difference on the interior common grid. |
x_at_max |
float
|
Value of the independent coordinate where |
tolerance |
float | None
|
Configured track tolerance if constrained, else |
within_tolerance |
bool
|
True when |
max_rel_diff |
float | None
|
Maximum relative difference |
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 |
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 |
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 |
first_diverging_x |
float | None
|
Coordinate value at |
ref_span |
float
|
Independent-variable span of the reference history. |
final_run_values |
dict[str, float]
|
Selected final candidate run values (such as
|
final_ref_values |
dict[str, float]
|
Selected final reference values (such as
|
extract_history_run_stats
¶
Extract final-stage step, retry, and iteration counts from tbl.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tbl
|
HistoryTable
|
Loaded |
required |
suite
|
str
|
Upstream suite name ( |
required |
Returns:
| Type | Description |
|---|---|
HistoryRunStats
|
|
HistoryRunStats
|
and |
load_history_file
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
HistoryTable
|
|
HistoryTable
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the file contains no header or zero data rows. |
join_history_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
|
required |
Returns:
| Type | Description |
|---|---|
HistoryTable
|
One table; |
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 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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If a file is malformed or the two files do not join. |
compare_histories
¶
Compare a FlexMESA history table against an upstream MESA reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
HistoryTable
|
Reference |
required |
run
|
HistoryTable
|
Candidate |
required |
spec
|
CaseManifestEntry
|
|
required |
num_grid
|
int
|
Number of uniform interior grid samples combined with interior
sample coordinates (default |
400
|
Returns:
| Type | Description |
|---|---|
HistoryComparison
|
Populated |
HistoryComparison
|
deviations, tolerance outcomes, and |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If coordinate arrays contain |
re_evaluate_comparison
¶
Re-evaluate comp against spec's current tolerances.
comparison_to_dict
¶
Serialize a HistoryComparison into a strict JSON-safe dictionary.
comparison_from_dict
¶
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 |
column_values |
tuple[ndarray, ...]
|
Tuple of 1D |
num_rows |
int
|
Number of data rows |
mesa_version_number |
str
|
|
FirstDiff
dataclass
¶
Earliest difference found between a reference history and a run history.
Attributes:
| Name | Type | Description |
|---|---|---|
part |
str
|
History part label (for example |
kind |
str
|
Category of mismatch ( |
model_number |
int | None
|
Evolutionary |
row_index |
int
|
0-based reference row index, or |
run_row_index |
int | None
|
0-based run row index, or |
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 |
run_value |
float | int | str | None
|
Candidate run scalar value (or descriptor), else |
abs_diff |
float | None
|
Absolute difference |
rel_diff |
float | None
|
Relative difference |
ulp_diff |
int | None
|
IEEE-754 binary64 ULP distance when both values are finite,
else |
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 |
kind |
HeaderDiffKind
|
Mismatch category ( |
ref_value |
float | int | str | None
|
Reference header value, or |
run_value |
float | int | str | None
|
Candidate run header value, or |
abs_diff |
float | None
|
Absolute difference for numeric values, else |
rel_diff |
float | None
|
Relative difference for numeric values, else |
ulp_diff |
int | None
|
IEEE-754 binary64 ULP distance for finite floats, else
|
PartComparison
dataclass
¶
Bit-identity comparison summary for one history part.
Attributes:
| Name | Type | Description |
|---|---|---|
part |
str
|
Relative part label (for example |
ref_path |
str | None
|
Reference file path string, or |
run_path |
str | None
|
Candidate run file path string, or |
reference_kind |
ReferenceKind
|
|
status |
PartStatusType
|
|
bit_identical |
bool
|
True iff all reference columns, rows, and values match
bit-for-bit across all parsed IEEE-754 |
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 |
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
|
max_ulp_diff_per_col |
dict[str, int | None]
|
Maximum IEEE-754 ULP distance per shared column,
or |
differing_columns |
tuple[str, ...]
|
Ordered shared columns with at least one difference. |
error |
str
|
Diagnostic error message when |
header_diffs |
tuple[HeaderDiff, ...]
|
Non-ignored MESA header scalar discrepancies. |
ignored_header_keys |
tuple[str, ...]
|
Sorted tuple of excluded header metadata keys
(default excludes |
FullHistoryComparison
dataclass
¶
Case-level full-history bit-identity result across all parts.
Attributes:
| Name | Type | Description |
|---|---|---|
suite |
str
|
Suite name ( |
case |
str
|
Case directory name. |
status |
StatusType
|
|
bit_identical |
bool
|
True iff |
byte_identical |
bool
|
True iff |
judged_part |
str | None
|
Primary/final part label, or |
identical_rows |
int
|
Sum of |
total_ref_rows |
int
|
Sum of |
total_run_rows |
int
|
Sum of |
compared_rows |
int
|
Sum of |
identical_cols |
int
|
Sum of |
total_ref_cols |
int
|
Sum of |
total_run_cols |
int
|
Sum of |
columns_only_in_ref |
tuple[str, ...]
|
Columns present in reference only (bare column
names when |
columns_only_in_run |
tuple[str, ...]
|
Columns present in run only (same naming rule). |
first_diff |
FirstDiff | None
|
Earliest discrepancy across |
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 |
tuple[PartComparison, ...]
|
Ordered tuple of |
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 |
load_full_history_file
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
FullHistoryTable
|
|
FullHistoryTable
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the file is malformed or lacks column headers. |
join_full_history_tables
¶
Concatenate ordered FullHistoryTable chunks from one run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
Sequence[FullHistoryTable]
|
Non-empty sequence of |
required |
Returns:
| Type | Description |
|---|---|
FullHistoryTable
|
Single combined |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
load_full_run_history
¶
Load a run history file, joining sibling map_history.data if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Path to |
required |
join_map_history
|
bool
|
When True and |
True
|
Returns:
| Type | Description |
|---|---|
FullHistoryTable
|
Combined |
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 |
required |
run
|
FullHistoryTable
|
Candidate run |
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'
|
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
|
False
|
exact_row_match
|
bool
|
When True (default), require 1-to-1 row counts and
|
True
|
ignored_header_keys
|
Collection[str]
|
Header metadata keys excluded from scalar
comparison. Defaults to |
DEFAULT_IGNORED_HEADER_KEYS
|
Returns:
| Type | Description |
|---|---|
PartComparison
|
Populated |
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 |
True
|
reference_kind
|
ReferenceKind
|
|
'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 |
DEFAULT_IGNORED_HEADER_KEYS
|
Returns:
| Type | Description |
|---|---|
PartComparison
|
|
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 ( |
required |
case
|
str
|
Case directory name. |
required |
ref_dir
|
Path | str | None
|
Explicit reference directory or file; defaults to
|
None
|
astero_tracks_dir
|
Path | str | None
|
Optional directory containing |
None
|
include_astero_tracks
|
bool
|
Include per-track |
True
|
Returns:
| Type | Description |
|---|---|
list[_ResolvedPart]
|
|
bool
|
zero-step artifact cases such as |
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
|
required |
run_dir
|
Path | str
|
Candidate FlexMESA output directory (or single history file). |
required |
suite
|
str
|
Suite name ( |
''
|
case
|
str
|
Case name. |
''
|
part_pairs
|
Sequence[tuple[str, Path | str, Path | str]] | None
|
Optional explicit sequence of
|
None
|
astero_tracks_dir
|
Path | str | None
|
Optional directory holding |
None
|
include_astero_tracks
|
bool
|
Whether to compare per-track |
True
|
prefix_only
|
bool
|
When True, compare covered |
False
|
exact_row_match
|
bool
|
When True (default), enforce 1-to-1 row counts and
|
True
|
ignored_header_keys
|
Collection[str]
|
Header metadata keys excluded from bit-for-bit
scalar comparison. Defaults to |
DEFAULT_IGNORED_HEADER_KEYS
|
Returns:
| Type | Description |
|---|---|
FullHistoryComparison
|
Aggregated |
part_comparison_to_dict
¶
Serialize a PartComparison into a strict JSON-safe dictionary.
part_comparison_from_dict
¶
Deserialize a PartComparison from part_comparison_to_dict.
comparison_to_dict
¶
Serialize a FullHistoryComparison into a strict JSON-safe dict.
comparison_from_dict
¶
Deserialize a FullHistoryComparison from comparison_to_dict.
main
¶
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: |
int
|
( |
int
|
|
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
¶
Return each stage's counters with MESA's testhub.yml block.
stage_step_deltas
property
¶
Return the aligned per-stage step counts of the run and MESA.
step_count_differs
property
¶
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
¶
Return whether primary and component comparisons meet tolerances.
is_diagnostic
property
¶
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
¶
Label of how the reported run was made.
Returns:
| Name | Type | Description |
|---|---|---|
str
|
|
|
str
|
passed strict control validation and executed its upstream |
|
str
|
extras logic, and otherwise |
|
reason |
str
|
|
str
|
unsupported controls and |
|
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 ( |
case |
str
|
Case directory name. |
status |
str
|
Execution status ( |
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 ( |
peak_rss_gb |
float
|
Peak resident memory of the worker in gigabytes ( |
history_path |
Path | None
|
Path to the emitted |
error_message |
str
|
Diagnostic error string when |
controls_ignored |
bool
|
True when the run used the |
n_controls_ignored |
int
|
Number of unsupported controls and sections the
strict run named before stopping ( |
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 |
mean_iters |
float | None
|
Mean Newton solver iterations per logged final-stage step,
or |
track_history_paths |
tuple[Path, ...]
|
Per-track |
stage_steps |
tuple[int, ...]
|
Model number at the end of each |
stages_total |
int
|
Number of |
stage_reached |
int | None
|
1-based stage the run ended in, or |
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 |
stdout_text |
str | None
|
The worker's standard output, compared with a declared
artifact |
final_stage_reached
property
¶
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 the unsupported controls and sections named in message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error text of a strict |
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 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
¶
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 and concatenate the history files of one MESA run in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[Path]
|
Non-empty ordered paths from
|
required |
Returns:
| Type | Description |
|---|---|
HistoryTable
|
One table with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the files do not share one column set. |
resolve_binary_component_reference_paths
¶
Locate stored LOGS1/LOGS2 component reference tracks.
resolve_full_reference_history_path
¶
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 |
Path | None
|
|
resolve_full_reference_history_paths
¶
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 ( |
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 ( |
list[Path]
|
files, |
list[Path]
|
is available. |
resolve_reference_history_path
¶
Resolve reference_path against root_dir, repo root, or cache.
resolve_effective_numerics_mode
¶
Resolve effective "strict"/"fast" mode from arg, env, or process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numerics_mode
|
str | None
|
Optional explicit mode override ( |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Canonical lowercase mode string ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
resolve_mesa_test_root
¶
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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the resolved directory does not contain
|
resolve_case_dir
¶
Resolve a case name or filesystem path to an existing directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suite
|
str
|
Suite name ( |
required |
case_or_path
|
str
|
Case directory name (such as |
required |
mesa_dir
|
Path | str | None
|
Optional MESA test-inputs root override. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Resolved |
Path
|
manifest entry declares |
Path
|
copy with those files replaced ( |
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
¶
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 |
stage_model_numbers
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
The per-stage model numbers; empty for reports without stages. |
stage_progress
¶
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 |
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 ( |
required |
completed
|
tuple[int, ...] | None
|
Model number at the end of each completed stage from the
run report, or |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
int | None
|
case with at most one stage, and |
tuple[int, int | None]
|
stage the run ended in, or |
tuple[int, int | None]
|
it (a stage without a declared output model decides nothing). |
history_model_span
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, int] | None
|
|
tuple[int, int] | None
|
|
history_steps
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
The step count, or |
locate_track_histories
¶
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 |
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 |
locate_written_history
¶
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 ( |
required |
out_target
|
Path
|
Output file or root directory passed to the tracer. |
required |
is_logs_dir
|
bool
|
True when |
required |
Returns:
| Type | Description |
|---|---|
Path | None
|
Path to the non-empty history file if present, else |
load_extras_factory
¶
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 ( |
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 |
False
|
write_profiles
|
bool
|
Enable writing radial |
False
|
is_logs_dir
|
bool
|
Treat |
True
|
numerics_mode
|
str | None
|
Arithmetic 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 |
None
|
extras
|
Any
|
Explicit pre-built test-side extras callback object; overrides
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Raw telemetry dictionary returned by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
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 |
False
|
write_profiles
|
bool
|
Enable writing radial |
False
|
is_logs_dir
|
bool
|
Treat |
True
|
numerics_mode
|
str | None
|
Arithmetic 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 |
None
|
timeout_sec
|
float | None
|
Optional wall-clock timeout in seconds ( |
None
|
max_rss_gb
|
float | None
|
Optional resident-memory ceiling in gigabytes ( |
None
|
monitor
|
RunMonitor | None
|
Optional polling hook ( |
None
|
monitor_interval_sec
|
float
|
Seconds between polls. |
MONITOR_INTERVAL_SEC
|
step_cap
|
int | None
|
Optional step cap: the case is stopped with status
|
None
|
Returns:
| Type | Description |
|---|---|
TraceRunOutcome
|
|
TraceRunOutcome
|
usage, emitted history path, and (for |
TraceRunOutcome
|
search histories. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
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 ( |
None
|
allow_unsupported_controls
|
bool
|
Skip the strict run and go straight to the diagnostic run when True. |
False
|
extras_factory
|
str | None
|
Optional |
None
|
timeout_sec
|
float | None
|
Optional wall-clock timeout in seconds ( |
None
|
max_rss_gb
|
float | None
|
Optional resident-memory ceiling in gigabytes ( |
None
|
monitor
|
RunMonitor | None
|
Optional polling hook applied to each of the two runs (see
|
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
|
None
|
deadline
|
float | None
|
Optional end of the whole harness run ( |
None
|
Returns:
| Type | Description |
|---|---|
TraceRunOutcome
|
The strict |
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
¶
Compute manifest-wide and run-level headline counts across records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
HarnessManifest
|
Loaded |
required |
records
|
list[CaseHarnessRecord]
|
Evaluated |
required |
known_gaps
|
dict[tuple[str, str], KnownGapSpec] | None
|
Optional |
None
|
numerics_mode
|
str
|
Arithmetic mode used for the run ( |
'strict'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of headline counts and gate violation lists. |
record_to_dict
¶
Convert a CaseHarnessRecord into a JSON-serializable dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rec
|
CaseHarnessRecord
|
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary. |
build_report_payload
¶
Assemble the complete JSON report dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
HarnessManifest
|
|
required |
records
|
list[CaseHarnessRecord]
|
Sequence of |
required |
known_gaps
|
dict[tuple[str, str], KnownGapSpec] | None
|
Optional |
None
|
numerics_mode
|
str
|
Arithmetic mode used for the run ( |
'strict'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Structured dictionary with |
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
|
|
required |
records
|
list[CaseHarnessRecord]
|
Evaluated |
required |
known_gaps
|
dict[tuple[str, str], KnownGapSpec] | None
|
Optional |
None
|
numerics_mode
|
str
|
Arithmetic mode used for the run ( |
'strict'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary with |
dict[str, Any]
|
normalized to |
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
|
|
required |
records
|
list[CaseHarnessRecord]
|
Sequence of |
required |
summary
|
dict[str, Any] | None
|
Optional precomputed summary dictionary. |
None
|
known_gaps
|
dict[tuple[str, str], KnownGapSpec] | None
|
Optional |
None
|
figure_links
|
dict[tuple[str, str], str] | None
|
Optional mapping from |
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 |
None
|
known_gaps_path
|
Path | str | None
|
Optional path to |
None
|
baseline_json_path
|
Path | str | None
|
Optional path to |
None
|
Returns:
| Type | Description |
|---|---|
tuple[HarnessManifest, dict[tuple[str, str], KnownGapSpec], list[CaseHarnessRecord]]
|
Tuple |
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 |
required |
gaps
|
dict[tuple[str, str], KnownGapSpec]
|
Loaded |
required |
stored_by_key
|
dict[tuple[str, str], dict[str, Any]]
|
Executed case rows (as written by
:func: |
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
|
enforce_step_counts
|
bool
|
Judge stored stage step counts as ``DECISIONS 70
|
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 ( |
case |
str
|
Upstream case name. |
kind |
str
|
One of |
detail |
str
|
Baseline and current values, for the report. |
budget_limited_keys
¶
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]]
|
|
frozenset[tuple[str, str]]
|
|
find_baseline_regressions
¶
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]]
|
|
frozenset()
|
Returns:
| Type | Description |
|---|---|
list[BaselineRegression]
|
Regressions in the order of |
list[BaselineRegression]
|
earliest kind that applies). |
merge_records_into_baseline
¶
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]]
|
|
frozenset()
|
Returns:
| Type | Description |
|---|---|
list[CaseHarnessRecord]
|
A list in the order of |
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 |
settings |
dict[str, Any]
|
The run settings shared by every shard. |
short_budget_cases |
frozenset[tuple[str, str]]
|
|
budgeted_cases |
frozenset[tuple[str, str]]
|
|
untested |
frozenset[tuple[str, str]]
|
|
missing_shards |
tuple[int, ...]
|
1-based indices of the shards that sent no report. |
per_shard |
dict[str, dict[int, Any]]
|
|
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 a "I/N" shard specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
str
|
Shard text, with |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
plan_shards
¶
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]]
|
|
frozenset()
|
weights
|
Mapping[tuple[str, str], float] | None
|
Optional cost per |
None
|
solo_sec
|
float | None
|
Weight above which an entry runs alone (needs
|
None
|
Returns:
| Type | Description |
|---|---|
list[list[CaseManifestEntry]]
|
|
list[list[CaseManifestEntry]]
|
order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
shard_entries
¶
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]]
|
|
frozenset()
|
weights
|
Mapping[tuple[str, str], float] | None
|
Optional cost per |
None
|
solo_sec
|
float | None
|
Weight above which an entry runs alone. |
None
|
Returns:
| Type | Description |
|---|---|
list[CaseManifestEntry]
|
The entries of shard |
merge_shard_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 |
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 |
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.
load_mesa_wall_times
¶
Read MESA 26.4.1's wall time on each case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], float]
|
|
dict[tuple[str, str], float]
|
with a positive MESA wall time. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file has no |
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.modcontinues its model number (star/private/read_model.f90:281-288; FlexMESAmodel_io.rs:348-353, 578) unlessset_initial_model_number(default.false.) resets it (star/job/run_star_support.f90: 2003-2007; FlexMESAstar_job_init.rs:844). -
num_retries:s% num_retries. It is read from the.mod(read_model.f90:288; FlexMESAmodel_io.rs:425-430) and then reset toinitial_number_retries(0) byset_initial_number_retries, which defaults to.true.(run_star_support.f90:2009-2012; FlexMESAmodel_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_onein 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 instruct_burn_mix.f90:55-56, 175-176), relax steps included; forRSPthe iterations theRSPstep reports. MESA does not count an iteration that leaves on a failedsolver_test_partials(star_solver.f90:333-337, before the increment at:339); FlexMESA has no such exit.solver_test_partialsis 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 ofdo_struct_burn_mixthat reaches the solver (struct_burn_mix.f90:177). FlexMESA counts one persolve_henyey_stepcall, whichdo_struct_burn_mixmakes once. One case differs: a call withdt <= 0is counted by MESA, whosedo_solver_convergethen returns without solving (struct_burn_mix.f90:377-379), and is not counted by FlexMESA, whosesolve_henyey_stepreturns before counting. Not reported for anRSPstage: MESA counts eachRSPstep as a solver call (struct_burn_mix.f90:57), FlexMESA'sRSPstep 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) andredos(total_step_redos) count the results ofdo_evolve_step_part1anddo_evolve_step_part2(star/private/evolve.f90:71-82, 483-493):stepscounts relax steps and a step whose timestep pick then retries, andretriesdoes 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_failedneeds a count of converged solver calls (total_num_solver_calls_converged), which FlexMESA does not keep.runtime_minutesis a wall time (case_timings.tomlrecords wall times),star_ageandlog_rel_run_E_errare not in the committed table, and theextra_testhubvalues are written by each case's ownrun_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 |
model_number |
int
|
Model number at the end of the stage. |
num_retries |
int
|
|
solver_iterations |
int
|
Newton iterations of the stage. |
solver_calls_made |
int | None
|
Structure-solver calls of the stage, or |
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 ( |
note |
str
|
Why no MESA block is paired, when |
counters_from_report
¶
Read the per-stage counters of a star trace report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rep
|
Mapping[str, Any]
|
Report of |
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
¶
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
¶
Return counters as JSON objects (see :func:counters_from_dicts).
counters_from_dicts
¶
Rebuild counters from :func:counters_to_dicts or stored row output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
Sequence[Mapping[str, Any]]
|
Objects with |
required |
Returns:
| Type | Description |
|---|---|
tuple[StageCounters, ...]
|
The counters, in order. |
load_mesa_testhub
¶
Read MESA's counter blocks grouped by inlist line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Optional path of |
None
|
Returns:
| Type | Description |
|---|---|
MesaTesthubTable
|
|
MesaTesthubTable
|
under it ( |
pair_stages
¶
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: |
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 inphotos/by modification time (antepenultimate_photo, lines 118-129; forbinarythe third newestb_*file without itsb_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
|
photo |
str
|
Restart photo: |
RestartCheck
dataclass
¶
Result of the photo-restart check of one case.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
str
|
|
photo |
str
|
The photo upstream restarts from ( |
reason |
str
|
Why the check did not pass, or did not run. |
parse_do1_test_source
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, RestartDirective]
|
|
load_restart_directives
¶
Read <mesa_dir>/<suite>/test_suite/do1_test_source.
Returns:
| Type | Description |
|---|---|
dict[str, RestartDirective]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
The suite has no |
antepenultimate_photo
¶
Return the photo upstream's auto restarts from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
photo_dir
|
Path
|
The case's |
required |
binary
|
bool
|
Pick among |
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
|
|
compare_restart
¶
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
|
|
required |
restart_history
|
Path
|
|
required |
photo_model_number
|
int
|
Model number of the photo the run restarted from. |
required |
Returns:
| Type | Description |
|---|---|
RestartCheck
|
|
RestartCheck
|
restarted run's data rows are exactly the uninterrupted run's rows |
RestartCheck
|
whose model number exceeds |
RestartCheck
|
byte for byte; otherwise |
check_status
¶
Return the restart-check result FlexMESA can give a case today.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directive
|
RestartDirective | None
|
The case's |
required |
Returns:
| Type | Description |
|---|---|
RestartCheck
|
|
RestartCheck
|
known), |
RestartCheck
|
else |
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
¶
Return the one-letter timeline symbol of verdict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verdict
|
str | None
|
A baseline row's verdict, or |
required |
Returns:
| Type | Description |
|---|---|
str
|
The symbol of the first verdict class whose name starts the verdict, |
str
|
|
baseline_verdicts
¶
Return {"suite/case": verdict} of a baseline payload.
build_history
¶
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]
|
|
dict[str, Any]
|
entry has |
dict[str, Any]
|
|
dict[str, Any]
|
commit's subject ends with, or |
dict[str, Any]
|
verdicts that differ from the previous entry's |
dict[str, Any]
|
(every verdict for the first entry; |
dict[str, Any]
|
its row). A |
dict[str, Any]
|
commit is kept only when it changed at least one verdict. |
Raises:
| Type | Description |
|---|---|
ShallowCloneError
|
|
ValueError
|
A commit's baseline is not valid JSON with |
CalledProcessError
|
|
entry_verdicts
¶
Return the full verdict map after each history entry, oldest first.
render_markdown
¶
Render the per-case status history page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
Mapping[str, Any]
|
History from :func: |
required |
timings_path
|
Path
|
|
required |
banner
|
str
|
Generated-file comment for the first line. |
required |
blob_url
|
str
|
URL prefix of repository files ( |
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 ( |
mesa_steps |
int | None
|
Step count of the MESA reference run, or |
step_factor |
float | None
|
Step bound as a multiple of |
from_baseline |
bool
|
True when |
load_wall_times
¶
Read the wall time of each executed case from a harness report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
A harness |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], float]
|
|
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 |
passing_keys
¶
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]]
|
|
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: |
required |
timeout_sec
|
float
|
The scheduled budget ( |
required |
factor
|
float
|
Multiple |
required |
floor_sec
|
float
|
Smallest derived budget. |
required |
step_factor
|
float | None
|
Multiple |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], CaseBudget]
|
A budget per selected |
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).
load_case_budgets
¶
Read the wall-time budget of each case from a budget table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
A |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], float]
|
|
dict[tuple[str, str], float]
|
seconds ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file has no |
load_projected_times
¶
Read each case's projected wall time from a budget table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
A |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file has no |
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 ( |
x_name |
str
|
Independent coordinate name (such as |
x |
float
|
Coordinate value of the failing point ( |
model |
int | None
|
|
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. |
StopRequest
dataclass
¶
A request from a monitor to stop a running case.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
str
|
Run status to report: |
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 |
step_limit |
int | None
|
Stop once the run's last |
step_message |
str
|
Report line used when the step bound stops the case. |
excess_limit |
int | None
|
Stop once the run's last |
mesa_stage_steps |
int
|
MESA's step count of that stage, for the report. |
find_early_divergence
¶
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 |
required |
run
|
HistoryTable
|
Partial run table, arrays of shape |
required |
spec
|
CaseManifestEntry
|
Case manifest entry giving |
required |
Returns:
| Type | Description |
|---|---|
EarlyDivergence | None
|
The earliest failing point over all tracked columns, or |
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
¶
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 |
HistoryTable | None
|
read or has no complete data row yet. |
single_stage_star_case
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when the |
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 |
required |
root_dir
|
Path | None
|
Manifest directory against which reference paths resolve. |
None
|
stop_on_excess_steps
|
bool
|
Stop a single-stage |
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 |
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 |
load_mesa_stage_steps
¶
Read the MESA per-stage step counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Optional path of |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], tuple[int, ...]]
|
|
stage_retries_taken
¶
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, ...]
|
|
required |
continued
|
tuple[bool, ...]
|
Whether each stage carried on the previous stage's count
( |
required |
Returns:
| Type | Description |
|---|---|
int
|
One value per stage: |
...
|
stage |
Raises:
| Type | Description |
|---|---|
ValueError
|
The two tuples differ in length, or the first stage is marked continued. |
load_mesa_stage_retries
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], tuple[int, ...]]
|
|
dict[tuple[str, str], tuple[int, ...]]
|
value per stage; empty when the file is absent. |
stage_deltas
¶
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 |
...
|
|
step_bound
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
mesa_case_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 |
required |
stage_steps
|
tuple[int, ...]
|
MESA's end-of-stage model numbers. |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
The step count, or |
load_mesa_case_steps
¶
Return :func:mesa_case_steps for every case that has a count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Optional path of |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], int]
|
|
step_cap
¶
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 |
required |
factor
|
float
|
Multiple of |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
The cap, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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.
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 |
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
|
routine_map_partial |
tuple[str, ...]
|
|
evidence_artifacts |
tuple[str, ...]
|
Committed generated reference/comparison artifacts. |
evidence_tests |
tuple[str, ...]
|
Test files exercising |
harness_cases |
tuple[str, ...]
|
Passing |
notes |
str
|
Provenance note (e.g. |
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 ( |
upstream_commit |
str
|
Pinned MESA git commit hash. |
archive_md5 |
str
|
MD5 checksum of |
entries |
tuple[PortManifestEntry, ...]
|
Tuple of per-file |
parse_port_manifest_text
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required schema fields or status values are invalid. |
load_port_manifest
¶
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 |
dump_port_manifest
¶
Serialize manifest into deterministic canonical TOML text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
PortManifest
|
|
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 |
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 |
None
|
base_manifest
|
PortManifest | None
|
Optional base-branch |
None
|
changed_paths
|
frozenset[str] | None
|
Repository-relative paths changed in |
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
¶
Read merge-by-merge headline rows from history.tsv.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history_path
|
Path
|
Path to |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
Ordered list of row dictionaries keyed by |
build_dashboard_data
¶
Assemble the complete dashboard data dictionary from repository files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_root
|
Path
|
Root directory of the |
required |
mesa_dir
|
Path | None
|
Optional MESA 26.4.1 |
None
|
manifest
|
PortManifest | None
|
Optional pre-loaded |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable dictionary backing all Markdown and JSON outputs. |
render_expected_files
¶
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 |
None
|
data
|
dict[str, Any] | None
|
Optional pre-computed |
None
|
Returns:
| Type | Description |
|---|---|
dict[Path, str]
|
Mapping from target |
verify_all_dashboard_invariants
¶
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 |
None
|
base_ref
|
str | None
|
Optional git base ref (e.g. |
None
|
check_outputs
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of validation error messages (empty when all checks pass). |
record_history_entry
¶
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 |
required |
date_utc
|
str
|
ISO date |
required |
commit_short
|
str
|
Short git commit SHA. |
required |
event_label
|
str
|
Short merge event label (e.g. |
required |
dashboard_main
¶
CLI entry point for flexmesa dashboard subcommands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str] | None
|
Optional list of CLI arguments following |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Process exit code ( |
flexmesa.testing.trace_cli
¶
Command-line interface for flexmesa trace and flexmesa harness.
trace_main
¶
Execute flexmesa trace star|binary|astero <case>.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str] | None
|
CLI arguments following |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Exit status ( |
int
|
|
int
|
first argument runs :func: |
gate_status
¶
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 |
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
|
|
harness_main
¶
Execute flexmesa harness table|run|merge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str] | None
|
CLI arguments following |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Exit status ( |
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 |
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, ...]]
|
|
StepDump
dataclass
¶
A parsed step dump.
Attributes:
| Name | Type | Description |
|---|---|---|
header |
list[str]
|
|
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
|
|
record |
str
|
Record type, or |
position |
int | None
|
0-based position among the model's solver records. |
zone |
int | None
|
1-based zone for zone records, else |
field |
str
|
Name of the differing field or column. |
mesa |
str
|
MESA's value (or record type for |
flex |
str
|
FlexMESA's value. |
ulps |
int | None
|
ULP distance for a value difference, else |
ColumnSummary
dataclass
¶
Per-column difference count of one zone record type in one model.
Attributes:
| Name | Type | Description |
|---|---|---|
record |
str
|
|
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. |
ulp_distance
¶
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
¶
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
¶
Parses a step dump.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Contents of a |
required |
Returns:
| Type | Description |
|---|---|
StepDump
|
The parsed dump. |
compare_zones
¶
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
¶
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 ( |
frozenset()
|
Returns:
| Type | Description |
|---|---|
Divergence | None
|
The first divergence in star, model, then record order. |
format_report
¶
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: |
required |
Returns:
| Type | Description |
|---|---|
str
|
The report text. |
compare_files
¶
Compares two dump files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mesa_path
|
Path
|
MESA |
required |
flex_path
|
Path
|
FlexMESA dump file. |
required |
ignore
|
frozenset[str]
|
See :func: |
frozenset()
|
Returns:
| Type | Description |
|---|---|
str
|
The report text and the first divergence ( |
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.
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
¶
Serialize a :class:PhaseTapComparison into JSON-safe primitives.
main
¶
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:
- The upper bound is the harness's first diverging model
Dplus one (the history row of modelDis written after its step, so a difference in the timestep it chooses first appears in thedtof modelD + 1). - MESA dumps already on disk are probed first, nearest the middle of the
interval first: the start-of-run dump of the
mesa_stepdumpsbundle, the windows of themesa_stepdump_windowsbundle, and the windows an earlier bisect wrote to its work directory. Each probe runs FlexMESA withflexmesa trace --compareover the same window. - 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_windowmodels (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 ( |
hi |
int
|
First model known or assumed to differ. |
hi_probe |
Probe | None
|
The probe that showed the difference at |
run_first |
int | None
|
First model of the run, when a start-of-run dump says. |
Probe
dataclass
¶
The outcome of comparing one window.
Attributes:
| Name | Type | Description |
|---|---|---|
window_id |
str
|
:attr: |
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 |
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
|
|
steps |
int
|
Models per star. |
stage |
int
|
1-based stage ( |
occurrence |
int
|
Crossing of |
path |
Path | None
|
The MESA dump, or |
source |
str
|
Where the dump comes from (bundle name or |
window_id
property
¶
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: |
work |
Path
|
Work directory. |
flex_cmd |
list[str]
|
Command prefix running |
flex_env |
dict[str, str]
|
Environment additions for FlexMESA ( |
trace_args |
list[str]
|
Extra |
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 |
mesa_cmd |
list[str] | None
|
Command prefix running |
roots |
list[tuple[Path, str]]
|
Directories searched for MESA dumps, besides the work one. |
max_window |
int
|
See :func: |
probe_steps |
int
|
See :func: |
ignore |
frozenset[str]
|
Record types or columns left out of the comparison. |
run |
Runner
|
Command runner (prints and runs). |
harness_bound
¶
Returns the harness's first diverging model, running it if needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
harness_args
|
Sequence[str]
|
Extra |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
The model, or |
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
¶
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: |
probe
¶
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
|
|
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
¶
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
|
|
required |
flex_side
|
bool
|
The dump is FlexMESA's, which records every restart
of the stage ( |
False
|
Raises:
| Type | Description |
|---|---|
BisectStop
|
With :data: |
bisect
¶
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: |
int
|
data: |
trace_status
¶
Returns the status= field of flexmesa trace's summary line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stdout
|
str
|
Output of one |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
|
str | None
|
or |
main
¶
Runs flexmesa trace bisect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str]
|
Arguments after |
required |
Returns:
| Type | Description |
|---|---|
int
|
Exit status (see :func: |
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 intext_differences(includingfile_typedescription text, standalone and inline!comments, header key ordering, quoting style,DvsEexponents,3.77D+02vs377spelling, whitespace, and line endings). - Extracts and compares MESA's computed scalar values inside inline
!comments onxmstar,R_center, andL_centerheader lines (star/private/write_model.f90:131-149). - Parses
file_typebitfields (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 leadinglndcolumn, structural zone mismatches (such as deleted cells or rows leavingn_shellsunchanged), and structuredprevious modelblocks. - Exit codes follow CLI convention:
0whenbyte_identical,2when differences are detected (value, structural, or text-only), and1on 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 ( |
raw |
str
|
Raw trimmed string token (quotes removed for string literals). |
int_val |
int | None
|
Parsed integer value when |
float_val |
float | None
|
Parsed IEEE-754 double when |
bits |
int | None
|
Unsigned 64-bit IEEE-754 representation when |
str_val |
str | None
|
String content when |
quoted |
bool
|
Whether the original token was quoted in the source file. |
quote_char |
str | None
|
Enclosing quote character ( |
ZoneTable
dataclass
¶
Per-zone arrays parsed from a .mod table section.
Attributes:
| Name | Type | Description |
|---|---|---|
columns |
tuple[str, ...]
|
Ordered zone column names (for example |
nz |
int
|
Number of parsed zone rows stored in each column array. |
bits |
dict[str, NDArray[uint64]]
|
Mapping from column name to 1D |
values |
dict[str, NDArray[float64]]
|
Mapping from column name to 1D |
raw_tokens |
dict[str, tuple[str, ...]]
|
Mapping from column name to raw trimmed cell strings of
length |
declared_nz |
int | None
|
Header |
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 |
PreviousModel
dataclass
¶
Structured previous model block (write_model.f90:218-231).
Attributes:
| Name | Type | Description |
|---|---|---|
properties |
dict[str, ModScalar]
|
Scalar key-value pairs inside |
property_order |
tuple[str, ...]
|
Ordered list of scalar keys as encountered. |
duplicate_keys |
tuple[str, ...]
|
Any repeated property keys within |
comment_properties |
dict[str, ModScalar]
|
Numeric scalars parsed from inline |
inline_comments |
dict[str, str]
|
Mapping from property key to inline |
comment_lines |
tuple[str, ...]
|
Standalone |
zones |
ZoneTable | None
|
Optional prior-step zone table present in archived models, or
|
trailing_lines |
tuple[str, ...]
|
Any unparsed non-blank, non-comment lines following the
|
ModFile
dataclass
¶
Complete structured representation of a MESA ASCII .mod file.
Attributes:
| Name | Type | Description |
|---|---|---|
comments |
tuple[str, ...]
|
Leading |
comment_lines |
tuple[str, ...]
|
All standalone |
file_type |
int
|
Integer bitmask header ( |
file_type_description |
str
|
Trailing description text on the |
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 |
inline_comments |
dict[str, str]
|
Mapping from header key to raw inline |
zones |
ZoneTable
|
Primary stellar structure and composition zone table. |
previous |
PreviousModel | None
|
Parsed |
trailing_lines |
tuple[str, ...]
|
Non-blank, non-comment lines outside |
raw_bytes |
bytes
|
Exact raw bytes of the file (or UTF-8 encoding in memory). |
raw_lines |
tuple[str, ...]
|
Lines from |
line_ending_style |
str
|
Line ending signature ( |
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 ( |
column |
str
|
Column name in both tables. |
n_diff |
int
|
Number of differing cells over |
signed_zero_matches |
int
|
Cells differing only in |
first_zone |
int
|
Earliest 1-based zone index where this column differs. |
first_a |
float
|
Value in file A at |
first_b |
float
|
Value in file B at |
first_bits_a |
int
|
IEEE-754 uint64 bits of |
first_bits_b |
int
|
IEEE-754 uint64 bits of |
first_ulps |
int | None
|
Signed-magnitude ULP distance at |
max_ulps |
int | None
|
Maximum ULP distance among non- |
max_abs_diff |
float | None
|
Maximum finite absolute difference, or |
max_rel_diff |
float | None
|
Maximum finite relative difference
|
has_nan |
bool
|
True if any differing cell involves |
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.
ulp_distance
¶
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 |
int | None
|
non-identical |
decode_file_type_bits
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
str
|
Ordered tuple of active flag names (with unknown bits formatted as |
...
|
|
parse_fortran_mod_float
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
float
|
Tuple |
int
|
|
Raises:
| Type | Description |
|---|---|
ModParseError
|
If |
parse_mod
¶
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 |
required |
raw_bytes
|
bytes | None
|
Optional raw byte buffer read from disk (defaults to UTF-8
encoding of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Structured |
ModFile
|
class: |
Raises:
| Type | Description |
|---|---|
ModParseError
|
If the file lacks a valid |
load_mod
¶
Load and parse a MESA or FlexMESA .mod file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Filesystem path to the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Parsed |
ModFile
|
class: |
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 two parsed .mod models at byte and binary64 bit precision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_a
|
ModFile
|
First parsed :class: |
required |
model_b
|
ModFile
|
Second parsed :class: |
required |
allow_signed_zero
|
bool
|
If |
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
|
|
comparison_verdict
¶
Return canonical verdict string for a :class:ModComparison.
comparison_to_dict
¶
Serialize a :class:ModComparison into an RFC-8259-safe dictionary.
format_report
¶
Format a concise human-readable report for a ModComparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmp
|
ModComparison
|
Comparison result produced by :func: |
required |
Returns:
| Type | Description |
|---|---|
str
|
Multi-line human-readable summary ending with a newline. |
compare_files
¶
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 |
required |
path_b
|
Path | str
|
Path to the second |
required |
allow_signed_zero
|
bool
|
Whether |
False
|
Returns:
| Type | Description |
|---|---|
tuple[str, ModComparison]
|
Tuple |
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 |
build_parser
¶
Build the CLI argument parser for flexmesa diff mod.
main
¶
Execute the mod_compare CLI entry point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
Sequence[str] | None
|
Argument list excluding the program name (default
|
None
|
prog
|
str
|
Program label shown in |
'flexmesa diff mod'
|
Returns:
| Type | Description |
|---|---|
int
|
|
int
|
(value, structural, or text-only), and |
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 ( |
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 ( |
crate |
str | None
|
Cargo package name for Rust tests, or |
role |
GapRole
|
Functional category ( |
expect_fail_when_run |
bool
|
Whether passing under |
reason |
str
|
Human-readable explanation anchored to open work. |
DiscoveredMarker
dataclass
¶
Test suppression marker extracted from Rust or Python source.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
GapKind
|
Marker type ( |
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 ( |
reason |
str
|
Extracted attribute or decorator text. |
KnownGapsAuditResult
dataclass
¶
Outcome summary of the bijective known-gaps verification gate.
only_unexpected_passes
property
¶
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).
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
¶
Verify an upstream MESA test file exists under zero-skip enforcement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Filesystem path expected from |
required |
label
|
str
|
Descriptive label included in the assertion message. |
'upstream test input'
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
bool
|
is unset. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
require_mesa_test_inputs_dir
¶
Resolve MESA_DIR or cached mesa_test_inputs without skipping.
Returns:
| Type | Description |
|---|---|
Path | None
|
Resolved directory containing |
Path | None
|
when |
Path | None
|
directory is absent on disk. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If |
extract_rust_test_ignores
¶
Extract #[ignore] markers and their test function names from Rust.
extract_python_test_markers
¶
Extract @pytest.mark.{xfail,skip,skipif} decorators via AST.
scan_imperative_python_skips
¶
Return file:line for runtime skip, xfail and importorskip calls.
discover_repo_test_markers
¶
Scan all Rust crates and Python sources for test suppression markers.
load_declared_test_gaps
¶
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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
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 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 ( |
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 |
None
|
history_gaps_path
|
Path | None
|
Override path to |
None
|
cargo_ignored_logs
|
Sequence[Path]
|
Optional Cargo |
()
|
require_all_rust_ignores_executed
|
bool
|
Require every |
False
|
fail_on_imperative_skips
|
bool
|
Include runtime |
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: |
render_markdown_summary
¶
Format a Markdown summary of the known-gaps bijective audit.
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.
ModuleHexAuditResult
dataclass
¶
resolve_hex_root
¶
Locate mesa_module_hex directory or fail cleanly when missing.
load_declared_module_gaps
¶
Parse known_module_gaps.toml into (by_module, duplicates).
verify_module_hex_gate
¶
Execute Level-2 IEEE-754 bit-exact checks across mesa_module_hex.
render_markdown_summary
¶
Format a Markdown table and violations for the Level-2 hex gate.
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 MESA26.4.1reference data (hex dumps,test_outputfixtures, Fortran oracle TSVs, MESA26.4.1histories, or unmodified*.defaultstables).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.
TestTaxonomy
dataclass
¶
Parsed test_taxonomy.toml catalog.
discover_test_files
¶
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 |
count_tests_in_file
¶
Count declared test functions in a Rust or Python test file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Absolute path to a |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of test functions found ( |
int
|
Rust; top-level and class |
detect_inline_test_kind
¶
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 |
str | None
|
present or on conflict; |
file_has_oracle_evidence
¶
Return True when code cites MESA oracle artifacts or hex tables.
validate_oracle_provenance
¶
Validate MESA-origin provenance artifact, existence, and code linkage.
load_test_taxonomy
¶
Parse test_taxonomy.toml into typed immutable records.
dump_test_taxonomy
¶
Render a TestTaxonomy in deterministic sorted TOML form.
verify_test_taxonomy
¶
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 |
None
|
manifest_path
|
Path | None
|
Override path to |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of human-readable verification errors (empty when clean). |
summarize_test_taxonomy
¶
Compute file-level classification and listed routine oracle counts.
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
¶
Returns publication figure dimensions (width_in, height_in).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layout
|
str
|
Either |
'single'
|
aspect
|
float
|
Height-to-width ratio ( |
0.78
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
mesa_rc_params
¶
Returns the canonical matplotlib rcParams dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of |
use_mesa_plot_style
¶
Applies the canonical FlexMESA publication style to mpl.rcParams.
init_ax
¶
Applies use_mesa_plot_style and returns (fig, ax).
finalize_fig
¶
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})\)
( |
required |
log_l
|
Any
|
Sequence of \(\log_{10}(L / L_\odot)\) ( |
required |
color_val
|
Any | None
|
Optional scalar sequence ( |
None
|
color_label
|
str
|
Colorbar label when |
'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 |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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}})\)
( |
required |
log_tc
|
Any
|
Sequence of \(\log_{10}(T_c / \mathrm{K})\) ( |
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 |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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 ( |
required |
mass_grid_msun
|
Any
|
Enclosed mass coordinates ( |
required |
mix_type_grid
|
Any
|
Mixing type integer grid ( |
required |
eps_nuc_grid
|
Any | None
|
Optional nuclear energy generation grid ( |
None
|
total_mass_msun
|
Any | None
|
Optional total stellar mass curve ( |
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 |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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_*\) ( |
required |
brunt_n2
|
Any
|
Squared Brunt-Vaisala frequency \(N^2\) ( |
required |
csound
|
Any
|
Adiabatic sound speed \(c_s\) ( |
required |
r_cm
|
Any
|
Radial coordinate \(r\) ( |
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 [ |
None
|
ax
|
Any | None
|
Optional pre-existing |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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 ( |
required |
obs_sigmas
|
Any
|
Observed frequency uncertainties ( |
required |
delta_nu
|
float
|
Large frequency separation \(\Delta\nu\) [ |
required |
model_freqs_uncorr
|
Any | None
|
Optional uncorrected model frequencies ( |
None
|
model_freqs_corr
|
Any | None
|
Optional surface-corrected model frequencies ( |
None
|
degrees
|
Any | None
|
Optional spherical degrees \(l_i \in \{0, 1, 2, 3\}\)
( |
None
|
ax
|
Any | None
|
Optional pre-existing |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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}\) ( |
required |
r010_obs
|
Any
|
Observed \(r_{010}\) ratios ( |
required |
r010_sigmas
|
Any
|
Observed \(r_{010}\) uncertainties ( |
required |
r010_model
|
Any | None
|
Optional model \(r_{010}\) ratios ( |
None
|
freqs_r02
|
Any | None
|
Optional reference frequencies for \(r_{02}\) ( |
None
|
r02_obs
|
Any | None
|
Optional observed \(r_{02}\) ratios ( |
None
|
r02_sigmas
|
Any | None
|
Optional observed \(r_{02}\) uncertainties ( |
None
|
r02_model
|
Any | None
|
Optional model \(r_{02}\) ratios ( |
None
|
ax
|
Any | None
|
Optional pre-existing |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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 ( |
required |
period_days
|
Any
|
Orbital periods ( |
required |
lg_mtransfer_rate
|
Any
|
Log mass-transfer rate
\(\log_{10}(|\dot{M}| / M_\odot\,\mathrm{yr}^{-1})\) ( |
required |
eccentricity
|
Any | None
|
Optional orbital eccentricity ( |
None
|
save_path
|
str | None
|
Optional output path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Any, Any]
|
Tuple |
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 |
columns |
dict[str, ndarray]
|
Mapping from canonical column name to a 1D |
num_zones |
int
|
Number of radial zones stored in the profile table. |
load_profile_file
¶
Load a 6-line-header MESA ASCII profileN.data file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Filesystem path to |
required |
Returns:
| Type | Description |
|---|---|
ProfileTable
|
Populated |
ProfileTable
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the parsed table has zero zones. |
resolve_case_entry
¶
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 |
required |
suite
|
str | None
|
Optional suite override ( |
None
|
manifest_path
|
Path | str | None
|
Optional override path to |
None
|
Returns:
| Type | Description |
|---|---|
CaseManifestEntry
|
Matching |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
suite
|
str | None
|
Optional suite name ( |
None
|
flexmesa_history
|
Path | str | None
|
Direct path to FlexMESA |
None
|
flexmesa_dir
|
Path | str | None
|
Output root directory containing FlexMESA |
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 |
None
|
save_path
|
Path | str | None
|
Optional output path for saving a |
None
|
termination_code
|
str
|
Optional termination label for title provenance. |
''
|
numerics_mode
|
str
|
Optional arithmetic mode label ( |
''
|
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 |
0
|
case_entry
|
CaseManifestEntry | None
|
Optional pre-resolved |
None
|
comparison
|
HistoryComparison | None
|
Optional precomputed |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
Tuple |
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 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 |
required |
ref_profile_path
|
Path | str | None
|
Optional path to reference MESA |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
Tuple |
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
|
required |
mass_grid_points
|
int
|
Uniform vertical grid size across |
120
|
xaxis
|
Literal['model_number', 'star_age']
|
Horizontal coordinate ( |
'star_age'
|
yaxis
|
Literal['mass', 'q', 'radius']
|
Vertical coordinate ( |
'mass'
|
history_path
|
Path | str | None
|
Optional |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
Tuple |
Axes
|
func: |
tuple[Figure, Axes]
|
func: |
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 |
None
|
profile_paths
|
Sequence[Path | str] | None
|
Optional sequence of at least two |
None
|
xaxis
|
Literal['model_number', 'star_age']
|
Horizontal coordinate ( |
'model_number'
|
yaxis
|
Literal['mass', 'q', 'radius']
|
Vertical coordinate ( |
'mass'
|
age_units
|
Literal['auto', 'yr', 'Myr']
|
Age unit when |
'auto'
|
log_xaxis
|
bool
|
Apply \(\log_{10}|x|\) scaling ( |
False
|
time_from_present
|
bool
|
Shift |
False
|
xaxis_reversed
|
bool | None
|
Optional override reversing horizontal axis direction
( |
None
|
show_mixing
|
bool
|
Render convective, overshoot, semiconvective,
thermohaline, and RTI regions ( |
True
|
show_burn
|
bool
|
Shade nuclear burning and cooling zones
( |
True
|
show_mass_boundaries
|
bool
|
Draw surface mass/radius and core boundaries
( |
True
|
show_luminosities
|
bool
|
Overlay |
False
|
burn_type_cutoff
|
float
|
Minimum \(|\log_{10}|\epsilon||\) threshold shown when
rendering |
0.0
|
mass_grid_points
|
int
|
Vertical interpolation grid length when rendering
from |
140
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
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.
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
Literal['logRho', 'column_depth', 'logxm']
|
Horizontal coordinate ( |
'logRho'
|
show_degeneracy_line
|
bool
|
Draw \(\epsilon_{\mathrm{F}}/k_{\mathrm{B}}T=4\)
from |
True
|
show_pgas_prad_line
|
bool
|
Draw \(P_{\mathrm{rad}} \approx P_{\mathrm{gas}}\)
( |
True
|
show_burn_lines
|
bool
|
Draw H/He/C/O ignition curves from
|
True
|
show_gamma1_4_3rd
|
bool
|
Draw \(\Gamma_1 < 4/3\) locus from
|
False
|
show_kap_lines
|
bool
|
Draw \(\kappa_{\mathrm{rad}} = \kappa_{\mathrm{cond}}\)
and \(e^-e^+\) curves from |
False
|
show_mix_types
|
bool
|
Highlight convective and non-convective mixing zones along the profile locus. |
True
|
full_trho_bounds
|
bool
|
Use wide |
False
|
mesa_dir
|
Path | str | None
|
Optional MESA |
None
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial coordinate name (default |
'mass'
|
ymin
|
float | None
|
Optional lower \(\log_{10}(\epsilon)\) bound overriding
|
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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial coordinate name (default |
'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
|
10
|
log_mass_frac_min
|
float
|
Lower \(\log_{10} X_i\) ( |
-5.1
|
log_mass_frac_max
|
float
|
Upper \(\log_{10} X_i\) ( |
0.25
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial coordinate name (default |
'mass'
|
show_rotation_details
|
bool
|
Plot individual rotational diffusivity curves
( |
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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial coordinate name (default |
'mass'
|
columns
|
Sequence[tuple[str, str, bool]] | None
|
Optional |
None
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial coordinate name (default |
'mass'
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
panels
|
Sequence[str | tuple[str, str | None]]
|
Non-empty sequence of column names |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Shared horizontal profile coordinate (default |
'mass'
|
axes
|
Sequence[Axes] | None
|
Optional pre-created stack of |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
Tuple |
ndarray
|
|
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 |
layout |
tuple[tuple[str, ...], ...]
|
Tuple of |
parse_inlist_text_summary_spec
¶
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 |
required |
summary_index
|
int
|
1-based |
1
|
namelist_name
|
str | None
|
Optional filter restricting parsing to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Populated |
TextSummarySpec
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
format_summary_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 |
required |
layout
|
Sequence[Sequence[str]] | None
|
Optional 2D sequence |
None
|
inlist_path
|
Path | str | None
|
Optional |
None
|
summary_index
|
int
|
1-based |
1
|
is_binary
|
bool
|
When |
False
|
model_number
|
int | None
|
Optional |
None
|
row_index
|
int
|
0-based (or negative) row index when |
-1
|
ref_history_path
|
Path | str | None
|
Optional MESA |
None
|
title
|
str
|
Optional panel title overriding |
''
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
Raises:
| Type | Description |
|---|---|
KeyError
|
If none of the requested columns exist in |
ValueError
|
If |
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 |
required |
layout
|
Sequence[Sequence[str]] | None
|
Optional 2D sequence |
None
|
inlist_path
|
Path | str | None
|
Optional |
None
|
summary_index
|
int
|
1-based |
1
|
model_number
|
int | None
|
Optional |
None
|
row_index
|
int
|
Row index when |
-1
|
mesa_binary_history
|
Path | str | None
|
Optional MESA |
None
|
title
|
str
|
Optional panel title. |
''
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
str
|
Radial profile coordinate (default |
'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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no magnetic-field columns ( |
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 |
required |
ref_history_path
|
Path | str | None
|
Optional MESA |
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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
None
|
profile_paths
|
Sequence[Path | str] | None
|
Optional sequence of |
None
|
ref_history_path
|
Path | str | None
|
Optional MESA |
None
|
xaxis
|
Literal['model_number', 'star_age']
|
Horizontal coordinate ( |
'model_number'
|
age_units
|
Literal['yr', 'Myr', 's']
|
Units when |
'yr'
|
log_xaxis
|
bool
|
Apply \(\log_{10}\) to |
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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
format_cmd_label
¶
Format photometric axis label (pgstar_color_magnitude.f90:887-920).
parse_inlist_cmd_spec
¶
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 |
required |
xaxis1
|
str | None
|
Primary horizontal column (for example |
None
|
xaxis2
|
str | None
|
Optional second horizontal column subtracted from |
None
|
panels
|
Sequence[str | tuple[str, str | None] | tuple[str, str | None, str | None, str | None]] | None
|
Sequence of panel specs: |
None
|
ref_history_path
|
Path | str | None
|
Optional MESA |
None
|
inlist_path
|
Path | str | None
|
Optional |
None
|
panel_index
|
int
|
1-based |
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 |
None
|
ax
|
Axes | None
|
Optional single target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
Tuple |
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 |
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
|
log_mass_frac_max
|
float
|
Upper colorbar bound for \(\log_{10} \bar{X}_i\)
(default |
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 |
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 |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
init_profile_path
|
Path | str | None
|
Optional initial |
None
|
ref_profile_path
|
Path | str | None
|
Optional MESA |
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
|
show_element_names
|
bool
|
Annotate staggered element symbols above curves. |
True
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
model_number
|
int | None
|
Optional |
None
|
row_index
|
int
|
Row index used when |
-1
|
eccentricity
|
float | None
|
Optional explicit orbital eccentricity override in
|
None
|
mesa_binary_history
|
Path | str | None
|
Optional MESA |
None
|
show_roche_lobes
|
bool
|
Draw critical Roche-lobe equipotential contours. |
True
|
show_stars
|
bool
|
Draw hatched stellar equipotential surfaces (or compact
markers when |
True
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
required |
mesa_binary_history
|
Path | str | None
|
Optional MESA |
None
|
columns
|
Sequence[str] | None
|
Optional sequence of column names overriding upstream defaults. |
None
|
xaxis
|
Literal['model_number', 'age']
|
Horizontal coordinate ( |
'model_number'
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 |
None
|
case
|
str | None
|
Optional manifest |
None
|
flexmesa_dir
|
Path | str | None
|
Optional run directory containing |
None
|
mesa_binary_history
|
Path | str | None
|
Optional reference MESA |
None
|
star1_history
|
Path | str | None
|
Optional path to Star 1 |
None
|
star2_history
|
Path | str | None
|
Optional path to Star 2 |
None
|
mesa_star1_history
|
Path | str | None
|
Optional reference Star 1 |
None
|
mesa_star2_history
|
Path | str | None
|
Optional reference Star 2 |
None
|
manifest_path
|
Path | str | None
|
Optional override path to |
None
|
orbit_model_number
|
int | None
|
Optional |
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
Tuple |
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 ( |
required |
panel_name
|
str
|
Any |
'HR'
|
binary_history
|
Path | str | None
|
Optional |
None
|
star_history
|
Path | str | None
|
Optional component |
None
|
star_profile
|
Path | str | None
|
Optional component |
None
|
star_profile_paths
|
Sequence[Path | str] | None
|
Optional sequence of component profiles (for
profile Kippenhahn or |
None
|
inlist_path
|
Path | str | None
|
Optional |
None
|
mesa_dir
|
Path | str | None
|
Optional MESA |
None
|
title
|
str
|
Optional custom title prefix overriding |
''
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, list[Axes]]
|
Tuple |
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 |
row |
int
|
Zero-based top row index. |
col |
int
|
Zero-based left column index. |
rowspan |
int
|
Vertical span in grid rows (default |
colspan |
int
|
Horizontal span in grid columns (default |
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 |
required |
x_col
|
str | None
|
Horizontal column name when |
None
|
y_col
|
str | None
|
Vertical column name when |
None
|
preset
|
str | None
|
Case-insensitive |
None
|
ref_history_path
|
Path | str | None
|
Optional MESA |
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 |
None
|
mesa_dir
|
Path | str | None
|
Optional MESA |
None
|
ax
|
Axes | None
|
Optional target |
None
|
save_path
|
Path | str | None
|
Optional output image path ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
Tuple |
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 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 |
profile_path |
Path | None
|
Latest |
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.
__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 |
None
|
panels
|
Sequence[GridPanelSpec | str] | None
|
Panel sequence passed to :func: |
('HR', 'TRho')
|
inlist_path
|
Path | str | None
|
Optional |
None
|
grid_index
|
int
|
1-based |
1
|
namelist_name
|
str | None
|
Optional |
None
|
file_cnt
|
int
|
Emit one frame every |
5
|
file_prefix
|
str
|
Filename prefix for emitted frames. |
'frame_'
|
file_format
|
str
|
Output image extension without leading dot
(default |
'png'
|
dpi
|
int
|
Raster resolution for saved frames (default |
150
|
write_latest
|
bool
|
Also atomically update |
True
|
render_on_finish
|
bool
|
Emit a terminal frame in |
True
|
is_binary
|
bool
|
Set |
False
|
ref_history_path
|
Path | str | None
|
Optional MESA |
None
|
ref_profile_path
|
Path | str | None
|
Optional MESA |
None
|
ref_binary_history_path
|
Path | str | None
|
Optional MESA binary history overlay. |
None
|
mesa_dir
|
Path | str | None
|
Optional MESA root for |
None
|
title
|
str
|
Optional figure super-title. |
''
|
on_frame
|
Callable[[LiveFrameRecord], None] | None
|
Optional callback invoked with each
:class: |
None
|
extras_startup
¶
StarExtras startup hook capturing case_dir if needed.
extras_binary_startup
¶
BinaryExtras startup hook capturing case_dir if needed.
extras_finish_step
¶
StarExtras step hook emitting frames every file_cnt steps.
extras_after_evolve
¶
StarExtras end-of-evolution hook ensuring a final frame.
extras_binary_after_evolve
¶
BinaryExtras end-of-evolution hook ensuring a final frame.
render_now
¶
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 |
required |
out_dir
|
Path | str
|
Output directory for rendered frames. |
required |
panels
|
Sequence[GridPanelSpec | str] | None
|
Panel names or |
('HR', 'TRho')
|
inlist_path
|
Path | str | None
|
Optional |
None
|
grid_index
|
int
|
1-based |
1
|
namelist_name
|
str | None
|
Optional |
None
|
is_binary
|
bool
|
Set |
False
|
poll_interval_sec
|
float
|
Polling sleep interval in seconds (must be |
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 |
None
|
file_prefix
|
str
|
Filename prefix for emitted frames. |
'frame_'
|
file_format
|
str
|
Image extension without leading dot (default |
'png'
|
dpi
|
int
|
Raster resolution for saved frames. |
150
|
write_latest
|
bool
|
Atomically maintain |
True
|
ref_history_path
|
Path | str | None
|
Optional MESA |
None
|
ref_profile_path
|
Path | str | None
|
Optional MESA |
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: |
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 |
namelist |
str
|
Source block, |
outputs |
tuple[str, ...]
|
Enabled outputs, a sorted subset of |
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
|
|
reason |
str
|
Empty when rendered, otherwise the explicit reason. |
figure |
Figure | None
|
The figure, or |
path |
Path | None
|
Saved image path when an output directory was given. |
case_inlist_paths
¶
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
¶
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 |
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 |
required |
history_path
|
Path | str | None
|
Star |
None
|
profile_path
|
Path | str | None
|
One |
None
|
profile_paths
|
Sequence[Path | str] | None
|
Profile files for panels that need a time series of
profiles, such as |
None
|
binary_history_path
|
Path | str | None
|
|
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
|
None
|
strict
|
bool
|
Raise |
False
|
Returns:
| Type | Description |
|---|---|
list[PanelResult]
|
One |
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 ( |
family |
str
|
Canonical panel family identifier (for example |
window_count |
int
|
Number of distinct |
status |
str
|
Implementation tier: |
flexmesa_builders |
str
|
Comma-separated |
issue |
str
|
Tracking GitHub issue reference ( |
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 |
panels |
tuple[PgstarPanelStatus, ...]
|
Ordered tuple of |
build_pgstar_coverage_report
¶
Parse upstream MESA plotting .defaults and summarize panel coverage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mesa_dir
|
Path
|
Path to extracted MESA |
required |
Returns:
| Type | Description |
|---|---|
PgstarCoverageReport
|
Populated |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any plotting |
ValueError
|
If upstream |
flexmesa.plotting.cli
¶
Command-line interface for flexmesa plot diagnostic figures (#173).
main
¶
Execute flexmesa plot CLI subcommands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str] | None
|
Arguments following |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Exit status code ( |
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 ( |
n_zones |
int
|
Number of stellar zones (\(N_{\mathrm{zones}}\)). |
stage0 |
LatencyStats
|
Stage 0 (sequential 1-thread |
stage1 |
LatencyStats
|
Stage 1 (parallel 4-thread |
stage2 |
LatencyStats
|
Stage 2 (XLA |
stage3 |
LatencyStats
|
Stage 3 (batched |
max_rel_err |
float
|
Maximum relative discrepancy across Stages 0..3. |
checksum |
float
|
Scalar |
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
|
t |
NDArray[float64]
|
Temperature \(T\) in \(\mathrm{K}\), shape |
log10_rho |
NDArray[float64]
|
Base-10 log density in \(\mathrm{g\,cm^{-3}}\), shape
|
rho |
NDArray[float64]
|
Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape
|
abar |
NDArray[float64]
|
Mean atomic weight \(\bar{A}\) in \(\mathrm{amu}\), shape
|
zbar |
NDArray[float64]
|
Mean ionic charge \(\bar{Z}\) in \(e\), shape |
create
classmethod
¶
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 |
BicubTable
dataclass
¶
Precomputed \(64 \times 64\) 2D bicubic spline table over \((\rho, T)\).
Attributes:
| Name | Type | Description |
|---|---|---|
x |
NDArray[float64]
|
Strictly ascending |
y |
NDArray[float64]
|
Strictly ascending |
coeffs |
NDArray[float64]
|
Bicubic spline coefficients |
x_jax |
Array
|
Device-resident JAX |
y_jax |
Array
|
Device-resident JAX |
coeffs_jax |
Array
|
Device-resident JAX |
ilinx |
bool
|
Uniform-spacing flag along |
iliny |
bool
|
Uniform-spacing flag along |
create
classmethod
¶
Builds the deterministic \(64 \times 64\) bicubic spline table.
Returns:
| Type | Description |
|---|---|
BicubTable
|
Initialized |
measure_us
¶
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
|
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
|
False
|
Returns:
| Type | Description |
|---|---|
LatencyStats
|
|
measure_and_capture
¶
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 |
required |
record_first_as_compile
|
bool
|
Whether to record first-call compile time. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[LatencyStats, T]
|
Tuple |
measure_stage3_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
|
required |
Returns:
| Type | Description |
|---|---|
LatencyStats
|
Two-tuple |
T
|
|
max_rel_diff
¶
Computes maximum elementwise relative difference between two arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
ArrayLike
|
Reference array-like input in |
required |
candidate
|
ArrayLike
|
Candidate array-like input in |
required |
Returns:
| Type | Description |
|---|---|
float
|
Maximum relative discrepancy across all elements, or |
float
|
entry is non-finite. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
max_err3
¶
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 |
make_block_tridiag_fixture
¶
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 |
NDArray[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
¶
Benchmarks two-variable 2nd-order automatic differentiation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ThermoGrid
|
Stellar thermodynamic profile across |
required |
n_warmup
|
int
|
Number of untimed warmup iterations. |
2
|
n_repeats
|
int
|
Number of timed iterations. |
7
|
Returns:
| Type | Description |
|---|---|
BenchRecord
|
|
bench_interp2d
¶
Benchmarks 2D bicubic spline evaluation (interp_2d) across Stages 0..3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ThermoGrid
|
Stellar thermodynamic profile across |
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
|
|
bench_neu
¶
Benchmarks thermal neutrino loss (neu) across Stages 0..3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ThermoGrid
|
Stellar thermodynamic profile across |
required |
n_warmup
|
int
|
Number of untimed warmup iterations. |
2
|
n_repeats
|
int
|
Number of timed iterations. |
7
|
Returns:
| Type | Description |
|---|---|
BenchRecord
|
|
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
¶
Benchmarks Cox Mixing-Length Theory (set_mlt) across Stages 0..3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ThermoGrid
|
Stellar thermodynamic profile across |
required |
n_warmup
|
int
|
Number of untimed warmup iterations. |
2
|
n_repeats
|
int
|
Number of timed iterations. |
7
|
Returns:
| Type | Description |
|---|---|
BenchRecord
|
|
bench_turb_tdc
¶
Benchmarks Kuhfuss 1D Time-Dependent Convection (set_tdc) Stages 0..3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ThermoGrid
|
Stellar thermodynamic profile across |
required |
n_warmup
|
int
|
Number of untimed warmup iterations. |
2
|
n_repeats
|
int
|
Number of timed iterations. |
7
|
Returns:
| Type | Description |
|---|---|
BenchRecord
|
|
run_all_wave1_benchmarks
¶
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 |
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
¶
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 |
bench_chem_comp
¶
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
|
|
bench_ion_fe56
¶
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
|
|
bench_ion_4d
¶
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
|
|
bench_colors_sed
¶
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
|
|
run_all_wave2_benchmarks
¶
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
¶
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
|
|
bench_eos_helm
¶
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
|
|
bench_eos_pc
¶
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
|
|
bench_eos_skye
¶
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
|
|
run_all_wave3a_benchmarks
¶
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 [ |
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
¶
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
|
|
bench_kap_fixed
¶
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
|
|
bench_rates_screen
¶
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
|
|
bench_net_eval
¶
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
|
|
bench_atm_table
¶
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
|
|
run_all_wave3b_benchmarks
¶
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 [ |
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
¶
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
¶
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 |
bench_star_micro_vars
¶
Benchmark zone/face stellar microphysics (star_micro_vars).
bench_star_hydro_eqns
¶
Benchmark coupled 1D Henyey residual & Jacobian (star_hydro_eqns).
bench_star_newton_step
¶
Benchmark Henyey linearize-and-solve step (star_newton_step).
bench_star_remesh
¶
Benchmark adaptive mesh spacing evaluation (star_remesh).
bench_star_evolve_step
¶
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 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
¶
Benchmark Wave 5.2 HLLC Riemann and RSP2 (w5_riemann_rsp2).
bench_w5_binary_rlof
¶
Benchmark Wave 5.3 interacting binary physics (w5_binary_rlof).
bench_w5_astero_seism
¶
Benchmark Wave 5.4 asteroseismic diagnostics (w5_astero_seism).
run_all_wave5_benchmarks
¶
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).
build_inventory
¶
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 the inventory deterministically, one routine per line.
validate_inventory
¶
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 inbenchmarks/dashboard/routine_inventory.json(Fortran names are matched without regard to case). A key is either a bare name orparent::namefor a contained procedure. A bare name that matches more than one routine of the file (for example three containedcheckprocedures) 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 (fnin Rust,defin 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 methodType::name. A qualified symbol requires animplblock forTypein the file (an inherent impl, a generic impl, orimpl Trait for Type) that holdsfn name. A bare Rust name is a violation when the file defines more than onefnof that name (free functions and methods together), because it cannot say which one is meant; useType::name.
Two structural checks run without an allow-list:
- every name in a file's
routine_map_partialis a key of that file'sroutine_map; - every routine declared not applicable in
port_status_na.toml(read byroutine_na, when that file exists) names exactly one routine of the inventory and is not also aroutine_mapkey 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
|
|
upstream_path |
str
|
Manifest |
routine |
str
|
The |
target |
str
|
The mapped |
detail |
str
|
What is missing (the file, or the offending symbol). |
match_routines
¶
Return the inventory routines that a routine_map key names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
|
required |
routines
|
list[list[Any]]
|
Inventory rows |
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
¶
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]
|
|
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Error messages, empty when every marker and declaration is valid. |
collect_violations
¶
Return every routine_map entry failing a gate check, sorted.
load_allowlist
¶
Load (declared counts, allowed violations) from the allow-list.
render_allowlist
¶
Render the allow-list for violations deterministically.
verify_routine_map
¶
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). |
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
¶
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 |
attribute
¶
Fill cases and basis on each backlog row, in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backlog
|
list[dict[str, Any]]
|
Rows with |
required |
gaps
|
list[tuple[str, str]]
|
Output of :func: |
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'sroutine_mapnames it, the mapped target passes theroutine_mapgate (the key is an inventory routine and every symbol is a function item), and it is not listed inroutine_map_partial;partial: mapped as above and listed in the file'sroutine_map_partial(the Rust counterpart implements only part of it);na: declared not applicable to a Rust port inport_status_na.toml(seeroutine_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
¶
Return each routine's own line count (span minus contained spans).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
routines
|
list[list[Any]]
|
Inventory rows |
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
¶
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 |
oracle_claims
¶
Evaluate every [[tests.oracles]] claim of the test taxonomy.
oracle_routine_ids
¶
Return (exact ids, print-only ids) of verified oracle routines.
build_table
¶
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
|
|
None
|
gaps
|
list[tuple[str, str]] | None
|
|
None
|
na_entries
|
list[NotApplicable] | None
|
Routines declared not applicable; read from
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable table with |
dict[str, Any]
|
|
render_outputs
¶
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 |
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 |
last |
int | None
|
Last line of the routine in the inventory, or |
load_na
¶
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
¶
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 |
reference |
str
|
Repository-relative path of the committed |
parser |
str
|
Parser kind (see :data: |
tolerances |
dict[str, dict[str, float]]
|
Mapping from field group to |
required_steps |
int
|
Evolution steps both runs take ( |
stdout_reference |
str
|
Optional repository-relative path of the per-model
lines extracted from |
StripScan
dataclass
¶
Parsed instability-strip scan file.
Attributes:
| Name | Type | Description |
|---|---|---|
header |
dict[str, float]
|
Model parameters ( |
models |
list[tuple[int, float, float, float, float, float]]
|
One |
edges |
dict[str, float]
|
|
table |
list[tuple[int, float, float]]
|
|
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 ( |
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 |
reference |
float
|
Value in the |
run |
float
|
Value in the |
tolerance |
float
|
Allowed absolute difference. |
excess |
float
|
|
ArtifactComparison
dataclass
¶
Result of comparing one run artifact with its MESA reference.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
str
|
|
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 |
stdout_checked |
bool
|
Whether per-model standard-output lines were compared. |
message |
str
|
One-line description for the case table. |
parse_spec
¶
Validate a [cases.artifact] TOML table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
dict[str, Any]
|
Parsed TOML table. |
required |
ctx
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
ArtifactSpec
|
The validated :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
On a missing key, unknown parser, absent tolerance group, or malformed tolerance. |
parse_instability_strip
¶
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
On a line the format does not allow. |
parse_stdout_models
¶
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a block is incomplete or malformed. |
compare_artifact
¶
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 |
required |
run_text
|
str | None
|
Contents of the file |
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
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
ArtifactComparison
|
class: |
compare_files
¶
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 |
required |
run_stdout
|
str | None
|
Captured per-model terminal lines, if any. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
ArtifactComparison
|
class: |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a committed reference file is absent. |
comparison_from_dict
¶
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, orbinary_history.data) into a dictionary of headers and 1Dfloat64arrays.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 upstreamastero/test_suite/<case>directory while streaming incremental MESA-formatLOGS/history.dataand 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 upstreambinary/test_suite/<case>directory while streaming incremental MESA-formatbinary_history.dataand componentLOGS1//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 upstreamstar/test_suite/<case>directory while streaming incremental MESA-formatLOGS/history.data(and optional profiles).
wave5_bench_py¶
w5_eval_astero_seism((nz: int) -> float): Evaluates thew5_astero_seismbenchmark scalar digest fornzzones.w5_eval_binary_rlof_batch((nz: int, parallel: bool = False) -> _ArrF64): Evaluates thew5_binary_rlofbenchmark profile acrossnzbinary configurations (shape(nz,)), dispatching across the persistent 4-thread worker team whenparallelisTrue.w5_eval_diff_rot_batch((nz: int, parallel: bool = False) -> _ArrF64): Evaluates thew5_diff_rotbenchmark profile acrossnzzones (shape(nz,)), dispatching across the persistent 4-thread worker team whenparallelisTrue.w5_eval_riemann_rsp2_batch((nz: int, parallel: bool = False) -> _ArrF64): Evaluates thew5_riemann_rsp2benchmark profile acrossnzzones (shape(nz,)), dispatching across the persistent 4-thread worker team whenparallelisTrue.