API Reference

grid_utils

generate_star_grid.grid_utils.cleanup_grid_data(parent_dir: str | Path, mode: str = 'none') None[source]

Remove or archive each model’s DATA/ folder after combined_history.hdf5 is built.

Refuses to do anything unless every model directory (one with a DATA/ subfolder) has a corresponding TAMS save file in grid_TAMS/ – this is a safety check against running cleanup while SLURM array jobs are still in progress, or have failed without producing output (see slurm/find_failed.sh).

Parameters:
  • parent_dir – Grid run directory containing one subdirectory per model.

  • mode – ‘none’ (no-op, default), ‘zip’ (archive each DATA/ to DATA.zip in the same model directory, then remove DATA/), or ‘delete’ (remove DATA/ without archiving).

Raises:

ValueError – If mode is not one of ‘none’, ‘zip’, ‘delete’.

generate_star_grid.grid_utils.coerce_cli_values(values: list) float | tuple | list[source]

Convert string tokens from an argparse nargs=’+’ argument into a constant, range, or list spec.

A single token containing ‘:’ or ‘,’ is parsed as a value-spec string (see parse_param_value): ‘MIN:MAX’ (continuous sweep, uses –num_points/–grid_type), ‘MIN:MAX:STEP’ (explicit values spaced by STEP, inclusive of both ends), or ‘V1,V2,…’ (explicit values).

Otherwise, the tokens are one or more plain numbers: a single value is held constant; two or more are used as an explicit list of values.

generate_star_grid.grid_utils.collect_profile_files(run_dir: Path, mesa_dir: Path, log_dir_name: str) None[source]

Copy MESA profile output from run_dir/DATA into grid_profiles/<log_dir_name>/.

Picks up every profile*.data file, its matching profile*.data.GYRE pulse file (written when write_pulse_data_with_profile = .true.), and profiles.index – so models with multiple saved profiles (profile_interval > 0) get all of them, not just the one at TAMS. No-op if no profile files were written.

Parameters:
  • run_dir – The model’s run directory (contains DATA/).

  • mesa_dir – Root grid directory (destination for grid_profiles/).

  • log_dir_name – Run directory name, used as the grid_profiles/ subdirectory.

generate_star_grid.grid_utils.compute_param_formats(param_specs: dict, grid_type: str = 'linear', num_points: int = 8, min_decimals: int = 1, max_decimals: int = 10, param_registry: dict | None = None) dict[source]

Choose the minimum decimal precision needed for each parameter’s directory label.

For a continuous swept parameter (a (min, max) tuple in param_specs), this is the fewest decimals such that every grid value in that range produces a unique formatted string, given the spacing implied by num_points. For a discrete swept parameter (a list of values), it’s the fewest decimals that give every value in the list a unique formatted string. For a fixed (scalar) parameter, it’s the fewest decimals that represent its value exactly.

For ‘sobol’ grids the actual sampled values aren’t reproducible across processes (Sobol scrambling isn’t seeded), so the same evenly-spaced num_points values used for ‘linear’ grids are used here for format selection only — this doesn’t affect the actual sampled points, just how many decimals are used to label them.

Parameters:
  • param_specs – Dict passed to generate_grid (scalars, (min, max) tuples, or lists of values).

  • grid_type – ‘linear’ or ‘sobol’.

  • num_points – Points per swept dimension (linear) or total samples (sobol).

  • min_decimals – Smallest number of decimals to use for any parameter.

  • max_decimals – Largest number of decimals to consider before giving up.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters.

Returns:

Dict mapping each param_registry key present in param_specs to a format spec string (e.g. ‘.3f’), for use with make_run_dir_name.

generate_star_grid.grid_utils.extract_constant_from_profile(profile_path: str | Path, key: str) float[source]

Extract a scalar constant from the header block of a MESA profile.data file.

Parameters:
  • profile_path – Path to the profile.data file.

  • key – Name of the constant to extract (e.g. ‘initial_z’).

Returns:

The float value associated with the key.

Raises:

ValueError – If the key is not found or its value cannot be parsed.

generate_star_grid.grid_utils.extract_constants_from_subdir_name(name: str, keys: list) dict[source]

Extract parameter values encoded in a subdirectory name.

Looks for each key as a ‘<key>_<value>’ token bounded by underscores or the start/end of the string, e.g. for keys=[‘M’, ‘Y’] and name=’M_1.114_Y_0.270_Z_0.020_alpha_2.00’, extracts {‘M’: 1.114, ‘Y’: 0.270}. Matching per-key (rather than blindly splitting on ‘_’) means labels that themselves contain underscores (e.g. extra MESA parameters like ‘overshoot_f_above_nonburn_core’) are handled correctly.

