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
¶
Convert an integer mixing code from MESA into a MixingType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
Integer mixing code ( |
required |
Returns:
| Type | Description |
|---|---|
MixingType | None
|
Corresponding |
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 vendoredcrlibm 1.0beta4(CRMATH 1.2from MESA SDK26.6.1, encapsulated inflexmesa-crlibm-sys, the sole workspace crate permitted to useunsafeFFI under#![deny(unsafe_op_in_unsafe_fn)]). Its contract is"correctly rounded toward zero as CRMATH does it"(*_rz, with*_rdforexp,acos, andacospi, plus*_rnonatan2andintrinsic_{log,log10,exp,pow}for upstream platform-libmcall sites tracked in#196and#198), explicit multiplication chains forpow2throughpow8andpow_i_/pow_r_/exp10_, anda * b + cwith no fused multiply-add contraction."strict"is the only mode judged against MESA26.4.1, across three fidelity levels:- Level 1:
"strict"mode is bit-identical across machines (x86_64andaarch64) and thread counts (1vs.4rayonthreads), enforced in CI. - Level 2:
"strict"kernels are bit-identical to MESA26.4.1against exact hexadecimal reference outputs wherever operations and evaluation order match (474,062tested inputs across47math sections inmesa_26_4_1_vectors.rs). - Level 3: Whole evolutionary trajectories are compared against real MESA
26.4.1histories within the#143history-harness tolerances (notes/audit/case_table.md). "fast": Evaluates platformstdf64intrinsics with hardwaremul_addpermitted."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.
safe_sqrt
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
Examples:
safe_log
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
Examples:
safe_log10
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
Examples:
log
¶
Compute the natural logarithm \(\ln(x)\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Positive scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
log10
¶
Compute the base-10 logarithm \(\log_{10}(x)\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Positive scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
log1p
¶
Compute \(\ln(1 + x)\) without cancellation near \(x = 0\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
log2
¶
Compute \(\log_{2}(x)\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Positive scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
exp
¶
Compute the natural exponential \(e^{x}\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
expm1
¶
Compute \(e^{x} - 1\) without cancellation near \(x = 0\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
exp10
¶
Compute the base-10 exponential \(10^{x} = \exp(x \ln 10)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
pow
¶
Raise base to power exponent (\(x^{y}\)) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
ArrayLike
|
Base scalar or array of shape |
required |
exponent
|
ArrayLike
|
Exponent scalar or array broadcastable to |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
powm1
¶
Compute the reciprocal \(x^{-1} = 1 / x\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
ArrayLike
|
Nonzero scalar or array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
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).
sgn
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
heaviside
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
str_to_double
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
float
|
Parsed Python |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
str_to_vector
¶
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 |
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; raisesValueErrorunlessmodeis"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.
define_and_report_duplicates
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
define
¶
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 |
required |
lookup
¶
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 |
entries
¶
Return all (key, value) pairs sorted lexicographically by key.
Returns:
| Type | Description |
|---|---|
list[tuple[str, int]]
|
Sorted list of |
IntegerIdict
¶
Integer-pair (k1, k2) dictionary matching MESA integer_idict.
define_and_report_duplicates
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
define
¶
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 |
required |
lookup
¶
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 |
entries
¶
Return all (key1, key2, value) tuples sorted by (key1, key2).
Returns:
| Type | Description |
|---|---|
list[tuple[int, int, int]]
|
Sorted list of |
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 ( |
value |
str
|
Text payload for |
Tokenizer
¶
Stateful stream tokenizer matching upstream MESA utils_lib::token.
__init__
¶
Initialize the tokenizer over text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Full multi-line input text to tokenize. |
required |
is_bad
¶
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 ( |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
is_bad_array
¶
Return True if any element in values is NaN or infinite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ndarray | Array
|
Array of arbitrary shape |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
replace_bad_nums
¶
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 |
required |
replacement
|
float
|
Finite scalar value substituted for non-finite entries. |
-1e+99
|
Returns:
| Type | Description |
|---|---|
Array
|
Array of shape |
Array
|
entries replaced by |
remove_underbars
¶
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 |
split_line
¶
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 |
tokenize
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
list[Token]
|
Sequence of |
list[Token]
|
|
Examples:
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.
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 |
d1 |
Array
|
First-order partial derivatives |
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])
tree_unflatten
classmethod
¶
Reconstruct DualOrder1 from flattened (val, d1) leaves.
constant
classmethod
¶
Construct a constant DualOrder1 with num_vars zero partials.
independent
classmethod
¶
Seed the index-th independent variable (\(\partial_i x_i = 1\)).
make_unary_operator
¶
Apply the first-order unary chain rule \(z = f(x)\).
make_binary_operator
¶
Apply the first-order binary chain rule \(z = g(x, y)\).
AutoDiffReal1VarOrder1
¶
AutoDiffReal2VarOrder1
¶
AutoDiffReal4VarOrder1
¶
AutoDiffRealStarOrder1
¶
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 |
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)
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_safe_sqrt
¶
Return (f, f', f'') for \(\sqrt{\max(x, 0)}\) without 0.0 * Inf.
unary_pow_scalar
¶
Return (f, f', f'') for \(x^{p}\) with constant exponent \(p\).
unary_rpow_scalar
¶
Return (f, f', f'') for \(b^{x}\) with constant base \(b > 0\).
binary_pow
¶
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
¶
Validates strictly monotonic 1D knot coordinates and finite values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
1D array of knot coordinates of shape |
required |
y
|
ndarray | ndarray
|
1D array of knot values of shape |
required |
min_points
|
int
|
Minimum number of knots required. |
2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple |
ndarray
|
shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes mismatch, |
interp_pm
¶
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 |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
coefficients |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_pm_slopes_only
¶
Computes only the knot values and Steffen (1990) monotonic slopes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
Knot coordinates of shape |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
JAX |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_4pt_pm
¶
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
|
required |
y
|
Sequence[float] | ndarray | ndarray
|
4-element knot value sequence of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_pm_autodiff
¶
Computes Steffen (1990) cubic coefficients on DualOrder1 knots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Sequence[DualOrder1]
|
Sequence of |
required |
y
|
Sequence[DualOrder1]
|
Sequence of |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[DualOrder1, DualOrder1, DualOrder1, DualOrder1]]
|
List of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
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 |
minmod4
¶
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 |
median
¶
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 |
interp_m3
¶
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 |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
which
|
str | MpLimiter
|
Slope-limiter variant ( |
QUARTIC
|
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
at each knot. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_m3a
¶
Computes Huynh (1993) average-slope MP coefficients (interp_m3a).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
Knot coordinates of shape |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
each knot. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_m3b
¶
Computes Huynh (1993) superbee-slope MP coefficients (interp_m3b).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
Knot coordinates of shape |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
each knot. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_m3q
¶
Computes Huynh (1993) quartic-slope MP coefficients (interp_m3q).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
Knot coordinates of shape |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
each knot. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
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 |
required |
coeffs
|
ndarray | ndarray
|
Spline coefficient array of shape |
required |
xs
|
ndarray | ndarray
|
Query coordinates of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray | ndarray, ndarray | ndarray]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_values
¶
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 |
required |
coeffs
|
ndarray | ndarray
|
Spline coefficient array of shape |
required |
xs
|
ndarray | ndarray
|
Query coordinates of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_value_and_slope
¶
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 |
required |
coeffs
|
ndarray | ndarray
|
Spline coefficient array of shape |
required |
x
|
float | ndarray
|
Scalar query coordinate in physical or dimensionless units. |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray | ndarray, ndarray | ndarray]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_value
¶
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 |
required |
coeffs
|
ndarray | ndarray
|
Spline coefficient array of shape |
required |
x
|
float | ndarray
|
Scalar query coordinate in physical or dimensionless units. |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
Scalar |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
integrate_values
¶
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 |
required |
coeffs
|
ndarray | ndarray
|
Spline coefficient array of shape |
required |
xs
|
ndarray | ndarray
|
Monotonic integration bounds of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Interpolates (old_x, old_y) onto new_x using builder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_x
|
ndarray | ndarray
|
Source knot coordinates of shape |
required |
old_y
|
ndarray | ndarray
|
Source knot values of shape |
required |
new_x
|
ndarray | ndarray
|
Target query coordinates of shape |
required |
builder
|
Callable[[ndarray | ndarray, ndarray | ndarray], ndarray | ndarray]
|
Spline builder callable returning an |
interp_pm
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
at |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interpolate_vector_pm
¶
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 |
required |
old_y
|
ndarray | ndarray
|
Source knot values of shape |
required |
new_x
|
ndarray | ndarray
|
Target query coordinates of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
interpolated values at |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_values_autodiff
¶
Evaluates a 1D cubic spline over DualOrder1 queries (O(M log N)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_x
|
Sequence[DualOrder1]
|
Sequence of |
required |
coeffs
|
Sequence[tuple[DualOrder1, DualOrder1, DualOrder1, DualOrder1]]
|
Sequence of |
required |
x
|
Sequence[DualOrder1]
|
Sequence of |
required |
Returns:
| Type | Description |
|---|---|
list[DualOrder1]
|
List of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interpolate_vector_pm_autodiff
¶
Interpolates DualOrder1 vectors via Steffen (1990) interp_pm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_x
|
Sequence[DualOrder1]
|
Sequence of |
required |
old_y
|
Sequence[DualOrder1]
|
Sequence of |
required |
new_x
|
Sequence[DualOrder1]
|
Sequence of |
required |
Returns:
| Type | Description |
|---|---|
list[DualOrder1]
|
List of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If spline construction or evaluation fails validation. |
interp_3_to_1
¶
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source spacings are non-monotonic or inputs are non-finite. |
interp_3_to_2
¶
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 |
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 |
float
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source spacings are non-monotonic or inputs are non-finite. |
interp_4_to_1
¶
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 |
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 |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
z
|
ndarray | ndarray
|
Grid values of shape |
required |
ibcxmin
|
BicubicBc | int
|
Boundary condition at |
NOT_A_KNOT
|
bcxmin
|
ndarray | ndarray | None
|
Boundary data of shape |
None
|
ibcxmax
|
BicubicBc | int
|
Boundary condition at |
NOT_A_KNOT
|
bcxmax
|
ndarray | ndarray | None
|
Boundary data of shape |
None
|
ibcymin
|
BicubicBc | int
|
Boundary condition at |
NOT_A_KNOT
|
bcymin
|
ndarray | ndarray | None
|
Boundary data of shape |
None
|
ibcymax
|
BicubicBc | int
|
Boundary condition at |
NOT_A_KNOT
|
bcymax
|
ndarray | ndarray | None
|
Boundary data of shape |
None
|
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
Tuple |
bool
|
array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If grid dimensions are |
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 |
df_dx |
ndarray
|
First partial derivative |
df_dy |
ndarray
|
First partial derivative |
d2f_dx2 |
ndarray
|
Second partial derivative |
d2f_dy2 |
ndarray
|
Second partial derivative |
d2f_dxdy |
ndarray
|
Mixed second partial derivative |
herm2xy_db
¶
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 |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
ilinx
|
bool
|
Whether |
True
|
iliny
|
bool
|
Whether |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
8-tuple |
ndarray
|
JAX scalars. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
interp_evbicub_db
¶
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 |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
ilinx
|
bool
|
Uniform spacing flag for |
required |
iliny
|
bool
|
Uniform spacing flag for |
required |
coeffs
|
ndarray | ndarray
|
Bicubic coefficient array of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
BicubicEval
|
class: |
BicubicEval
|
d2f_dxdy)``. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If grid dimensions are |
interp_evbicub_mask_db
¶
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 |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
ilinx
|
bool
|
Uniform spacing flag for |
required |
iliny
|
bool
|
Uniform spacing flag for |
required |
coeffs
|
ndarray | ndarray
|
Bicubic coefficient array of shape |
required |
ict
|
Sequence[int | bool]
|
6-element selector sequence for |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
JAX |
ndarray
|
packed from index 0. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Evaluates Akima (1996) bivariate interpolation at points (xi, yi).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xd
|
ndarray | ndarray
|
Strictly ascending x-grid of shape |
required |
yd
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
zd
|
ndarray | ndarray
|
Grid values of shape |
required |
xi
|
ndarray | ndarray
|
Query x-coordinates of shape |
required |
yi
|
ndarray | ndarray
|
Query y-coordinates of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
JAX |
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
¶
Evaluates Akima (1996) surface fitting on target grid (xi, yi).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xd
|
ndarray | ndarray
|
Strictly ascending x-grid of shape |
required |
yd
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
zd
|
ndarray | ndarray
|
Grid values of shape |
required |
xi
|
ndarray | ndarray
|
1D target x-grid of shape |
required |
yi
|
ndarray | ndarray
|
1D target y-grid of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
JAX |
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
¶
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 |
required |
yd
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
zd
|
ndarray | ndarray
|
Grid values of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
JAX |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
flexmesa.interp_2d.bipm
¶
Two-dimensional piecewise-monotonic cubic interpolation (bipm_db).
interp_mkbipm_db
¶
Constructs 2D piecewise-monotonic cubic spline coefficients along x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
Strictly ascending x-grid of shape |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
z
|
ndarray | ndarray
|
Grid values of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray | ndarray
|
|
ndarray | ndarray
|
Steffen (1990) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If grid dimensions are |
interp_evbipm_db
¶
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 |
required |
yget
|
float | ndarray
|
Query y-coordinate in |
required |
x
|
ndarray | ndarray
|
Strictly ascending x-grid of shape |
required |
y
|
ndarray | ndarray
|
Strictly ascending y-grid of shape |
required |
coeffs
|
ndarray | ndarray
|
Coefficient array of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
float | ndarray | ndarray
|
Scalar |
Raises:
| Type | Description |
|---|---|
ValueError
|
If grid dimensions are |
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 a scattered 2D cubic Shepard interpolant (interp_cshep2_db).
interp_cshep2_db
¶
Fit a scattered 2D cubic Shepard interpolant (interp_cshep2_db).
interp_cs2val_db
¶
Evaluate scattered 2D cubic Shepard interpolant (interp_cs2val_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 ( |
|
NOT_A_KNOT |
Not-a-knot boundary condition ( |
|
FIRST_DERIV |
Match specified first derivative ( |
|
SECOND_DERIV |
Match specified second derivative ( |
|
ZERO_FIRST_DERIV |
Zero first derivative ( |
|
ZERO_SECOND_DERIV |
Natural spline / zero second derivative ( |
|
DIVIDED_DIFF_1 |
Match first divided difference ( |
|
DIVIDED_DIFF_2 |
Match second divided difference ( |
|
DIVIDED_DIFF_3 |
Match third divided difference ( |
splinck_db
¶
Checks strict ascending order and approximate uniform spacing of x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
1D coordinate array of shape |
required |
ztol
|
float
|
Relative spacing tolerance (default |
0.001
|
axis
|
str
|
Axis label for error reporting. |
'x'
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
reshape_grid_2d
¶
Validates and reshapes a 2D or flat grid array to (nx, ny).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
ndarray | ndarray
|
Grid values of shape |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
y
|
ndarray | ndarray
|
Knot values of shape |
required |
ibcxmin
|
BicubicBc | int
|
Left boundary condition code in |
NOT_A_KNOT
|
bcxmin
|
float
|
Left boundary value (used when |
0.0
|
ibcxmax
|
BicubicBc | int
|
Right boundary condition code in |
NOT_A_KNOT
|
bcxmax
|
float
|
Right boundary value (used when |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple |
bool
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Computes the LU factorization \(P A = L U\) with partial pivoting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ArrayLike
|
Dense square matrix of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Tuple |
NDArray[int64]
|
unit lower-triangular \(L\) strictly below the diagonal and upper |
tuple[NDArray[float64], NDArray[int64]]
|
triangular \(U\) on/above the diagonal, and |
tuple[NDArray[float64], NDArray[int64]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dgetrs
¶
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 |
required |
ipiv
|
ArrayLike
|
0-based pivot array of shape |
required |
b
|
ArrayLike
|
Right-hand side vector of shape |
required |
trans
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes mismatch, inputs are non-finite, or \(U\) is singular. |
solve_dense
¶
Solves the dense linear system \(A x = b\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ArrayLike
|
Dense coefficient matrix of shape |
required |
b
|
ArrayLike
|
Right-hand side vector of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
multiply_xa
¶
Evaluates \(b = x^{\top} A\) (or \(x^{\top} A + c\)) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ArrayLike
|
Dense matrix of shape |
required |
x
|
ArrayLike
|
Left vector of shape |
required |
c
|
ArrayLike | None
|
Optional additive vector of shape |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Row-vector product of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If input dimensions do not match |
lu_factored_square_mv
¶
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 |
required |
ipiv
|
ArrayLike
|
0-based pivot indices of shape |
required |
x
|
ArrayLike
|
Input vector of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Product vector \(y = A x\) of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes do not match |
lu_factored_square_mm
¶
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 |
required |
ipiv
|
ArrayLike
|
0-based pivot indices of shape |
required |
b
|
ArrayLike
|
Right-hand matrix of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Product matrix \(C = A B\) of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dimensions do not match |
rcond_dense
¶
Estimates the 1-norm reciprocal condition number \(\mathrm{rcond}(A)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ArrayLike
|
Unfactored matrix of shape |
required |
lu
|
ArrayLike
|
Factored LU matrix of shape |
required |
ipiv
|
ArrayLike
|
0-based pivot indices of shape |
required |
Returns:
| Type | Description |
|---|---|
float
|
Reciprocal 1-norm condition number in \([0, 1]\) (dimensionless). |
solve_dense_jax
¶
Differentiable dense linear solver \(A(p) x(p) = b(p)\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Array
|
Dense JAX array of shape |
required |
b
|
Array
|
Right-hand side JAX array of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Solution JAX array |
Array
|
and |
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
¶
Converts a dense (N, N) matrix a into band storage (ldab, N).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ArrayLike
|
Dense square matrix of shape |
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Banded matrix |
Raises:
| Type | Description |
|---|---|
ValueError
|
If bandwidths or |
band_to_dense
¶
Converts a banded matrix ab of shape (ldab, N) to dense (N, N).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
ArrayLike
|
Banded matrix of shape |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
band_multiply_xa
¶
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Row-vector product \(b = x^{\top} A\) of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dimensions do not match |
dgbtrf
¶
Computes the banded LU factorization \(P A = L U\) (dgbtrf).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
ArrayLike
|
Banded matrix of shape |
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 |
NDArray[int64]
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dimensions are invalid, inputs are non-finite, or a pivot is zero. |
dgbtrs
¶
Solves \(A x = b\) using the banded LU factorization from [dgbtrf].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lu_ab
|
ArrayLike
|
Factored band buffer of shape |
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 |
required |
b
|
ArrayLike
|
Right-hand side vector of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution vector |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes mismatch, inputs are non-finite, or \(U\) is singular. |
solve_banded
¶
Factors and solves a banded linear system \(A x = b\) in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
ArrayLike
|
Banded matrix of shape |
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 |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution vector |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes mismatch, inputs are non-finite, or \(A\) is singular. |
rcond_banded
¶
Estimates the 1-norm reciprocal condition number of a banded matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
ArrayLike
|
Unfactored band buffer |
required |
lu_ab
|
ArrayLike
|
Factored band buffer |
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 |
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
¶
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 |
required |
dblk
|
ArrayLike
|
Diagonal blocks of shape |
required |
ublk
|
ArrayLike
|
Super-diagonal blocks of shape |
required |
b
|
ArrayLike
|
Input vector of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Product array matching the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If block or vector dimensions do not match. |
block_multiply_xa
¶
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 |
required |
dblk
|
ArrayLike
|
Diagonal blocks |
required |
ublk
|
ArrayLike
|
Super-diagonal blocks |
required |
x
|
ArrayLike
|
Left vector of shape |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Upstream's product, matching the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If block or vector dimensions do not match. |
block_thomas_factor
¶
Factors a block-tridiagonal system via the block Thomas algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
ArrayLike
|
Sub-diagonal blocks |
required |
dblk
|
ArrayLike
|
Diagonal blocks |
required |
ublk
|
ArrayLike
|
Super-diagonal blocks |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Tuple |
NDArray[float64]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any diagonal block is singular or shapes are invalid. |
block_thomas_solve
¶
Solves a block-tridiagonal system from [block_thomas_factor] factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
ArrayLike
|
Sub-diagonal blocks |
required |
d_factored
|
ArrayLike
|
Factored diagonal blocks |
required |
u_factored
|
ArrayLike
|
Factored super-diagonal blocks |
required |
ipiv
|
ArrayLike
|
Pivot array |
required |
b
|
ArrayLike
|
Right-hand side of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If block dimensions mismatch or a diagonal block is singular. |
solve_block_tridiagonal
¶
Factors and solves a block-tridiagonal linear system \(A x = b\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
ArrayLike
|
Sub-diagonal blocks |
required |
dblk
|
ArrayLike
|
Diagonal blocks |
required |
ublk
|
ArrayLike
|
Super-diagonal blocks |
required |
b
|
ArrayLike
|
Right-hand side |
required |
method
|
Literal['thomas', 'bcyclic']
|
Solver algorithm ( |
'thomas'
|
parallel
|
bool
|
When |
False
|
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Solution array |
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
¶
Differentiable block-tridiagonal linear solver in JAX float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
Array
|
Sub-diagonal JAX array |
required |
dblk
|
Array
|
Diagonal JAX array |
required |
ublk
|
Array
|
Super-diagonal JAX array |
required |
b
|
Array
|
Right-hand side JAX array |
required |
solver_mode
|
SolverMode
|
JAX solver strategy ( |
'pcr'
|
Returns:
| Type | Description |
|---|---|
Array
|
Solution JAX array |
Array
|
(dimensionless), differentiable via |
Array
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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):
solve_block_tridiag_pcr(solver_mode="pcr"): Vectorized Hockney & Jesshope (1981) / Hirshman et al. (2010) parallel block cyclic reduction in pure JAXfloat64. Replaces the \(2 n_z\) sequentialjax.lax.scansteps 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.solve_block_tridiag_rust_ffi(solver_mode="rust_ffi"): Zero-copy host callback to Safe Rust's Hirshman et al. (2010)solve_block_tridiag_bcyclicviajax.pure_callback, paired with an analytical Implicit Function Theorem@jax.custom_vjprule that solves the transpose block-tridiagonal adjoint system \(A^\top \lambda = \bar{x}\).
validate_jax_blocks
¶
Coerces (lblk, dblk, ublk, b) to JAX float64 and validates shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
Array
|
Sub-diagonal blocks of shape |
required |
dblk
|
Array
|
Diagonal blocks of shape |
required |
ublk
|
Array
|
Super-diagonal blocks of shape |
required |
b
|
Array
|
Right-hand side of shape |
required |
Returns:
| Type | Description |
|---|---|
tuple[Array, Array, Array, Array, int, int]
|
Six-tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If array ranks or dimensions are incompatible. |
solve_block_tridiag_pcr
¶
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:
and eliminates couplings at distance \(\pm s\) across all \(n_z\) shells in parallel via two fused batched matrix-matrix products:
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 |
required |
dblk
|
Array
|
Diagonal blocks of shape |
required |
ublk
|
Array
|
Super-diagonal blocks of shape |
required |
b
|
Array
|
Right-hand side of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Solution array |
Array
|
compatible with |
Array
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If input array ranks or dimensions are incompatible. |
solve_block_tridiag_rust_ffi
¶
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}\):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lblk
|
Array
|
Sub-diagonal blocks of shape |
required |
dblk
|
Array
|
Diagonal blocks of shape |
required |
ublk
|
Array
|
Super-diagonal blocks of shape |
required |
b
|
Array
|
Right-hand side of shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Solution array |
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
¶
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 |
required |
include_diag
|
bool
|
Retain zero diagonal entries when |
False
|
Returns:
| Type | Description |
|---|---|
NDArray[int64]
|
Tuple |
NDArray[int64]
|
non-zero values in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dense_to_row_0_based
¶
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 |
required |
include_diag
|
bool
|
Retain zero diagonal entries when |
False
|
Returns:
| Type | Description |
|---|---|
NDArray[int64]
|
Tuple |
NDArray[int64]
|
values in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
row_sparse_to_dense
¶
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 |
required |
colind
|
ArrayLike
|
1-based column index array of shape |
required |
values
|
ArrayLike
|
Non-zero values of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Dense matrix of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pointer or index bounds are invalid. |
row_sparse_0_based_to_dense
¶
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 |
required |
colind
|
ArrayLike
|
0-based column index array of shape |
required |
values
|
ArrayLike
|
Non-zero values of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Dense matrix of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
Always raised because upstream reads out of bounds on
every call ( |
dense_to_col_sparse
¶
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 |
required |
include_diag
|
bool
|
Retain zero diagonal entries when |
False
|
Returns:
| Type | Description |
|---|---|
tuple[NDArray[int64], NDArray[int64], NDArray[float64]]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dense_to_col_0_based
¶
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 |
required |
include_diag
|
bool
|
Retain zero diagonal entries when |
False
|
Returns:
| Type | Description |
|---|---|
tuple[NDArray[int64], NDArray[int64], NDArray[float64]]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
column_sparse_to_dense
¶
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 |
required |
rowind
|
ArrayLike
|
1-based row index array of shape |
required |
values
|
ArrayLike
|
Non-zero values of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Dense matrix of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pointer or index bounds are invalid. |
col_sparse_0_based_to_dense
¶
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 |
required |
rowind
|
ArrayLike
|
0-based row index array of shape |
required |
values
|
ArrayLike
|
Non-zero values of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Dense matrix of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pointer or index bounds are invalid. |
find_loc_in_sparse
¶
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 [ |
required |
n
|
int
|
Matrix dimension \(N \ge 1\). |
required |
ia
|
ArrayLike
|
Outer pointer array of shape |
required |
ja
|
ArrayLike
|
Inner index array of shape |
required |
i
|
int
|
Row index (1-based or 0-based matching |
required |
j
|
int
|
Column index (1-based or 0-based matching |
required |
hint
|
int | None
|
Optional previous location hint in the same index base. |
None
|
Returns:
| Type | Description |
|---|---|
int | None
|
Index into |
int | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If \(f(a)\) and \(f(b)\) have the same strict sign. |
RuntimeError
|
If |
eval_brent_safe_zero
¶
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 |
required |
func
|
Callable[[float], float]
|
Scalar callable |
required |
fa_in
|
float
|
Caller-supplied value |
required |
fb_in
|
float
|
Caller-supplied value |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
brent_local_min
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If \(a \ge b\), \(\epsilon \le 0\), or \(t < 0\). |
local_min
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
brent_global_min
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If \(a \ge b\) or inputs/outputs are non-finite. |
glomin
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
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
¶
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 |
required |
imax
|
int
|
Maximum outward expansion steps. |
50
|
Returns:
| Type | Description |
|---|---|
tuple[tuple[float, float], tuple[float, float]]
|
Nested tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
safe_root_with_brackets
¶
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 |
required |
x1_in
|
float
|
First bracket endpoint. |
required |
x3_in
|
float
|
Second bracket endpoint. |
required |
y1_in
|
float
|
Function value |
required |
y3_in
|
float
|
Function value |
required |
imax
|
int
|
Ignored, matching |
100
|
epsx
|
float
|
Abscissa convergence tolerance. |
1e-12
|
epsy
|
float
|
Residual convergence tolerance on |
1e-12
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
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 |
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 |
None
|
y3_opt
|
float | None
|
Optional function value at |
None
|
newt_imax
|
int
|
Maximum pure Newton steps before bracketing. |
10
|
imax
|
int
|
Bracketing step budget passed to :func: |
100
|
epsx
|
float
|
Abscissa tolerance. |
1e-12
|
epsy
|
float
|
Residual tolerance. |
1e-12
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
Propagated from |
safe_root_without_brackets
¶
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 |
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 |
100
|
epsx
|
float
|
Abscissa tolerance. |
1e-12
|
epsy
|
float
|
Residual tolerance. |
1e-12
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
Propagated from :func: |
safe_root_jax
¶
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 |
required |
x1
|
float
|
Lower bracket endpoint. |
required |
x3
|
float
|
Upper bracket endpoint. |
required |
params
|
Array
|
1D JAX parameter array of shape |
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 |
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 |
iterations |
int
|
Number of Newton iterations completed. |
residual_norm |
float
|
Final RMS residual norm. |
correction_norm |
float
|
Final RMS correction norm. |
newton_solve_dense
¶
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 |
required |
eval_res
|
Callable[[NDArray[float64]], ArrayLike]
|
Residual callable |
required |
eval_jac
|
Callable[[NDArray[float64]], ArrayLike]
|
Jacobian callable |
required |
config
|
NewtonConfig | None
|
Optional :class: |
None
|
Returns:
| Type | Description |
|---|---|
NewtonResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs, residuals, or Jacobians are invalid or singular. |
RuntimeError
|
If |
newton_solve_banded
¶
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 |
required |
eval_res
|
Callable[[NDArray[float64]], ArrayLike]
|
Residual callable |
required |
eval_jac_band
|
Callable[[NDArray[float64]], ArrayLike]
|
Banded Jacobian callable returning |
required |
config
|
NewtonConfig | None
|
Optional :class: |
None
|
Returns:
| Type | Description |
|---|---|
NewtonResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs, residuals, or Jacobians are invalid or singular. |
RuntimeError
|
If |
newton_solve_block_tridiagonal
¶
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 |
required |
eval_res
|
Callable[[NDArray[float64]], ArrayLike]
|
Residual callable returning shape |
required |
eval_blocks
|
Callable[[NDArray[float64]], tuple[ArrayLike, ArrayLike, ArrayLike]]
|
Callable returning |
required |
config
|
NewtonConfig | None
|
Optional :class: |
None
|
Returns:
| Type | Description |
|---|---|
NewtonResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs, residuals, or blocks are invalid or singular. |
RuntimeError
|
If |
newton_solve_jax
¶
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 |
required |
y_init
|
Array
|
Initial guess of shape |
required |
params
|
Array
|
Parameter vector of shape |
required |
max_iter
|
int
|
Maximum Newton iterations. |
30
|
tol
|
float
|
Residual norm stopping tolerance. |
1e-12
|
Returns:
| Type | Description |
|---|---|
Array
|
Converged state |
Array
|
and |
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
¶
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 |
required |
func
|
Callable[[float], float]
|
Scalar callable |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
integrate
¶
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 |
required |
min_x
|
float
|
Lower integration limit. |
required |
max_x
|
float
|
Upper integration limit. |
required |
eps
|
float
|
Local truncation error tolerance ( |
1e-08
|
max_steps
|
int
|
Maximum integrand evaluations allowed. |
20000
|
Returns:
| Type | Description |
|---|---|
tuple[float, int]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If limits are non-finite or |
RuntimeError
|
If |
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 |
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 |
dense_eval
¶
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 |
rk2
¶
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 |
required |
h
|
float
|
Step size. |
required |
derivs
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Updated state array of shape |
rk4
¶
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 |
required |
h
|
float
|
Step size. |
required |
derivs
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Updated state array of shape |
dopri5
¶
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 |
required |
fcn
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Right-hand side callable |
required |
h0
|
float
|
Initial trial step size ( |
0.0
|
hmax
|
float
|
Maximum step size magnitude ( |
0.0
|
rtol
|
float
|
Relative local error tolerance ( |
1e-08
|
atol
|
float
|
Absolute local error tolerance ( |
1e-08
|
max_steps
|
int
|
Maximum integration steps allowed. |
100000
|
Returns:
| Type | Description |
|---|---|
DopriResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If |
dop853
¶
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 |
required |
fcn
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Right-hand side callable |
required |
h0
|
float
|
Initial trial step size. |
0.0
|
hmax
|
float
|
Maximum step size magnitude. |
0.0
|
rtol
|
float
|
Relative local error tolerance ( |
1e-10
|
atol
|
float
|
Absolute local error tolerance ( |
1e-10
|
max_steps
|
int
|
Maximum integration steps allowed. |
100000
|
Returns:
| Type | Description |
|---|---|
DopriResult
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If |
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 |
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: |
required |
t0
|
float
|
Initial time (dimensionless). |
required |
t_end
|
float
|
Final time (dimensionless). |
required |
y0
|
ArrayLike
|
Initial state vector of shape |
required |
fcn
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Right-hand side callable |
required |
jac
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Jacobian callable |
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tolerances are invalid, stage matrices are singular, or local errors are non-finite. |
RuntimeError
|
If |
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: |
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 |
required |
fcn
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Right-hand side callable |
required |
jac_dense
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Jacobian callable |
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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tolerances or bandwidths are invalid, stage matrices are singular, or local errors are non-finite. |
RuntimeError
|
If |
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: |
required |
mass_diag
|
ArrayLike
|
Diagonal mass matrix entries of shape |
required |
t0
|
float
|
Initial time (dimensionless). |
required |
t_end
|
float
|
Final time (dimensionless). |
required |
y0
|
ArrayLike
|
Initial state vector of shape |
required |
fcn
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Right-hand side callable |
required |
jac
|
Callable[[float, NDArray[float64]], ArrayLike]
|
Jacobian callable |
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: |
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
¶
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 |
neumaier_sum
¶
Evaluates the Neumaier compensated sum of a 1D array in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
1D sequence of shape |
required |
Returns:
| Type | Description |
|---|---|
float
|
Compensated scalar sum in |
binary_search
¶
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 |
required |
val
|
float
|
Query value (same physical units as |
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 |
binary_search_1based
¶
1-based wrapper around :func:binary_search matching upstream Fortran.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vec
|
ArrayLike
|
1D monotonic knot vector of shape |
required |
val
|
float
|
Query value (same physical units as |
required |
hint
|
int
|
1-based interval hint ( |
0
|
Returns:
| Type | Description |
|---|---|
int
|
1-based index in |
qsort_index
¶
Returns 0-based permutation indices sorting vals ascending.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vals
|
ArrayLike
|
1D array of shape |
required |
Returns:
| Type | Description |
|---|---|
NDArray[intp]
|
Integer index array |
NDArray[intp]
|
is non-decreasing. |
linear_interp
¶
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 |
find0
¶
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 |
required |
x2
|
float
|
Second abscissa. |
required |
y2
|
float
|
Function value at |
required |
Returns:
| Type | Description |
|---|---|
float
|
Secant zero abscissa |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
find0_quadratic
¶
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 |
required |
x2
|
float
|
Interior abscissa strictly between |
required |
y2
|
float
|
Function value at |
required |
x3
|
float
|
Third abscissa. |
required |
y3
|
float
|
Function value at |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If abscissas are not strictly monotonic or |
find_max_quadratic
¶
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 |
required |
x2
|
float
|
Interior abscissa between |
required |
y2
|
float
|
Function value at |
required |
x3
|
float
|
Third abscissa. |
required |
y3
|
float
|
Function value at |
required |
Returns:
| Type | Description |
|---|---|
float
|
Tuple |
float
|
|
two_piece_linear_coeffs
¶
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 |
float
|
\(f(x) = a_0 f(x_0) + a_1 f(x_1) + a_2 f(x_2)\). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
beta |
float
|
Expansion coefficient (default |
gamma |
float
|
Contraction coefficient (default |
delta |
float
|
Shrink coefficient (default |
enforce_bounds |
bool
|
Penalize points outside |
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 |
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
¶
Evaluates the Park-Miller ran1_zah uniform PRNG in \([0, 1)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
32-bit integer state (\(\ne 0\); |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, int]
|
Tuple |
i4_uniform
¶
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 |
perm_uniform
¶
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 |
nm_simplex
¶
Minimizes an \(n\)-dimensional objective via Nelder-Mead simplex search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_lower
|
ArrayLike
|
Lower box scale array of shape |
required |
x_upper
|
ArrayLike
|
Upper box scale array of shape |
required |
x_first
|
ArrayLike
|
Initial vertex array of shape |
required |
fcn
|
Callable[[NDArray[float64]], float]
|
Objective callable |
required |
config
|
SimplexConfig | None
|
Optional :class: |
None
|
Returns:
| Type | Description |
|---|---|
SimplexResult
|
class: |
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 |
f_min |
float
|
Minimum objective value |
num_evals |
int
|
Total number of objective evaluations performed. |
newuoa
¶
Minimizes an unconstrained objective via Powell's NEWUOA algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
calfun
|
Callable[[NDArray[float64]], float]
|
Objective callable |
required |
x0
|
ArrayLike
|
Initial parameter vector of shape |
required |
npt
|
int | None
|
Number of interpolation conditions in
|
None
|
rhobeg
|
float
|
Initial trust-region radius ( |
0.1
|
rhoend
|
float
|
Final trust-region radius ( |
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
|
evaluation count |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
fit_min_frobenius_quad
¶
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 |
f_min |
float
|
Minimum objective value |
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 |
required |
x0
|
ArrayLike
|
Initial parameter vector of shape |
required |
xl
|
ArrayLike
|
Lower bound array of shape |
required |
xu
|
ArrayLike
|
Upper bound array of shape |
required |
npt
|
int | None
|
Number of interpolation conditions in
|
None
|
rhobeg
|
float
|
Initial trust-region radius ( |
0.1
|
rhoend
|
float
|
Final trust-region radius ( |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If dimensions, |
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 |
|
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
¶
Parse an MLT option string into an MltOption enum member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Option string ( |
required |
Returns:
| Type | Description |
|---|---|
MltOption
|
Matching |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Parse a semiconvection option string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Option string ( |
required |
Returns:
| Type | Description |
|---|---|
SemiconvectionOption
|
Matching |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Parse a thermohaline option string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Option string ( |
required |
Returns:
| Type | Description |
|---|---|
ThermohalineOption
|
Matching |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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). |
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 |
MltParams
dataclass
¶
Non-differentiable configuration parameters for set_mlt.
Attributes:
| Name | Type | Description |
|---|---|---|
option |
MltOption
|
Geometric MLT prescription ( |
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
¶
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). |
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
¶
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 ( |
required |
inp
|
MltInputs
|
Thermodynamic and structure inputs ( |
required |
backend
|
Backend
|
Execution backend ( |
'auto'
|
Returns:
| Type | Description |
|---|---|
TurbOutput
|
|
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 |
required |
chi_rho
|
Array
|
\((\partial \ln P / \partial \ln \rho)_T\), shape
|
required |
cp
|
Array
|
Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\), shape
|
required |
grav
|
Array
|
Gravitational acceleration \(g\) in \(\mathrm{cm\,s^{-2}}\), shape
|
required |
lambda_
|
Array
|
Mixing length \(\Lambda\) in \(\mathrm{cm}\), shape |
required |
rho
|
Array
|
Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape |
required |
p
|
Array
|
Total pressure \(P\) in \(\mathrm{dyn\,cm^{-2}}\), shape |
required |
t
|
Array
|
Temperature \(T\) in \(\mathrm{K}\), shape |
required |
opacity
|
Array
|
Rosseland opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\), shape
|
required |
gradr
|
Array
|
Radiative gradient \(\nabla_r\), shape |
required |
grada
|
Array
|
Adiabatic gradient \(\nabla_{\mathrm{ad}}\), shape |
required |
gradl
|
Array
|
Ledoux gradient \(\nabla_L\), shape |
required |
mixing_length_alpha
|
float
|
Mixing-length parameter \(\alpha_{\mathrm{MLT}}\). |
2.0
|
Returns:
| Type | Description |
|---|---|
Array
|
Five-tuple |
Array
|
arrays with shape |
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 ( |
num_iters |
int
|
Number of Newton iterations taken in the TDC root solver. |
set_tdc
¶
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 ( |
required |
inp
|
TdcInputs
|
Differentiable thermodynamic inputs ( |
required |
Returns:
| Type | Description |
|---|---|
TdcOutput
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
d1val1 |
float
|
Derivative with respect to the Newton variable \(Z\) ( |
d1_array |
_FloatArray
|
First-order partials with respect to structure variables
( |
d1val1_d1_array |
_FloatArray
|
Mixed second partials with respect to \(Z\) and the
structure variables ( |
__init__
¶
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 |
required |
d1val1_d1_array
|
_FloatArray
|
Mixed partials of shape |
required |
constant
classmethod
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
AutoDiffRealTdc
|
Constant |
convert
classmethod
¶
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 |
required |
num_vars
|
int
|
Number of structure variables |
required |
Returns:
| Type | Description |
|---|---|
AutoDiffRealTdc
|
Lifted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
unconvert
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
float | DualOrder1
|
|
flexmesa.turb.tdc_search
¶
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
¶
Narrow a bracket \([Z_{\mathrm{lb}}, Z_{\mathrm{ub}}]\) where \(Q(Z) = 0\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info_p
|
TdcInfo[float]
|
Primal |
required |
y_is_positive
|
bool
|
Sign flag ( |
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 |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If \(Q(Z_{\mathrm{lb}})\) and \(Q(Z_{\mathrm{ub}})\) have the same sign. |
dq_dz_bisection_search
¶
Locate a stationary point \(dQ/dZ = 0\) on \(Y < 0\) where \(A_f > 0\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info_z
|
TdcInfo[DualOrder1]
|
1D |
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 |
af_bisection_search
¶
Locate the largest \(Z\) on \(Y < 0\) such that \(A_f(Z) > 0\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info_p
|
TdcInfo[float]
|
Primal |
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
¶
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 |
required |
info_t
|
TdcInfo[AutoDiffRealTdc]
|
Nested dual TDC state ( |
required |
scale
|
float
|
Luminosity scale for relative residual convergence. |
required |
y_is_positive
|
bool
|
Sign flag ( |
required |
zlb
|
float
|
Lower bound \(Z_{\mathrm{lb}}\). |
required |
zub
|
float
|
Upper bound \(Z_{\mathrm{ub}}\). |
required |
Returns:
| Type | Description |
|---|---|
AutoDiffRealTdc
|
Two-tuple |
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
¶
Project all differentiable fields to primal float scalars.
Returns:
| Type | Description |
|---|---|
TdcInfo[float]
|
A |
to_z_dual
¶
to_tdc
¶
Lift every structure field into AutoDiffRealTdc (convert).
Returns:
| Type | Description |
|---|---|
TdcInfo[AutoDiffRealTdc]
|
Two-tuple |
bool
|
field as an |
tuple[TdcInfo[AutoDiffRealTdc], bool]
|
fields are plain |
tuple[TdcInfo[AutoDiffRealTdc], bool]
|
field was a |
Raises:
| Type | Description |
|---|---|
ValueError
|
If two |
set_y
¶
Map logarithmic coordinate \(Z = \ln|Y|\) to \(Y = \pm \exp(Z)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_is_positive
|
bool
|
Sign flag ( |
required |
z
|
S
|
Dimensionless logarithmic superadiabaticity \(Z = \ln|Y|\). |
required |
Returns:
| Type | Description |
|---|---|
S
|
Dimensionless superadiabaticity \(Y = \pm \exp(Z)\). |
safe_tanh
¶
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 |
S
|
|
flux_limiter_function
¶
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 ( |
S
|
and a quintic blend on \([0.95, 1.0)\)). |
eval_xis
¶
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 ( |
required |
y
|
S
|
Dimensionless envelope-corrected superadiabaticity \(Y_{\mathrm{env}}\). |
required |
Returns:
| Type | Description |
|---|---|
S
|
Three-tuple |
S
|
\mathrm{s^{-1}}, \mathrm{cm^{-1}})$ for $2\,dw/dt = \xi_0 + \xi_1 w |
S
|
|
eval_af
¶
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
¶
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 ( |
required |
y
|
S
|
Superadiabaticity \(Y = \nabla_T - \nabla_L\). |
required |
Returns:
| Type | Description |
|---|---|
S
|
Two-tuple |
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 ( |
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
¶
Evaluate Langer (1983, 1985) semiconvective mixing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
SemiconvectionParams
|
Non-differentiable configuration ( |
required |
inp
|
SemiconvectionInputs
|
Differentiable thermodynamic inputs ( |
required |
Returns:
| Type | Description |
|---|---|
TurbOutput
|
|
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 |
required |
t
|
Array
|
Temperature \(T\) in \(\mathrm{K}\), shape |
required |
opacity
|
Array
|
Rosseland opacity \(\kappa\) in \(\mathrm{cm^2\,g^{-1}}\), shape
|
required |
rho
|
Array
|
Mass density \(\rho\) in \(\mathrm{g\,cm^{-3}}\), shape |
required |
cp
|
Array
|
Specific heat \(C_P\) in \(\mathrm{erg\,g^{-1}\,K^{-1}}\), shape
|
required |
gradr
|
Array
|
Radiative gradient \(\nabla_r\), shape |
required |
grada
|
Array
|
Adiabatic gradient \(\nabla_{\mathrm{ad}}\), shape |
required |
gradl
|
Array
|
Ledoux gradient \(\nabla_L\), shape |
required |
alpha_semiconvection
|
float
|
Efficiency parameter \(\alpha_{\mathrm{sc}}\). |
0.1
|
Returns:
| Type | Description |
|---|---|
tuple[Array, Array, Array, Array]
|
Four-tuple |
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 ( |
gradl_composition_term |
float
|
Dimensionless composition gradient term
\(\nabla_L - \nabla_{\mathrm{ad}}\) ( |
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 ( |
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 ( |
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)\) ( |
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
¶
Evaluate thermohaline mixing outputs (set_thermohaline in turb.f90).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
ThermohalineParams
|
Non-differentiable configuration ( |
required |
inp
|
ThermohalineInputs
|
Differentiable thermodynamic inputs ( |
required |
Returns:
| Type | Description |
|---|---|
TurbOutput
|
|
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 offlexmesa-constprinted by upstreamconst/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, andkerg.is_fortran_float_token((token: str) -> bool): ReturnsTrueiftokenis a Fortran floating-point literal (standard IEEE literals,D/dexponents, or exponent-less1.0-10notation).parse_fortran_float((token: str) -> float): Parses a Fortran or IEEE-754 floating-point literal intof64, raisingValueErroron invalid input.
math_solvers, math_hex_probe, and math_vec_audit¶
crmath_cos((x: float) -> float): Evaluates \(\cos(x)\) usingflexmesa_math::cos(crmathinstrictmode).crmath_exp((x: float) -> float): Evaluates \(\exp(x)\) usingflexmesa_math::exp(crmathinstrictmode).crmath_sin((x: float) -> float): Evaluates \(\sin(x)\) usingflexmesa_math::sin(crmathinstrictmode).exp10_array((xs: _ArrF64) -> _ArrF64): Evaluatesexp10elementwise over a 1D C-contiguousf64array.safe_log_array((xs: _ArrF64) -> _ArrF64): Evaluatessafe_logelementwise over a 1D C-contiguousf64array.safe_log10_array((xs: _ArrF64) -> _ArrF64): Evaluatessafe_log10elementwise over a 1D C-contiguousf64array.safe_sqrt_array((xs: _ArrF64) -> _ArrF64): Evaluatessafe_sqrtelementwise over a 1D C-contiguousf64array.eval_autodiff_order2_zone((x: float, y: float) -> list[float]): Evaluatesf(x, y) = exp(0.1*x*y) + x^1.5 / (y + 2)inAutoDiffReal2VarOrder2, returning[val, df_dx, df_dy, d2f_dx2, d2f_dxdy, d2f_dy2].eval_autodiff_order2_batch((x: _ArrF64, y: _ArrF64, parallel: bool = False) -> _ArrF64): Evaluateseval_autodiff_order2_zoneacross 1D arraysx, yof shape(nz,), dispatching across the persistent 4-threadrayonpool whenparallel=Trueandnz >= 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=Trueruns the level reductions in the persistent 4-threadrayonpool.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 33flexmesa_mathscalar and integer/real-power functions atx, returning(name, value)pairs.auto_diff_test_suite_values(() -> list[float]): Computes theauto_diff1-variable, 2-variable, andAutoDiffRealStarOrder1probe vector (387f64outputs).strict_math_vectors_sha256((vec_path: str) -> tuple[int, str]): Evaluates all inputs invec_pathunderNumericsMode::Strictand 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 invec_pathunderNumericsMode::FastagainstNumericsMode::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)overn_itersblack-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 arraysx_q, y_qof shape(nz,), returning a(nz, 6)array and dispatching across the persistent 4-threadrayonpool whenparallel=Trueandnz >= 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]): Evaluatesset_mltinf64at 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 withDualOrder1<6>sensitivities acrosss_frac, dispatching across the persistent 4-threadrayonworker pool whenparallel=Trueandnz >= 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_TDCinturb/public/turb.f90) at one point with CGSparams(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) andinputs(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 withDualOrder1<6>sensitivities acrosss_frac, dispatching across the persistent 4-threadrayonworker pool whenparallel=Trueandnz >= 32.