Skip to content

Foundational Numerics & Convection (constants, math, utils, auto_diff, interp_1d, interp_2d, mtx, num, turb)

This reference page covers the nine foundational numerical, spline interpolation, linear algebra, nonlinear solver, and convective mixing subpackages in FlexMESA.

For architectural details on hybrid dispatch, dual-number automatic differentiation, and block-tridiagonal solvers (bcyclic vs. PCR), see Hybrid Architecture, Autodiff & Solvers and Convection, Diffusion, Rotation & Dynamos.


Quick Usage Example

import jax
import jax.numpy as jnp
import flexmesa.turb as turb
from flexmesa import constants

# Differentiate Mixing Length Theory (MLT) temperature gradient wrt gradr
d_gradt_d_gradr = jax.grad(
    lambda gradr: turb.set_mlt_jax(
        1.0, 1.0, 2.0e8, 2.7e4, 1.5e9, 1.0e-5, 1.0e8, 1.0e5, 1.0, gradr, 0.40, 0.40
    )[1]
)(jnp.float64(0.45))
print(
    f"MSUN={constants.MSUN:.6e} g, d(grad_T)/d(grad_r)={float(d_gradt_d_gradr):.6f}"
)

Physical & Astronomical Constants (flexmesa.constants)

CODATA physical constants and IAU/MESA solar reference quantities in CGS units (MSUN, RSUN, LSUN, SECYER, SECDAY, STANDARD_CGRAV, CLIGHT, KERG, CRAD, AVO, ME, MP, PLANCK_H, EV2ERG). In Safe Rust, the corresponding crate is flexmesa_const.

flexmesa.constants

Physical, mathematical, and astronomical CGS constants for FlexMESA.

This module ports upstream MESA's const_def module in IEEE-754 double precision (float64). Fundamental physical constants follow CODATA 2018 exact definitions, and solar/planetary reference values follow the IAU 2012 and IAU 2015 Resolution B3 nominal conversion constants.

Examples:

>>> from flexmesa import constants
>>> constants.MixingType.from_code(0) is constants.MixingType.NO_MIXING
True

MixingType

Bases: IntEnum

Mixing process classification matching upstream MESA const_def.

from_code classmethod

from_code(code)

Convert an integer mixing code from MESA into a MixingType.

Parameters:

Name Type Description Default
code int

Integer mixing code (-1 through 10).

required

Returns:

Type Description
MixingType | None

Corresponding MixingType member, or None if out of range.

code

code()

Return the integer mixing code matching MESA const_def.


Numerics Modes (strict vs. fast) & CRMATH Elementary Intrinsics (flexmesa.math)