Parameters:
  • name – Subdirectory name string.

  • keys – Parameter keys to extract (e.g. [‘M’, ‘Y’, ‘Z’, ‘alpha’]).

Returns:

Dict mapping each found key to its float value.

generate_star_grid.grid_utils.extract_mass(subdir_name: str) float[source]

Return the mass value encoded in a subdirectory name (e.g. M_1.114_... → 1.114).

generate_star_grid.grid_utils.generate_grid(param_specs: dict, grid_type: str = 'linear', num_points: int = 8) list[source]

Generate a list of parameter dictionaries for a MESA grid.

Each parameter is one of:
  • a fixed scalar: held constant across the whole grid.

  • a (min, max) tuple: a continuous sweep, sampled at num_points values via linspace (‘linear’) or a Sobol sequence (‘sobol’).

  • a list of explicit values: a discrete sweep, used as-is. Combined with everything else via Cartesian product, e.g. a continuous mass sweep at 200 points combined with initial_z=[0.014, 0.02] yields 400 total parameter sets (200 per Z value).

Parameters:
  • param_specs

    Dict mapping parameter names to a fixed float value, a (min, max) tuple, or a list of values. Example:

    {
        "initial_mass": (0.7, 1.2),
        "initial_y": 0.27,
        "initial_z": [0.014, 0.02],
        "mixing_length_alpha": 2.0,
    }
    

  • grid_type – ‘linear’ (Cartesian product of linspace grids) or ‘sobol’ (quasi-random Sobol sequence; num_points must be a power of 2). Only applies to (min, max)-tuple parameters; discrete-list parameters are always used as-is.

  • num_points – Points per continuous-sweep dimension (linear) or total continuous samples (sobol).

Returns:

List of parameter dicts, one per grid point.

generate_star_grid.grid_utils.list_inlist_params(inlist_text: str) list[source]

List the namelist parameter names assigned in an inlist’s text.

Matches lines of the form ‘key = value’ (Fortran namelist assignment), including array-indexed parameters like ‘overshoot_f(1)’. Comment lines (starting with ‘!’) and lines with no assignment are ignored.

Parameters:

inlist_text – Raw text of an inlist/inlist_template file.

Returns:

Sorted list of unique parameter names, e.g. [‘initial_mass’, ‘mixing_length_alpha’, ‘overshoot_f(1)’, …].

generate_star_grid.grid_utils.load_history_with_constants_from_profile(parent_dir: str | Path, history_filename: str = 'history.data', profile_filename_glob: str = 'profile*.data', use_subdir_as_track: bool = False, skiprows_history: int = 5, constant_columns: list | None = None, save_as_hdf5: bool = False, hdf5_filename: str | None = 'combined_history.hdf5', extract_constants_from_dirname: bool = False, hdf5_key: str = 'history', overwrite: bool = True, return_preview_rows: int = 5) DataFrame[source]

Load MESA history files from model subdirectories and enrich with constant parameters.

Constants are sourced from either the subdirectory name or a profile.data file. Data is written incrementally to HDF5 to avoid loading all tracks into memory.

Parameters:
  • parent_dir – Directory containing one subdirectory per stellar model.

  • history_filename – Name of the MESA history file inside each model’s DATA/ folder.

  • profile_filename_glob – Glob pattern to locate a profile file per model.

  • use_subdir_as_track – Use the subdirectory name as the Track ID; otherwise use integer index.

  • skiprows_history – Header lines to skip in history files (default 5 for MESA).

  • constant_columns – Parameter names to add as constant columns (e.g. [‘Y’, ‘Z’, ‘alpha’]).

  • save_as_hdf5 – Write output to an HDF5 file in parent_dir.

  • hdf5_filename – Output HDF5 filename.

  • extract_constants_from_dirname – Parse constants from the subdirectory name rather than a profile.data file.

  • hdf5_key – HDF5 store key.

  • overwrite – Delete any existing HDF5 file before writing.

  • return_preview_rows – Number of rows from the first track to return as a preview.

Returns:

Preview DataFrame of the first return_preview_rows rows, or an empty DataFrame if no history files were found.

generate_star_grid.grid_utils.load_mesa_histories_from_subdirs(parent_dir: str | Path, history_filename: str = 'history.data', use_subdir_as_track: bool = False, skiprows: int = 5, save_as_hdf5: bool = False, hdf5_filename: str | None = 'grid_history.hdf5') DataFrame[source]

Load all MESA history files from subdirectories into a single DataFrame.

Parameters:
  • parent_dir – Directory containing one subdirectory per stellar model.

  • history_filename – Name of the history file in each subdirectory.

  • use_subdir_as_track – Use subdirectory name as track label; otherwise use integer index.

  • skiprows – Header lines to skip (default 5 for MESA).

  • save_as_hdf5 – Save the combined DataFrame to an HDF5 file.

  • hdf5_filename – Output HDF5 filename (saved in parent_dir).

Returns:

Combined DataFrame with a ‘track’ column identifying each stellar model.

generate_star_grid.grid_utils.make_run_dir_name(params: dict, param_formats: dict | None = None, param_registry: dict | None = None) str[source]

Build the run directory name from a parameter dict.

Uses the canonical order and labels in param_registry (PARAM_FORMAT by default). Only parameters present in both params and param_registry are included, so adding a new swept parameter to the registry automatically includes it in all directory and log file names without any other code changes.

Parameters:
  • params – Parameter dict (keys matching param_registry entries).

  • param_formats – Optional per-key format overrides (e.g. from compute_param_formats), falling back to param_registry’s defaults for any key not present.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters.

Returns:

Directory name string, e.g. ‘M_0.700000_Y_0.270_Z_0.0200_alpha_2.00’.

generate_star_grid.grid_utils.parse_extra_params(param_args: list, inlist_text: str) tuple[source]

Parse –param KEY=SPEC arguments into param_specs and param_registry entries.

Each KEY is validated against inlist_text via resolve_param_key (raising a ValueError listing close matches and available parameters if it isn’t a settable inlist parameter). Resolved keys are used directly as both the param_specs key and the registry’s inlist_key/label.

Parameters:
  • param_args – List of ‘KEY=SPEC’ strings from –param (repeatable).

  • inlist_text – Raw text of the inlist_template file.

Returns:

dicts to merge into param_ranges and param_registry respectively.

Return type:

(extra_specs, extra_registry)

generate_star_grid.grid_utils.parse_param_value(spec_str: str) float | tuple | list[source]

Parse a value-spec string into a fixed float, (min, max) tuple, or list.

  • 'VALUE' -> float(VALUE) (constant)

  • 'MIN:MAX' -> (float(MIN), float(MAX)) (continuous sweep, uses –num_points/–grid_type)

  • 'MIN:MAX:STEP' -> [v0, v1, ..., MAX] (explicit values spaced by STEP, inclusive of both ends; see _expand_range)

  • 'V1,V2,...' -> [float(V1), float(V2), ...] (explicit values)

generate_star_grid.grid_utils.print_grid_dry_run(param_specs: dict, grid_type: str = 'linear', num_points: int = 8, avg_data_mb: float = 20.0, param_registry: dict | None = None) None[source]

Print a plan summary for a grid without building or running MESA.

Reports the constant and swept parameters, the number of MESA models that would run (broken down incrementally per swept dimension), an estimated total disk footprint, and example directory/file names.

Parameters:
  • param_specs – Dict passed to generate_grid (scalars, (min, max) tuples, or lists of values).

  • grid_type – ‘linear’ or ‘sobol’.

  • num_points – Points per swept dimension (linear) or total samples (sobol).

  • avg_data_mb – Estimated MESA output size (MB) per model, used for the disk usage estimate.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters added via –param.

generate_star_grid.grid_utils.resolve_param_key(key: str, inlist_text: str) str[source]

Validate that key is a parameter settable in an inlist, and return its spelling as it appears there.

Matching is case-insensitive (MESA’s Fortran namelists are case-insensitive), e.g. resolve_param_key(‘Overshoot_F(1)’, inlist_text) -> ‘overshoot_f(1)’.

Parameters:
  • key – Parameter name as given by the user (e.g. on the command line).

  • inlist_text – Raw text of the inlist_template file.

Returns:

The parameter’s spelling as it appears in inlist_text.

Raises:

ValueError – If key doesn’t match any parameter settable in inlist_text. The message lists close matches (via difflib, if any) and every parameter available in inlist_text.

generate_star_grid.grid_utils.run_grid(param_ranges: dict, grid_type: str = 'linear', num_points: int = 8, max_workers: int = 2, param_registry: dict | None = None) None[source]

Build MESA, generate the parameter grid, and run all models in parallel.

Must be called from the grid run directory (the one containing inlist_template, rn, etc.).

Parameters:
  • param_ranges – Parameter spec dict passed to generate_grid.

  • grid_type – ‘linear’ or ‘sobol’.

  • num_points – Grid points per swept dimension (linear) or total samples (sobol).

  • max_workers – Parallel MESA processes. Use 1 for serial/debug mode.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters added via –param.