flexmesa.math (backed in Rust by crates/flexmesa-math and crates/flexmesa-crlibm-sys) provides the single arithmetic layer called by all physics crates (#165). Two run-level numerics modes are compiled from the same Rust physics source and selected via flexmesa.set_numerics_mode, flexmesa.numerics_mode_context, or --numerics-mode {strict,fast} on the CLI:

  • "strict" (default): Evaluates vendored crlibm 1.0beta4 (CRMATH 1.2 from MESA SDK 26.6.1, encapsulated in flexmesa-crlibm-sys, the sole workspace crate permitted to use unsafe FFI under #![deny(unsafe_op_in_unsafe_fn)]). Its contract is "correctly rounded toward zero as CRMATH does it" (*_rz, with *_rd for exp, acos, and acospi, plus *_rn on atan2 and intrinsic_{log,log10,exp,pow} for upstream platform-libm call sites tracked in #196 and #198), explicit multiplication chains for pow2 through pow8 and pow_i_/pow_r_/exp10_, and a * b + c with no fused multiply-add contraction. "strict" is the only mode judged against MESA 26.4.1, across three fidelity levels:
  • Level 1: "strict" mode is bit-identical across machines (x86_64 and aarch64) and thread counts (1 vs. 4 rayon threads), enforced in CI.
  • Level 2: "strict" kernels are bit-identical to MESA 26.4.1 against exact hexadecimal reference outputs wherever operations and evaluation order match (474,062 tested inputs across 47 math sections in mesa_26_4_1_vectors.rs).
  • Level 3: Whole evolutionary trajectories are compared against real MESA 26.4.1 histories within the #143 history-harness tolerances (notes/audit/case_table.md).
  • "fast": Evaluates platform std f64 intrinsics with hardware mul_add permitted. "fast" results are hardware-dependent, are validated exclusively against "strict" (notes/audit/fast_vs_strict.md), and are never compared against MESA.

Upstream real(qp) (IEEE-754 binary128 under gfortran on x86_64) is represented in Rust by flexmesa_math::Quad, a software binary128 type with round-to-nearest-even +, -, *, /, integer powers, comparisons, and conversions to and from f64 (DECISIONS #46). It uses integer arithmetic only, so it gives the same bits in both numerics modes and on every machine. It is checked against test vectors computed with exact rational arithmetic, which is a check of the arithmetic and not a comparison with MESA. It has no Python binding. Upstream's compensated-summation type built on it, accurate_real (num/public/accurate_sum.f90), is flexmesa_num::AccurateReal. Both are used for the mass-change bookkeeping (mass_utils.f90) and the mass-change heating term (eps_mdot.f90), which upstream evaluates entirely in real(qp). Its first use is the cell-specific kinetic and potential energy of the star energy equation, remesh energy bookkeeping and total-energy diagnostics (crates/flexmesa-star/src/cell_energy.rs, after cell_specific_KE_qp, cell_specific_PE_qp and get_dke_dt_dpe_dt in star/private/star_utils.f90:2147-2370).

import flexmesa
from flexmesa import _rust

assert flexmesa.get_numerics_mode() == "strict"
strict_val = _rust.exp10(1.25)

with flexmesa.numerics_mode_context("fast") as active_mode:
    assert active_mode == "fast"
    fast_val = _rust.exp10(1.25)

assert flexmesa.get_numerics_mode() == "strict"
print(f"exp10(1.25): strict={strict_val:.16e}, |fast - strict|={abs(fast_val - strict_val):.2e}")

flexmesa.math.intrinsics

IEEE-754 float64 elementary and domain-safe mathematical intrinsics.

This module ports upstream MESA's math module (math_lib_intrinsic.f90, math_pown.f90, and math_io.f90) to JAX-traceable 64-bit floating-point functions. Domain-safe functions (safe_sqrt, safe_log, safe_log10) use the double-jnp.where pattern so that neither primal values nor forward/reverse automatic differentiation gradients ever evaluate 0.0 * NaN or 0.0 * Inf.

as_f64

as_f64(val)

Convert scalar or array input val to a float64 JAX array.

safe_sqrt

safe_sqrt(val)

Compute the domain-safe square root \(\sqrt{\max(x, 0)}\).

Uses the double-where guard so negative inputs evaluate to 0.0 with zero derivative, while NaN inputs propagate NaN.

Parameters:

Name Type Description Default
val ArrayLike

Input scalar or array of shape (*batch,) (dimensionless).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,) with \(\sqrt{\max(x, 0)}\).

Examples:

>>> import flexmesa.math as fmath
>>> float(fmath.safe_sqrt(4.0))
2.0
>>> float(fmath.safe_sqrt(-9.0))
0.0

safe_log

safe_log(val)

Compute the domain-safe natural logarithm \(\ln(\max(10^{-99}, x))\).

Returns -99.0 where val is non-finite (NaN or ±Inf), matching MESA's safe_log safeguard without propagating NaN through jnp.where.

Parameters:

Name Type Description Default
val ArrayLike

Input scalar or array of shape (*batch,) (dimensionless).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

Examples:

>>> import flexmesa.math as fmath
>>> float(fmath.safe_log(1.0))
0.0
>>> float(fmath.safe_log(float("nan")))
-99.0

safe_log10

safe_log10(val)

Compute the domain-safe base-10 log \(\log_{10}(\max(10^{-99}, x))\).

Returns -99.0 where val is non-finite (NaN or ±Inf) or <= 1e-99.

Parameters:

Name Type Description Default
val ArrayLike

Input scalar or array of shape (*batch,) (dimensionless).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

Examples:

>>> import flexmesa.math as fmath
>>> abs(float(fmath.safe_log10(10.0)) - 1.0) <= 1e-15
True
>>> float(fmath.safe_log10(0.0))
-99.0

log

log(val)

Compute the natural logarithm \(\ln(x)\) in float64.

Parameters:

Name Type Description Default
val ArrayLike

Positive scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

log10

log10(val)

Compute the base-10 logarithm \(\log_{10}(x)\) in float64.

Parameters:

Name Type Description Default
val ArrayLike

Positive scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

log1p

log1p(val)

Compute \(\ln(1 + x)\) without cancellation near \(x = 0\).

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,) with \(x > -1\).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

log2

log2(val)

Compute \(\log_{2}(x)\) in float64.

Parameters:

Name Type Description Default
val ArrayLike

Positive scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

exp

exp(val)

Compute the natural exponential \(e^{x}\) in float64.

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

expm1

expm1(val)

Compute \(e^{x} - 1\) without cancellation near \(x = 0\).

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

exp10

exp10(val)

Compute the base-10 exponential \(10^{x} = \exp(x \ln 10)\).

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

hypot

hypot(lhs, rhs)

Compute the Euclidean hypotenuse \(\sqrt{x^{2} + y^{2}}\) in float64.

pow

pow(base, exponent)

Raise base to power exponent (\(x^{y}\)) in float64.

Parameters:

Name Type Description Default
base ArrayLike

Base scalar or array of shape (*batch,).

required
exponent ArrayLike

Exponent scalar or array broadcastable to (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

powi

powi(base, exponent)

Raise base to an integer power exponent (\(x^{n}\)) in float64.

powm1

powm1(val)

Compute the reciprocal \(x^{-1} = 1 / x\).

Parameters:

Name Type Description Default
val ArrayLike

Nonzero scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

pow2

pow2(val)

Compute \(x^{2}\) via repeated multiplication.

pow3

pow3(val)

Compute \(x^{3}\) via repeated multiplication.

pow4

pow4(val)

Compute \(x^{4}\) via repeated multiplication.

pow5

pow5(val)

Compute \(x^{5}\) via repeated multiplication.

pow6

pow6(val)

Compute \(x^{6}\) via repeated multiplication.

pow7

pow7(val)

Compute \(x^{7}\) via repeated multiplication.

pow8

pow8(val)

Compute \(x^{8}\) via repeated multiplication.

flexmesa.math.trig

Trigonometric, half-turn (pi-scaled), hyperbolic, sign, and string helpers.

Provides radian and half-turn trigonometric functions, hyperbolic functions, MESA's symmetric heaviside and sgn step functions, and Fortran string parsers (str_to_double, str_to_vector).

cos

cos(val)

Compute \(\cos(x)\) for \(x\) in radians.

sin

sin(val)

Compute \(\sin(x)\) for \(x\) in radians.

tan

tan(val)

Compute \(\tan(x)\) for \(x\) in radians.

cospi

cospi(val)

Compute \(\cos(\pi x)\) for half-turn argument \(x\).

sinpi

sinpi(val)

Compute \(\sin(\pi x)\) for half-turn argument \(x\).

tanpi

tanpi(val)

Compute \(\tan(\pi x)\) for half-turn argument \(x\).

acos

acos(val)

Compute \(\arccos(x)\) in radians.

asin

asin(val)

Compute \(\arcsin(x)\) in radians.

atan

atan(val)

Compute \(\arctan(x)\) in radians.

acospi

acospi(val)

Compute \(\arccos(x) / \pi\) in half-turns.

asinpi

asinpi(val)

Compute \(\arcsin(x) / \pi\) in half-turns.

atanpi

atanpi(val)

Compute \(\arctan(x) / \pi\) in half-turns.

cosh

cosh(val)

Compute \(\cosh(x)\).

sinh

sinh(val)

Compute \(\sinh(x)\).

tanh

tanh(val)

Compute \(\tanh(x)\).

acosh

acosh(val)

Compute \(\operatorname{arcosh}(x)\).

asinh

asinh(val)

Compute \(\operatorname{arsinh}(x)\).

atanh

atanh(val)

Compute \(\operatorname{artanh}(x)\).

sgn

sgn(val)

Evaluate the three-valued signum function \(\operatorname{sgn}(x)\).

Returns -1.0 where val < 0.0, 0.0 where val == 0.0, +1.0 where val > 0.0, and NaN where val is NaN.

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

heaviside

heaviside(val)

Evaluate the symmetric Heaviside step function \(H(x)\).

Returns 0.0 where val < 0.0, 0.5 where val == 0.0, 1.0 where val > 0.0, and NaN where val is NaN.

Parameters:

Name Type Description Default
val ArrayLike

Scalar or array of shape (*batch,).

required

Returns:

Type Description
Array

float64 JAX array of shape (*batch,).

str_to_double

str_to_double(token)

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

Parameters:

Name Type Description Default
token str

String representation of a floating-point value (supports D/d exponent markers).

required

Returns:

Type Description
float

Parsed Python float.

Raises:

Type Description
ValueError

If token cannot be parsed as a valid float.

str_to_vector

str_to_vector(text)

Parse whitespace-delimited Fortran/IEEE-754 numbers into a 1D JAX array.

Parameters:

Name Type Description Default
text str

Whitespace-separated string of floating-point tokens.

required

Returns:

Type Description
Array

1D float64 JAX array of shape (N,).

Raises:

Type Description
ValueError

If any token cannot be parsed as a valid float.


  • NumericsMode (Literal["strict", "fast"]): Type alias of the two run-level arithmetic modes.
  • get_numerics_mode (() -> NumericsMode): Returns the active Rust arithmetic mode ("strict" or "fast", default "strict").
  • set_numerics_mode ((mode: NumericsMode | str) -> None): Sets the process-wide Rust arithmetic mode; raises ValueError unless mode is "strict" or "fast".
  • numerics_mode_context ((mode: NumericsMode | str) -> Iterator[NumericsMode]): Context manager that temporarily switches the Rust arithmetic mode and restores the previous mode on exit.

Array, Checkpoint Codec, Timing & Thread-Pool Utilities (flexmesa.utils)

Floating-point finiteness guards (is_bad), array helpers, Safe Rust persistent worker-pool utilities, and the deterministic IEEE-754 little-endian serde binary codec (flexmesa_utils::bin_codec with shared 13-byte NumericsMode wire framing for StarModel and BinarySystem checkpoints).

flexmesa.utils

Core numerical guards, dictionaries, and stream tokenizers for FlexMESA.

This module ports upstream MESA's utils package, routing scalar/NumPy finiteness checks, string normalizers, and the stateful .net stream tokenizer through the compiled Safe Rust flexmesa._rust extension while providing JAX jnp.where finiteness guards for traced arrays.

IntegerDict

String-keyed integer dictionary matching upstream MESA integer_dict.

Upstream stores keys in character(len=50) and compares them with blank padding (utils/private/utils_dict.f90): a key is stored as its first 50 characters without trailing blanks, a lookup key matches after removing trailing blanks only, and a longer lookup key never matches.

__init__

__init__()

Initialize an empty IntegerDict.

define_and_report_duplicates

define_and_report_duplicates(key, value)

Define key -> value and return True if key existed.

Parameters:

Name Type Description Default
key str

String key (cut to 50 characters, trailing blanks dropped).

required
value int

Integer value to associate with key.

required

Returns:

Type Description
bool

True if key already existed prior to this definition.

define

define(key, value)

Define key -> value, overwriting any existing entry.

Parameters:

Name Type Description Default
key str

String key (cut to 50 characters, trailing blanks dropped).

required
value int

Integer value to associate with key.

required

create_hash

create_hash()

No-op hook for upstream MESA integer_dict_create_hash.

lookup

lookup(key)

Look up the integer value associated with key.

Parameters:

Name Type Description Default
key str

String key to query.

required

Returns:

Type Description
int | None

Associated integer value, or None if key is not present.

is_empty

is_empty()

Return True if the dictionary contains no entries.

__len__

__len__()

Return the number of entries in the dictionary.

entries

entries()

Return all (key, value) pairs sorted lexicographically by key.

Returns:

Type Description
list[tuple[str, int]]

Sorted list of (key, value) pairs.

IntegerIdict

Integer-pair (k1, k2) dictionary matching MESA integer_idict.

__init__

__init__()

Initialize an empty IntegerIdict.

define_and_report_duplicates

define_and_report_duplicates(key1, key2, value)

Define (key1, key2) -> value and report whether the key existed.

Parameters:

Name Type Description Default
key1 int

First integer key component.

required
key2 int

Second integer key component.

required
value int

Integer value to associate with (key1, key2).

required

Returns:

Type Description
bool

True if (key1, key2) was already defined prior to this call.

define

define(key1, key2, value)

Define (key1, key2) -> value, overwriting any existing entry.

Parameters:

Name Type Description Default
key1 int

First integer key component.

required
key2 int

Second integer key component.

required
value int

Integer value to associate with (key1, key2).

required

create_hash

create_hash()

No-op compatibility hook for MESA integer_idict_create_hash.

lookup

lookup(key1, key2)

Look up the integer value associated with (key1, key2).

Parameters:

Name Type Description Default
key1 int

First integer key component.

required
key2 int

Second integer key component.

required

Returns:

Type Description
int | None

Associated integer value, or None if (key1, key2) is absent.

is_empty

is_empty()

Return True if the dictionary contains no entries.

__len__

__len__()

Return the number of entries in the dictionary.

entries

entries()

Return all (key1, key2, value) tuples sorted by (key1, key2).

Returns:

Type Description
list[tuple[int, int, int]]

Sorted list of (key1, key2, value) entries.

TokenKind

Bases: StrEnum

Lexical token classification matching upstream MESA utils_def.

Token dataclass

Lexical token emitted by Tokenizer and tokenize.

Attributes:

Name Type Description
kind TokenKind

Token category (TokenKind).

value str

Text payload for NAME and STRING tokens, or symbol text.

Tokenizer

Stateful stream tokenizer matching upstream MESA utils_lib::token.

__init__

__init__(text)

Initialize the tokenizer over text.

Parameters:

Name Type Description Default
text str

Full multi-line input text to tokenize.

required

next_token

next_token()

Advance and return the next Token, or Token(TokenKind.EOF).

Returns:

Type Description
Token

Next lexical Token in the stream.

is_bad

is_bad(value)

Return True when value is NaN or infinite.

Delegates to flexmesa_utils::is_bad via flexmesa._rust.

Parameters:

Name Type Description Default
value float

Scalar floating-point number (float64).

required

Returns:

Type Description
bool

True if value is NaN or \(\pm\infty\), False otherwise.

Examples:

>>> from flexmesa import utils
>>> utils.is_bad(1.0)
False
>>> utils.is_bad(float("nan"))
True

is_bad_array

is_bad_array(values)

Return True if any element in values is NaN or infinite.

Parameters:

Name Type Description Default
values ndarray | Array

Array of arbitrary shape (*batch,) in float64.

required

Returns:

Type Description
bool

True if at least one element of values is non-finite.

replace_bad_nums

replace_bad_nums(values, replacement=-1e+99)

Replace non-finite (NaN or \(\pm\infty\)) values with replacement.

Applies jnp.where before any arithmetic so that masked NaN entries never propagate through 0.0 * NaN in values or automatic-differentiation gradients.

Parameters:

Name Type Description Default
values ndarray | Array

Input array of shape (*batch,) in float64.

required
replacement float

Finite scalar value substituted for non-finite entries.

-1e+99

Returns:

Type Description
Array

Array of shape (*batch,) with dtype=float64 and all non-finite

Array

entries replaced by replacement.

remove_underbars

remove_underbars(text)

Replace underscores with spaces after trimming trailing whitespace.

Delegates to flexmesa_utils::remove_underbars via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Input string from a MESA control or column header.

required

Returns:

Type Description
str

String with trailing spaces removed and '_' replaced by ' '.

split_line

split_line(line, num)

Split line on whitespace into at most num tokens.

Delegates to flexmesa_utils::split_line via flexmesa._rust.

Parameters:

Name Type Description Default
line str

Whitespace-delimited input string.

required
num int

Maximum number of tokens to extract.

required

Returns:

Type Description
list[str]

List of at most num whitespace-delimited substrings.

tokenize

tokenize(text)

Tokenize text into a list of Token objects ending with EOF.

Delegates directly to flexmesa_utils::tokenize via flexmesa._rust.

Parameters:

Name Type Description Default
text str

Multi-line input string in MESA .net or list syntax.

required

Returns:

Type Description
list[Token]

Sequence of Token objects terminated by

list[Token]

Token(TokenKind.EOF, "").

Examples:

>>> from flexmesa import utils
>>> [t.value for t in utils.tokenize("add_isos(ih1, ihe4)")]
['add_isos', '(', 'ih1', ',', 'ihe4', ')', '']

Forward-Mode Dual & Hyperdual Numbers (flexmesa.auto_diff)

First-order (AutoDiffRealOrder1) and second-order (AutoDiffRealOrder2) forward-mode automatic differentiation types mirroring crates/flexmesa-autodiff (DualOrder1<N>, DualOrder2<N>, StarAdOrder1).

flexmesa.auto_diff.base

Shared typed elementary method mixin (AutoDiffBase) for auto_diff.

Provides all 32 unary elementary functions (sin, cos, exp, log, safe_log, safe_sqrt, etc.), fixed integer powers (pow2 through pow8), scalar exponentiation (powf, powi, rpow), and value-based relational comparisons shared by DualOrder1 and AutoDiffReal2VarOrder2.

AutoDiffBase

Mixin providing typed elementary methods and value comparisons.

apply_unary

apply_unary(kernel)

Propagate a unary kernel (f, f', f'') through self.

sign

sign()

Compute \(\operatorname{sgn}(x)\) with zero derivative.

abs

abs()

Compute \(|x|\).

sqrt

sqrt()

Compute \(\sqrt{x}\).

safe_sqrt

safe_sqrt()

Compute \(\sqrt{\max(x, 0)}\).

exp

exp()

Compute \(\exp(x)\).

expm1

expm1()

Compute \(e^{x} - 1\).

exp10

exp10()

Compute \(10^{x}\).

powm1

powm1()

Compute \(x^{-1}\).

log

log()

Compute \(\ln(x)\).

safe_log

safe_log()

Compute \(\operatorname{safe\_log}(x)\).

log1p

log1p()

Compute \(\ln(1 + x)\).

log10

log10()

Compute \(\log_{10}(x)\).

safe_log10

safe_log10()

Compute \(\operatorname{safe\_log10}(x)\).

log2

log2()

Compute \(\log_{2}(x)\).

sin

sin()

Compute \(\sin(x)\).

cos

cos()

Compute \(\cos(x)\).

tan

tan()

Compute \(\tan(x)\).

sinpi

sinpi()

Compute \(\sin(\pi x)\).

cospi

cospi()

Compute \(\cos(\pi x)\).

tanpi

tanpi()

Compute \(\tan(\pi x)\).

sinh

sinh()

Compute \(\sinh(x)\).

cosh

cosh()

Compute \(\cosh(x)\).

tanh

tanh()

Compute \(\tanh(x)\).

asin

asin()

Compute \(\arcsin(x)\).

acos

acos()

Compute \(\arccos(x)\).

atan

atan()

Compute \(\arctan(x)\).

asinpi

asinpi()

Compute \(\arcsin(x) / \pi\).

acospi

acospi()

Compute \(\arccos(x) / \pi\).

atanpi

atanpi()

Compute \(\arctan(x) / \pi\).

asinh

asinh()

Compute \(\operatorname{arsinh}(x)\).

acosh

acosh()

Compute \(\operatorname{arcosh}(x)\).

atanh

atanh()

Compute \(\operatorname{artanh}(x)\).

pow2

pow2()

Compute \(x^{2}\).

pow3

pow3()

Compute \(x^{3}\).

pow4

pow4()

Compute \(x^{4}\).

pow5

pow5()

Compute \(x^{5}\).

pow6

pow6()

Compute \(x^{6}\).

pow7

pow7()

Compute \(x^{7}\).

pow8

pow8()

Compute \(x^{8}\).

powf

powf(exponent)

Raise self to a constant floating-point exponent (\(x^{p}\)).

powi

powi(exponent)

Raise self to a constant integer exponent (\(x^{n}\)).

rpow

rpow(base)

Raise positive scalar base to exponent self (\(b^{x}\)).

flexmesa.auto_diff.order1

First-order forward-mode dual numbers (DualOrder1) as JAX PyTrees.

Provides DualOrder1 and MESA-compatible fixed-arity subclasses for 1, 2, 4, and 33 independent variables (AutoDiffReal1VarOrder1, AutoDiffReal2VarOrder1, AutoDiffReal4VarOrder1, AutoDiffRealStarOrder1).

DualOrder1

Bases: AutoDiffBase

First-order forward-mode dual number with N partial derivatives.

Attributes:

Name Type Description
val Array

Primal value float64 JAX array of shape (*batch,).

d1 Array

First-order partial derivatives float64 JAX array of shape (*batch, N).

Examples:

>>> from flexmesa.auto_diff import AutoDiffReal2VarOrder1
>>> x = AutoDiffReal2VarOrder1.independent(3.0, 0)
>>> y = AutoDiffReal2VarOrder1.independent(2.0, 1)
>>> z = x * y + x.pow2()
>>> float(z.val), [float(v) for v in z.d1]
(15.0, [8.0, 3.0])

__init__

__init__(val, d1)

Initialize DualOrder1 with float64 val and d1 arrays.

tree_flatten

tree_flatten()

Flatten DualOrder1 into (val, d1) leaves for JAX PyTrees.

tree_unflatten classmethod

tree_unflatten(aux_data, children)

Reconstruct DualOrder1 from flattened (val, d1) leaves.

constant classmethod

constant(val, num_vars=None)

Construct a constant DualOrder1 with num_vars zero partials.

independent classmethod

independent(val, index, num_vars=None)

Seed the index-th independent variable (\(\partial_i x_i = 1\)).

make_unary_operator

make_unary_operator(z_val, z_d1x)

Apply the first-order unary chain rule \(z = f(x)\).

make_binary_operator

make_binary_operator(other, z_val, z_d1x, z_d1y)

Apply the first-order binary chain rule \(z = g(x, y)\).

apply_unary

apply_unary(kernel)

Propagate a unary kernel (f, f', f'') through self.

pow

pow(other)

Raise self to a dual or scalar exponent other (\(x^{y}\)).

max

max(other)

Compute \(\max(x, y)\) using MESA's Heaviside subgradient.

min

min(other)

Compute \(\min(x, y)\) using MESA's Heaviside subgradient.

dim

dim(other)

Compute \(\operatorname{dim}(x, y) = \max(x - y, 0)\).

AutoDiffReal1VarOrder1

Bases: DualOrder1

One-variable first-order dual number (auto_diff_real_1var_order1).

AutoDiffReal2VarOrder1

Bases: DualOrder1

Two-variable first-order dual number (auto_diff_real_2var_order1).

AutoDiffReal4VarOrder1

Bases: DualOrder1

Four-variable first-order dual number (auto_diff_real_4var_order1).

AutoDiffRealStarOrder1

Bases: DualOrder1

Stellar 33-variable first-order dual (auto_diff_real_star_order1).

flexmesa.auto_diff.order2

Two-variable second-order hyperdual numbers (AutoDiffReal2VarOrder2).

Ports MESA's auto_diff_real_2var_order2 (auto_diff_real_2nd_order) as a registered JAX PyTree propagating exact first and second partial derivatives (val, d1val1, d1val2, d2val1, d1val1_d1val2, d2val2) in float64.

AutoDiffReal2VarOrder2

Bases: AutoDiffBase

Two-variable second-order forward-mode hyperdual number.

Attributes:

Name Type Description
val Array

Primal value \(f(x_1, x_2)\) of shape (*batch,).

d1val1 Array

First partial derivative \(\partial f / \partial x_1\).

d1val2 Array

First partial derivative \(\partial f / \partial x_2\).

d2val1 Array

Second partial derivative \(\partial^2 f / \partial x_1^2\).

d1val1_d1val2 Array

Mixed partial \(\partial_{12} f\).

d2val2 Array

Second partial derivative \(\partial^2 f / \partial x_2^2\).

Examples:

>>> from flexmesa.auto_diff import AutoDiffReal2VarOrder2
>>> x = AutoDiffReal2VarOrder2.var1(2.0)
>>> y = AutoDiffReal2VarOrder2.var2(3.0)
>>> z = x * y + x.pow2()
>>> (float(z.val), float(z.d1val1), float(z.d2val1))
(10.0, 7.0, 2.0)

__init__

__init__(
    val,
    d1val1=0.0,
    d1val2=0.0,
    d2val1=0.0,
    d1val1_d1val2=0.0,
    d2val2=0.0,
)

Initialize all six float64 hyperdual components.

tree_flatten

tree_flatten()

Flatten hyperdual components for JAX PyTree transformations.

tree_unflatten classmethod

tree_unflatten(aux_data, children)

Reconstruct AutoDiffReal2VarOrder2 from flattened PyTree leaves.

constant classmethod

constant(val)

Construct a constant hyperdual with zero derivatives.

var1 classmethod

var1(val)

Seed the first independent variable \(x_1\) (d1val1 = 1.0).

var2 classmethod

var2(val)

Seed the second independent variable \(x_2\) (d1val2 = 1.0).

make_unary_operator

make_unary_operator(z_val, z_d1x, z_d2x)

Apply MESA's second-order unary chain rule.

make_binary_operator

make_binary_operator(
    other, z_val, z_d1x, z_d1y, z_d2x, z_d1x_d1y, z_d2y
)

Apply MESA's second-order binary chain rule.

apply_unary

apply_unary(kernel)

Propagate a unary kernel (f, f', f'') through self.

differentiate_1

differentiate_1()

Extract \(\partial / \partial x_1\) with zero second partials.

differentiate_2

differentiate_2()

Extract \(\partial / \partial x_2\) with zero second partials.

pow

pow(other)

Raise self to a hyperdual or scalar exponent other (\(x^{y}\)).

max

max(other)

Compute \(\max(x, y)\) using MESA's Heaviside subgradient.

min

min(other)

Compute \(\min(x, y)\) using MESA's Heaviside subgradient.

dim

dim(other)

Compute \(\operatorname{dim}(x, y) = \max(x - y, 0)\).

__neg__

__neg__()

Negate all six hyperdual components directly without squaring.

__add__

__add__(other)

Add a hyperdual or scalar operand.

__radd__

__radd__(other)

Add a scalar left operand to self.

__sub__

__sub__(other)

Subtract a hyperdual or scalar operand from self.

__rsub__

__rsub__(other)

Subtract self from a scalar left operand.

__mul__

__mul__(other)

Multiply self by a hyperdual or scalar operand.

__rmul__

__rmul__(other)

Multiply a scalar left operand by self.

__truediv__

__truediv__(other)

Divide self by a hyperdual or scalar operand.

__rtruediv__

__rtruediv__(other)

Divide a scalar left operand by self (\(c / y = c y^{-1}\)).

__pow__

__pow__(other)

Raise self to power other (\(x^{y}\)).

flexmesa.auto_diff.kernels

Shared JAX float64 first- and second-derivative kernels for auto_diff.

Each unary kernel returns a 3-tuple (f(x), f'(x), f''(x)) of float64 JAX arrays so that DualOrder1 and AutoDiffReal2VarOrder2 share identical elementary derivative formulas and domain-safety guards.

unary_sign

unary_sign(val)

Return (f, f', f'') for \(\operatorname{sgn}(x)\).

unary_abs

unary_abs(val)

Return (f, f', f'') for \(|x|\).

unary_sqrt

unary_sqrt(val)

Return (f, f', f'') for \(\sqrt{x}\) on \(x > 0\).

unary_safe_sqrt

unary_safe_sqrt(val)

Return (f, f', f'') for \(\sqrt{\max(x, 0)}\) without 0.0 * Inf.

unary_exp

unary_exp(val)

Return (f, f', f'') for \(\exp(x)\).

unary_expm1

unary_expm1(val)

Return (f, f', f'') for \(e^{x} - 1\).

unary_exp10

unary_exp10(val)

Return (f, f', f'') for \(10^{x}\).

unary_powm1

unary_powm1(val)

Return (f, f', f'') for \(x^{-1}\).

unary_log

unary_log(val)

Return (f, f', f'') for \(\ln(x)\).

unary_safe_log

unary_safe_log(val)

Return (f, f', f'') for \(\operatorname{safe\_log}(x)\).

unary_log1p

unary_log1p(val)

Return (f, f', f'') for \(\ln(1 + x)\).

unary_log10

unary_log10(val)

Return (f, f', f'') for \(\log_{10}(x)\).

unary_safe_log10

unary_safe_log10(val)

Return (f, f', f'') for \(\operatorname{safe\_log10}(x)\).

unary_log2

unary_log2(val)

Return (f, f', f'') for \(\log_{2}(x)\).

unary_sin

unary_sin(val)

Return (f, f', f'') for \(\sin(x)\).

unary_cos

unary_cos(val)

Return (f, f', f'') for \(\cos(x)\).

unary_tan

unary_tan(val)

Return (f, f', f'') for \(\tan(x)\).

unary_sinpi

unary_sinpi(val)

Return (f, f', f'') for \(\sin(\pi x)\).

unary_cospi

unary_cospi(val)

Return (f, f', f'') for \(\cos(\pi x)\).

unary_tanpi

unary_tanpi(val)

Return (f, f', f'') for \(\tan(\pi x)\).

unary_sinh

unary_sinh(val)

Return (f, f', f'') for \(\sinh(x)\).

unary_cosh

unary_cosh(val)

Return (f, f', f'') for \(\cosh(x)\).

unary_tanh

unary_tanh(val)

Return (f, f', f'') for \(\tanh(x)\).

unary_asin

unary_asin(val)

Return (f, f', f'') for \(\arcsin(x)\).

unary_acos

unary_acos(val)

Return (f, f', f'') for \(\arccos(x)\).

unary_atan

unary_atan(val)

Return (f, f', f'') for \(\arctan(x)\).

unary_asinpi

unary_asinpi(val)

Return (f, f', f'') for \(\arcsin(x) / \pi\).

unary_acospi

unary_acospi(val)

Return (f, f', f'') for \(\arccos(x) / \pi\).

unary_atanpi

unary_atanpi(val)

Return (f, f', f'') for \(\arctan(x) / \pi\).

unary_asinh

unary_asinh(val)

Return (f, f', f'') for \(\operatorname{arsinh}(x)\).

unary_acosh

unary_acosh(val)

Return (f, f', f'') for \(\operatorname{arcosh}(x)\).

unary_atanh

unary_atanh(val)

Return (f, f', f'') for \(\operatorname{artanh}(x)\).

unary_pown

unary_pown(val, degree)

Return (f, f', f'') for \(x^{2}\) through \(x^{8}\).

unary_pow_scalar

unary_pow_scalar(val, exponent)

Return (f, f', f'') for \(x^{p}\) with constant exponent \(p\).

unary_rpow_scalar

unary_rpow_scalar(base, exponent)

Return (f, f', f'') for \(b^{x}\) with constant base \(b > 0\).

binary_pow

binary_pow(lhs, rhs)

Return (z, dz/dx, dz/dy, d2z/dx2, d2z/dxdy, d2z/dy2) for \(x^{y}\).


1D Monotonic & Piecewise-Cubic Interpolation (flexmesa.interp_1d)

Steffen (1990) piecewise-monotonic (interp_pm) and Huynh (1993) monotonicity-preserving (interp_mp) 1D cubic Hermite splines and conservative Lagrangian remeshing integrators.

flexmesa.interp_1d.pm

Steffen (1990) piecewise-monotonic cubic interpolation (interp_pm).

Reference

Steffen, M. (1990), "A simple method for monotonic interpolation in one dimension", Astronomy and Astrophysics, 239, 443-450.

validate_1d_grid

validate_1d_grid(x, y, min_points=2)

Validates strictly monotonic 1D knot coordinates and finite values.

Parameters:

Name Type Description Default
x ndarray | ndarray

1D array of knot coordinates of shape (N,) in physical or dimensionless units (strictly increasing or strictly decreasing).

required
y ndarray | ndarray

1D array of knot values of shape (N,) in physical or dimensionless units.

required
min_points int

Minimum number of knots required.

2

Returns:

Type Description
ndarray

Tuple (x_arr, y_arr) converted to 1D float64 NumPy arrays of

ndarray

shape (N,).

Raises:

Type Description
ValueError

If shapes mismatch, N < min_points, values are non-finite, or x is not strictly monotonic.

interp_pm

interp_pm(x, y, *, backend='auto')

Computes Steffen (1990) piecewise-monotonic cubic coefficients.

On subinterval [x[i], x[i + 1]] with offset dx = x_eval - x[i], the interpolant is evaluated via Horner's rule: f(x_eval) = c[i, 0] + dx * (c[i, 1] + dx * (c[i, 2] + dx * c[i, 3])).

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (N, 4) containing the local cubic

ndarray | ndarray

coefficients [c0, c1, c2, c3] at each knot.

Raises:

Type Description
ValueError

If x and y fail grid validation.

interp_pm_slopes_only

interp_pm_slopes_only(x, y)

Computes only the knot values and Steffen (1990) monotonic slopes.

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required

Returns:

Type Description
ndarray

JAX float64 array of shape (N, 4) with [:, 0] = y,

ndarray

[:, 1] = df/dx, and [:, 2:] = 0.

Raises:

Type Description
ValueError

If x and y fail grid validation.

interp_4pt_pm

interp_4pt_pm(x, y)

Computes cubic coefficients on the middle interval of a 4-point stencil.

For x[1] <= x_eval <= x[2] and dx = x_eval - x[1], the interpolated value is y[1] + dx * (a[0] + dx * (a[1] + dx * a[2])).

Parameters:

Name Type Description Default
x Sequence[float] | ndarray | ndarray

4-element strictly monotonic knot coordinate sequence of shape (4,) in physical or dimensionless units.

required
y Sequence[float] | ndarray | ndarray

4-element knot value sequence of shape (4,) in physical or dimensionless units.

required

Returns:

Type Description
ndarray | ndarray

float64 array [a0, a1, a2] of shape (3,).

Raises:

Type Description
ValueError

If x and y do not have length 4 or fail grid validation.

interp_pm_autodiff

interp_pm_autodiff(x, y)

Computes Steffen (1990) cubic coefficients on DualOrder1 knots.

Parameters:

Name Type Description Default
x Sequence[DualOrder1]

Sequence of N >= 2 strictly monotonic DualOrder1 knot coordinates in physical or dimensionless units.

required
y Sequence[DualOrder1]

Sequence of N DualOrder1 knot values in physical or dimensionless units.

required

Returns:

Type Description
list[tuple[DualOrder1, DualOrder1, DualOrder1, DualOrder1]]

List of N 4-tuples (c0, c1, c2, c3) of DualOrder1 values.

Raises:

Type Description
ValueError

If x and y have mismatched lengths, fewer than 2 points, non-finite values/derivatives, or non-monotonic abscissas.

flexmesa.interp_1d.mp

Huynh (1993) and Suresh & Huynh (1997) monotonicity-preserving splines.

References

Huynh, H. T. (1993), "Accurate Monotone Cubic Interpolation", SIAM Journal on Numerical Analysis, 30(1), 57-100. Suresh, A., & Huynh, H. T. (1997), "Accurate Monotonicity-Preserving Schemes with Runge-Kutta Time Stepping", Journal of Computational Physics, 136, 83-99.

MpLimiter

Bases: IntEnum

Slope-limiter variant for Huynh (1993) MP cubic interpolation.

minmod

minmod(a, b)

Two-argument minmod limiter matching upstream minmod1.

Parameters:

Name Type Description Default
a float

First scalar slope argument in physical or dimensionless units.

required
b float

Second scalar slope argument in physical or dimensionless units.

required

Returns:

Type Description
float

Limited scalar 0.5 * (sign(1, a) + sign(1, b)) * min(|a|, |b|).

minmod4

minmod4(a, b, c, d)

Four-argument sequential minmod limiter matching minmod4_1.

Parameters:

Name Type Description Default
a float

First scalar argument.

required
b float

Second scalar argument.

required
c float

Third scalar argument.

required
d float

Fourth scalar argument.

required

Returns:

Type Description
float

Sequentially limited value minmod(minmod(minmod(a, b), c), d).

median

median(a, b, c)

Median of three numbers via a + minmod(b - a, c - a).

Parameters:

Name Type Description Default
a float

First scalar argument.

required
b float

Second scalar argument.

required
c float

Third scalar argument.

required

Returns:

Type Description
float

Median of (a, b, c).

interp_m3

interp_m3(x, y, which=MpLimiter.QUARTIC, *, backend='auto')

Computes Huynh (1993) monotonicity-preserving cubic spline coefficients.

For N <= 3, delegates to :func:flexmesa.interp_1d.pm.interp_pm matching upstream MESA m3 (mk_pmlinear / mk_pmquad).

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
which str | MpLimiter

Slope-limiter variant (MpLimiter or "average", "quartic", "super_bee").

QUARTIC
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (N, 4) with [c0, c1, c2, c3]

ndarray | ndarray

at each knot.

Raises:

Type Description
ValueError

If N < 2, x is not strictly monotonic, or which is unknown.

interp_m3a

interp_m3a(x, y, *, backend='auto')

Computes Huynh (1993) average-slope MP coefficients (interp_m3a).

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (N, 4) with [c0, c1, c2, c3] at

ndarray | ndarray

each knot.

Raises:

Type Description
ValueError

If x and y fail grid validation.

interp_m3b

interp_m3b(x, y, *, backend='auto')

Computes Huynh (1993) superbee-slope MP coefficients (interp_m3b).

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (N, 4) with [c0, c1, c2, c3] at

ndarray | ndarray

each knot.

Raises:

Type Description
ValueError

If x and y fail grid validation.

interp_m3q

interp_m3q(x, y, *, backend='auto')

Computes Huynh (1993) quartic-slope MP coefficients (interp_m3q).

Parameters:

Name Type Description Default
x ndarray | ndarray

Knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (N, 4) with [c0, c1, c2, c3] at

ndarray | ndarray

each knot.

Raises:

Type Description
ValueError

If x and y fail grid validation.

flexmesa.interp_1d.eval

Spline evaluation and definite integration (interp_1d).

Provides vectorized float64 JAX evaluation of 1D cubic splines and exact piecewise-analytic definite integration across monotonic knot grids.

interp_values_and_slopes

interp_values_and_slopes(
    init_x, coeffs, xs, *, backend="auto"
)

Evaluates a 1D cubic spline and its first derivative at query points.

Supports jax.grad, jax.hessian, and jax.vmap with respect to both xs and coeffs.

Parameters:

Name Type Description Default
init_x ndarray | ndarray

Strictly monotonic knot coordinates of shape (N,) in physical or dimensionless units.

required
coeffs ndarray | ndarray

Spline coefficient array of shape (N, 4).

required
xs ndarray | ndarray

Query coordinates of shape (M,) in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
tuple[ndarray | ndarray, ndarray | ndarray]

Tuple (vals, slopes) of float64 arrays of shape (M,).

Raises:

Type Description
ValueError

If init_x and coeffs shapes are incompatible.

interp_values

interp_values(init_x, coeffs, xs, *, backend='auto')

Evaluates a 1D cubic spline at query points xs (interp_values).

Parameters:

Name Type Description Default
init_x ndarray | ndarray

Strictly monotonic knot coordinates of shape (N,).

required
coeffs ndarray | ndarray

Spline coefficient array of shape (N, 4).

required
xs ndarray | ndarray

Query coordinates of shape (M,).

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of interpolated values of shape (M,).

Raises:

Type Description
ValueError

If init_x and coeffs shapes are incompatible.

interp_value_and_slope

interp_value_and_slope(
    init_x, coeffs, x, *, backend="auto"
)

Evaluates a 1D cubic spline value and slope at a single scalar x.

Parameters:

Name Type Description Default
init_x ndarray | ndarray

Strictly monotonic knot coordinates of shape (N,).

required
coeffs ndarray | ndarray

Spline coefficient array of shape (N, 4).

required
x float | ndarray

Scalar query coordinate in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
tuple[ndarray | ndarray, ndarray | ndarray]

Tuple (val, slope) of scalar float64 values.

Raises:

Type Description
ValueError

If init_x and coeffs shapes are incompatible.

interp_value

interp_value(init_x, coeffs, x, *, backend='auto')

Evaluates a 1D cubic spline value at a single scalar x.

Parameters:

Name Type Description Default
init_x ndarray | ndarray

Strictly monotonic knot coordinates of shape (N,).

required
coeffs ndarray | ndarray

Spline coefficient array of shape (N, 4).

required
x float | ndarray

Scalar query coordinate in physical or dimensionless units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

Scalar float64 value containing f(x).

Raises:

Type Description
ValueError

If init_x and coeffs shapes are incompatible.

integrate_values

integrate_values(init_x, coeffs, xs, *, backend='auto')

Integrates a 1D cubic spline over adjacent segments [xs[k-1], xs[k]].

Returns an array integrals of shape (M,) with integrals[0] = 0 and integrals[k] = \int_{xs[k-1]}^{xs[k]} f(x)\,dx for k >= 1.

Reproduces upstream MESA 26.4.1 do_integrate_values (interp_1d/private/interp_1d_misc.f90:29-109), including two properties recorded in deferred issue #218: on a decreasing grid the lower sub-interval is not subtracted, and the sweep starts at the first cell, so xs[0] is expected to lie in it.

Parameters:

Name Type Description Default
init_x ndarray | ndarray

Strictly monotonic knot coordinates of shape (N,) (N >= 2) in physical or dimensionless units.

required
coeffs ndarray | ndarray

Spline coefficient array of shape (N, 4).

required
xs ndarray | ndarray

Monotonic integration bounds of shape (M,) aligned with init_x direction and lying within init_x bounds.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (M,) containing segment integrals.

Raises:

Type Description
ValueError

If init_x, coeffs, or xs fail validation or xs lies outside init_x or reverses direction.

flexmesa.interp_1d.remesh

Fixed-point stencil remeshing and DualOrder1 1D spline evaluation.

Provides hydrostatic Lagrangian remeshing stencils (interp_3_to_1, interp_3_to_2, interp_4_to_1), convenience vector interpolation wrappers (interpolate_vector, interpolate_vector_pm), and first-order forward-mode DualOrder1 spline evaluation (interp_values_autodiff, interpolate_vector_pm_autodiff).

interpolate_vector

interpolate_vector(
    old_x, old_y, new_x, builder=pm.interp_pm
)

Interpolates (old_x, old_y) onto new_x using builder.

Parameters:

Name Type Description Default
old_x ndarray | ndarray

Source knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
old_y ndarray | ndarray

Source knot values of shape (N,) in physical or dimensionless units.

required
new_x ndarray | ndarray

Target query coordinates of shape (M,) in physical or dimensionless units.

required
builder Callable[[ndarray | ndarray, ndarray | ndarray], ndarray | ndarray]

Spline builder callable returning an (N, 4) coefficient array (default :func:flexmesa.interp_1d.pm.interp_pm).

interp_pm

Returns:

Type Description
ndarray | ndarray

float64 array of shape (M,) containing interpolated values

ndarray | ndarray

at new_x.

Raises:

Type Description
ValueError

If old_x, old_y, or new_x fail validation.

interpolate_vector_pm

interpolate_vector_pm(old_x, old_y, new_x)

Interpolates (old_x, old_y) onto new_x using interp_pm.

Parameters:

Name Type Description Default
old_x ndarray | ndarray

Source knot coordinates of shape (N,) (N >= 2), strictly monotonic, in physical or dimensionless units.

required
old_y ndarray | ndarray

Source knot values of shape (N,) in physical or dimensionless units.

required
new_x ndarray | ndarray

Target query coordinates of shape (M,) in physical or dimensionless units.

required

Returns:

Type Description
ndarray | ndarray

float64 array of shape (M,) containing Steffen (1990)

ndarray | ndarray

interpolated values at new_x.

Raises:

Type Description
ValueError

If old_x, old_y, or new_x fail validation.

interp_values_autodiff

interp_values_autodiff(init_x, coeffs, x)

Evaluates a 1D cubic spline over DualOrder1 queries (O(M log N)).

Parameters:

Name Type Description Default
init_x Sequence[DualOrder1]

Sequence of N >= 1 strictly monotonic DualOrder1 knots in physical or dimensionless units.

required
coeffs Sequence[tuple[DualOrder1, DualOrder1, DualOrder1, DualOrder1]]

Sequence of N 4-tuples (c0, c1, c2, c3) of DualOrder1 spline coefficients.

required
x Sequence[DualOrder1]

Sequence of M DualOrder1 query abscissas in physical or dimensionless units.

required

Returns:

Type Description
list[DualOrder1]

List of M interpolated DualOrder1 values.

Raises:

Type Description
ValueError

If init_x and coeffs have mismatched or zero length, init_x is not strictly monotonic, or any input contains non-finite values or derivatives.

interpolate_vector_pm_autodiff

interpolate_vector_pm_autodiff(old_x, old_y, new_x)

Interpolates DualOrder1 vectors via Steffen (1990) interp_pm.

Parameters:

Name Type Description Default
old_x Sequence[DualOrder1]

Sequence of N >= 2 strictly monotonic DualOrder1 knot coordinates in physical or dimensionless units.

required
old_y Sequence[DualOrder1]

Sequence of N DualOrder1 knot values in physical or dimensionless units.

required
new_x Sequence[DualOrder1]

Sequence of M DualOrder1 target query coordinates.

required

Returns:

Type Description
list[DualOrder1]

List of M interpolated DualOrder1 values at new_x.

Raises:

Type Description
ValueError

If spline construction or evaluation fails validation.

interp_3_to_1

interp_3_to_1(pdqm1, pdq00, ndqm1, pfm1, pf00, pfp1)

Remeshes 3 points spaced by (pdqm1, pdq00) to offset ndqm1.

Parameters:

Name Type Description Default
pdqm1 float

First source cell spacing in Lagrangian coordinate units.

required
pdq00 float

Second source cell spacing in Lagrangian coordinate units.

required
ndqm1 float

Target offset from the first knot in Lagrangian coordinate units.

required
pfm1 float

Value at the first knot in physical or dimensionless units.

required
pf00 float

Value at the second knot in physical or dimensionless units.

required
pfp1 float

Value at the third knot in physical or dimensionless units.

required

Returns:

Type Description
float

Interpolated scalar float64 value at offset ndqm1.

Raises:

Type Description
ValueError

If source spacings are non-monotonic or inputs are non-finite.

interp_3_to_2

interp_3_to_2(pdqm1, pdq00, ndqm1, ndq00, pfm1, pf00, pfp1)

Remeshes 3 points spaced by (pdqm1, pdq00) onto 2 target offsets.

Parameters:

Name Type Description Default
pdqm1 float

First source cell spacing in Lagrangian coordinate units.

required
pdq00 float

Second source cell spacing in Lagrangian coordinate units.

required
ndqm1 float

First target cell spacing from the origin.

required
ndq00 float

Second target cell spacing (evaluated at ndqm1 + ndq00).

required
pfm1 float

Value at the first knot in physical or dimensionless units.

required
pf00 float

Value at the second knot in physical or dimensionless units.

required
pfp1 float

Value at the third knot in physical or dimensionless units.

required

Returns:

Type Description
float

Tuple (nf00, nfp1) of interpolated float64 values at ndqm1

float

and ndqm1 + ndq00.

Raises:

Type Description
ValueError

If source spacings are non-monotonic or inputs are non-finite.

interp_4_to_1

interp_4_to_1(
    pdqm1, pdq00, pdqp1, ndq00, pfm1, pf00, pfp1, pfp2
)

Remeshes 4 points spaced by (pdqm1, pdq00, pdqp1) to ndq00.

Parameters:

Name Type Description Default
pdqm1 float

First source cell spacing in Lagrangian coordinate units.

required
pdq00 float

Second source cell spacing in Lagrangian coordinate units.

required
pdqp1 float

Third source cell spacing in Lagrangian coordinate units.

required
ndq00 float

Target offset from the origin in Lagrangian coordinate units.

required
pfm1 float

Value at the first knot in physical or dimensionless units.

required
pf00 float

Value at the second knot in physical or dimensionless units.

required
pfp1 float

Value at the third knot in physical or dimensionless units.

required
pfp2 float

Value at the fourth knot in physical or dimensionless units.

required

Returns:

Type Description
float

Interpolated scalar float64 value at offset ndq00.

Raises:

Type Description
ValueError

If source spacings are non-monotonic or inputs are non-finite.


2D Bicubic & Akima Surface Interpolation (flexmesa.interp_2d)

2D bicubic Hermite splines (interp_mkbicub_db, interp_evbicub_db) and Akima bivariate surface interpolators used across EOS, opacity, ionization, and atmosphere tables.

flexmesa.interp_2d.bicub

Two-dimensional C^2 bicubic spline setup (interp_mkbicub_db).

Constructs \(C^2\) bicubic spline coefficient tables [f, f_xx, f_yy, f_xxyy] over a rectangular grid (x, y) of shape (nx, ny) by solving 1D cubic splines along x and y with optional inhomogeneous boundary-condition correction matching upstream PSPLINE / MESA do_mkbicub_db.

interp_mkbicub_db

interp_mkbicub_db(
    x,
    y,
    z,
    ibcxmin=BicubicBc.NOT_A_KNOT,
    bcxmin=None,
    ibcxmax=BicubicBc.NOT_A_KNOT,
    bcxmax=None,
    ibcymin=BicubicBc.NOT_A_KNOT,
    bcymin=None,
    ibcymax=BicubicBc.NOT_A_KNOT,
    bcymax=None,
    *,
    backend="auto",
)

Constructs 2D C^2 bicubic spline coefficients on grid (x, y).

Parameters:

Name Type Description Default
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,) (nx >= 4) in physical or dimensionless units.

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,) (ny >= 4) in physical or dimensionless units.

required
z ndarray | ndarray

Grid values of shape (nx, ny) or flat (nx * ny,) in row-major order.

required
ibcxmin BicubicBc | int

Boundary condition at x[0].

NOT_A_KNOT
bcxmin ndarray | ndarray | None

Boundary data of shape (ny,) at x[0].

None
ibcxmax BicubicBc | int

Boundary condition at x[-1].

NOT_A_KNOT
bcxmax ndarray | ndarray | None

Boundary data of shape (ny,) at x[-1].

None
ibcymin BicubicBc | int

Boundary condition at y[0].

NOT_A_KNOT
bcymin ndarray | ndarray | None

Boundary data of shape (nx,) at y[0].

None
ibcymax BicubicBc | int

Boundary condition at y[-1].

NOT_A_KNOT
bcymax ndarray | ndarray | None

Boundary data of shape (nx,) at y[-1].

None
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

Tuple (coeffs, ilinx, iliny) where coeffs is a float64

bool

array of shape (nx, ny, 4) containing [f, f_xx, f_yy, f_xxyy].

Raises:

Type Description
ValueError

If grid dimensions are < 4, non-ascending, mismatched with z or boundary arrays, or contain non-finite values.

flexmesa.interp_2d.bicub_eval

Two-dimensional bicubic spline evaluation (herm2xy_db, fvbicub_db).

Evaluates \(C^2\) bicubic splines and their first and second partial derivatives in float64 JAX arithmetic, compatible with jax.grad and jax.hessian.

BicubicEval dataclass

Evaluated value and partial derivatives of a 2D bicubic spline.

Attributes:

Name Type Description
f ndarray

Interpolated value f(x, y) (dimensionless or physical units).

df_dx ndarray

First partial derivative df/dx.

df_dy ndarray

First partial derivative df/dy.

d2f_dx2 ndarray

Second partial derivative d^2f/dx^2.

d2f_dy2 ndarray

Second partial derivative d^2f/dy^2.

d2f_dxdy ndarray

Mixed second partial derivative d^2f/(dx dy).

herm2xy_db

herm2xy_db(xget, yget, x, y, ilinx=True, iliny=True)

Locates the 2D grid cell and local coordinates (herm2xy_db).

Parameters:

Name Type Description Default
xget float | ndarray

Query x-coordinate in physical or dimensionless units.

required
yget float | ndarray

Query y-coordinate in physical or dimensionless units.

required
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,).

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,).

required
ilinx bool

Whether x is uniformly spaced within 1e-3.

True
iliny bool

Whether y is uniformly spaced within 1e-3.

True

Returns:

Type Description
ndarray

8-tuple (ix, jy, xp, yp, hx, hxi, hy, hyi) of float64/int32

ndarray

JAX scalars.

Raises:

Type Description
ValueError

If x or y fails grid validation, or if concrete (xget, yget) is non-finite or lies outside the grid beyond relative tolerance 4e-7.

interp_evbicub_db

interp_evbicub_db(
    xget,
    yget,
    x,
    y,
    ilinx,
    iliny,
    coeffs,
    *,
    backend="auto",
)

Evaluates 2D bicubic spline value and derivatives (fvbicub_db).

Fully differentiable in float64 via jax.grad and jax.hessian.

Parameters:

Name Type Description Default
xget float | ndarray

Query x-coordinate in physical or dimensionless units.

required
yget float | ndarray

Query y-coordinate in physical or dimensionless units.

required
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,).

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,).

required
ilinx bool

Uniform spacing flag for x.

required
iliny bool

Uniform spacing flag for y.

required
coeffs ndarray | ndarray

Bicubic coefficient array of shape (nx, ny, 4) from :func:flexmesa.interp_2d.bicub.interp_mkbicub_db.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
BicubicEval

class:BicubicEval containing ``(f, df_dx, df_dy, d2f_dx2, d2f_dy2,

BicubicEval

d2f_dxdy)``.

Raises:

Type Description
ValueError

If grid dimensions are < 4, coeffs shape is mismatched, or inputs are non-finite or out of range.

interp_evbicub_mask_db

interp_evbicub_mask_db(
    xget,
    yget,
    x,
    y,
    ilinx,
    iliny,
    coeffs,
    ict,
    *,
    backend="auto",
)

Packs selected bicubic outputs according to 6-element mask ict.

Parameters:

Name Type Description Default
xget float | ndarray

Query x-coordinate.

required
yget float | ndarray

Query y-coordinate.

required
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,).

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,).

required
ilinx bool

Uniform spacing flag for x.

required
iliny bool

Uniform spacing flag for y.

required
coeffs ndarray | ndarray

Bicubic coefficient array of shape (nx, ny, 4).

required
ict Sequence[int | bool]

6-element selector sequence for [f, df_dx, df_dy, d2f_dx2, d2f_dy2, d2f_dxdy].

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray

JAX float64 array of shape (6,) containing requested values

ndarray

packed from index 0.

Raises:

Type Description
ValueError

If ict does not have length 6 or evaluation fails.

flexmesa.interp_2d.akima

Akima (1996, ACM Algorithm 760) rectangular-grid bivariate interpolation.

Implements bivariate bicubic polynomial evaluation (interp_rgbi3p_db) and rectangular surface fitting (interp_rgsf3p_db) from the estimated grid partial derivatives \((z_x, z_y, z_{xy})\) produced by rgpd3p_db.

Reference

Akima, H. (1996), "Algorithm 760: Rectangular-Grid-Data Surface Fitting that Has the Accuracy of a Bicubic Polynomial", ACM Transactions on Mathematical Software, 22(3), 357-361.

interp_rgbi3p_db

interp_rgbi3p_db(xd, yd, zd, xi, yi)

Evaluates Akima (1996) bivariate interpolation at points (xi, yi).

Parameters:

Name Type Description Default
xd ndarray | ndarray

Strictly ascending x-grid of shape (nxd,) (nxd >= 2).

required
yd ndarray | ndarray

Strictly ascending y-grid of shape (nyd,) (nyd >= 2).

required
zd ndarray | ndarray

Grid values of shape (nxd, nyd) or flat (nxd * nyd,).

required
xi ndarray | ndarray

Query x-coordinates of shape (*batch,).

required
yi ndarray | ndarray

Query y-coordinates of shape (*batch,) matching xi.

required

Returns:

Type Description
ndarray

JAX float64 array of shape (*batch,) containing interpolated

ndarray

values.

Raises:

Type Description
ValueError

If grid or query arrays have mismatched shapes, fewer than 2 grid points per axis, non-ascending knot coordinates, or non-finite values.

interp_rgsf3p_db

interp_rgsf3p_db(xd, yd, zd, xi, yi)

Evaluates Akima (1996) surface fitting on target grid (xi, yi).

Parameters:

Name Type Description Default
xd ndarray | ndarray

Strictly ascending x-grid of shape (nxd,) (nxd >= 2).

required
yd ndarray | ndarray

Strictly ascending y-grid of shape (nyd,) (nyd >= 2).

required
zd ndarray | ndarray

Grid values of shape (nxd, nyd) or flat (nxd * nyd,).

required
xi ndarray | ndarray

1D target x-grid of shape (nxi,).

required
yi ndarray | ndarray

1D target y-grid of shape (nyi,).

required

Returns:

Type Description
ndarray

JAX float64 array of shape (nxi, nyi) containing surface values.

Raises:

Type Description
ValueError

If grid or target arrays fail validation or contain non-finite values.

flexmesa.interp_2d.akima_pd

Akima (1996, ACM Algorithm 760) partial-derivative estimation (rgpd3p_db).

Estimates first partial derivatives \((z_x, z_y)\) and cross partial derivative \(z_{xy}\) at every node of a rectangular grid \((x_d, y_d)\) by taking volatility- weighted averages over up to four 4-point 1D stencils along each coordinate and up to sixteen 4x4 2D stencils across the grid.

Reference

Akima, H. (1996), "Algorithm 760: Rectangular-Grid-Data Surface Fitting that Has the Accuracy of a Bicubic Polynomial", ACM Transactions on Mathematical Software, 22(3), 357-361.

rgpd3p_db

rgpd3p_db(xd, yd, zd)

Estimates partial derivatives (z_x, z_y, z_xy) on grid (xd, yd).

Implements Akima (1996) subroutine RGPD3P_db in float64. At each grid point (xd[ix], yd[iy]), evaluates up to four 4-point 1D Lagrange stencils along x and y and up to sixteen 4x4 2D tensor-product stencils to estimate (z_x, z_y, z_xy) without spurious oscillations.

Parameters:

Name Type Description Default
xd ndarray | ndarray

Strictly ascending x-grid of shape (nxd,) (nxd >= 2) in physical or dimensionless units.

required
yd ndarray | ndarray

Strictly ascending y-grid of shape (nyd,) (nyd >= 2) in physical or dimensionless units.

required
zd ndarray | ndarray

Grid values of shape (nxd, nyd) or flat (nxd * nyd,).

required

Returns:

Type Description
ndarray

JAX float64 array of shape (nxd, nyd, 3) containing

ndarray

[zx, zy, zxy] at each grid point.

Raises:

Type Description
ValueError

If nxd < 2, nyd < 2, grids are non-ascending, or zd contains non-finite values.

flexmesa.interp_2d.bipm

Two-dimensional piecewise-monotonic cubic interpolation (bipm_db).

interp_mkbipm_db

interp_mkbipm_db(x, y, z, *, backend='auto')

Constructs 2D piecewise-monotonic cubic spline coefficients along x.

Parameters:

Name Type Description Default
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,) (nx >= 4) in physical or dimensionless units.

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,) (ny >= 4) in physical or dimensionless units.

required
z ndarray | ndarray

Grid values of shape (nx, ny) or flat (nx * ny,) in row-major order.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
ndarray | ndarray

float64 array of shape (nx, ny, 4) containing 1D

ndarray | ndarray

Steffen (1990) x-spline coefficients for each y slice.

Raises:

Type Description
ValueError

If grid dimensions are < 4, non-ascending, or non-finite.

interp_evbipm_db

interp_evbipm_db(
    xget, yget, x, y, coeffs, *, backend="auto"
)

Evaluates the 2D piecewise-monotonic cubic interpolant at (xget, yget).

Performs four 1D cubic evaluations along x on a 4-point y stencil followed by a 4-point 1D interp_pm along y.

Parameters:

Name Type Description Default
xget float | ndarray

Query x-coordinate in [x[0], x[-1]).

required
yget float | ndarray

Query y-coordinate in [y[0], y[-1]).

required
x ndarray | ndarray

Strictly ascending x-grid of shape (nx,) (nx >= 4).

required
y ndarray | ndarray

Strictly ascending y-grid of shape (ny,) (ny >= 4).

required
coeffs ndarray | ndarray

Coefficient array of shape (nx, ny, 4) from :func:interp_mkbipm_db.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
float | ndarray | ndarray

Scalar float64 value containing the interpolated value.

Raises:

Type Description
ValueError

If grid dimensions are < 4, non-ascending, mismatched with coeffs, or if (xget, yget) is non-finite or outside [x[0], x[-1]) x [y[0], y[-1]).

flexmesa.interp_2d.renka790

Scattered 2D cubic Shepard interpolation (ACM TOMS Algorithm 790).

Direct double-precision (float64) port of Robert J. Renka's CSHEP2D package (renka790_db.f in upstream MESA interp_2d/private/renka790_db.f).

Cshep2Interpolant dataclass

Scattered 2D cubic Shepard interpolant (ACM TOMS Algorithm 790).

fit classmethod

fit(x, y, f, nc=17, nw=32, nr=6)

Fit a scattered 2D cubic Shepard interpolant (interp_cshep2_db).

eval

eval(px, py)

Evaluate \(C(px, py)\) (interp_cs2val_db).

eval_grad

eval_grad(px, py)

Evaluate \((C, C_x, C_y)\) (interp_cs2grd_db).

eval_hess

eval_hess(px, py)

Evaluate \((C, C_x, C_y, C_{xx}, C_{xy}, C_{yy})\) (cs2hes_db).

interp_cshep2_db

interp_cshep2_db(x, y, f, nc=17, nw=32, nr=6)

Fit a scattered 2D cubic Shepard interpolant (interp_cshep2_db).

interp_cs2val_db

interp_cs2val_db(interp, px, py)

Evaluate scattered 2D cubic Shepard interpolant (interp_cs2val_db).

interp_cs2grd_db

interp_cs2grd_db(interp, px, py)

Evaluate value and gradient (interp_cs2grd_db).

cs2hes_db

cs2hes_db(interp, px, py)

Evaluate value, gradient, and Hessian (cs2hes_db).

flexmesa.interp_2d.spline1d

One-dimensional C^2 cubic spline helpers (mkspline_db, splinck_db).

Ports the 1D \(C^2\) tridiagonal spline solver (V_SPLINE_db, cspline_db, mkspline_db) and grid uniformity checker (splinck_db) from upstream PSPLINE / MESA interp_2d/private/bicub_db.f into float64 NumPy/JAX.

BicubicBc

Bases: IntEnum

Boundary condition codes for 1D and 2D cubic splines (-1..=7).

Attributes:

Name Type Description
PERIODIC

Periodic boundary condition (-1).

NOT_A_KNOT

Not-a-knot boundary condition (0, MESA default).

FIRST_DERIV

Match specified first derivative (1).

SECOND_DERIV

Match specified second derivative (2).

ZERO_FIRST_DERIV

Zero first derivative (3).

ZERO_SECOND_DERIV

Natural spline / zero second derivative (4).

DIVIDED_DIFF_1

Match first divided difference (5).

DIVIDED_DIFF_2

Match second divided difference (6).

DIVIDED_DIFF_3

Match third divided difference (7).

splinck_db

splinck_db(x, ztol=0.001, axis='x')

Checks strict ascending order and approximate uniform spacing of x.

Parameters:

Name Type Description Default
x ndarray | ndarray

1D coordinate array of shape (N,) in physical or dimensionless units.

required
ztol float

Relative spacing tolerance (default 1e-3).

0.001
axis str

Axis label for error reporting.

'x'

Returns:

Type Description
bool

True (ilinx = 1) if uniformly spaced within ztol, False

bool

(ilinx = 2) otherwise.

Raises:

Type Description
ValueError

If x contains non-finite values or is not strictly ascending.

reshape_grid_2d

reshape_grid_2d(z, nx, ny, name='z')

Validates and reshapes a 2D or flat grid array to (nx, ny).

Parameters:

Name Type Description Default
z ndarray | ndarray

Grid values of shape (nx, ny) or flat (nx * ny,).

required
nx int

Expected x-grid length.

required
ny int

Expected y-grid length.

required
name str

Parameter name for error reporting.

'z'

Returns:

Type Description
ndarray

2D float64 NumPy array of shape (nx, ny).

Raises:

Type Description
ValueError

If z does not have shape (nx, ny) or (nx * ny,) or contains non-finite values.

interp_mkspline_db

interp_mkspline_db(
    x,
    y,
    ibcxmin=BicubicBc.NOT_A_KNOT,
    bcxmin=0.0,
    ibcxmax=BicubicBc.NOT_A_KNOT,
    bcxmax=0.0,
)

Computes second derivatives f''(x_i) of a 1D C^2 cubic spline.

Parameters:

Name Type Description Default
x ndarray | ndarray

Strictly ascending knot coordinates of shape (N,) (N >= 4) in physical or dimensionless units.

required
y ndarray | ndarray

Knot values of shape (N,) in physical or dimensionless units.

required
ibcxmin BicubicBc | int

Left boundary condition code in -1..=7.

NOT_A_KNOT
bcxmin float

Left boundary value (used when ibcxmin in (1, 2)).

0.0
ibcxmax BicubicBc | int

Right boundary condition code in 0..=7.

NOT_A_KNOT
bcxmax float

Right boundary value (used when ibcxmax in (1, 2)).

0.0

Returns:

Type Description
ndarray

Tuple (fxx, uniform) where fxx has shape (N,) (float64)

bool

and uniform indicates even spacing within 1e-3.

Raises:

Type Description
ValueError

If x or y has fewer than 4 points, mismatched shapes, non-ascending knot coordinates, non-finite values, or invalid boundary condition codes.


Dense, Banded & Block-Tridiagonal Linear Solvers (flexmesa.mtx)

Dense LU with partial pivoting, banded Gaussian elimination, sequential block-Thomas (solve_block_tridiagonal), Hirshman et al. (2010) parallel odd-even block cyclic reduction (solve_block_tridiag_bcyclic), native GPU \(\lceil\log_2 N\rceil\) Parallel Cyclic Reduction (solve_block_tridiag_pcr), and @jax.custom_vjp adjoint solvers (solve_block_tridiagonal_jax).

flexmesa.mtx.dense

Dense LU factorization, linear system solvers, and JAX differentiable solve.

Stores dense \(N \times N\) matrices in row-major order (a[i, j], float64). Provides dgetrf (LU factorization with partial pivoting), dgetrs (forward/backward substitution for 1D vectors and 2D multi-RHS matrices), solve_dense, multiply_xa, lu_factored_square_mv, lu_factored_square_mm, rcond_dense, and the JAX-differentiable solve_dense_jax.

dgetrf

dgetrf(a)

Computes the LU factorization \(P A = L U\) with partial pivoting.

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Tuple (lu, ipiv) where lu has shape (N, N) in float64 storing

NDArray[int64]

unit lower-triangular \(L\) strictly below the diagonal and upper

tuple[NDArray[float64], NDArray[int64]]

triangular \(U\) on/above the diagonal, and ipiv has shape (N,) in

tuple[NDArray[float64], NDArray[int64]]

int64 storing 0-based pivot row indices.

Raises:

Type Description
ValueError

If a is not a finite 2D square matrix or is singular.

dgetrs

dgetrs(lu, ipiv, b, *, trans=False)

Solves \(A x = b\) (or \(A^{\top} x = b\)) from [dgetrf] LU factors.

Parameters:

Name Type Description Default
lu ArrayLike

Factored LU matrix of shape (N, N) in float64 (dimensionless).

required
ipiv ArrayLike

0-based pivot array of shape (N,) in int64 (dimensionless).

required
b ArrayLike

Right-hand side vector of shape (N,) or matrix of shape (N, nrhs) in float64 (dimensionless).

required
trans bool

When True, solves the transposed system \(A^{\top} x = b\).

False

Returns:

Type Description
NDArray[float64]

Solution array x of the same shape as b in float64.

Raises:

Type Description
ValueError

If shapes mismatch, inputs are non-finite, or \(U\) is singular.

solve_dense

solve_dense(a, b)

Solves the dense linear system \(A x = b\) in float64.

Parameters:

Name Type Description Default
a ArrayLike

Dense coefficient matrix of shape (N, N) in float64 (dimensionless).

required
b ArrayLike

Right-hand side vector of shape (N,) or matrix (N, nrhs) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Solution array x matching the shape of b in float64.

Raises:

Type Description
ValueError

If a is singular or input dimensions are incompatible.

multiply_xa

multiply_xa(a, x, c=None)

Evaluates \(b = x^{\top} A\) (or \(x^{\top} A + c\)) in float64.

Parameters:

Name Type Description Default
a ArrayLike

Dense matrix of shape (N, N) in float64 (dimensionless).

required
x ArrayLike

Left vector of shape (N,) in float64 (dimensionless).

required
c ArrayLike | None

Optional additive vector of shape (N,) in float64 (dimensionless).

None

Returns:

Type Description
NDArray[float64]

Row-vector product of shape (N,) in float64.

Raises:

Type Description
ValueError

If input dimensions do not match (N, N) and (N,).

lu_factored_square_mv

lu_factored_square_mv(lu, ipiv, x)

Evaluates \(y = A x = P^{-1} L U x\) directly from [dgetrf] factors.

Parameters:

Name Type Description Default
lu ArrayLike

Factored LU matrix of shape (N, N) in float64 (dimensionless).

required
ipiv ArrayLike

0-based pivot indices of shape (N,) in int64 (dimensionless).

required
x ArrayLike

Input vector of shape (N,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Product vector \(y = A x\) of shape (N,) in float64.

Raises:

Type Description
ValueError

If shapes do not match (N, N) and (N,).

lu_factored_square_mm

lu_factored_square_mm(lu, ipiv, b)

Evaluates \(C = A B = P^{-1} L U B\) directly from [dgetrf] factors.

Parameters:

Name Type Description Default
lu ArrayLike

Factored LU matrix of shape (N, N) in float64 (dimensionless).

required
ipiv ArrayLike

0-based pivot indices of shape (N,) in int64 (dimensionless).

required
b ArrayLike

Right-hand matrix of shape (N, M) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Product matrix \(C = A B\) of shape (N, M) in float64.

Raises:

Type Description
ValueError

If dimensions do not match (N, N) and (N, M).

rcond_dense

rcond_dense(a, lu, ipiv)

Estimates the 1-norm reciprocal condition number \(\mathrm{rcond}(A)\).

Parameters:

Name Type Description Default
a ArrayLike

Unfactored matrix of shape (N, N) in float64 (dimensionless).

required
lu ArrayLike

Factored LU matrix of shape (N, N) in float64 (dimensionless).

required
ipiv ArrayLike

0-based pivot indices of shape (N,) in int64 (dimensionless).

required

Returns:

Type Description
float

Reciprocal 1-norm condition number in \([0, 1]\) (dimensionless).

solve_dense_jax

solve_dense_jax(a, b)

Differentiable dense linear solver \(A(p) x(p) = b(p)\) in float64.

Parameters:

Name Type Description Default
a Array

Dense JAX array of shape (N, N) in float64 (dimensionless).

required
b Array

Right-hand side JAX array of shape (N,) or (N, nrhs) in float64 (dimensionless).

required

Returns:

Type Description
Array

Solution JAX array x in float64 supporting jax.grad, jax.jvp,

Array

and jax.vmap via implicit linear-solve differentiation.

flexmesa.mtx.band

Banded matrix storage conversions, LU factorization, and linear solvers.

For an \(N \times N\) banded matrix with \(k_l\) sub-diagonals and \(k_u\) super-diagonals stored in a buffer ab of shape (ldab, n) in float64: - In general band conversions (dense_to_band, band_to_dense) with ldab >= kl + ku + 1, entry \(A_{i,j}\) resides at row = (ldab - 1 - kl) + i - j and column j. - In banded LU factorization (dgbtrf, dgbtrs, solve_banded) with ldab >= 2 * kl + ku + 1, the top kl rows (0..kl) provide workspace for pivot fill-in and the original diagonal resides at row = ldab - 1 - kl.

dense_to_band

dense_to_band(a, ml, mu, ldab=None)

Converts a dense (N, N) matrix a into band storage (ldab, N).

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required
ml int

Number of sub-diagonals \(m_l \ge 0\).

required
mu int

Number of super-diagonals \(m_u \ge 0\).

required
ldab int | None

Leading row dimension of output buffer (>= ml + mu + 1). Defaults to ml + mu + 1.

None

Returns:

Type Description
NDArray[float64]

Banded matrix ab of shape (ldab, N) in float64.

Raises:

Type Description
ValueError

If bandwidths or ldab are invalid for a.

band_to_dense

band_to_dense(ab, ml, mu)

Converts a banded matrix ab of shape (ldab, N) to dense (N, N).

Parameters:

Name Type Description Default
ab ArrayLike

Banded matrix of shape (ldab, N) in float64 (dimensionless).

required
ml int

Number of sub-diagonals \(m_l \ge 0\).

required
mu int

Number of super-diagonals \(m_u \ge 0\).

required

Returns:

Type Description
NDArray[float64]

Dense matrix a of shape (N, N) in float64.

Raises:

Type Description
ValueError

If ab shape or (ml, mu) bandwidths are invalid.

band_multiply_xa

band_multiply_xa(ab, kl, ku, x)

Evaluates \(b = x^{\top} A\) for a compact banded matrix ab.

Matches upstream do_band_multiply_xa where \(A_{i,j}\) resides at ab[ku + i - j, j].

Parameters:

Name Type Description Default
ab ArrayLike

Compact band matrix of shape (ldab, N) (ldab >= kl + ku + 1) in float64 (dimensionless).

required
kl int

Lower bandwidth \(k_l \ge 0\).

required
ku int

Upper bandwidth \(k_u \ge 0\).

required
x ArrayLike

Left vector of shape (N,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Row-vector product \(b = x^{\top} A\) of shape (N,) in float64.

Raises:

Type Description
ValueError

If dimensions do not match (ldab, N) and (N,).

dgbtrf

dgbtrf(ab, kl, ku)

Computes the banded LU factorization \(P A = L U\) (dgbtrf).

Parameters:

Name Type Description Default
ab ArrayLike

Banded matrix of shape (ldab, N) with ldab >= 2 * kl + ku + 1 and diagonal at row = ldab - 1 - kl in float64 (dimensionless).

required
kl int

Lower bandwidth \(k_l \ge 0\).

required
ku int

Upper bandwidth \(k_u \ge 0\).

required

Returns:

Type Description
NDArray[float64]

Tuple (lu_ab, ipiv) where lu_ab has shape (ldab, N) in float64

NDArray[int64]

and ipiv has shape (N,) in int64 storing 0-based pivot indices.

Raises:

Type Description
ValueError

If dimensions are invalid, inputs are non-finite, or a pivot is zero.

dgbtrs

dgbtrs(lu_ab, kl, ku, ipiv, b)

Solves \(A x = b\) using the banded LU factorization from [dgbtrf].

Parameters:

Name Type Description Default
lu_ab ArrayLike

Factored band buffer of shape (ldab, N) in float64 (dimensionless).

required
kl int

Lower bandwidth \(k_l \ge 0\).

required
ku int

Upper bandwidth \(k_u \ge 0\).

required
ipiv ArrayLike

0-based pivot indices of shape (N,) in int64 (dimensionless).

required
b ArrayLike

Right-hand side vector of shape (N,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Solution vector x of shape (N,) in float64.

Raises:

Type Description
ValueError

If shapes mismatch, inputs are non-finite, or \(U\) is singular.

solve_banded

solve_banded(ab, kl, ku, b)

Factors and solves a banded linear system \(A x = b\) in float64.

Parameters:

Name Type Description Default
ab ArrayLike

Banded matrix of shape (ldab, N) (ldab >= 2 * kl + ku + 1) in float64 (dimensionless).

required
kl int

Lower bandwidth \(k_l \ge 0\).

required
ku int

Upper bandwidth \(k_u \ge 0\).

required
b ArrayLike

Right-hand side vector of shape (N,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Solution vector x of shape (N,) in float64.

Raises:

Type Description
ValueError

If shapes mismatch, inputs are non-finite, or \(A\) is singular.

rcond_banded

rcond_banded(ab, lu_ab, kl, ku, ipiv)

Estimates the 1-norm reciprocal condition number of a banded matrix.

Parameters:

Name Type Description Default
ab ArrayLike

Unfactored band buffer (ldab, N) in float64 (dimensionless).

required
lu_ab ArrayLike

Factored band buffer (ldab, N) in float64 (dimensionless).

required
kl int

Lower bandwidth \(k_l \ge 0\).

required
ku int

Upper bandwidth \(k_u \ge 0\).

required
ipiv ArrayLike

0-based pivot indices (N,) in int64 (dimensionless).

required

Returns:

Type Description
float

Reciprocal 1-norm condition number in \([0, 1]\) (dimensionless).

flexmesa.mtx.block_tridiag

Block-tridiagonal matrix-vector products and linear solvers (mtx).

Represents a block-tridiagonal matrix across nz shells and nvar variables per shell via three arrays lblk, dblk, and ublk of shape (nz, nvar, nvar) in float64, where shell k has sub-diagonal block lblk[k] (\(k > 0\)), diagonal block dblk[k], and super-diagonal block ublk[k] (\(k + 1 < n_z\)). Supports Safe Rust sequential Thomas and Hirshman et al. (2010) bcyclic odd-even cyclic reduction via flexmesa._rust, as well as JAX-differentiable solvers (solver_mode="pcr", "scan", or "rust_ffi").

block_dble_mv

block_dble_mv(lblk, dblk, ublk, b)

Evaluates \(y_k = L_k b_{k-1} + D_k b_k + U_k b_{k+1}\) in float64.

Parameters:

Name Type Description Default
lblk ArrayLike

Sub-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
dblk ArrayLike

Diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
ublk ArrayLike

Super-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
b ArrayLike

Input vector of shape (nz, nvar) or (nz * nvar,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Product array matching the shape of b in float64.

Raises:

Type Description
ValueError

If block or vector dimensions do not match.

block_multiply_xa

block_multiply_xa(lblk, dblk, ublk, x, *, backend='auto')

Evaluates upstream do_block_multiply_xa for a block-tridiagonal system.

Upstream documents this as the left product \(b = x^{\top} A\) but pairs the off-diagonal blocks as \(b_k = x_k D_k + x_k U_k + x_{k+1} L_k\) (mtx/private/mtx_support.f90:746-781). That pairing is reproduced here (deferred upstream bug #362).

Parameters:

Name Type Description Default
lblk ArrayLike

Sub-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
dblk ArrayLike

Diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
ublk ArrayLike

Super-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
x ArrayLike

Left vector of shape (nz, nvar) or (nz * nvar,) in float64 (dimensionless).

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
NDArray[float64]

Upstream's product, matching the shape of x.

Raises:

Type Description
ValueError

If block or vector dimensions do not match.

block_thomas_factor

block_thomas_factor(lblk, dblk, ublk)

Factors a block-tridiagonal system via the block Thomas algorithm.

Parameters:

Name Type Description Default
lblk ArrayLike

Sub-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
dblk ArrayLike

Diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
ublk ArrayLike

Super-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Tuple (d_factored, u_factored, ipiv) of shapes (nz, nvar, nvar),

NDArray[float64]

(nz, nvar, nvar), and (nz, nvar).

Raises:

Type Description
ValueError

If any diagonal block is singular or shapes are invalid.

block_thomas_solve

block_thomas_solve(lblk, d_factored, u_factored, ipiv, b)

Solves a block-tridiagonal system from [block_thomas_factor] factors.

Parameters:

Name Type Description Default
lblk ArrayLike

Sub-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
d_factored ArrayLike

Factored diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
u_factored ArrayLike

Factored super-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
ipiv ArrayLike

Pivot array (nz, nvar) in int64 (dimensionless).

required
b ArrayLike

Right-hand side of shape (nz, nvar) or (nz * nvar,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Solution array x matching the shape of b in float64.

Raises:

Type Description
ValueError

If block dimensions mismatch or a diagonal block is singular.

solve_block_tridiagonal

solve_block_tridiagonal(
    lblk,
    dblk,
    ublk,
    b,
    *,
    method="thomas",
    parallel=False,
    backend="auto",
)

Factors and solves a block-tridiagonal linear system \(A x = b\).

Parameters:

Name Type Description Default
lblk ArrayLike

Sub-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
dblk ArrayLike

Diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
ublk ArrayLike

Super-diagonal blocks (nz, nvar, nvar) in float64 (dimensionless).

required
b ArrayLike

Right-hand side (nz, nvar) or (nz * nvar,) in float64 (dimensionless).

required
method Literal['thomas', 'bcyclic']

Solver algorithm ("thomas" sequential block-Thomas or "bcyclic" Hirshman et al. 2010 odd-even cyclic reduction).

'thomas'
parallel bool

When method == "bcyclic", whether to run the reduction levels across the persistent 4-thread rayon pool.

False
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
NDArray[float64]

Solution array x matching the shape of b in float64

NDArray[float64]

(dimensionless).

Raises:

Type Description
ValueError

If block dimensions mismatch, inputs are non-finite, or a diagonal block is singular.

solve_block_tridiagonal_jax

solve_block_tridiagonal_jax(
    lblk, dblk, ublk, b, *, solver_mode="pcr"
)

Differentiable block-tridiagonal linear solver in JAX float64.

Parameters:

Name Type Description Default
lblk Array

Sub-diagonal JAX array (nz, nvar, nvar) in float64 (dimensionless).

required
dblk Array

Diagonal JAX array (nz, nvar, nvar) in float64 (dimensionless).

required
ublk Array

Super-diagonal JAX array (nz, nvar, nvar) in float64 (dimensionless).

required
b Array

Right-hand side JAX array (nz, nvar) in float64 (dimensionless).

required
solver_mode SolverMode

JAX solver strategy ("pcr" vectorized Parallel Cyclic Reduction, "scan" sequential jax.lax.scan block-Thomas, or "rust_ffi" Safe Rust bcyclic with analytical custom_vjp).

'pcr'

Returns:

Type Description
Array

Solution JAX array x of shape (nz, nvar) in float64

Array

(dimensionless), differentiable via jax.grad, jax.jacfwd, and

Array

jax.jacrev.

Raises:

Type Description
ValueError

If solver_mode is not "pcr", "scan", or "rust_ffi".

flexmesa.mtx.pcr

Parallel Cyclic Reduction (PCR) and Rust FFI block-tridiagonal solvers.

Provides two high-throughput, differentiable block-tridiagonal solvers for Tier C coupled stellar structure and burn/mix systems (\(A x = b\) across \(n_z\) shells and \(n_{\mathrm{var}}\) variables per shell):

  1. solve_block_tridiag_pcr (solver_mode="pcr"): Vectorized Hockney & Jesshope (1981) / Hirshman et al. (2010) parallel block cyclic reduction in pure JAX float64. Replaces the \(2 n_z\) sequential jax.lax.scan steps of block-Thomas elimination with \(\lceil \log_2 n_z \rceil\) parallel block-row reduction steps, each performing a single batched (nz, nvar, nvar) solve and two fused matrix-matrix updates across all \(n_z\) zones simultaneously on GPU or CPU.
  2. solve_block_tridiag_rust_ffi (solver_mode="rust_ffi"): Zero-copy host callback to Safe Rust's Hirshman et al. (2010) solve_block_tridiag_bcyclic via jax.pure_callback, paired with an analytical Implicit Function Theorem @jax.custom_vjp rule that solves the transpose block-tridiagonal adjoint system \(A^\top \lambda = \bar{x}\).

validate_jax_blocks

validate_jax_blocks(lblk, dblk, ublk, b)

Coerces (lblk, dblk, ublk, b) to JAX float64 and validates shapes.

Parameters:

Name Type Description Default
lblk Array

Sub-diagonal blocks of shape (nz, nvar, nvar) (dimensionless).

required
dblk Array

Diagonal blocks of shape (nz, nvar, nvar) (dimensionless).

required
ublk Array

Super-diagonal blocks of shape (nz, nvar, nvar) (dimensionless).

required
b Array

Right-hand side of shape (nz, nvar) (dimensionless).

required

Returns:

Type Description
tuple[Array, Array, Array, Array, int, int]

Six-tuple (l64, d64, u64, b64, nz, nvar) in jnp.float64.

Raises:

Type Description
ValueError

If array ranks or dimensions are incompatible.

solve_block_tridiag_pcr

solve_block_tridiag_pcr(lblk, dblk, ublk, b)

Solves a block-tridiagonal system in JAX float64 via \(\log_2\) PCR.

At reduction level \(m \in \{0, \dots, \lceil \log_2 n_z \rceil - 1\}\) with stride \(s = 2^m\), normalizes each block row by \(D_k^{(m)}\) in a single batched (nz, nvar, nvar) solve:

\[\hat{L}_k = \left(D_k^{(m)}\right)^{-1} L_k^{(m)}, \quad \hat{U}_k = \left(D_k^{(m)}\right)^{-1} U_k^{(m)}, \quad \hat{b}_k = \left(D_k^{(m)}\right)^{-1} b_k^{(m)},\]

and eliminates couplings at distance \(\pm s\) across all \(n_z\) shells in parallel via two fused batched matrix-matrix products:

\[D_k^{(m+1)} = D_k^{(m)} - L_k^{(m)} \hat{U}_{k-s} - U_k^{(m)} \hat{L}_{k+s},$$ $$b_k^{(m+1)} = b_k^{(m)} - L_k^{(m)} \hat{b}_{k-s} - U_k^{(m)} \hat{b}_{k+s},$$ $$L_k^{(m+1)} = -L_k^{(m)} \hat{L}_{k-s}, \quad U_k^{(m+1)} = -U_k^{(m)} \hat{U}_{k+s}.\]

After \(P = \lceil \log_2 n_z \rceil\) steps, \(2^P \ge n_z\) so all off-diagonal couplings vanish and \(x_k = (D_k^{(P)})^{-1} b_k^{(P)}\).

Parameters:

Name Type Description Default
lblk Array

Sub-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
dblk Array

Diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
ublk Array

Super-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
b Array

Right-hand side of shape (nz, nvar) in float64 (dimensionless).

required

Returns:

Type Description
Array

Solution array x of shape (nz, nvar) in float64 (dimensionless),

Array

compatible with jax.jit, jax.vmap, jax.grad, jax.jacfwd, and

Array

jax.jacrev.

Raises:

Type Description
ValueError

If input array ranks or dimensions are incompatible.

solve_block_tridiag_rust_ffi

solve_block_tridiag_rust_ffi(lblk, dblk, ublk, b)

Solves \(A x = b\) via Safe Rust bcyclic FFI with analytical IFT VJP.

Executes the forward pass in compiled Safe Rust (flexmesa._rust.solve_block_tridiag_bcyclic) and computes reverse adjoints via the Implicit Function Theorem transpose system \(A^\top \lambda = \bar{x}\):

\[\bar{b}_k = \lambda_k, \quad \bar{D}_k = -\lambda_k x_k^\top, \quad \bar{L}_k = -\lambda_k x_{k-1}^\top, \quad \bar{U}_k = -\lambda_k x_{k+1}^\top.\]

Parameters:

Name Type Description Default
lblk Array

Sub-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
dblk Array

Diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
ublk Array

Super-diagonal blocks of shape (nz, nvar, nvar) in float64 (dimensionless).

required
b Array

Right-hand side of shape (nz, nvar) in float64 (dimensionless).

required

Returns:

Type Description
Array

Solution array x of shape (nz, nvar) in float64 (dimensionless).

flexmesa.mtx.sparse

Sparse matrix format conversions (CSR and CSC, 1-based and 0-based).

Ports upstream mtx_formats.dek and mtx_support.f90, raising explicit ValueError where upstream's 0-based routines read out of bounds (#674).

SparseFormat

Bases: IntEnum

Sparse matrix storage convention matching upstream mtx_def.f90.

dense_to_row_sparse

dense_to_row_sparse(a, *, include_diag=False)

Converts a dense (N, N) matrix into 1-based CSR (rowptr, colind, v).

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required
include_diag bool

Retain zero diagonal entries when True.

False

Returns:

Type Description
NDArray[int64]

Tuple (rowptr, colind, values) with 1-based indices in int64 and

NDArray[int64]

non-zero values in float64.

Raises:

Type Description
ValueError

If a is not a non-empty square 2D array.

dense_to_row_0_based

dense_to_row_0_based(a, *, include_diag=False)

Converts a dense (N, N) matrix into 0-based CSR (rowptr, colind, v).

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required
include_diag bool

Retain zero diagonal entries when True.

False

Returns:

Type Description
NDArray[int64]

Tuple (rowptr, colind, values) with 0-based indices in int64 and

NDArray[int64]

values in float64.

Raises:

Type Description
ValueError

If a is not a non-empty square 2D array.

row_sparse_to_dense

row_sparse_to_dense(n, rowptr, colind, values)

Converts a 1-based CSR matrix into a dense (N, N) float64 array.

Parameters:

Name Type Description Default
n int

Matrix dimension \(N \ge 1\).

required
rowptr ArrayLike

1-based row pointer array of shape (N + 1,) in int64.

required
colind ArrayLike

1-based column index array of shape (nz,) in int64.

required
values ArrayLike

Non-zero values of shape (nz,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Dense matrix of shape (N, N) in float64.

Raises:

Type Description
ValueError

If pointer or index bounds are invalid.

row_sparse_0_based_to_dense

row_sparse_0_based_to_dense(n, rowptr, colind, values)

Converts a 0-based CSR matrix into a dense (N, N) float64 array.

Upstream mtx/private/mtx_support.f90:428-447 reads rowptr(n+1) outside rowptr(0:n) on every call with n >= 1 and indexes values(nz) and a(ndim, n) with 0-based k and colind(k) (deferred upstream bug #674, DECISIONS #43).

Parameters:

Name Type Description Default
n int

Matrix dimension \(N \ge 1\).

required
rowptr ArrayLike

0-based row pointer array of shape (N + 1,) in int64.

required
colind ArrayLike

0-based column index array of shape (nz,) in int64.

required
values ArrayLike

Non-zero values of shape (nz,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Dense matrix of shape (N, N) in float64 (never returns cleanly).

Raises:

Type Description
ValueError

Always raised because upstream reads out of bounds on every call (#674).

dense_to_col_sparse

dense_to_col_sparse(a, *, include_diag=False)

Converts a dense (N, N) matrix into 1-based CSC (colptr, rowind, v).

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required
include_diag bool

Retain zero diagonal entries when True.

False

Returns:

Type Description
tuple[NDArray[int64], NDArray[int64], NDArray[float64]]

Tuple (colptr, rowind, values) with 1-based indices in int64.

Raises:

Type Description
ValueError

If a is not a non-empty square 2D array.

dense_to_col_0_based

dense_to_col_0_based(a, *, include_diag=False)

Converts a dense (N, N) matrix into 0-based CSC (colptr, rowind, v).

Parameters:

Name Type Description Default
a ArrayLike

Dense square matrix of shape (N, N) in float64 (dimensionless).

required
include_diag bool

Retain zero diagonal entries when True.

False

Returns:

Type Description
tuple[NDArray[int64], NDArray[int64], NDArray[float64]]

Tuple (colptr, rowind, values) with 0-based indices in int64.

Raises:

Type Description
ValueError

If a is not a non-empty square 2D array.

column_sparse_to_dense

column_sparse_to_dense(n, colptr, rowind, values)

Converts a 1-based CSC matrix into a dense (N, N) float64 array.

Parameters:

Name Type Description Default
n int

Matrix dimension \(N \ge 1\).

required
colptr ArrayLike

1-based column pointer array of shape (N + 1,) in int64.

required
rowind ArrayLike

1-based row index array of shape (nz,) in int64.

required
values ArrayLike

Non-zero values of shape (nz,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Dense matrix of shape (N, N) in float64.

Raises:

Type Description
ValueError

If pointer or index bounds are invalid.

col_sparse_0_based_to_dense

col_sparse_0_based_to_dense(n, colptr, rowind, values)

Converts a 0-based CSC matrix into a dense (N, N) float64 array.

Parameters:

Name Type Description Default
n int

Matrix dimension \(N \ge 1\).

required
colptr ArrayLike

0-based column pointer array of shape (N + 1,) in int64.

required
rowind ArrayLike

0-based row index array of shape (nz,) in int64.

required
values ArrayLike

Non-zero values of shape (nz,) in float64 (dimensionless).

required

Returns:

Type Description
NDArray[float64]

Dense matrix of shape (N, N) in float64.

Raises:

Type Description
ValueError

If pointer or index bounds are invalid.

find_loc_in_sparse

find_loc_in_sparse(
    sparse_format, n, ia, ja, i, j, hint=None
)

Finds the position of entry (i, j) in a sparse matrix (ia, ja).

Uses 1-based (i, j) and return index for 1-based formats. For COMPRESSED_COL_SPARSE_0_BASED, reproduces upstream's colptr(j) - 1 ..= colptr(j + 1) search range (mtx/public/mtx_formats.dek:261-280) and raises ValueError wherever that search leaves colptr(0:n) or rowind(0:nz-1) (#674, DECISIONS #43).

Parameters:

Name Type Description Default
sparse_format SparseFormat

Storage convention from [SparseFormat].

required
n int

Matrix dimension \(N \ge 1\).

required
ia ArrayLike

Outer pointer array of shape (N + 1,) in int64.

required
ja ArrayLike

Inner index array of shape (nz,) in int64.

required
i int

Row index (1-based or 0-based matching sparse_format).

required
j int

Column index (1-based or 0-based matching sparse_format).

required
hint int | None

Optional previous location hint in the same index base.

None

Returns:

Type Description
int | None

Index into values (in the format's index base) if present, else

int | None

None.

Raises:

Type Description
ValueError

If ia is too short, indices or pointer bounds are invalid, or COMPRESSED_COL_SPARSE_0_BASED reaches an upstream out-of-bounds read (#674).


Nonlinear Root Finders, Quadrature & Stiff ODE Integrators (flexmesa.num)

Brent's method (safe_root_with_brackets), 1D/multi-D Newton-Raphson, adaptive Simpson quadrature, explicit Runge-Kutta (rk4, dopri5), and L-stable stiff Rosenbrock (rodas4, ros3p) integrators.

flexmesa.num.brent

Brent (1973) root-finding and univariate local/global minimization (num).

Ports num/private/mod_brent.f90 (eval_brent_safe_zero, eval_brent_local_min, and eval_brent_global_min) into float64 Python.

brent_safe_zero

brent_safe_zero(
    a,
    b,
    eps,
    t,
    epsy,
    func,
    df_a=None,
    df_b=None,
    max_iter=200,
)

Finds a root \(x \in [a, b]\) of \(f(x) = 0\) via Brent's (1973) method.

Combines bisection, linear secant interpolation, and inverse quadratic interpolation so that the bracket contracts superlinearly on smooth functions while never converging slower than bisection.

Parameters:

Name Type Description Default
a float

Lower or first bracket endpoint.

required
b float

Upper or second bracket endpoint.

required
eps float

Relative abscissa tolerance (\(\ge 0\)).

required
t float

Absolute abscissa tolerance (\(\ge 0\)).

required
epsy float

Residual stopping tolerance on \(|f(x)|\).

required
func Callable[[float], float]

Scalar callable func(x) returning \(f(x)\) in float64.

required
df_a float | None

Optional pre-evaluated \(f(a)\).

None
df_b float | None

Optional pre-evaluated \(f(b)\).

None
max_iter int

Maximum Brent iterations allowed.

200

Returns:

Type Description
tuple[float, float]

Tuple (root_x, f_at_root) in float64.

Raises:

Type Description
ValueError

If \(f(a)\) and \(f(b)\) have the same strict sign.

RuntimeError

If max_iter is exceeded.

eval_brent_safe_zero

eval_brent_safe_zero(
    a, b, machep, t, epsy, func, fa_in, fb_in
)

Finds a root of \(f(x) = 0\) matching upstream eval_brent_safe_zero.

Ports num/private/mod_brent.f90:513-705 directly: unbounded loop (no iteration cap), no finiteness guards, and no opposite-sign check on fa_in and fb_in. Keeps upstream's a in place of q at mod_brent.f90:653 (#194).

Parameters:

Name Type Description Default
a float

First bracket endpoint (arbitrary units).

required
b float

Second bracket endpoint (arbitrary units).

required
machep float

Relative abscissa tolerance factor.

required
t float

Absolute abscissa convergence tolerance.

required
epsy float

Residual stopping tolerance on |f(x)|.

required
func Callable[[float], float]

Scalar callable func(x) returning f(x).

required
fa_in float

Caller-supplied value f(a).

required
fb_in float

Caller-supplied value f(b).

required

Returns:

Type Description
tuple[float, float]

Tuple (sb, fb) in float64.

brent_local_min

brent_local_min(max_tries, a, b, eps, t, func)

Finds a local minimum \((x_{\min}, f(x_{\min}))\) of \(f\) on \([a, b]\).

Combines golden-section search with successive parabolic interpolation (eval_brent_local_min in mod_brent.f90).

Parameters:

Name Type Description Default
max_tries int

Maximum function evaluations allowed.

required
a float

Lower search bound (\(a < b\)).

required
b float

Upper search bound (\(b > a\)).

required
eps float

Relative abscissa tolerance (\(> 0\)).

required
t float

Absolute abscissa tolerance (\(\ge 0\)).

required
func Callable[[float], float]

Objective callable func(x) returning \(f(x)\) in float64.

required

Returns:

Type Description
tuple[float, float]

Tuple (x_min, f_min) in float64.

Raises:

Type Description
ValueError

If \(a \ge b\), \(\epsilon \le 0\), or \(t < 0\).

local_min

local_min(max_tries, a, b, eps, t, func)

Alias for :func:brent_local_min matching upstream local_min.

Parameters:

Name Type Description Default
max_tries int

Maximum function evaluations allowed.

required
a float

Lower search bound (\(a < b\)).

required
b float

Upper search bound (\(b > a\)).

required
eps float

Relative abscissa tolerance (\(> 0\)).

required
t float

Absolute abscissa tolerance (\(\ge 0\)).

required
func Callable[[float], float]

Objective callable func(x) returning \(f(x)\) in float64.

required

Returns:

Type Description
tuple[float, float]

Tuple (x_min, f_min) in float64.

brent_global_min

brent_global_min(max_tries, a, b, c, m, e, t, func)

Seeks the global minimum \((x_{\min}, f(x_{\min}))\) of \(f\) on \([a, b]\).

Implements Brent's (1973) global minimization algorithm (eval_global_min / glomin in mod_brent.f90) using parabolic under-estimators with second-derivative bound \(m\).

Parameters:

Name Type Description Default
max_tries int

Maximum outer interval-advance iterations.

required
a float

Lower search bound (\(a < b\)).

required
b float

Upper search bound (\(b > a\)).

required
c float

Initial candidate abscissa in \([a, b]\).

required
m float

Upper bound on \(f''(x)\) on \([a, b]\).

required
e float

Positive bound on absolute evaluation error in \(f(x)\).

required
t float

Positive absolute abscissa tolerance.

required
func Callable[[float], float]

Objective callable func(x) returning \(f(x)\) in float64.

required

Returns:

Type Description
tuple[float, float]

Tuple (x_min, f_min) in float64.

Raises:

Type Description
ValueError

If \(a \ge b\) or inputs/outputs are non-finite.

glomin

glomin(max_tries, a, b, c, m, e, t, func)

Alias for :func:brent_global_min matching Burkardt/MESA glomin.

Parameters:

Name Type Description Default
max_tries int

Maximum outer interval-advance iterations.

required
a float

Lower search bound (\(a < b\)).

required
b float

Upper search bound (\(b > a\)).

required
c float

Initial candidate abscissa in \([a, b]\).

required
m float

Upper bound on \(f''(x)\) on \([a, b]\).

required
e float

Positive bound on absolute evaluation error in \(f(x)\).

required
t float

Positive absolute abscissa tolerance.

required
func Callable[[float], float]

Objective callable func(x) returning \(f(x)\) in float64.

required

Returns:

Type Description
tuple[float, float]

Tuple (x_min, f_min) in float64.

flexmesa.num.root

Bracketed and derivative-assisted root-finding with JAX implicit VJP.

Ports num/private/mod_root.f90 (do_look_for_brackets, do_safe_root_with_brackets, do_safe_root_with_guess) into float64 Python and provides :func:safe_root_jax with a custom JAX vector-Jacobian product (@jax.custom_vjp) via the implicit function theorem: $\(\frac{\partial x^*}{\partial p} = -\left(\frac{\partial f}{\partial x}(x^*, p)\right)^{-1} \frac{\partial f}{\partial p}(x^*, p).\)$

look_for_brackets

look_for_brackets(x, dx, func, imax=50)

Brackets a root outward from x matching do_look_for_brackets.

Mirrors num/private/mod_root.f90:168-256: starts from x1 = x3 = x and widens by jump = 2**i * dx for i = 1..imax (moving both ends at i = 1 and then whichever endpoint value is closer to zero) until y1 * y3 <= 0. No bounds, no finiteness checks, and signed dx.

Parameters:

Name Type Description Default
x float

Initial center point (arbitrary units).

required
dx float

Initial step increment (used with its sign).

required
func Callable[[float], tuple[float, float]]

Callable returning (f(x), df_dx(x)).

required
imax int

Maximum outward expansion steps.

50

Returns:

Type Description
tuple[tuple[float, float], tuple[float, float]]

Nested tuple ((x1, x3), (y1, y3)) bracketing a root.

Raises:

Type Description
ValueError

If i >= 31 where upstream's 32-bit integer 2**i overflows (num/private/mod_root.f90:199, #669), or if no bracket is found within imax steps.

safe_root_with_brackets

safe_root_with_brackets(
    func,
    x1_in,
    x3_in,
    y1_in,
    y3_in,
    imax=100,
    epsx=1e-12,
    epsy=1e-12,
)

Finds a root via eval_brent_safe_zero (mod_root.f90:27-45).

Parameters:

Name Type Description Default
func Callable[[float], tuple[float, float]]

Callable returning (f(x), df_dx(x)).

required
x1_in float

First bracket endpoint.

required
x3_in float

Second bracket endpoint.

required
y1_in float

Function value f(x1_in).

required
y3_in float

Function value f(x3_in).

required
imax int

Ignored, matching do_safe_root_with_brackets (num/private/mod_root.f90:42-43).

100
epsx float

Abscissa convergence tolerance.

1e-12
epsy float

Residual convergence tolerance on |f(x)|.

1e-12

Returns:

Type Description
tuple[float, float]

Tuple (root_x, f_at_root) in float64.

safe_root_with_guess

safe_root_with_guess(
    func,
    x_guess,
    dx,
    x1_opt=None,
    x3_opt=None,
    y1_opt=None,
    y3_opt=None,
    newt_imax=10,
    imax=100,
    epsx=1e-12,
    epsy=1e-12,
)

Finds a root from x_guess matching do_safe_root_with_guess.

Mirrors num/private/mod_root.f90:47-164: runs up to newt_imax unbounded Newton steps from x_guess, stopping only on abs(y) < max(epsy, abs(dydx) * epsx) (:102), exiting Newton on ValueError, dydx == 0, or increasing abs(y) (:89-108), then falling back to :func:look_for_brackets and delegating to :func:safe_root_with_brackets.

Parameters:

Name Type Description Default
func Callable[[float], tuple[float, float]]

Callable returning (f(x), df_dx(x)).

required
x_guess float

Initial root estimate.

required
dx float

Outward bracket search step if Newton steps do not bracket.

required
x1_opt float | None

Optional first bracket abscissa.

None
x3_opt float | None

Optional second bracket abscissa.

None
y1_opt float | None

Optional function value at x1_opt.

None
y3_opt float | None

Optional function value at x3_opt.

None
newt_imax int

Maximum pure Newton steps before bracketing.

10
imax int

Bracketing step budget passed to :func:look_for_brackets.

100
epsx float

Abscissa tolerance.

1e-12
epsy float

Residual tolerance.

1e-12

Returns:

Type Description
tuple[float, float]

Tuple (root_x, f_at_root) in float64.

Raises:

Type Description
ValueError

Propagated from func outside the Newton loop or from :func:look_for_brackets.

safe_root_without_brackets

safe_root_without_brackets(
    func,
    x_guess,
    dx,
    newt_imax=10,
    imax=100,
    epsx=1e-12,
    epsy=1e-12,
)

Finds a root from x_guess matching safe_root_without_brackets.

Mirrors num/public/num_safe_root.dek:120-144: calls :func:safe_root_with_guess with no initial brackets and newt_imax = min(imax, newt_imax) (:143).

Parameters:

Name Type Description Default
func Callable[[float], tuple[float, float]]

Callable returning (f(x), df_dx(x)).

required
x_guess float

Initial root estimate.

required
dx float

Outward bracket search step.

required
newt_imax int

Maximum pure Newton steps before bracketing.

10
imax int

Bracketing step budget (also caps newt_imax).

100
epsx float

Abscissa tolerance.

1e-12
epsy float

Residual tolerance.

1e-12

Returns:

Type Description
tuple[float, float]

Tuple (root_x, f_at_root) in float64.

Raises:

Type Description
ValueError

Propagated from :func:safe_root_with_guess.

safe_root_jax

safe_root_jax(
    f_scalar,
    x1,
    x3,
    params,
    imax=100,
    epsx=1e-13,
    epsy=1e-13,
)

Solves \(f(x^*(p), p) = 0\) on \([x_1, x_3]\) with implicit JAX VJP.

Uses safeguarded Brent root-finding (brent_safe_zero) for the primal solve and propagates reverse-mode cotangents via the implicit function theorem: $\(\frac{\partial x^*}{\partial p} = -\left(\frac{\partial f}{\partial x}(x^*, p)\right)^{-1} \frac{\partial f}{\partial p}(x^*, p).\)$

Parameters:

Name Type Description Default
f_scalar Callable[[Array, Array], Array]

Differentiable JAX callable f_scalar(x, params) returning a scalar float64 residual.

required
x1 float

Lower bracket endpoint.

required
x3 float

Upper bracket endpoint.

required
params Array

1D JAX parameter array of shape (K,) in float64.

required
imax int

Maximum root-finding iterations.

100
epsx float

Abscissa tolerance.

1e-13
epsy float

Residual tolerance.

1e-13

Returns:

Type Description
Array

Scalar float64 JAX array \(x^*(p)\) supporting jax.grad.

flexmesa.num.newton

Damped Newton-Raphson solver for dense, banded, and block-tridiagonal grids.

Ports MESA's Newton-Raphson iteration (num/private/mod_newton.f90 and num/test/src/test_newton.f90) with line-search damping across dense, banded, and block-tridiagonal Jacobians (:mod:flexmesa.mtx), plus a JAX-differentiable implicit Newton solver (:func:newton_solve_jax) using @jax.custom_vjp.

NewtonConfig dataclass

Configuration for damped Newton-Raphson solvers.

Attributes:

Name Type Description
max_iter int

Maximum Newton iterations allowed.

tol_correction_norm float

Maximum RMS correction norm.

tol_max_correction float

Maximum supremum correction norm.

tol_residual_norm float

Maximum RMS residual norm.

min_damping float

Minimum line-search damping factor.

NewtonResult dataclass

Convergence diagnostics returned by Newton-Raphson solvers.

Attributes:

Name Type Description
y NDArray[float64]

Converged state vector of shape (n,) in float64.

iterations int

Number of Newton iterations completed.

residual_norm float

Final RMS residual norm.

correction_norm float

Final RMS correction norm.

newton_solve_dense

newton_solve_dense(y_init, eval_res, eval_jac, config=None)

Solves \(F(y) = 0\) with dense \((N, N)\) Jacobian via damped Newton-Raphson.

Parameters:

Name Type Description Default
y_init ArrayLike

Initial state vector of shape (n,).

required
eval_res Callable[[NDArray[float64]], ArrayLike]

Residual callable eval_res(y) returning shape (n,).

required
eval_jac Callable[[NDArray[float64]], ArrayLike]

Jacobian callable eval_jac(y) returning shape (n, n).

required
config NewtonConfig | None

Optional :class:NewtonConfig settings.

None

Returns:

Type Description
NewtonResult

class:NewtonResult with converged state and norm diagnostics.

Raises:

Type Description
ValueError

If inputs, residuals, or Jacobians are invalid or singular.

RuntimeError

If config.max_iter is exceeded.

newton_solve_banded

newton_solve_banded(
    kl, ku, y_init, eval_res, eval_jac_band, config=None
)

Solves \(F(y) = 0\) with banded Jacobian (2*kl + ku + 1, n).

Parameters:

Name Type Description Default
kl int

Number of sub-diagonals (\(k_l \ge 0\)).

required
ku int

Number of super-diagonals (\(k_u \ge 0\)).

required
y_init ArrayLike

Initial state vector of shape (n,).

required
eval_res Callable[[NDArray[float64]], ArrayLike]

Residual callable eval_res(y) returning shape (n,).

required
eval_jac_band Callable[[NDArray[float64]], ArrayLike]

Banded Jacobian callable returning (ldab, n).

required
config NewtonConfig | None

Optional :class:NewtonConfig settings.

None

Returns:

Type Description
NewtonResult

class:NewtonResult with converged state and norm diagnostics.

Raises:

Type Description
ValueError

If inputs, residuals, or Jacobians are invalid or singular.

RuntimeError

If config.max_iter is exceeded.

newton_solve_block_tridiagonal

newton_solve_block_tridiagonal(
    nvar, nz, y_init, eval_res, eval_blocks, config=None
)

Solves \(F(y) = 0\) across nz shells and nvar variables per shell.

Parameters:

Name Type Description Default
nvar int

Variables per shell (\(n_{\mathrm{var}} \ge 1\)).

required
nz int

Number of shells (\(n_z \ge 1\)).

required
y_init ArrayLike

Initial state vector of shape (nz * nvar,) or (nz, nvar).

required
eval_res Callable[[NDArray[float64]], ArrayLike]

Residual callable returning shape (nz * nvar,).

required
eval_blocks Callable[[NDArray[float64]], tuple[ArrayLike, ArrayLike, ArrayLike]]

Callable returning (lblk, dblk, ublk) each of shape (nz, nvar, nvar).

required
config NewtonConfig | None

Optional :class:NewtonConfig settings.

None

Returns:

Type Description
NewtonResult

class:NewtonResult with converged state and norm diagnostics.

Raises:

Type Description
ValueError

If inputs, residuals, or blocks are invalid or singular.

RuntimeError

If config.max_iter is exceeded.

newton_solve_jax

newton_solve_jax(
    res_fn, y_init, params, max_iter=30, tol=1e-12
)

Solves \(F(y^*(p), p) = 0\) in JAX float64 with implicit VJP.

Uses Newton-Raphson with jax.jacfwd for the primal solve and propagates reverse-mode cotangents via the implicit function theorem: $\(J_y^\top v = g, \qquad \bar{p} = -J_p^\top v,\)$ with \(J_y = \partial F / \partial y\) and \(J_p = \partial F / \partial p\) evaluated at \((y^*, p)\).

Parameters:

Name Type Description Default
res_fn Callable[[Array, Array], Array]

Differentiable JAX callable res_fn(y, params) returning residual of shape (n,) in float64.

required
y_init Array

Initial guess of shape (n,) in float64.

required
params Array

Parameter vector of shape (k,) in float64.

required
max_iter int

Maximum Newton iterations.

30
tol float

Residual norm stopping tolerance.

1e-12

Returns:

Type Description
Array

Converged state y_star of shape (n,) supporting jax.grad

Array

and jax.jacrev.

Raises:

Type Description
ValueError

If the residual norm becomes non-finite.

flexmesa.num.quadrature

Ridders differentiation and adaptive Simpson 3/8 quadrature (num).

Ports num/private/mod_num_lib.f90 numerical differentiation (dfridr) and adaptive recursive Simpson 3/8 quadrature with Richardson extrapolation (integrate) into float64 Python.

dfridr

dfridr(hx, func)

Estimates f'(0) and its error via Ridders polynomial extrapolation.

Evaluates symmetric finite-difference quotients at geometrically decreasing step sizes \(h_i = h_0 / 1.4^i\) (\(0 \le i < 10\)) and builds a Neville extrapolation tableau to eliminate leading truncation error orders.

Parameters:

Name Type Description Default
hx float

Initial non-zero step size (same units as the argument of func).

required
func Callable[[float], float]

Scalar callable func(dx) evaluated at symmetric offsets.

required

Returns:

Type Description
tuple[float, float]

Tuple (derivative, error_estimate) in float64.

Raises:

Type Description
ValueError

If hx == 0.0 or hx is non-finite.

integrate

integrate(func, min_x, max_x, eps=1e-08, max_steps=20000)

Evaluates definite integral via adaptive Simpson 3/8 quadrature.

Subdivides \([\min_x, \max_x]\) into three equal subintervals per recursion level and applies a 4th-order Richardson correction \((S_f - S_c) / 15\) once \(|S_f - S_c| \le \epsilon\).

Parameters:

Name Type Description Default
func Callable[[float], float]

Scalar integrand callable func(x).

required
min_x float

Lower integration limit.

required
max_x float

Upper integration limit.

required
eps float

Local truncation error tolerance (> 0).

1e-08
max_steps int

Maximum integrand evaluations allowed.

20000

Returns:

Type Description
tuple[float, int]

Tuple (integral_value, num_evaluations).

Raises:

Type Description
ValueError

If limits are non-finite or eps <= 0.

RuntimeError

If max_steps is exceeded.

flexmesa.num.rk

Explicit Runge-Kutta (rk2, rk4, dopri5, dop853) integrators.

Ports Hairer & Wanner's Dormand-Prince 5(4) (num/private/mod_dopri5.f) with Shampine 4th-order dense output (contd5) and high-order adaptive Runge-Kutta integration into float64 NumPy/Python.

DopriResult dataclass

Result of an adaptive Dormand-Prince integration.

Attributes:

Name Type Description
y NDArray[float64]

Final state vector of shape (n,) in float64.

nfcn int

Total right-hand side evaluations performed.

nstep int

Total integration steps attempted.

naccpt int

Number of accepted steps.

nrejct int

Number of rejected steps.

history list[tuple[float, float, NDArray[float64]]]

List of (x_old, h, rcont) tuples per accepted step, where rcont has shape (5, n) in float64.

dense_eval

dense_eval(x_query)

Evaluates Shampine's 4th-order dense polynomial at x_query.

Parameters:

Name Type Description Default
x_query float

Target abscissa inside the integration span.

required

Returns:

Type Description
NDArray[float64]

Interpolated state vector of shape (n,) in float64.

rk2

rk2(t, y, h, derivs)

Performs a single midpoint 2nd-order Runge-Kutta step \(y(t + h)\).

Parameters:

Name Type Description Default
t float

Current independent variable value.

required
y ArrayLike

State vector of shape (n,) in float64.

required
h float

Step size.

required
derivs Callable[[float, NDArray[float64]], ArrayLike]

Callable derivs(t, y) returning \(f(t, y)\) of shape (n,).

required

Returns:

Type Description
NDArray[float64]

Updated state array of shape (n,) in float64.

rk4

rk4(t, y, h, derivs)

Performs a single classical 4th-order Runge-Kutta step \(y(t + h)\).

Parameters:

Name Type Description Default
t float

Current independent variable value.

required
y ArrayLike

State vector of shape (n,) in float64.

required
h float

Step size.

required
derivs Callable[[float, NDArray[float64]], ArrayLike]

Callable derivs(t, y) returning \(f(t, y)\) of shape (n,).

required

Returns:

Type Description
NDArray[float64]

Updated state array of shape (n,) in float64.

dopri5

dopri5(
    x0,
    x_end,
    y0,
    fcn,
    h0=0.0,
    hmax=0.0,
    rtol=1e-08,
    atol=1e-08,
    max_steps=100000,
)

Integrates \(y'(x) = f(x, y)\) via adaptive Dormand-Prince 5(4).

Parameters:

Name Type Description Default
x0 float

Initial independent variable value.

required
x_end float

Final independent variable value.

required
y0 ArrayLike

Initial state vector of shape (n,).

required
fcn Callable[[float, NDArray[float64]], ArrayLike]

Right-hand side callable fcn(x, y) returning shape (n,).

required
h0 float

Initial trial step size (0.0 selects 1e-4).

0.0
hmax float

Maximum step size magnitude (0.0 uses |x_end - x0|).

0.0
rtol float

Relative local error tolerance (> 0).

1e-08
atol float

Absolute local error tolerance (> 0).

1e-08
max_steps int

Maximum integration steps allowed.

100000

Returns:

Type Description
DopriResult

class:DopriResult with final state and dense-output history.

Raises:

Type Description
ValueError

If y0 is empty or rtol, atol <= 0.

RuntimeError

If max_steps is exceeded.

dop853

dop853(
    x0,
    x_end,
    y0,
    fcn,
    h0=0.0,
    hmax=0.0,
    rtol=1e-10,
    atol=1e-10,
    max_steps=100000,
)

High-precision adaptive Dormand-Prince integrator (dop853 API).

Parameters:

Name Type Description Default
x0 float

Initial independent variable value.

required
x_end float

Final independent variable value.

required
y0 ArrayLike

Initial state vector of shape (n,).

required
fcn Callable[[float, NDArray[float64]], ArrayLike]

Right-hand side callable fcn(x, y) returning shape (n,).

required
h0 float

Initial trial step size.

0.0
hmax float

Maximum step size magnitude.

0.0
rtol float

Relative local error tolerance (> 0).

1e-10
atol float

Absolute local error tolerance (> 0).

1e-10
max_steps int

Maximum integration steps allowed.

100000

Returns:

Type Description
DopriResult

class:DopriResult with final state and dense-output history.

Raises:

Type Description
ValueError

If y0 is empty, tolerances are non-positive, or local errors become non-finite.

RuntimeError

If max_steps is exceeded or step size underflows.

flexmesa.num.rosenbrock

L-stable Rosenbrock-Wanner stiff ODE/DAE integrators (num).

Ports Hairer & Wanner's Rosenbrock family (num/private/mod_rosenbrock.f) supporting all 7 MESA Rosenbrock variants (Ros2, Rose2, Ros3p, Ros3pl, Rodas3, Rodas4, Rodasp) with dense and banded Jacobians solved via :mod:flexmesa.mtx.

RosenbrockVariant

Bases: Enum

Rosenbrock-Wanner solver variants matching num_def.f90.

RosenbrockResult dataclass

Summary of an adaptive Rosenbrock integration.

Attributes:

Name Type Description
y NDArray[float64]

Final state vector of shape (n,) in float64.

nfcn int

Total right-hand side evaluations performed.

njac int

Total Jacobian evaluations performed.

naccpt int

Number of accepted steps.

nrejct int

Number of rejected steps.

rosenbrock_dense

rosenbrock_dense(
    variant,
    t0,
    t_end,
    y0,
    fcn,
    jac,
    h0=0.0,
    hmax=0.0,
    rtol=1e-06,
    atol=1e-08,
    max_steps=100000,
)

Integrates a stiff ODE system \(y' = f(t, y)\) with dense Jacobian.

Parameters:

Name Type Description Default
variant RosenbrockVariant

Selected :class:RosenbrockVariant.

required
t0 float

Initial time (dimensionless).

required
t_end float

Final time (dimensionless).

required
y0 ArrayLike

Initial state vector of shape (n,) (arbitrary units).

required
fcn Callable[[float, NDArray[float64]], ArrayLike]

Right-hand side callable fcn(t, y) returning shape (n,).

required
jac Callable[[float, NDArray[float64]], ArrayLike]

Jacobian callable jac(t, y) returning shape (n, n).

required
h0 float

Initial step size (dimensionless).

0.0
hmax float

Maximum step size (dimensionless).

0.0
rtol float

Relative tolerance (dimensionless).

1e-06
atol float

Absolute tolerance (arbitrary units).

1e-08
max_steps int

Maximum number of steps.

100000

Returns:

Type Description
RosenbrockResult

class:RosenbrockResult with final state and counters.

Raises:

Type Description
ValueError

If tolerances are invalid, stage matrices are singular, or local errors are non-finite.

RuntimeError

If max_steps is exceeded or step size underflows.

rosenbrock_banded

rosenbrock_banded(
    variant,
    ml,
    mu,
    t0,
    t_end,
    y0,
    fcn,
    jac_dense,
    h0=0.0,
    hmax=0.0,
    rtol=1e-06,
    atol=1e-08,
    max_steps=100000,
)

Integrates a stiff ODE system \(y' = f(t, y)\) with banded Jacobian.

Parameters:

Name Type Description Default
variant RosenbrockVariant

Selected :class:RosenbrockVariant.

required
ml int

Number of sub-diagonals (\(m_l \ge 0\)).

required
mu int

Number of super-diagonals (\(m_u \ge 0\)).

required
t0 float

Initial time (dimensionless).

required
t_end float

Final time (dimensionless).

required
y0 ArrayLike

Initial state vector of shape (n,) (arbitrary units).

required
fcn Callable[[float, NDArray[float64]], ArrayLike]

Right-hand side callable fcn(t, y) returning shape (n,).

required
jac_dense Callable[[float, NDArray[float64]], ArrayLike]

Jacobian callable jac_dense(t, y) returning (n, n).

required
h0 float

Initial step size (dimensionless).

0.0
hmax float

Maximum step size (dimensionless).

0.0
rtol float

Relative tolerance (dimensionless).

1e-06
atol float

Absolute tolerance (arbitrary units).

1e-08
max_steps int

Maximum number of steps.

100000

Returns:

Type Description
RosenbrockResult

class:RosenbrockResult with final state and counters.

Raises:

Type Description
ValueError

If tolerances or bandwidths are invalid, stage matrices are singular, or local errors are non-finite.

RuntimeError

If max_steps is exceeded or step size underflows.

rosenbrock_dae_diag

rosenbrock_dae_diag(
    variant,
    mass_diag,
    t0,
    t_end,
    y0,
    fcn,
    jac,
    h0=0.0,
    hmax=0.0,
    rtol=1e-06,
    atol=1e-08,
    max_steps=100000,
)

Integrates a stiff index-1 DAE \(M y' = f(t, y)\) with diagonal \(M\).

Parameters:

Name Type Description Default
variant RosenbrockVariant

Selected :class:RosenbrockVariant.

required
mass_diag ArrayLike

Diagonal mass matrix entries of shape (n,).

required
t0 float

Initial time (dimensionless).

required
t_end float

Final time (dimensionless).

required
y0 ArrayLike

Initial state vector of shape (n,) (arbitrary units).

required
fcn Callable[[float, NDArray[float64]], ArrayLike]

Right-hand side callable fcn(t, y) returning shape (n,).

required
jac Callable[[float, NDArray[float64]], ArrayLike]

Jacobian callable jac(t, y) returning shape (n, n).

required
h0 float

Initial step size (dimensionless).

0.0
hmax float

Maximum step size (dimensionless).

0.0
rtol float

Relative tolerance (dimensionless).

1e-06
atol float

Absolute tolerance (arbitrary units).

1e-08
max_steps int

Maximum number of steps.

100000

Returns:

Type Description
RosenbrockResult

class:RosenbrockResult with final state and counters.

flexmesa.num.search

Compensated summation, binary search, and quadratic interpolation (num).

Ports utility solvers from upstream MESA num/public/num_lib.f90 into float64 NumPy/Python, including Knuth two_sum, Neumaier compensated summation, monotonic binary_search, permutation index sorting qsort_index, find0, find0_quadratic, and find_max_quadratic.

two_sum

two_sum(a, b)

Computes the exact Knuth 2Sum transformation (sum, error).

Parameters:

Name Type Description Default
a float

First scalar summand (dimensionless).

required
b float

Second scalar summand (dimensionless).

required

Returns:

Type Description
tuple[float, float]

Tuple (s, e) such that s + e == a + b in exact real arithmetic.

neumaier_sum

neumaier_sum(values)

Evaluates the Neumaier compensated sum of a 1D array in float64.

Parameters:

Name Type Description Default
values ArrayLike

1D sequence of shape (N,) (dimensionless).

required

Returns:

Type Description
float

Compensated scalar sum in float64.

binary_search(vec, val, hint=None)

Locates the 0-based interval index k in a monotonic array vec.

For increasing vec, returns None if val < vec[0], n - 1 if val >= vec[n - 1], or k such that vec[k] <= val < vec[k + 1]. For decreasing vec, returns None if val > vec[0], n - 1 if val <= vec[n - 1], or k such that vec[k] >= val > vec[k + 1].

Parameters:

Name Type Description Default
vec ArrayLike

1D monotonic knot vector of shape (n,).

required
val float

Query value (same physical units as vec).

required
hint int | None

Optional 0-based interval guess probed in \(O(1)\) time before falling back to bisection.

None

Returns:

Type Description
int | None

0-based interval index k or None if out of bounds at the start.

binary_search_1based

binary_search_1based(vec, val, hint=0)

1-based wrapper around :func:binary_search matching upstream Fortran.

Parameters:

Name Type Description Default
vec ArrayLike

1D monotonic knot vector of shape (n,).

required
val float

Query value (same physical units as vec).

required
hint int

1-based interval hint (0 indicates no hint).

0

Returns:

Type Description
int

1-based index in 0..=n.

qsort_index

qsort_index(vals)

Returns 0-based permutation indices sorting vals ascending.

Parameters:

Name Type Description Default
vals ArrayLike

1D array of shape (n,) (dimensionless).

required

Returns:

Type Description
NDArray[intp]

Integer index array idx of shape (n,) such that vals[idx]

NDArray[intp]

is non-decreasing.

linear_interp

linear_interp(x1, y1, x2, y2, x)

Evaluates linear interpolation between (x1, y1) and (x2, y2).

Parameters:

Name Type Description Default
x1 float

First abscissa.

required
y1 float

First ordinate.

required
x2 float

Second abscissa.

required
y2 float

Second ordinate.

required
x float

Target evaluation abscissa.

required

Returns:

Type Description
float

Interpolated ordinate y(x) in float64.

find0

find0(x1, y1, x2, y2)

Finds the linear secant root between (x1, y1) and (x2, y2).

Parameters:

Name Type Description Default
x1 float

First abscissa.

required
y1 float

Function value at x1.

required
x2 float

Second abscissa.

required
y2 float

Function value at x2 (must have opposite sign to y1).

required

Returns:

Type Description
float

Secant zero abscissa x0 in [min(x1, x2), max(x1, x2)].

Raises:

Type Description
ValueError

If y1 and y2 have the same strict sign.

find0_quadratic

find0_quadratic(x1, y1, x2, y2, x3, y3)

Finds the root of the quadratic through three monotonic points.

Parameters:

Name Type Description Default
x1 float

First abscissa (arbitrary units).

required
y1 float

Function value at x1 (arbitrary units).

required
x2 float

Interior abscissa strictly between x1 and x3.

required
y2 float

Function value at x2.

required
x3 float

Third abscissa.

required
y3 float

Function value at x3 (opposite sign to y1).

required

Returns:

Type Description
tuple[float, float]

Tuple (root_x, poly_y) at the root inside [x1, x3].

Raises:

Type Description
ValueError

If abscissas are not strictly monotonic or y1, y3 do not bracket zero.

find_max_quadratic

find_max_quadratic(x1, y1, x2, y2, x3, y3)

Finds the extremum (xmax, ymax, ierr) of a 3-point quadratic.

Mirrors find_max_quadratic in num/public/num_lib.f90:558-578 in upstream's exact expression order and error tests: computes dx1, dx2, a, b, c, dxmax, xmax, and ymax without a concavity or finiteness guard, then tests ymax < y2, y2 < max(y1, y2) (deferred upstream bug #671), and strict monotonicity of (x1, x2, x3), returning ierr = -1 when any check fails while still returning (xmax, ymax).

Parameters:

Name Type Description Default
x1 float

First abscissa (arbitrary units).

required
y1 float

Function value at x1 (arbitrary units).

required
x2 float

Interior abscissa between x1 and x3.

required
y2 float

Function value at x2 (arbitrary units).

required
x3 float

Third abscissa.

required
y3 float

Function value at x3.

required

Returns:

Type Description
float

Tuple (xmax, ymax, ierr) where ierr is 0 on success or

float

-1 if any upstream validation check fails.

two_piece_linear_coeffs

two_piece_linear_coeffs(x, x0, x1, x2)

Solves for two-piece linear weights (a0, a1, a2) on (x0, x1, x2).

Mirrors two_piece_linear_coeffs in MESA num/public/num_lib.f90 (lines 580-613) in upstream's order of operations: the weight of the far node on the segment holding x is computed first and clipped to [0, 1], and the near node takes one minus that weight. A query outside [x0, x2] takes the nearest endpoint's coefficients.

Parameters:

Name Type Description Default
x float

Query point (arbitrary units).

required
x0 float

First grid abscissa (arbitrary units).

required
x1 float

Middle grid abscissa (arbitrary units).

required
x2 float

Third grid abscissa (arbitrary units).

required

Returns:

Type Description
float

Tuple (a0, a1, a2) such that

float

\(f(x) = a_0 f(x_0) + a_1 f(x_1) + a_2 f(x_2)\).

Raises:

Type Description
ValueError

If (x0, x1, x2) is not strictly monotonic, or if x is NaN (upstream leaves the coefficients unset).

flexmesa.num.simplex

Nelder-Mead simplex optimization and Park-Miller ran1_zah PRNG (num).

Ports num/private/mod_simplex.f90 and num/private/mod_random.f90 into float64 Python/NumPy.

SimplexConfig dataclass

Configuration parameters for :func:nm_simplex.

Attributes:

Name Type Description
max_evals int

Maximum objective evaluations allowed.

x_tol float

Relative simplex vertex diameter tolerance.

f_tol float

Objective function spread convergence tolerance.

alpha float

Reflection coefficient (default 1.0).

beta float

Expansion coefficient (default 2.0).

gamma float

Contraction coefficient (default 0.5).

delta float

Shrink coefficient (default 0.5).

enforce_bounds bool

Penalize points outside [x_lower, x_upper].

adaptive_random_search bool

Use MESA's adaptive random search on contraction failure.

seed int

Initial PRNG seed for adaptive random search.

centroid_weight_power float

Power for inverse-objective centroid weighting.

SimplexResult dataclass

Result returned by :func:nm_simplex.

Attributes:

Name Type Description
x_min NDArray[float64]

Best parameter vector of shape (n,) in float64.

f_min float

Minimum objective value \(f(x_{\min})\).

num_evals int

Total objective evaluations performed.

num_iters int

Number of Nelder-Mead iterations completed.

num_shrinks int

Number of full simplex shrink steps performed.

r8_uniform_01

r8_uniform_01(seed)

Evaluates the Park-Miller ran1_zah uniform PRNG in \([0, 1)\).

Parameters:

Name Type Description Default
seed int

32-bit integer state (\(\ne 0\); 0 is mapped to 123459876).

required

Returns:

Type Description
tuple[float, int]

Tuple (uniform_value, next_seed).

i4_uniform

i4_uniform(a, b, seed)

Draws a uniform integer in [min(a, b), max(a, b)] via ran1_zah.

Parameters:

Name Type Description Default
a int

First integer bound.

required
b int

Second integer bound.

required
seed int

32-bit integer PRNG state.

required

Returns:

Type Description
tuple[int, int]

Tuple (random_int, next_seed).

perm_uniform

perm_uniform(n, seed)

Generates a random 1-based permutation of 1..=n via i4_uniform.

Parameters:

Name Type Description Default
n int

Permutation length (\(\ge 1\)).

required
seed int

32-bit integer PRNG state.

required

Returns:

Type Description
tuple[NDArray[int64], int]

Tuple (perm_array, next_seed) with perm_array of shape (n,).

nm_simplex

nm_simplex(x_lower, x_upper, x_first, fcn, config=None)

Minimizes an \(n\)-dimensional objective via Nelder-Mead simplex search.

Parameters:

Name Type Description Default
x_lower ArrayLike

Lower box scale array of shape (n,).

required
x_upper ArrayLike

Upper box scale array of shape (n,).

required
x_first ArrayLike

Initial vertex array of shape (n,).

required
fcn Callable[[NDArray[float64]], float]

Objective callable fcn(x) taking a (n,) float64 array.

required
config SimplexConfig | None

Optional :class:SimplexConfig settings.

None

Returns:

Type Description
SimplexResult

class:SimplexResult containing the minimizer and diagnostic counts.

Raises:

Type Description
ValueError

If input arrays are empty or have mismatched lengths.

flexmesa.num.newuoa

Powell (2006) unconstrained quadratic-interpolation optimizer (NEWUOA).

Ports MESA's num/private/mod_newuoa.f unconstrained derivative-free trust-region optimizer into float64 NumPy.

NewuoaResult dataclass

Result returned by :func:newuoa.

Attributes:

Name Type Description
x_min NDArray[float64]

Best parameter vector (n,) in float64.

f_min float

Minimum objective value f(x_min).

num_evals int

Total number of objective evaluations performed.

newuoa

newuoa(
    calfun,
    x0,
    npt=None,
    rhobeg=0.1,
    rhoend=1e-06,
    maxfun=5000,
    max_valid_value=1e99,
)

Minimizes an unconstrained objective via Powell's NEWUOA algorithm.

Parameters:

Name Type Description Default
calfun Callable[[NDArray[float64]], float]

Objective callable f(x) -> float accepting a 1D (n,) float64 array.

required
x0 ArrayLike

Initial parameter vector of shape (n,) with n >= 2.

required
npt int | None

Number of interpolation conditions in [n + 2, (n + 1)(n + 2) // 2] (defaults to 2 * n + 1).

None
rhobeg float

Initial trust-region radius (> 0).

0.1
rhoend float

Final trust-region radius (0 < rhoend <= rhobeg).

1e-06
maxfun int

Maximum number of objective evaluations allowed.

5000
max_valid_value float

Upper bound on acceptable objective values.

1e+99

Returns:

Type Description
NewuoaResult

class:NewuoaResult with best point x_min, value f_min, and

NewuoaResult

evaluation count num_evals.

Raises:

Type Description
ValueError

If n < 2, npt is out of bounds, or rhobeg / rhoend are non-positive.

fit_min_frobenius_quad

fit_min_frobenius_quad(
    n, npt, kopt, scale, xpt, fval, h_prev
)

Fits the minimum-Frobenius-norm quadratic model around xpt[kopt].

flexmesa.num.bobyqa

Powell (2009) bound-constrained quadratic optimizer (BOBYQA).

Ports MESA's num/private/mod_bobyqa.f box-constrained derivative-free trust-region optimizer into float64 NumPy.

BobyqaResult dataclass

Result returned by :func:bobyqa.

Attributes:

Name Type Description
x_min NDArray[float64]

Best feasible parameter vector (n,) in float64.

f_min float

Minimum objective value f(x_min).

num_evals int

Total number of objective evaluations performed.

bobyqa

bobyqa(
    calfun,
    x0,
    xl,
    xu,
    npt=None,
    rhobeg=0.1,
    rhoend=1e-06,
    maxfun=5000,
    max_valid_value=1e99,
)

Minimizes a box-constrained objective via Powell's BOBYQA algorithm.

Parameters:

Name Type Description Default
calfun Callable[[NDArray[float64]], float]

Objective callable f(x) -> float accepting a 1D (n,) float64 array.

required
x0 ArrayLike

Initial parameter vector of shape (n,) with n >= 2.

required
xl ArrayLike

Lower bound array of shape (n,).

required
xu ArrayLike

Upper bound array of shape (n,) with xu - xl >= 2 * rhobeg.

required
npt int | None

Number of interpolation conditions in [n + 2, (n + 1)(n + 2) // 2] (defaults to 2 * n + 1).

None
rhobeg float

Initial trust-region radius (> 0).

0.1
rhoend float

Final trust-region radius (0 < rhoend <= rhobeg).

1e-06
maxfun int

Maximum number of objective evaluations allowed.

5000
max_valid_value float

Upper bound on acceptable objective values.

1e+99

Returns:

Type Description
BobyqaResult

class:BobyqaResult with best feasible point x_min, value

BobyqaResult

f_min, and evaluation count num_evals.

Raises:

Type Description
ValueError

If dimensions, npt, or box widths xu - xl < 2*rhobeg are invalid.


Turbulent Convection & Mixing (flexmesa.turb)

Local Mixing Length Theory (set_mlt, Cox & Giuli 1968, Henyey 1965, Mihalas 1978), implicit Kuhfuss (1986) Time-Dependent Convection (set_tdc, carrying partial derivatives through the Newton iteration on AutoDiffRealTdc in both Safe Rust and Python/JAX, matching turb/private/tdc.f90:253-345), Langer (1983) semiconvection (set_semiconvection), and Kippenhahn (1980) / Brown (2013) thermohaline mixing (set_thermohaline).

flexmesa.turb.types

Shared data structures and scalar-dual dispatch for flexmesa.turb.

Defines configuration parameter dataclasses, thermodynamic input dataclasses, output structures, and generic mathematical dispatch over IEEE-754 float and first-order forward-mode dual numbers (flexmesa.auto_diff.DualOrder1).

MltOption

Bases: _OptionEnum

Geometric Mixing-Length Theory prescription (MLT_option in mlt.f90).

Attributes:

Name Type Description
COX

Cox & Giuli (1968) optically thick prescription (\(a_0 = 9/4\)).

TDC

Alias for COX used when falling back from TDC to MLT.

HENYEY

Henyey, Vardya, & Bodenheimer (1965) prescription.

ML1

Bohm-Vitense (1958) standard ML1 prescription.

ML2

Bohm & Cassinelli (1971) ML2 prescription.

MIHALAS

Mihalas (1978) optically thin/thick bridged prescription.

from_str classmethod

from_str(name)

Parse an MLT option string into an MltOption enum member.

Parameters:

Name Type Description Default
name str

Option string ("Cox", "TDC", "Henyey", "ML1", "ML2", or "Mihalas").

required

Returns:

Type Description
MltOption

Matching MltOption variant.

Raises:

Type Description
ValueError

If name is not a recognized MLT prescription.

SemiconvectionOption

Bases: _OptionEnum

Semiconvective mixing prescription (semiconvection_option).

Attributes:

Name Type Description
LANGER_85_GRADT_IS_GRADR

Langer (1985) diffusivity with \(\nabla_T = \nabla_r\).

LANGER_85

Full Langer (1985) quadratic solution for \(\nabla_T\).

from_str classmethod

from_str(name)

Parse a semiconvection option string.

Parameters:

Name Type Description Default
name str

Option string ("Langer_85 mixing; gradT = gradr" or "Langer_85").

required

Returns:

Type Description
SemiconvectionOption

Matching SemiconvectionOption variant.

Raises:

Type Description
ValueError

If name is not recognized.

ThermohalineOption

Bases: _OptionEnum

Thermohaline mixing prescription (thermohaline_option).

Attributes:

Name Type Description
KIPPENHAHN

Kippenhahn, Ruschenplatt, & Thomas (1980) formula.

TRAXLER_GARAUD_STELLMACH_11

Traxler, Garaud, & Stellmach (2011) fit.

BROWN_GARAUD_STELLMACH_13

Brown, Garaud, & Stellmach (2013) model.

from_str classmethod

from_str(name)

Parse a thermohaline option string.

Parameters:

Name Type Description Default
name str

Option string ("Kippenhahn", "Traxler_Garaud_Stellmach_11", or "Brown_Garaud_Stellmach_13").

required

Returns:

Type Description
ThermohalineOption

Matching ThermohalineOption variant.

Raises:

Type Description
ValueError

If name is not recognized.

DrivingSpecies dataclass

Atomic charge \(Z\) and mass number \(A\) of a thermohaline-driving species.

Attributes:

Name Type Description
chem_z float

Atomic charge number \(Z\) (dimensionless).

chem_a float

Atomic mass number \(A = Z + N\) (dimensionless).

he4 classmethod

he4()

Return \({}^4\mathrm{He}\) (\(Z = 2, A = 4\)).

he3 classmethod

he3()

Return \({}^3\mathrm{He}\) (\(Z = 2, A = 3\)).

c12 classmethod

c12()

Return \({}^{12}\mathrm{C}\) (\(Z = 6, A = 12\)).

TurbOutput dataclass

Standard output container for turbulent mixing prescriptions.

Attributes:

Name Type Description
gamma ScalarOrDual

Convective efficiency \(\Gamma\) (dimensionless).

grad_t ScalarOrDual

Actual temperature gradient \(\nabla_T\) (dimensionless).

y_face ScalarOrDual

Superadiabaticity \(Y_{\mathrm{face}}\) (dimensionless).

conv_vel ScalarOrDual

Convective or effective mixing speed in \(\mathrm{cm\,s^{-1}}\).

d ScalarOrDual

Compositional diffusion coefficient \(D\) in \(\mathrm{cm^2\,s^{-1}}\).

mixing_type MixingType

Active MixingType classification.

MltParams dataclass

Non-differentiable configuration parameters for set_mlt.

Attributes:

Name Type Description
option MltOption

Geometric MLT prescription (MltOption).

mixing_length_alpha float

Mixing-length parameter \(\alpha_{\mathrm{MLT}}\).

henyey_nu float

Henyey velocity parameter \(\nu\).

henyey_y float

Henyey optical-depth parameter \(y\).

max_conv_vel float

Maximum convective speed in \(\mathrm{cm\,s^{-1}}\).

cox classmethod

cox(mixing_length_alpha)

Create standard Cox MLT parameters for \(\alpha_{\mathrm{MLT}}\).

MltInputs dataclass

Differentiable thermodynamic and structure inputs for set_mlt.

Attributes:

Name Type Description
chi_t ScalarOrDual

\((\partial \ln P / \partial \ln T)_\rho\) (dimensionless).

chi_rho ScalarOrDual

\((\partial \ln P / \partial \ln \rho)_T\) (dimensionless).

cp ScalarOrDual

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

grav ScalarOrDual

Local gravitational acceleration \(g\) in \(\mathrm{cm\,s^{-2}}\).

lambda_ ScalarOrDual

Mixing length \(\Lambda\) in \(\mathrm{cm}\).

rho ScalarOrDual

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

p ScalarOrDual

Total pressure \(P\) in \(\mathrm{dyn\,cm^{-2}}\).

t ScalarOrDual

Temperature \(T\) in \(\mathrm{K}\).

opacity ScalarOrDual

Rosseland mean opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

gradr ScalarOrDual

Radiative temperature gradient \(\nabla_r\) (dimensionless).

grada ScalarOrDual

Adiabatic temperature gradient \(\nabla_{\mathrm{ad}}\).

gradl ScalarOrDual

Ledoux temperature gradient \(\nabla_L\) (dimensionless).

val_of

val_of(x)

Extract primal float value from a scalar or dual input.

const_like

const_like(proto: float, v: float) -> float
const_like(proto: DualOrder1, v: float) -> _ad.DualOrder1
const_like(
    proto: AutoDiffRealTdc, v: float
) -> _tdc_dual.AutoDiffRealTdc
const_like(proto: ScalarOrDual, v: float) -> ScalarOrDual
const_like(proto: TdcScalar, v: float) -> TdcScalar
const_like(proto, v)

Construct a constant matching the type/arity of proto.

with_val_like

with_val_like(x: float, new_val: float) -> float
with_val_like(
    x: DualOrder1, new_val: float
) -> _ad.DualOrder1
with_val_like(
    x: AutoDiffRealTdc, new_val: float
) -> _tdc_dual.AutoDiffRealTdc
with_val_like(
    x: ScalarOrDual, new_val: float
) -> ScalarOrDual
with_val_like(x: TdcScalar, new_val: float) -> TdcScalar
with_val_like(x, new_val)

Replace the primal value of x while preserving its derivatives.

s_abs

s_abs(x: float) -> float
s_abs(x: DualOrder1) -> _ad.DualOrder1
s_abs(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_abs(x: ScalarOrDual) -> ScalarOrDual
s_abs(x: TdcScalar) -> TdcScalar
s_abs(x)

Evaluate \(|x|\) for float, DualOrder1, or AutoDiffRealTdc.

s_sqrt

s_sqrt(x: float) -> float
s_sqrt(x: DualOrder1) -> _ad.DualOrder1
s_sqrt(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_sqrt(x: ScalarOrDual) -> ScalarOrDual
s_sqrt(x: TdcScalar) -> TdcScalar
s_sqrt(x)

Evaluate \(\sqrt{x}\) for float, DualOrder1, or AutoDiffRealTdc.

s_exp

s_exp(x: float) -> float
s_exp(x: DualOrder1) -> _ad.DualOrder1
s_exp(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_exp(x: ScalarOrDual) -> ScalarOrDual
s_exp(x: TdcScalar) -> TdcScalar
s_exp(x)

Evaluate \(\exp(x)\) for float, DualOrder1, or AutoDiffRealTdc.

s_log

s_log(x: float) -> float
s_log(x: DualOrder1) -> _ad.DualOrder1
s_log(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_log(x: ScalarOrDual) -> ScalarOrDual
s_log(x: TdcScalar) -> TdcScalar
s_log(x)

Evaluate \(\ln(x)\) for float, DualOrder1, or AutoDiffRealTdc.

s_powf

s_powf(x: float, p: float) -> float
s_powf(x: DualOrder1, p: float) -> _ad.DualOrder1
s_powf(
    x: AutoDiffRealTdc, p: float
) -> _tdc_dual.AutoDiffRealTdc
s_powf(x: ScalarOrDual, p: float) -> ScalarOrDual
s_powf(x: TdcScalar, p: float) -> TdcScalar
s_powf(x, p)

Evaluate \(x^p\) for float, DualOrder1, or AutoDiffRealTdc.

s_pow2

s_pow2(x: float) -> float
s_pow2(x: DualOrder1) -> _ad.DualOrder1
s_pow2(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_pow2(x: ScalarOrDual) -> ScalarOrDual
s_pow2(x: TdcScalar) -> TdcScalar
s_pow2(x)

Evaluate \(x^2\) for float, DualOrder1, or AutoDiffRealTdc.

s_pow3

s_pow3(x: float) -> float
s_pow3(x: DualOrder1) -> _ad.DualOrder1
s_pow3(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_pow3(x: ScalarOrDual) -> ScalarOrDual
s_pow3(x: TdcScalar) -> TdcScalar
s_pow3(x)

Evaluate \(x^3\) for float, DualOrder1, or AutoDiffRealTdc.

s_pow4

s_pow4(x: float) -> float
s_pow4(x: DualOrder1) -> _ad.DualOrder1
s_pow4(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_pow4(x: ScalarOrDual) -> ScalarOrDual
s_pow4(x: TdcScalar) -> TdcScalar
s_pow4(x)

Evaluate \(x^4\) for float, DualOrder1, or AutoDiffRealTdc.

s_tanh

s_tanh(x: float) -> float
s_tanh(x: DualOrder1) -> _ad.DualOrder1
s_tanh(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_tanh(x: ScalarOrDual) -> ScalarOrDual
s_tanh(x: TdcScalar) -> TdcScalar
s_tanh(x)

Evaluate \(\tanh(x)\) for float, DualOrder1, or AutoDiffRealTdc.

s_tan

s_tan(x: float) -> float
s_tan(x: DualOrder1) -> _ad.DualOrder1
s_tan(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_tan(x: ScalarOrDual) -> ScalarOrDual
s_tan(x: TdcScalar) -> TdcScalar
s_tan(x)

Evaluate \(\tan(x)\) for float, DualOrder1, or AutoDiffRealTdc.

s_atan

s_atan(x: float) -> float
s_atan(x: DualOrder1) -> _ad.DualOrder1
s_atan(x: AutoDiffRealTdc) -> _tdc_dual.AutoDiffRealTdc
s_atan(x: ScalarOrDual) -> ScalarOrDual
s_atan(x: TdcScalar) -> TdcScalar
s_atan(x)

Evaluate \(\arctan(x)\) for scalar or dual inputs.

flexmesa.turb.mlt

Local Mixing-Length Theory (set_mlt, turb/private/mlt.f90).

Solves the cubic convective efficiency equation (Cox & Giuli 1968, §14.82) $\(a_0 \Gamma^3 + \Gamma^2 + \Gamma - a_0 B^3 = 0\)$ across six geometric MLT prescriptions (Cox, TDC, Henyey, ML1, ML2, and Mihalas), supporting IEEE-754 float, forward-mode DualOrder1, and vectorized/differentiable JAX float64 arrays (set_mlt_jax).

All inputs and outputs use CGS physical units (cm, g, s, erg, K, dyn) and dimensionless logarithmic temperature gradients \(d\ln T / d\ln P\).

set_mlt

set_mlt(params, inp, *, backend='auto')

Evaluate local Mixing-Length Theory (calc_MLT in mlt.f90).

Matches upstream turb/private/mlt.f90:53-181, where each bare return (f1 <= 0, Gamma <= 0, is_bad(Zeta)) leaves unwritten outputs at the caller's no-mixing baseline (star/private/turb_support.f90:283-288) with ierr = 0. Explicit input validation on degenerate inputs is deferred to #330.

Parameters:

Name Type Description Default
params MltParams

Non-differentiable MLT configuration parameters (MltParams).

required
inp MltInputs

Thermodynamic and structure inputs (MltInputs) with float or DualOrder1 fields in CGS units.

required
backend Backend

Execution backend ("auto", "rust", or "jax").

'auto'

Returns:

Type Description
TurbOutput

TurbOutput containing `(gamma, grad_t, y_face, conv_vel, d,

TurbOutput

mixing_type)`.

set_mlt_jax

set_mlt_jax(
    chi_t,
    chi_rho,
    cp,
    grav,
    lambda_,
    rho,
    p,
    t,
    opacity,
    gradr,
    grada,
    gradl,
    mixing_length_alpha=2.0,
)

Evaluate Cox Mixing-Length Theory in pure JAX float64.

Compatible with jax.jit, jax.vmap, and jax.grad. Applies safe jnp.where masking before logarithmic and power operations so gradients remain finite across radiative (\(\nabla_r \le \nabla_L\)) and convective (\(\nabla_r > \nabla_L\)) zones.

Parameters:

Name Type Description Default
chi_t Array

\((\partial \ln P / \partial \ln T)_\rho\), shape (*batch,).

required
chi_rho Array

\((\partial \ln P / \partial \ln \rho)_T\), shape (*batch,).

required
cp Array

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\), shape (*batch,).

required
grav Array

Gravitational acceleration \(g\) in \(\mathrm{cm\,s^{-2}}\), shape (*batch,).

required
lambda_ Array

Mixing length \(\Lambda\) in \(\mathrm{cm}\), shape (*batch,).

required
rho Array

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape (*batch,).

required
p Array

Total pressure \(P\) in \(\mathrm{dyn\,cm^{-2}}\), shape (*batch,).

required
t Array

Temperature \(T\) in \(\mathrm{K}\), shape (*batch,).

required
opacity Array

Rosseland opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\), shape (*batch,).

required
gradr Array

Radiative gradient \(\nabla_r\), shape (*batch,).

required
grada Array

Adiabatic gradient \(\nabla_{\mathrm{ad}}\), shape (*batch,).

required
gradl Array

Ledoux gradient \(\nabla_L\), shape (*batch,).

required
mixing_length_alpha float

Mixing-length parameter \(\alpha_{\mathrm{MLT}}\).

2.0

Returns:

Type Description
Array

Five-tuple (gamma, grad_t, y_face, conv_vel, d) of float64 JAX

Array

arrays with shape (*batch,).

flexmesa.turb.tdc

Time-Dependent Convection solver (set_tdc, turb/private/tdc.f90).

Solves the Kuhfuss (1986) / Smolec time-dependent convection energy balance equation $\(Q(Y) = (L - L_0 \nabla_L) - L_0 Y - c_0 A_f(Y_{\mathrm{env}}) Y_{\mathrm{env}} = 0\)$ over \(Z = \ln|Y| \in [-100, 100]\) using bisection bracketing followed by damped Newton-Raphson refinement (bracket_plus_newton_search). The Newton iteration runs on AutoDiffRealTdc (upstream's auto_diff_real_tdc), so the returned \(Y\) carries the structure partials of the last Newton update (turb/private/tdc.f90:253-345).

TdcParams dataclass

Non-differentiable configuration parameters for set_tdc.

Attributes:

Name Type Description
conv_vel_start float

Initial convective speed \(v_{\mathrm{conv,start}}\) in \(\mathrm{cm\,s^{-1}}\).

mixing_length_alpha float

Mixing-length parameter \(\alpha_{\mathrm{MLT}}\).

tdc_alpha_d float

Turbulent dissipation multiplier \(\alpha_D\).

tdc_alpha_r float

Radiative damping multiplier \(\alpha_R\).

tdc_alpha_pt float

Turbulent pressure work multiplier \(\alpha_{P_t}\).

tdc_alpha_c float

Convective flux multiplier \(\alpha_C\).

tdc_alpha_s float

Buoyant source multiplier \(\alpha_S\).

dt float

Time step \(\Delta t\) in \(\mathrm{s}\).

cgrav float

Gravitational constant \(G\) in \(\mathrm{cm^3\,g^{-1}\,s^{-2}}\).

m float

Enclosed mass \(m\) at the cell face in \(\mathrm{g}\).

scale float

Luminosity scale for relative residual convergence in \(\mathrm{erg\,s^{-1}}\).

max_conv_vel float

Upper cap on convective velocity in \(\mathrm{cm\,s^{-1}}\).

include_mlt_corr_to_tdc bool

Include steady-state Cox MLT geometric correction \(\Gamma / (1 + \Gamma)\).

use_tdc_enthalpy_flux_limiter bool

Enable Wuchterl & Feuchtinger (1998) quintic enthalpy flux limiter.

TdcInputs dataclass

Differentiable thermodynamic and structure inputs for set_tdc.

Attributes:

Name Type Description
chi_t ScalarOrDual

\((\partial \ln P / \partial \ln T)_\rho\) (dimensionless).

chi_rho ScalarOrDual

\((\partial \ln P / \partial \ln \rho)_T\) (dimensionless).

gradr ScalarOrDual

Radiative temperature gradient \(\nabla_r\) (dimensionless).

r ScalarOrDual

Radial coordinate \(r\) at the cell face in \(\mathrm{cm}\).

p ScalarOrDual

Total pressure \(P\) in \(\mathrm{dyn\,cm^{-2}}\).

t ScalarOrDual

Temperature \(T\) in \(\mathrm{K}\).

rho ScalarOrDual

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

dv ScalarOrDual

Specific volume change \(\Delta(1/\rho)\) in \(\mathrm{cm^3\,g^{-1}}\).

cp ScalarOrDual

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

opacity ScalarOrDual

Rosseland mean opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

scale_height ScalarOrDual

Pressure scale height \(H_P\) in \(\mathrm{cm}\).

gradl ScalarOrDual

Ledoux temperature gradient \(\nabla_L\) (dimensionless).

grada ScalarOrDual

Adiabatic temperature gradient \(\nabla_{\mathrm{ad}}\).

eq_div_w ScalarOrDual

Coupled source term \(E_q / w\) in \(\mathrm{cm\,s^{-2}}\).

grav ScalarOrDual

Local gravitational acceleration \(g\) in \(\mathrm{cm\,s^{-2}}\).

energy ScalarOrDual

Specific internal energy \(e\) in \(\mathrm{erg\,g^{-1}}\).

TdcOutput dataclass

Output structure returned by set_tdc.

Attributes:

Name Type Description
output TurbOutput

Standard turbulent transport outputs (TurbOutput).

num_iters int

Number of Newton iterations taken in the TDC root solver.

set_tdc

set_tdc(params, inp)

Evaluate Time-Dependent Convection (set_TDC in turb/public/turb.f90).

Calls set_mlt with Cox MLT unconditionally before packing TdcInfo (turb/public/turb.f90:142-145) and enforces upstream's mixing_length_alpha == 0 / dt <= 0 guard in get_TDC_solution (turb/private/tdc.f90:65-67).

Parameters:

Name Type Description Default
params TdcParams

Non-differentiable configuration parameters (TdcParams).

required
inp TdcInputs

Differentiable thermodynamic inputs (TdcInputs) with float or DualOrder1 fields.

required

Returns:

Type Description
TdcOutput

TdcOutput pairing TurbOutput with num_iters.

Raises:

Type Description
ValueError

If mixing_length_alpha == 0 or dt <= 0.

RuntimeError

If the TDC root solver fails to converge.

flexmesa.turb.tdc_dual

Nested dual number of the TDC Newton solver (auto_diff_real_tdc).

Mirrors crates/flexmesa-turb/src/tdc_dual.rs and upstream auto_diff/private/auto_diff_real_tdc_module.f90. Each instance holds a primal value val, its derivative with respect to the Newton variable \(Z = \ln|Y|\) (d1val1), N structure partials (d1_array), and the N mixed second partials (d1val1_d1_array). Iterating bracket_plus_newton_search on this type carries structure partials through every Newton update, matching turb/private/tdc.f90:253-345.

AutoDiffRealTdc

Value, Newton derivative, N structure partials, and N mixed partials.

Attributes:

Name Type Description
val float

Primal scalar value (val).

d1val1 float

Derivative with respect to the Newton variable \(Z\) (d1val1).

d1_array _FloatArray

First-order partials with respect to structure variables (d1Array), 1D float64 array of shape (N,).

d1val1_d1_array _FloatArray

Mixed second partials with respect to \(Z\) and the structure variables (d1val1_d1Array), 1D float64 array of shape (N,).

num_vars property

num_vars

Return the number of tracked structure variables N.

__init__

__init__(val, d1val1, d1_array, d1val1_d1_array)

Initialize an AutoDiffRealTdc number.

Parameters:

Name Type Description Default
val float

Primal scalar value.

required
d1val1 float

Derivative with respect to the Newton variable \(Z\).

required
d1_array _FloatArray

Structure partials of shape (N,).

required
d1val1_d1_array _FloatArray

Mixed partials of shape (N,).

required

constant classmethod

constant(val, num_vars)

Construct a constant with num_vars zero structure partials.

Parameters:

Name Type Description Default
val float

Scalar value.

required
num_vars int

Number of structure variables N.

required

Returns:

Type Description
AutoDiffRealTdc

Constant AutoDiffRealTdc with all derivatives zeroed.

convert classmethod

convert(x, num_vars)

Lift a scalar or DualOrder1 into AutoDiffRealTdc (convert).

Copies val and d1_array and zeroes d1val1 and d1val1_d1_array (turb/private/tdc_support.f90:424-430).

Parameters:

Name Type Description Default
x float | DualOrder1

Plain float or DualOrder1 input.

required
num_vars int

Number of structure variables N.

required

Returns:

Type Description
AutoDiffRealTdc

Lifted AutoDiffRealTdc instance.

Raises:

Type Description
ValueError

If x is a DualOrder1 whose arity differs from num_vars.

unconvert

unconvert(*, is_dual)

Project back to DualOrder1 or plain float (unconvert).

Drops d1val1 and d1val1_d1_array while preserving val and d1_array (turb/private/tdc_support.f90:443-447).

Parameters:

Name Type Description Default
is_dual bool

Return a DualOrder1 when True, or a float when False.

required

Returns:

Type Description
float | DualOrder1

DualOrder1 carrying (val, d1_array) or scalar float.

with_val

with_val(new_val)

Return a copy with val replaced and all derivatives preserved.

with_d1val1

with_d1val1(d1val1)

Return a copy with d1val1 set (Z%d1val1 = 1d0, tdc.f90:261).

differentiate_1

differentiate_1()

Differentiate with respect to \(Z\) (differentiate_1).

abs

abs()

Evaluate \(|x|\) (abs_self).

sqrt

sqrt()

Evaluate \(\sqrt{x}\) (sqrt_self).

exp

exp()

Evaluate \(\exp(x)\) (exp_self).

log

log()

Evaluate \(\ln(x)\) (log_self).

powf

powf(y)

Evaluate \(x^y\) for a scalar exponent y (pow_self_real).

pow2

pow2()

Evaluate \(x^2\) (pow2_self).

pow3

pow3()

Evaluate \(x^3\) (pow3_self).

pow4

pow4()

Evaluate \(x^4\) (pow4_self).

tanh

tanh()

Evaluate \(\tanh(x)\) (tanh_self).

tan

tan()

Evaluate \(\tan(x)\) (tan_self).

atan

atan()

Evaluate \(\arctan(x)\) (atan_self).

1D bisection and damped Newton-Raphson searches for TDC (tdc.f90).

Operates in the 1D logarithmic coordinate \(Z = \ln|Y|\): 1. q_bisection_search: Narrows a sign-changing bracket for \(Q(Y(Z)) = 0\) to width \(< 1.0\). 2. dq_dz_bisection_search: Locates a stationary point \(dQ/dZ = 0\) on the negative-\(Y\) branch where \(A_f(Z) > 0\). 3. af_bisection_search: Locates the largest \(Z\) on the negative-\(Y\) branch before \(A_f(Z)\) vanishes. 4. bracket_plus_newton_search: Bisection narrowing from [zlb, zub] followed by damped Newton-Raphson refinement on AutoDiffRealTdc, carrying structure partials through the Newton updates as in turb/private/tdc.f90:219-380.

q_bisection_search(
    info_p, y_is_positive, lower_bound_z, upper_bound_z
)

Narrow a bracket \([Z_{\mathrm{lb}}, Z_{\mathrm{ub}}]\) where \(Q(Z) = 0\).

Parameters:

Name Type Description Default
info_p TdcInfo[float]

Primal float TDC state (TdcInfo[float]).

required
y_is_positive bool

Sign flag (True for \(Y > 0\), False for \(Y < 0\)).

required
lower_bound_z float

Initial lower bound \(Z_{\mathrm{lb}}\).

required
upper_bound_z float

Initial upper bound \(Z_{\mathrm{ub}}\).

required

Returns:

Type Description
tuple[float, float, float]

Three-tuple (z_mid, lb_out, ub_out) with narrowed bounds.

Raises:

Type Description
RuntimeError

If \(Q(Z_{\mathrm{lb}})\) and \(Q(Z_{\mathrm{ub}})\) have the same sign.

dq_dz_bisection_search(
    info_z, lower_bound_z_in, upper_bound_z_in
)

Locate a stationary point \(dQ/dZ = 0\) on \(Y < 0\) where \(A_f > 0\).

Parameters:

Name Type Description Default
info_z TdcInfo[DualOrder1]

1D DualOrder1(num_vars=1) TDC state (TdcInfo).

required
lower_bound_z_in float

Lower bound \(Z_{\mathrm{lb}}\).

required
upper_bound_z_in float

Upper bound \(Z_{\mathrm{ub}}\).

required

Returns:

Type Description
float | None

Stationary coordinate \(Z_1\) if a bracketed stationary point exists with

float | None

\(A_f > 0\), or None otherwise.

af_bisection_search(
    info_p, lower_bound_z_in, upper_bound_z_in
)

Locate the largest \(Z\) on \(Y < 0\) such that \(A_f(Z) > 0\).

Parameters:

Name Type Description Default
info_p TdcInfo[float]

Primal float TDC state (TdcInfo[float]).

required
lower_bound_z_in float

Lower bound \(Z_{\mathrm{lb}}\) where \(A_f > 0\).

required
upper_bound_z_in float

Upper bound \(Z_{\mathrm{ub}}\) where \(A_f = 0\).

required

Returns:

Type Description
float

Largest coordinate \(Z_0\) where \(A_f(Z_0) > 0\) to tolerance \(10^{-4}\).

Raises:

Type Description
RuntimeError

If the bounds do not straddle the \(A_f = 0\) transition.

bracket_plus_newton_search(
    info_p, info_t, scale, y_is_positive, zlb, zub
)

Solve \(Q(Y(Z)) = 0\) via bisection narrowing and damped Newton refinement.

Runs the Newton loop on AutoDiffRealTdc (auto_diff_real_tdc), matching bracket_plus_Newton_search in turb/private/tdc.f90:230-379 and crates/flexmesa-turb/src/tdc_search.rs:203-306. The returned \(Y\) carries the structure partials produced by the last Newton update.

Parameters:

Name Type Description Default
info_p TdcInfo[float]

Primal float TDC state (TdcInfo[float]).

required
info_t TdcInfo[AutoDiffRealTdc]

Nested dual TDC state (TdcInfo[AutoDiffRealTdc]).

required
scale float

Luminosity scale for relative residual convergence.

required
y_is_positive bool

Sign flag (True for \(Y > 0\), False for \(Y < 0\)).

required
zlb float

Lower bound \(Z_{\mathrm{lb}}\).

required
zub float

Upper bound \(Z_{\mathrm{ub}}\).

required

Returns:

Type Description
AutoDiffRealTdc

Two-tuple (y_final, iter_taken) of converged AutoDiffRealTdc root

int

\(Y^*\) and iteration count.

Raises:

Type Description
RuntimeError

If bracketing or Newton refinement fails to converge.

flexmesa.turb.tdc_support

Time-dependent convection physics kernels (turb/private/tdc_support.f90).

Provides the Kuhfuss (1986) / Smolec time-dependent convection velocity evolution (eval_xis, eval_af), Wuchterl & Feuchtinger (1998) quintic smootherstep enthalpy flux limiter (flux_limiter_function), and luminosity residual evaluation (compute_q) generic over float, DualOrder1, and AutoDiffRealTdc.

TdcInfo dataclass

Internal state container for TDC evaluations independent of \(Y\).

Matches tdc_info in turb/private/tdc_support.f90.

Attributes:

Name Type Description
include_mlt_corr_to_tdc bool

Include steady-state Cox MLT geometric correction \(\Gamma / (1 + \Gamma)\).

use_tdc_enthalpy_flux_limiter bool

Enable Wuchterl & Feuchtinger (1998) quintic enthalpy flux limiter.

mixing_length_alpha float

Mixing-length parameter \(\alpha_{\mathrm{MLT}}\).

tdc_alpha_c float

Convective flux multiplier \(\alpha_C\).

tdc_alpha_s float

Buoyant source multiplier \(\alpha_S\).

tdc_alpha_d float

Turbulent drag multiplier \(\alpha_D\).

tdc_alpha_r float

Radiative damping multiplier \(\alpha_R\).

tdc_alpha_pt float

Turbulent pressure work multiplier \(\alpha_{P_t}\).

dt float

Time step \(\Delta t\) in \(\mathrm{s}\).

a0 S

Initial scaled convective speed \(A_0\) in \(\mathrm{cm\,s^{-1}}\).

c0 S

Convective luminosity prefactor \(c_0\) in \(\mathrm{erg\,cm^{-1}}\).

lum S

Total luminosity \(L\) in \(\mathrm{erg\,s^{-1}}\).

l0 S

Radiative luminosity scale \(L_0 = L / \nabla_r\) in \(\mathrm{erg\,s^{-1}}\).

gradl S

Ledoux temperature gradient \(\nabla_L\) (dimensionless).

grada S

Adiabatic temperature gradient \(\nabla_{\mathrm{ad}}\).

t S

Temperature \(T\) in \(\mathrm{K}\).

rho S

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

dv S

Specific volume change \(\Delta(1/\rho)\) in \(\mathrm{cm^3\,g^{-1}}\).

cp S

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

kap S

Rosseland mean opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

hp S

Pressure scale height \(H_P\) in \(\mathrm{cm}\).

gamma S

Steady-state Cox MLT efficiency \(\Gamma\) (dimensionless).

eq_div_w S

Coupled source term \(E_q / w\) in \(\mathrm{cm\,s^{-2}}\).

h S

Specific enthalpy \(h = e + P/\rho\) in \(\mathrm{erg\,g^{-1}}\).

to_primal

to_primal()

Project all differentiable fields to primal float scalars.

Returns:

Type Description
TdcInfo[float]

A TdcInfo[float] instance for scalar bisection evaluations.

to_z_dual

to_z_dual()

Project all differentiable fields to 1D constant DualOrder1.

Returns:

Type Description
TdcInfo[DualOrder1]

A TdcInfo[DualOrder1] instance whose scalar fields are 1-variable

TdcInfo[DualOrder1]

dual constants for 1D differentiation with respect to \(Z = \ln|Y|\).

to_tdc

to_tdc()

Lift every structure field into AutoDiffRealTdc (convert).

Returns:

Type Description
TdcInfo[AutoDiffRealTdc]

Two-tuple (info_tdc, has_dual) where info_tdc carries every

bool

field as an AutoDiffRealTdc of common arity N (N = 0 when all

tuple[TdcInfo[AutoDiffRealTdc], bool]

fields are plain float), and has_dual is True if any input

tuple[TdcInfo[AutoDiffRealTdc], bool]

field was a DualOrder1.

Raises:

Type Description
ValueError

If two DualOrder1 fields disagree in arity.

set_y

set_y(y_is_positive, z)

Map logarithmic coordinate \(Z = \ln|Y|\) to \(Y = \pm \exp(Z)\).

Parameters:

Name Type Description Default
y_is_positive bool

Sign flag (True for \(Y > 0\), False for \(Y < 0\)).

required
z S

Dimensionless logarithmic superadiabaticity \(Z = \ln|Y|\).

required

Returns:

Type Description
S

Dimensionless superadiabaticity \(Y = \pm \exp(Z)\).

safe_tanh

safe_tanh(x)

Evaluate numerically safe hyperbolic tangent clamping \(|x| > 50\).

Parameters:

Name Type Description Default
x S

Dimensionless input argument.

required

Returns:

Type Description
S

Dimensionless clamped \(\tanh(x)\) matching safe_tanh in

S

tdc_support.f90.

flux_limiter_function

flux_limiter_function(x)

Evaluate Wuchterl & Feuchtinger (1998) \(C^2\) quintic smootherstep.

Parameters:

Name Type Description Default
x S

Dimensionless ratio of convective source enthalpy to specific enthalpy \(h\).

required

Returns:

Type Description
S

Dimensionless limited ratio (x for \(x < 0.95\), 1.0 for \(x \ge 1.0\),

S

and a quintic blend on \([0.95, 1.0)\)).

eval_xis

eval_xis(info, y)

Evaluate \((\xi_0, \xi_1, \xi_2)\) of the TDC velocity equation.

Parameters:

Name Type Description Default
info TdcInfo[S]

Precomputed cell-face TDC state (TdcInfo).

required
y S

Dimensionless envelope-corrected superadiabaticity \(Y_{\mathrm{env}}\).

required

Returns:

Type Description
S

Three-tuple (xi0, xi1, xi2) in $(\mathrm{cm^2\,s^{-3}},

S

\mathrm{s^{-1}}, \mathrm{cm^{-1}})$ for $2\,dw/dt = \xi_0 + \xi_1 w

S
  • \xi_2 w^2$, matching eval_xis in tdc_support.f90.

eval_af

eval_af(dt, a0, xi0, xi1, xi2)

Evaluate final scaled convective speed \(A_f(\Delta t)\) (eval_Af).

Parameters:

Name Type Description Default
dt float

Time step \(\Delta t\) in \(\mathrm{s}\).

required
a0 S

Initial scaled speed \(A_0\) in \(\mathrm{cm\,s^{-1}}\).

required
xi0 S

Buoyant source coefficient \(\xi_0\) in \(\mathrm{cm^2\,s^{-3}}\).

required
xi1 S

Linear damping coefficient \(\xi_1\) in \(\mathrm{s^{-1}}\).

required
xi2 S

Quadratic drag coefficient \(\xi_2\) in \(\mathrm{cm^{-1}}\).

required

Returns:

Type Description
S

Final scaled convective speed \(A_f(\Delta t)\) in

S

\(\mathrm{cm\,s^{-1}}\).

compute_q

compute_q(info, y)

Evaluate luminosity residual \(Q(Y)\) and final speed \(A_f\) (compute_Q).

Parameters:

Name Type Description Default
info TdcInfo[S]

Precomputed cell-face TDC state (TdcInfo).

required
y S

Superadiabaticity \(Y = \nabla_T - \nabla_L\).

required

Returns:

Type Description
S

Two-tuple (q, af) of luminosity residual \(Q(Y)\) in

S

\(\mathrm{erg\,s^{-1}}\) and final scaled speed \(A_f\) in

tuple[S, S]

\(\mathrm{cm\,s^{-1}}\).

flexmesa.turb.semiconvection

Semiconvective mixing (set_semiconvection, semiconvection.f90).

Implements Langer, El Eid, & Fricke (1983, 1985) semiconvective mixing diffusivity $\(D_{\mathrm{sc}} = \frac{\alpha_{\mathrm{sc}} K_r}{6 C_P \rho} \frac{\nabla_r - \nabla_{\mathrm{ad}}}{\nabla_L - \nabla_r}\)$ and temperature-gradient prescriptions ("Langer_85 mixing; gradT = gradr" and "Langer_85").

SemiconvectionParams dataclass

Non-differentiable configuration parameters for set_semiconvection.

Attributes:

Name Type Description
option SemiconvectionOption

Semiconvection prescription (SemiconvectionOption).

alpha_semiconvection float

Efficiency parameter \(\alpha_{\mathrm{sc}}\).

cgrav float

Gravitational constant \(G\) in \(\mathrm{cm^3\,g^{-1}\,s^{-2}}\).

gradl_composition_term float

Ledoux composition term \(B = \nabla_L - \nabla_{\mathrm{ad}}\).

m float

Enclosed mass \(m\) at the cell face in \(\mathrm{g}\).

SemiconvectionInputs dataclass

Differentiable thermodynamic inputs for set_semiconvection.

Attributes:

Name Type Description
lum ScalarOrDual

Total luminosity \(L\) across the face in \(\mathrm{erg\,s^{-1}}\).

lambda_ ScalarOrDual

Mixing length \(\Lambda\) in \(\mathrm{cm}\).

t ScalarOrDual

Temperature \(T\) in \(\mathrm{K}\).

p ScalarOrDual

Total pressure \(P\) in \(\mathrm{dyn\,cm^{-2}}\).

pr ScalarOrDual

Radiation pressure \(P_{\mathrm{rad}}\) in \(\mathrm{dyn\,cm^{-2}}\).

beta ScalarOrDual

Gas-to-total pressure ratio \(\beta = P_{\mathrm{gas}} / P\).

opacity ScalarOrDual

Rosseland mean opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

rho ScalarOrDual

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

cp ScalarOrDual

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

gradr ScalarOrDual

Radiative temperature gradient \(\nabla_r\) (dimensionless).

grada ScalarOrDual

Adiabatic temperature gradient \(\nabla_{\mathrm{ad}}\).

gradl ScalarOrDual

Ledoux temperature gradient \(\nabla_L\) (dimensionless).

set_semiconvection

set_semiconvection(params, inp)

Evaluate Langer (1983, 1985) semiconvective mixing.

Parameters:

Name Type Description Default
params SemiconvectionParams

Non-differentiable configuration (SemiconvectionParams).

required
inp SemiconvectionInputs

Differentiable thermodynamic inputs (SemiconvectionInputs).

required

Returns:

Type Description
TurbOutput

TurbOutput containing `(gamma, grad_t, y_face, conv_vel, d,

TurbOutput

mixing_type)`.

set_semiconvection_jax

set_semiconvection_jax(
    lambda_,
    t,
    opacity,
    rho,
    cp,
    gradr,
    grada,
    gradl,
    alpha_semiconvection=0.1,
)

Evaluate Langer (1985) semiconvective diffusivity in pure JAX float64.

Parameters:

Name Type Description Default
lambda_ Array

Mixing length \(\Lambda\) in \(\mathrm{cm}\), shape (*batch,).

required
t Array

Temperature \(T\) in \(\mathrm{K}\), shape (*batch,).

required
opacity Array

Rosseland opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\), shape (*batch,).

required
rho Array

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape (*batch,).

required
cp Array

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\), shape (*batch,).

required
gradr Array

Radiative gradient \(\nabla_r\), shape (*batch,).

required
grada Array

Adiabatic gradient \(\nabla_{\mathrm{ad}}\), shape (*batch,).

required
gradl Array

Ledoux gradient \(\nabla_L\), shape (*batch,).

required
alpha_semiconvection float

Efficiency parameter \(\alpha_{\mathrm{sc}}\).

0.1

Returns:

Type Description
tuple[Array, Array, Array, Array]

Four-tuple (grad_t, y_face, conv_vel, d) of float64 JAX arrays.

flexmesa.turb.thermohaline

Thermohaline (salt-finger) mixing (set_thermohaline, thermohaline.f90).

Computes compositional diffusivity \(D_{\mathrm{thrm}}\) when the thermal gradient is Schwarzschild stable (\(\nabla_r < \nabla_{\mathrm{ad}}\)) but destabilized by an inverted molecular-weight gradient (\(\nabla_L - \nabla_{\mathrm{ad}} < 0\)) across three prescriptions: 1. ThermohalineOption.KIPPENHAHN: Kippenhahn, Ruschenplatt, & Thomas (1980). 2. ThermohalineOption.TRAXLER_GARAUD_STELLMACH_11: Traxler, Garaud, & Stellmach (2011, ApJL, 728, L29, eq. 24). 3. ThermohalineOption.BROWN_GARAUD_STELLMACH_13: Brown, Garaud, & Stellmach (2013, ApJ, 768, 34, eqs. 19, 20, 33).

ThermohalineParams dataclass

Non-differentiable parameters for set_thermohaline.

Attributes:

Name Type Description
option ThermohalineOption

Thermohaline prescription (ThermohalineOption).

gradl_composition_term float

Dimensionless composition gradient term \(\nabla_L - \nabla_{\mathrm{ad}}\) (dlnMu/dlnP * chiY/chiT).

xh1 float

Hydrogen mass fraction \(X({}^1\mathrm{H})\) (dimensionless, in \([0, 1]\)).

thermohaline_coeff float

Dimensionless multiplicative efficiency factor \(\alpha_{\mathrm{th}}\).

species DrivingSpecies

Driving isotope charge and mass number (DrivingSpecies).

ThermohalineInputs dataclass

Differentiable thermodynamic and structure inputs for set_thermohaline.

Attributes:

Name Type Description
lambda_ ScalarOrDual

Mixing length \(\Lambda\) in \(\mathrm{cm}\).

grada ScalarOrDual

Adiabatic temperature gradient \(\nabla_{\mathrm{ad}}\).

gradr ScalarOrDual

Radiative temperature gradient \(\nabla_r\).

t ScalarOrDual

Temperature \(T\) in \(\mathrm{K}\).

opacity ScalarOrDual

Rosseland mean opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

rho ScalarOrDual

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

cp ScalarOrDual

Specific heat at constant pressure \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

get_d_thermohaline

get_d_thermohaline(
    option,
    grada,
    gradr,
    t,
    opacity,
    rho,
    cp,
    gradl_composition_term,
    species,
    xh1,
    thermohaline_coeff,
)

Compute scalar thermohaline diffusivity \(D_{\mathrm{thrm}}\) in CGS.

Matches get_D_thermohaline in turb/private/thermohaline.f90.

Parameters:

Name Type Description Default
option ThermohalineOption

Thermohaline prescription (ThermohalineOption).

required
grada float

Adiabatic gradient \(\nabla_{\mathrm{ad}}\) (dimensionless).

required
gradr float

Radiative gradient \(\nabla_r\) (dimensionless).

required
t float

Temperature \(T\) in \(\mathrm{K}\).

required
opacity float

Rosseland opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\).

required
rho float

Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\).

required
cp float

Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\).

required
gradl_composition_term float

\(\nabla_L - \nabla_{\mathrm{ad}}\).

required
species DrivingSpecies

Driving isotope \((Z, A)\) (DrivingSpecies).

required
xh1 float

Hydrogen mass fraction \(X({}^1\mathrm{H})\).

required
thermohaline_coeff float

Multiplicative efficiency factor.

required

Returns:

Type Description
float

Thermohaline diffusion coefficient \(D_{\mathrm{thrm}}\) in

float

\(\mathrm{cm^2\,s^{-1}}\).

set_thermohaline

set_thermohaline(params, inp)

Evaluate thermohaline mixing outputs (set_thermohaline in turb.f90).

Parameters:

Name Type Description Default
params ThermohalineParams

Non-differentiable configuration (ThermohalineParams).

required
inp ThermohalineInputs

Differentiable thermodynamic inputs (ThermohalineInputs).

required

Returns:

Type Description
TurbOutput

TurbOutput with mixing_type = MixingType.THERMOHALINE_MIXING.


Compiled Rust Extension Bridge (flexmesa._rust)

Low-level Safe Rust PyO3 bindings exposed via flexmesa._rust for constants, utilities, elementary math, automatic differentiation, splines, linear solvers, and convection (_ArrF64 denotes a float64 NumPy ndarray).

tier_a_data and tier_a_parse

  • const_probe_values (() -> list[float]): Returns the 23 CGS constants of flexmesa-const printed by upstream const/test, in order: pi, ln10, boltz_sigma, boltz_sigma*4, boltz_sigma*4/clight, boltz_sigma/clight, crad, secyer, Msun, Rsun, Lsun, ly, m_earth, au, amu, mn, mp, me, planck_h, qe, avo, clight, and kerg.
  • is_fortran_float_token ((token: str) -> bool): Returns True if token is a Fortran floating-point literal (standard IEEE literals, D/d exponents, or exponent-less 1.0-10 notation).
  • parse_fortran_float ((token: str) -> float): Parses a Fortran or IEEE-754 floating-point literal into f64, raising ValueError on invalid input.

math_solvers, math_hex_probe, and math_vec_audit

  • crmath_cos ((x: float) -> float): Evaluates \(\cos(x)\) using flexmesa_math::cos (crmath in strict mode).
  • crmath_exp ((x: float) -> float): Evaluates \(\exp(x)\) using flexmesa_math::exp (crmath in strict mode).
  • crmath_sin ((x: float) -> float): Evaluates \(\sin(x)\) using flexmesa_math::sin (crmath in strict mode).
  • exp10_array ((xs: _ArrF64) -> _ArrF64): Evaluates exp10 elementwise over a 1D C-contiguous f64 array.
  • safe_log_array ((xs: _ArrF64) -> _ArrF64): Evaluates safe_log elementwise over a 1D C-contiguous f64 array.
  • safe_log10_array ((xs: _ArrF64) -> _ArrF64): Evaluates safe_log10 elementwise over a 1D C-contiguous f64 array.
  • safe_sqrt_array ((xs: _ArrF64) -> _ArrF64): Evaluates safe_sqrt elementwise over a 1D C-contiguous f64 array.
  • eval_autodiff_order2_zone ((x: float, y: float) -> list[float]): Evaluates f(x, y) = exp(0.1*x*y) + x^1.5 / (y + 2) in AutoDiffReal2VarOrder2, returning [val, df_dx, df_dy, d2f_dx2, d2f_dxdy, d2f_dy2].
  • eval_autodiff_order2_batch ((x: _ArrF64, y: _ArrF64, parallel: bool = False) -> _ArrF64): Evaluates eval_autodiff_order2_zone across 1D arrays x, y of shape (nz,), dispatching across the persistent 4-thread rayon pool when parallel=True and nz >= 64.
  • solve_block_tridiag_bcyclic ((nvar: int, nz: int, lblk: _ArrF64, dblk: _ArrF64, ublk: _ArrF64, rhs: _ArrF64, parallel: bool = False) -> _ArrF64): Solves a block-tridiagonal system \(A x = b\) via Hirshman et al. (2010) odd-even block cyclic reduction (bcyclic); parallel=True runs the level reductions in the persistent 4-thread rayon pool.
  • mtx_solve_dense ((n: int, a_flat: _ArrF64, b: _ArrF64) -> _ArrF64): Solves a dense \(n \times n\) linear system \(A x = b\) via pure Rust LU.
  • math_test_suite_eval ((x: float) -> list[tuple[str, float]]): Evaluates 33 flexmesa_math scalar and integer/real-power functions at x, returning (name, value) pairs.
  • auto_diff_test_suite_values (() -> list[float]): Computes the auto_diff 1-variable, 2-variable, and AutoDiffRealStarOrder1 probe vector (387 f64 outputs).
  • strict_math_vectors_sha256 ((vec_path: str) -> tuple[int, str]): Evaluates all inputs in vec_path under NumericsMode::Strict and returns (vector_count, sha256_hex) over canonicalized (section, output_u64_be) records (#165).
  • compare_fast_vs_strict_vectors ((vec_path: str) -> list[tuple[str, int, int, int, int, float, float]]): Evaluates all inputs in vec_path under NumericsMode::Fast against NumericsMode::Strict (#165), returning (section, total, finite_pairs, nonfinite_mismatch_count, max_ulp, max_abs, max_rel) in section order.
  • measure_dispatch_overhead_ns ((n_iters: int) -> tuple[float, float, float, float]): Measures (strict_exp_ns, fast_exp_ns, strict_fma_ns, fast_fma_ns) over n_iters black-boxed calls (#165).

interp_2d

  • interp_evbicub_batch ((x_q: _ArrF64, y_q: _ArrF64, x: _ArrF64, y: _ArrF64, coeffs_flat: _ArrF64, parallel: bool = False) -> _ArrF64): Evaluates a 2D bicubic spline over 1D query arrays x_q, y_q of shape (nz,), returning a (nz, 6) array and dispatching across the persistent 4-thread rayon pool when parallel=True and nz >= 64.

turb_py

  • set_mlt_f64 ((option: str, mixing_length_alpha: float, henyey_y_param: float, henyey_nu_param: float, chi_t: float, chi_rho: float, cp: float, grav: float, lambda_mlt: float, rho: float, p: float, t: float, opacity: float, gradr: float, grada: float, gradl: float) -> tuple[list[float], int]): Evaluates set_mlt in f64 at a single zone across all 6 geometric MLT prescriptions ("Cox", "TDC", "Henyey", "ML1", "ML2", "Mihalas") with local CGS inputs, dimensionless \(\alpha\), and Henyey \((y, \nu)\) parameters, returning ([gamma, grad_t, y_face, conv_vel, d], mixing_type_code).
  • set_mlt_batch ((s_frac: _ArrF64, parallel: bool = False) -> _ArrF64): Evaluates Cox (1968) MLT with DualOrder1<6> sensitivities across s_frac, dispatching across the persistent 4-thread rayon worker pool when parallel=True and nz >= 64.
  • turb_set_tdc_f64 ((params: Sequence[float], include_mlt_corr_to_tdc: bool, use_tdc_enthalpy_flux_limiter: bool, inputs: Sequence[float]) -> tuple[float, float, float, float, float, int]): Evaluates Time-Dependent Convection (set_TDC in turb/public/turb.f90) at one point with CGS params (conv_vel_start, mixing_length_alpha, tdc_alpha_d, tdc_alpha_r, tdc_alpha_pt, tdc_alpha_c, tdc_alpha_s, dt, cgrav, m, scale, max_conv_vel) and inputs (chi_t, chi_rho, gradr, r, p, t, rho, dv, cp, opacity, scale_height, gradl, grada, eq_div_w, grav, energy), returning (gamma, grad_t, y_face, conv_vel, d, num_iters).
  • set_tdc_batch ((s_frac: _ArrF64, parallel: bool = False) -> _ArrF64): Evaluates Kuhfuss (1986) TDC with DualOrder1<6> sensitivities across s_frac, dispatching across the persistent 4-thread rayon worker pool when parallel=True and nz >= 32.