generate_star_grid.grid_utils.run_mesa_model(template_file: Path, mesa_dir: Path, params: dict, log_path: Path, param_formats: dict | None = None, param_registry: dict | None = None) None[source]

Set up a run directory for a single MESA model and execute it.

Creates a subdirectory named by the parameter values under mesa_dir, writes the updated inlist, copies MESA runtime files, runs MESA, then archives the output TAMS model, inlist, and any saved profiles (see collect_profile_files).

Parameters:
  • template_file – Path to the inlist_template file.

  • mesa_dir – Root directory of the grid run (must contain rn, star, inlist, etc.).

  • params – Parameter dict with keys matching param_registry entries (initial_mass, initial_y, initial_z, mixing_length_alpha, plus any extra parameters added via –param).

  • log_path – File path where MESA stdout/stderr will be written.

  • param_formats – Optional per-key directory-naming format overrides (see compute_param_formats). Does not affect the values written into the inlist itself.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters.

generate_star_grid.grid_utils.task_wrapper(args: tuple) None[source]

Unpack args and run a single MESA model; for use with ProcessPoolExecutor.

Parameters:

args – Tuple of (params, template_file, mesa_dir, param_formats, param_registry).

generate_star_grid.grid_utils.update_inlist(template_text: str, params: dict, log_dir: str, param_registry: dict | None = None) str[source]

Substitute parameter values into a MESA inlist template.

Handles every key in params that’s also in param_registry (PARAM_FORMAT’s four built-in parameters by default, plus any extra parameters added via –param). Also sets log_directory to ‘DATA’ and save_model_filename to TAMS_<log_dir>.mod, matching the run directory name.

Parameters:
  • template_text – Raw text of the inlist_template file.

  • params – Parameter dict (keys matching param_registry entries).

  • log_dir – Run directory name (from make_run_dir_name), used to name the saved TAMS model file.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to substitute extra (non-built-in) parameters too.

Returns:

Modified inlist text.

generate_star_grid.grid_utils.write_grid_notes(param_specs: dict, param_formats: dict, grid_type: str, num_points: int, out_path: str | Path, param_registry: dict | None = None) None[source]

Write a notes.txt summarizing a grid’s constant and swept parameters.

Records, for each param_registry parameter: whether it’s held constant, swept over a continuous range, or swept over a discrete list of values; its value(s); the spacing between grid points (for continuous sweeps); and the directory-naming format chosen for it.

Parameters:
  • param_specs – Dict passed to generate_grid (scalars, (min, max) tuples, or lists of values).

  • param_formats – Dict from compute_param_formats mapping each key to a format spec (e.g. ‘.3f’).

  • grid_type – ‘linear’ or ‘sobol’.

  • num_points – Points per swept dimension (linear) or total samples (sobol).

  • out_path – File path to write the notes to.

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters.

grid_utils_cont

Continuation variant of grid_utils for resumed stellar evolution runs.

Use this module when you want to restart models from an existing TAMS save file (e.g. to continue evolution past the main sequence). The run logic is identical to grid_utils except that update_inlist and run_mesa_model handle the extra bookkeeping for loading/saving continuation models.

generate_star_grid.grid_utils_cont.run_grid(param_ranges: dict, grid_type: str = 'linear', num_points: int = 8, max_workers: int = 2, resume: bool = False, resume_edit_path: str = None, param_registry: dict | None = None) None[source]

Build MESA, generate the parameter grid, and run all models in parallel.

Must be called from the grid run directory. When resume=True, a Python script at resume_edit_path is imported; it must define:

  • resume_tag (str): appended to archived inlist filenames

  • modifications (list of callables): each takes (inlist_text, params) and returns modified inlist_text

Parameters:
  • param_ranges – Parameter spec dict passed to generate_grid.

  • grid_type – ‘linear’ or ‘sobol’.

  • num_points – Grid points per swept dimension (linear) or total samples (sobol).

  • max_workers – Parallel MESA processes. Use 1 for serial/debug mode.

  • resume – Continue from existing TAMS models.

  • resume_edit_path – Path to the resume edits script (required when resume=True).

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to include extra (non-built-in) parameters added via –param.

generate_star_grid.grid_utils_cont.run_mesa_model(run_dir: Path, log_path: Path, mesa_dir: Path, params: dict, resume: bool = False, tams_dir=None) None[source]

Copy MESA runtime files into run_dir and execute MESA.

Assumes inlist_project is already written to run_dir. On completion, moves the output model file to grid_TAMS/ (new run) or grid_CONT/ (continuation run).

Parameters:
  • run_dir – Pre-created directory for this model run.

  • log_path – File path where MESA stdout/stderr will be written.

  • mesa_dir – Root grid directory (source of rn, star, inlist, etc.).

  • params – Parameter dict (must include initial_mass).

  • resume – If True, also copies the TAMS file into run_dir before running.

  • tams_dir – Directory containing TAMS_<run_dir_name>.mod files (required when resume=True).

generate_star_grid.grid_utils_cont.task_wrapper(args: tuple) None[source]

Unpack args, write the inlist, and run a single MESA model (with optional resume).

Parameters:

args – Tuple of (params, template_file, mesa_dir, resume, modifications, tag, param_formats, param_registry). modifications is a list of callables f(inlist_text, params) -> inlist_text applied after the standard substitutions (used for resume edits). tag is an optional string appended to the archived inlist filename. param_formats holds per-key directory-naming format overrides (see compute_param_formats). param_registry is a dict like PARAM_FORMAT (label/fmt/inlist_key per key); defaults to PARAM_FORMAT if None.

generate_star_grid.grid_utils_cont.update_inlist(template_text: str, params: dict, log_dir: str, resume: bool = False, tams_dir=None, param_registry: dict | None = None) str[source]

Substitute parameter values into a MESA inlist template, with optional resume support.

Handles every key in params that’s also in param_registry (PARAM_FORMAT’s four built-in parameters by default, plus any extra parameters added via –param). When resume=True, also enables load_saved_model and sets load_model_filename to the corresponding TAMS file; the output save file is named cont_<mass>.mod.

Parameters:
  • template_text – Raw text of the inlist_template file.

  • params – Parameter dict (keys matching param_registry entries).

  • log_dir – Unused; kept for API compatibility. log_directory is always set to ‘DATA’.

  • resume – If True, configure the inlist to load an existing TAMS model.

  • tams_dir – Directory containing TAMS_<run_dir_name>.mod files (required when resume=True).

  • param_registry – Dict like PARAM_FORMAT (label/fmt/inlist_key per key). Defaults to PARAM_FORMAT; pass an extended copy to substitute extra (non-built-in) parameters too.

Returns:

Modified inlist text.

resume_utils

generate_star_grid.resume_utils.get_next_resume_index(base_path: Path, prefix: str) int[source]

Return the next available resume index for a given inlist prefix.

Scans base_path for files matching <prefix>_resume<N> and returns the next integer after the highest found (or 1 if only the base file exists).

Parameters:
  • base_path – Directory containing inlist files.

  • prefix – Base inlist name (e.g. ‘inlist_M_1.000_Y_0.270_Z_0.020_alpha_2.00’).

Returns:

Next available resume index.

generate_star_grid.resume_utils.modify_inlist_for_resume(inlist_path: Path, modifications: dict, output_path: Path = None, tag: str = None) Path[source]

Apply parameter modifications to an existing inlist for a resumed run.

Replaces matching key = value lines in the inlist. If a key is not found, it is inserted after the &controls block header, or appended at the end.

Parameters:
  • inlist_path – Path to the original inlist file (e.g. from grid_inlists/).

  • modifications – Dict of parameter names to new values, e.g. {'xa_central_lower_limit': '1d-3'}.

  • output_path – Directory to write the modified inlist (default: same as inlist_path’s parent).

  • tag – Optional string appended to the output filename (e.g. ‘_rgb’).

Returns:

Path to the written modified inlist file.

make_grid

generate_star_grid.make_grid.main(parent_dir: Path, save_as_hdf5: bool, hdf5_filename: str, constant_columns: list, cleanup: str = 'none')[source]

Load MESA history files from a grid run directory and optionally save to HDF5.

Parameters:
  • parent_dir – Directory containing one subdirectory per stellar model.

  • save_as_hdf5 – Write combined output to an HDF5 file.

  • hdf5_filename – Output HDF5 filename (written into parent_dir).

  • constant_columns – Parameter names to extract from subdirectory names and add as constant columns (e.g. [‘M’, ‘Y’, ‘Z’, ‘alpha’]).

  • cleanup – ‘none’, ‘zip’, or ‘delete’. After a successful HDF5 save, archive (‘zip’) or remove (‘delete’) each model’s DATA/ folder (see cleanup_grid_data). Only applies when save_as_hdf5 is True.

make_starpasta_grid

make_yrec_grid

generate_star_grid.make_yrec_grid.get_prefix(name)[source]

Extract prefix such as ‘0.725_solar’ from strings like ‘0.725_solar_0001’. Modify this if your filename pattern is different.

generate_star_grid.make_yrec_grid.main()[source]