API Reference¶
Cosmology¶
Three individual masses: conventions and quick start¶
For the energy-density equations, the meaning of \(N_{\mathrm{eff}}\), and the two thermal prescriptions compared with matched CLASS calculations, see Neutrino thermal prescriptions.
These are analytic background/growth calculations. The neural models instead fix the masses or take a degenerate mass sum. See Migration notes.
import jax.numpy as jnp
import jaxace
cosmo = jaxace.w0waCDMCosmology(
ln10As=3.044, ns=0.965, h=0.67,
omega_b=0.0224, omega_c=0.12,
m_nu=(0.0, 0.0086, 0.0502), # individual physical masses in eV
Neff=3.044, neutrino_prescription="hybrid",
)
z = jnp.array([0.0, 1.0, 3.0])
E = cosmo.E_z(z)
chi = cosmo.r_z(z)
D, f = cosmo.D_f_z(z, species="cb", reltol=1e-10, abstol=1e-12)
| Quantity | API | Units / convention |
|---|---|---|
| Expansion | E_z, E_a |
H/H₀ |
| Radial / transverse comoving distance | r_z, dM_z |
Mpc, not Mpc/h |
| Angular-diameter / luminosity distance | dA_z, dL_z |
Mpc |
| Growth factor | D_z |
D(aᵢ)=aᵢ at aᵢ=1/139, not D(0)=1 |
| Growth rate | f_z |
d ln D / d ln a |
| Both growth quantities | D_f_z |
(D, f) from one solve |
The constructor fields omega_b, omega_c, omega_k mean physical densities
ω_b=Ω_b h², ω_c=Ω_c h², ω_k=Ω_k h². Standalone functions instead take
Ω_cb=Ω_b+Ω_c (excluding neutrinos), and spell the mass keyword mν:
Exactly three masses are required; the default is (0, 0, 0). Scalar totals
are rejected, and no mass hierarchy is inferred. Masses and Neff can be
differentiated; the prescription and growth species are static choices.
The dimensionless Fermi–Dirac integral is tabulated once at import. Runtime expansion, distances and growth use lookup interpolation, with a moment-series extension for very large arguments, not repeated momentum quadrature. Distance integration still uses its existing 100-point redshift quadrature.
- The default
"hybrid"selects temperature below Neff = 3.044 and radiation at or above it. neutrino_prescription="temperature"scales neutrino temperatures with Neff;"radiation"keeps temperatures fixed and requires Neff ≳ 3.0396.species="cb"is cold+baryon growth with smooth neutrinos."m"adds a mass-induced neutrino source approximation, not full scale-dependent growth.- Growth queries require
1/139 <= a=1/(1+z) <= 1.01. Invalid numerical domains return NaN, also under JIT; wrong shapes/static choices raise ValueError. - Scalar inputs produce scalar outputs; use one-dimensional redshift arrays for batched growth. Tighten ODE tolerances and check convergence for derivatives.
jaxace.w0waCDMCosmology
dataclass
¶
w0waCDMCosmology(ln10As: float, ns: float, h: float, omega_b: float, omega_c: float, omega_k: float = 0.0, m_nu: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: float = -1.0, wa: float = 0.0, Neff: float = 3.044, neutrino_prescription: str = 'hybrid')
Parameters for analytic expansion, distances and approximate growth.
h is H0/(100 km/s/Mpc). omega_b, omega_c and omega_k
are physical densities Ω_b h², Ω_c h² and Ω_k h², not density fractions.
ln10As and ns are stored but do not enter the background equations.
m_nu contains exactly three individual, finite, nonnegative masses in
eV, with zeros allowed. Its default is three massless species. No total-mass
splitting or oscillation constraints are imposed. Trained neural emulators
instead fix the masses or take a degenerate mass sum.
Neff defaults to 3.044. neutrino_prescription="temperature" scales
the three temperatures by (Neff/3.044)**0.25 from Tnu/Tgamma=0.71611, and
scales the reference massless remainder by Neff/3.044. "radiation"
fixes the temperatures and varies only massless radiation (Neff >= 3.0396
approximately). The default "hybrid" selects temperature rescaling below 3.044
and radiation at or above 3.044. Values are continuous; Neff derivatives
generally have a kink, with the radiation-side derivative selected at
equality. Masses and the photon temperature, 2.7255 K, stay fixed.
Methods accept scalar redshifts or redshift arrays. Distances are in Mpc,
E is H/H0, and growth is not normalized to D(0)=1. Prefer D_f_z when
both growth factor and rate are needed. Neither growth source is a full
scale-dependent neutrino perturbation calculation.
Wrong mass shapes and unknown static prescriptions raise ValueError;
invalid numerical domains produce NaN on evaluation, including under JIT.
The constructor keyword is m_nu; standalone functions use mν and
take Ωcb0=(omega_b+omega_c)/h**2 rather than physical densities.
D_f_z
¶
D_f_z(z: Union[float, ndarray], species: str = 'cb', *, reltol=1e-06, abstol=1e-08) -> Union[float, jnp.ndarray]
Linear growth factor and growth rate (D(z), f(z)).
species: "cb" (default, cold + baryon source, Effort.jl
convention) or "m" (mass-induced neutrino source approximation).
See :func:growth_solver for its limitations.
D_z
¶
D_z(z: Union[float, ndarray], species: str = 'cb', *, reltol=1e-06, abstol=1e-08) -> Union[float, jnp.ndarray]
Linear growth factor D(z).
species: "cb" (default, cold + baryon source, Effort.jl
convention) or "m" (mass-induced neutrino source approximation).
Neither is full scale-dependent perturbation growth. See :func:growth_solver.
E_a
¶
Dimensionless Hubble parameter E(a) = H(a)/H0.
E_z
¶
Dimensionless Hubble parameter E(z) = H(z)/H0.
dA_z
¶
Angular diameter distance in Mpc.
dL_z
¶
Luminosity distance at redshift z in Mpc.
dM_z
¶
Transverse comoving distance in Mpc (affected by curvature).
d̃A_z
¶
Dimensionless angular diameter distance d̃A(z).
d̃M_z
¶
Dimensionless transverse comoving distance d̃M(z).
f_z
¶
f_z(z: Union[float, ndarray], species: str = 'cb', *, reltol=1e-06, abstol=1e-08) -> Union[float, jnp.ndarray]
Growth rate f(z) = d log D / d log a.
species: "cb" (default, cold + baryon source, Effort.jl
convention) or "m" (mass-induced neutrino source approximation).
See :func:growth_solver for its limitations.
r_z
¶
Line-of-sight comoving distance in Mpc.
r̃_z
¶
Dimensionless comoving distance r̃(z).
Ωm_a
¶
Matter density parameter Ωₘ(a) at scale factor a.
Ωtot_z
¶
Total density parameter at redshift z (always 1.0 for flat universe).
ρc_z
¶
Critical density at redshift z in M☉/Mpc³.
Background Functions¶
Hubble Functions¶
jaxace.E_z
¶
E_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
jaxace.E_a
¶
E_a(a: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
Dimensionless Hubble parameter E(a) = H(a)/H0.
The normalized Hubble parameter is given by:
where:
- \(\Omega_{\gamma,0}\) is the photon density parameter today
- \(\Omega_{\mathrm{cb},0}\) is the cold dark matter + baryon density parameter today
- \(\Omega_{\Lambda,0}\) is the dark energy density parameter today (from Friedmann closure, including curvature)
- \(\rho_{\mathrm{DE}}(a)\) is the normalized dark energy density
- \(\Omega_{\nu}(a)\) is the massive neutrino contribution
- \(\Omega_{k,0}\) is the curvature density parameter today
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
Hubble parameter E(a). Handles NaN/Inf inputs by propagating them appropriately. |
Union[float, ndarray]
|
Returns NaN for invalid parameter combinations. |
jaxace.dlogEdloga
¶
dlogEdloga(a: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
Matter Density¶
jaxace.Ωm_a
¶
Ωm_a(a: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
Growth Functions¶
jaxace.D_z
¶
D_z(z, Ωcb0, h, mν=_neutrinos.MASSLESS, w0=-1.0, wa=0.0, Ωk0=0.0, species='cb', Neff=3.044, neutrino_prescription='hybrid', reltol=1e-06, abstol=1e-08) -> Union[float, jnp.ndarray]
Linear growth factor D(z).
The growth factor uses the early-time normalization set by
:func:growth_solver, namely D(a_i) = a_i in matter domination. It is not
rescaled to D(z=0) = 1.
species selects the growth-equation source term, see
:func:growth_solver: "cb" (default) sources growth with the cold +
baryon density only (the smooth-neutrino approximation);
"m" adds the mass-induced neutrino source approximation. Neither
is a full scale-dependent growth prediction. The default retains the
historical cb-source equation, not bitwise outputs of older ODE solvers.
Queries outside 1/139 <= a <= 1.01 return NaN.
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
jnp.ndarray: Linear growth factor D(z). Returns NaN for NaN inputs, handles invalid parameters gracefully. |
jaxace.f_z
¶
f_z(z, Ωcb0, h, mν=_neutrinos.MASSLESS, w0=-1.0, wa=0.0, Ωk0=0.0, species='cb', Neff=3.044, neutrino_prescription='hybrid', reltol=1e-06, abstol=1e-08) -> Union[float, jnp.ndarray]
Growth rate f(z) = d log D / d log a.
The growth rate is defined as:
where D is the linear growth factor.
species selects the growth-equation source term used to compute D,
see :func:growth_solver: "cb" (historical default source) or "m".
Queries outside 1/139 <= a <= 1.01 return NaN.
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
jnp.ndarray: Growth rate f(z). Returns NaN for NaN inputs, handles invalid parameters gracefully. |
jaxace.D_f_z
¶
D_f_z(z, Ωcb0, h, mν=_neutrinos.MASSLESS, w0=-1.0, wa=0.0, Ωk0=0.0, species='cb', Neff=3.044, neutrino_prescription='hybrid', reltol=1e-06, abstol=1e-08)
Linear growth factor and growth rate (D(z), f(z)).
species selects the growth-equation source term, see
:func:growth_solver: "cb" (historical default source) or "m".
Queries outside 1/139 <= a <= 1.01 return NaN.
Distance Functions¶
jaxace.r_z
¶
r_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
Line-of-sight comoving distance r(z) in Mpc.
This is the conformal distance scaled to physical units. Curvature affects this distance through E(z). The additional geometric curvature mapping is applied by dM_z to obtain transverse distance.
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
Line-of-sight comoving distance in Mpc |
jaxace.dM_z
¶
dM_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
jaxace.dA_z
¶
dA_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
jaxace.dL_z
¶
dL_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
Luminosity distance at redshift z.
For curved universes, uses transverse comoving distance: dL(z) = dM(z) * (1 + z)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Union[float, ndarray]
|
Redshift |
required |
Ωcb0
|
Union[float, ndarray]
|
Present-day matter density parameter (CDM + baryons) |
required |
h
|
Union[float, ndarray]
|
Dimensionless Hubble parameter (H0 = 100h km/s/Mpc) |
required |
mν
|
Union[tuple, ndarray]
|
Three neutrino masses (m1, m2, m3) in eV |
MASSLESS
|
w0
|
Union[float, ndarray]
|
Dark energy equation of state parameter |
-1.0
|
wa
|
Union[float, ndarray]
|
Dark energy equation of state evolution parameter |
0.0
|
Ωk0
|
Union[float, ndarray]
|
Curvature density parameter |
0.0
|
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
Luminosity distance in Mpc |
Density Functions¶
jaxace.ρc_z
¶
ρc_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0, Ωk0: Union[float, ndarray] = 0.0, Neff=3.044, neutrino_prescription='hybrid') -> Union[float, jnp.ndarray]
jaxace.Ωtot_z
¶
Ωtot_z(z: Union[float, ndarray], Ωcb0: Union[float, ndarray], h: Union[float, ndarray], mν: Union[tuple, ndarray] = _neutrinos.MASSLESS, w0: Union[float, ndarray] = -1.0, wa: Union[float, ndarray] = 0.0) -> Union[float, jnp.ndarray]
Utility Functions¶
Neural Network Emulators¶
jaxace.init_emulator
¶
init_emulator(nn_dict: Dict[str, Any], weight: ndarray, emulator_type: Type[FlaxEmulator] = FlaxEmulator, validate: bool = True, validate_weights: Optional[bool] = None) -> FlaxEmulator
Initialize an emulator from neural network dictionary and weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nn_dict
|
Dict[str, Any]
|
Neural network specification dictionary |
required |
weight
|
ndarray
|
Flattened weight array |
required |
emulator_type
|
Type[FlaxEmulator]
|
Type of emulator (currently only FlaxEmulator) |
FlaxEmulator
|
validate
|
bool
|
Whether to validate nn_dict structure |
True
|
validate_weights
|
Optional[bool]
|
Whether to validate weight dimensions |
None
|
Returns:
| Type | Description |
|---|---|
FlaxEmulator
|
Initialized FlaxEmulator instance |
jaxace.load_trained_emulator
¶
load_trained_emulator(path: str, backend: Type[FlaxEmulator] = FlaxEmulator, weights_file: str = 'weights.npy', inminmax_file: str = 'inminmax.npy', outminmax_file: str = 'outminmax.npy', nn_setup_file: str = 'nn_setup.json', postprocessing_file: str = 'postprocessing.py', validate: bool = True) -> GenericEmulator
Load a trained emulator from disk.
This function matches Julia's AbstractCosmologicalEmulators.load_trained_emulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory path containing the emulator files |
required |
backend
|
Type[FlaxEmulator]
|
Emulator backend type (FlaxEmulator) |
FlaxEmulator
|
weights_file
|
str
|
Filename for neural network weights (default: "weights.npy") |
'weights.npy'
|
inminmax_file
|
str
|
Filename for input normalization (default: "inminmax.npy") |
'inminmax.npy'
|
outminmax_file
|
str
|
Filename for output normalization (default: "outminmax.npy") |
'outminmax.npy'
|
nn_setup_file
|
str
|
Filename for network architecture (default: "nn_setup.json") |
'nn_setup.json'
|
postprocessing_file
|
str
|
Filename for postprocessing function (default: "postprocessing.py") |
'postprocessing.py'
|
validate
|
bool
|
Whether to validate the loaded data (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
GenericEmulator
|
GenericEmulator instance ready for evaluation |
Example
emu = load_trained_emulator("/path/to/emulator/") output = emu.run_emulator(input_params)
jaxace.load_trained_emulator_from_artifact
¶
load_trained_emulator_from_artifact(artifact_name: str, artifacts_toml: Optional[str] = None, backend: Type[FlaxEmulator] = FlaxEmulator, **kwargs) -> GenericEmulator
Load a trained emulator from an artifact defined in Artifacts.toml.
This function automatically downloads and caches emulators from remote sources (e.g., Zenodo) using the fetch-artifacts system, then loads them using load_trained_emulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artifact_name
|
str
|
Name of the artifact as defined in Artifacts.toml |
required |
artifacts_toml
|
Optional[str]
|
Optional path to Artifacts.toml file. If None, looks for Artifacts.toml in the package root. |
None
|
backend
|
Type[FlaxEmulator]
|
Emulator backend type (FlaxEmulator) |
FlaxEmulator
|
**kwargs
|
Any
|
Additional arguments passed to load_trained_emulator (e.g., weights_file, validate, etc.) |
{}
|
Returns:
| Type | Description |
|---|---|
GenericEmulator
|
GenericEmulator instance ready for evaluation |
Example
Load from default Artifacts.toml¶
emu = load_trained_emulator_from_artifact("mnuw0waCDM_onemassiveneutrino_sigma8") output = emu.run_emulator(input_params)
Load from custom Artifacts.toml¶
emu = load_trained_emulator_from_artifact( ... "mnuw0waCDM_onemassiveneutrino_sigma8", ... artifacts_toml="/path/to/Artifacts.toml" ... )
Note
On first use, this will download the emulator from the URL specified in Artifacts.toml. Subsequent uses will load from the local cache (typically ~/.fetch_artifacts/).
jaxace.FlaxEmulator
dataclass
¶
FlaxEmulator(model: Module, parameters: Dict[str, Any], states: Optional[Dict[str, Any]] = None, description: Dict[str, Any] = None)
Bases: AbstractTrainedEmulator
Flax-based emulator with automatic JIT compilation.
Key features: 1. Automatic JIT compilation on first use 2. Automatic batch detection and vmap application 3. Cached compiled functions for performance
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
Flax model (nn.Module) |
parameters |
Dict[str, Any]
|
Model parameters dictionary |
states |
Optional[Dict[str, Any]]
|
Model states (usually empty for standard feedforward networks) |
description |
Dict[str, Any]
|
Emulator description dictionary |
run_emulator
¶
Run the emulator with automatic JIT compilation and batch detection.
This method automatically: 1. Converts numpy arrays to JAX arrays 2. Detects if input is a batch or single sample 3. Applies JIT compilation 4. Uses vmap for batch processing
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_data
|
Union[ndarray, ndarray]
|
Input array (single sample or batch) Shape: (n_features,) for single or (n_samples, n_features) for batch |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Output array from the neural network |
__call__
¶
Allow the emulator to be called directly as a function.
jaxace.GenericEmulator
dataclass
¶
GenericEmulator(trained_emulator: AbstractTrainedEmulator, in_minmax: ndarray, out_minmax: ndarray, postprocessing: callable = None)
Bases: AbstractTrainedEmulator
Generic emulator that wraps a trained neural network with normalization and postprocessing.
This class provides a complete emulator interface that: 1. Normalizes inputs using min-max scaling 2. Runs the underlying neural network 3. Denormalizes outputs 4. Applies optional postprocessing
This matches the Julia AbstractCosmologicalEmulators.jl GenericEmulator struct.
Attributes:
| Name | Type | Description |
|---|---|---|
trained_emulator |
AbstractTrainedEmulator
|
The underlying trained neural network (FlaxEmulator) |
in_minmax |
ndarray
|
Input normalization parameters, shape (n_input_features, 2) Column 0 is min, column 1 is max |
out_minmax |
ndarray
|
Output normalization parameters, shape (n_output_features, 2) Column 0 is min, column 1 is max |
postprocessing |
callable
|
Optional postprocessing function with signature (input_params, output, emulator) -> processed_output |
run_emulator
¶
run_emulator(input_params: Union[ndarray, ndarray], auxiliary_params: Union[ndarray, ndarray, None] = None) -> jnp.ndarray
Run the complete emulator pipeline.
Steps: 1. Normalize inputs using in_minmax 2. Run the neural network 3. Denormalize outputs using out_minmax 4. Apply postprocessing function
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_params
|
Union[ndarray, ndarray]
|
Input parameters, shape (n_features,) or (n_samples, n_features) |
required |
auxiliary_params
|
Union[ndarray, ndarray, None]
|
Deprecated. Present only for compatibility with older jaxace postprocessing functions. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Processed output array |
__call__
¶
__call__(input_params: Union[ndarray, ndarray], auxiliary_params: Union[ndarray, ndarray, None] = None) -> jnp.ndarray
Allow the emulator to be called directly as a function.
Postprocessing signature
Custom postprocessing functions should use the AbstractCosmologicalEmulators.jl-compatible signature
postprocessing(input_params, output, emulator). Legacy four-argument
functions with auxiliary_params are accepted for backward compatibility
but are not the canonical 0.6.0 API.
Utilities¶
jaxace.maximin
¶
maximin(input_data: Union[ndarray, ndarray], minmax: Union[ndarray, ndarray]) -> Union[np.ndarray, jnp.ndarray]
Normalize input data using min-max scaling. Matches Julia's maximin function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_data
|
Union[ndarray, ndarray]
|
Input array to normalize (shape: (n_features,) or (n_features, n_samples)) |
required |
minmax
|
Union[ndarray, ndarray]
|
Array of shape (n_features, 2) where column 0 is min, column 1 is max |
required |
Returns:
| Type | Description |
|---|---|
Union[ndarray, ndarray]
|
Normalized array in range [0, 1] |
jaxace.inv_maximin
¶
inv_maximin(output_data: Union[ndarray, ndarray], minmax: Union[ndarray, ndarray]) -> Union[np.ndarray, jnp.ndarray]
Denormalize output data from min-max scaling. Matches Julia's inv_maximin function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_data
|
Union[ndarray, ndarray]
|
Normalized array (shape: (n_features,) or (n_features, n_samples)) |
required |
minmax
|
Union[ndarray, ndarray]
|
Array of shape (n_features, 2) where column 0 is min, column 1 is max |
required |
Returns:
| Type | Description |
|---|---|
Union[ndarray, ndarray]
|
Denormalized array |
Interpolation¶
Cubic B-splines require finite, strictly increasing source sites. This is
checked for concrete inputs and is a precondition when the sites are traced.
At either endpoint, query derivatives use the interior polynomial convention;
clamp and zero have zero query derivatives strictly outside the interval.
This is an explicit choice at the extension's boundary kink, not a claim of
two-sided differentiability there.
Coefficient construction uses four-entry local basis rows, a seven-row banded collocation factorization, and batched forward/transpose substitutions, following the Julia algorithms. Implicit solve derivatives preserve both value and site activity. For N sites and M right-hand sides, factorization costs O(N) and solving costs O(NM), with fixed bandwidth. These are scaling statements, not hardware speedup guarantees.
Ordinary B-spline evaluation and prepared plans use local four-entry query
stencils, not dense query-basis matrices. Compact construction/application no
longer inherits a quadratic workspace limit. Explicit plan.operator access
still has a 64 MiB limit; explicit basis_matrix output has a 512 MiB limit.
These are materialization guards, not bounds on compiler, AD or process memory.
Eager factorization rejects pivots below Julia's ten-epsilon threshold in the
geometry dtype. Compiled code cannot raise the same data-dependent exception;
valid nonsingular geometry remains a precondition under transformations.
jaxace.akima_interpolation
¶
Akima spline interpolation for 1D or 2D data.
This is a direct translation of AbstractCosmologicalEmulators.jl's akima_interpolation function. Evaluates the Akima spline that interpolates the data points (t_i, u_i) at new abscissae t_new.
The Akima spline is a piecewise cubic polynomial that uses weighted averaging of local slopes to determine derivatives at each node. This dampens oscillations without explicit shape constraints. The spline is C¹ continuous but generally not C².
This implementation is fully compatible with JAX's jit and automatic differentiation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Ordinates (function values) at data nodes. The 1D
case has shape |
required |
t
|
ndarray
|
Strictly increasing abscissae (x-coordinates), shape
|
required |
t_new
|
ndarray
|
Query point(s) where spline is evaluated, scalar or array. |
required |
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
jnp.ndarray: Interpolated value(s) at |
Example (1D): >>> import jax.numpy as jnp >>> t = jnp.linspace(0, 1, 10) >>> u = jnp.sin(2 * jnp.pi * t) >>> t_new = jnp.linspace(0, 1, 50) >>> u_new = akima_interpolation(u, t, t_new)
Example (2D - multiple columns): >>> # Interpolate Jacobian with 11 parameter columns >>> k_in = jnp.linspace(0.01, 0.3, 50) >>> jacobian = jnp.randn(50, 11) # 11 parameters >>> k_out = jnp.linspace(0.01, 0.3, 100) >>> result = akima_interpolation(jacobian, k_in, k_out) # (100, 11)
# Works with jit
>>> akima_jit = jax.jit(akima_interpolation)
>>> u_new = akima_jit(u, t, t_new)
# Works with autodiff
>>> grad_fn = jax.grad(lambda u: jnp.sum(akima_interpolation(u, t, t_new)))
>>> grad_u = grad_fn(u)
jaxace.cubic_spline_interpolation
¶
Natural Cubic Spline interpolation for 1D or 2D data.
This is a direct translation of AbstractCosmologicalEmulators.jl's cubic_spline_interpolation function. Evaluates the Natural Cubic Spline that interpolates the data points (t_i, u_i) at new abscissae t_new.
This implementation is fully compatible with JAX's jit and automatic differentiation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Ordinates (function values) at data nodes. The 1D
case has shape |
required |
t
|
ndarray
|
Strictly increasing abscissae (x-coordinates), shape
|
required |
t_new
|
ndarray
|
Query point(s) where spline is evaluated, scalar or array. |
required |
Returns:
| Type | Description |
|---|---|
Union[float, ndarray]
|
jnp.ndarray: Interpolated value(s) at |
jaxace.cubic_b_spline_interpolation
¶
Not-a-knot interpolation of vector or column-batched matrix values.
Fixed values, changing query points¶
Use a prepared spline when the ordinates and source knots are fixed while the query grid changes.
jaxace.AkimaSpline
dataclass
¶
Construct an Akima spline from (u, t) or stored coefficients.
jaxace.prepare_akima_spline
¶
Precompute the Akima spline coefficients for repeated evaluation. This structure acts as a valid JAX PyTree for JIT and grad.
jaxace.evaluate_akima_spline
¶
Evaluate a precomputed Akima spline at new points.
jaxace.CubicSpline
dataclass
¶
Natural cubic spline with fixed values u and source knots t.
jaxace.prepare_cubic_spline
¶
Precompute cubic-spline coefficients for changing query grids.
jaxace.evaluate_cubic_spline
¶
Evaluate a prepared :class:CubicSpline at t_new.
jaxace.CubicBSpline
dataclass
¶
Prepared not-a-knot spline with local O(Q) query geometry.
Matrix values represent independent columns. Query derivatives use the
interior polynomial at endpoint equality. Geometry is validated eagerly;
dynamic throw is unsupported under JAX transformations.
jaxace.prepare_cubic_b_spline
¶
Prepare coefficients for fixed values/sites and changing queries.
jaxace.evaluate_cubic_b_spline
¶
Evaluate a prepared spline at scalar or vector query coordinates.
Fixed grids, changing values¶
Use a plan when the source and target grids are fixed while the ordinates
change. Plans expect one-dimensional source and target grids and vector or
matrix values with shape (n_knots, n_series), where each column is an
independent series.
jaxace.AkimaSplinePlan
dataclass
¶
Interpolation plan for fixed t and t_new with changing u.
jaxace.prepare_akima_spline_plan
¶
Prepare an :class:AkimaSplinePlan for fixed source and target grids.
jaxace.CubicSplinePlan
dataclass
¶
Natural-cubic plan for fixed grids and changing values u.
The plan stores an n_knots × n_knots dense operator mapping source
values to natural-spline second derivatives, so storage is O(n_knots²).
With the current dense JAX solve, construction is O(n_knots³).
Applying a completed plan costs O(n_knots² + n_query) for one value
vector and O(n_knots² * n_series + n_query * n_series) for a matrix.
The representation is intended for moderate grids reused enough times to
amortize construction.
jaxace.prepare_cubic_spline_plan
¶
Prepare a :class:CubicSplinePlan for fixed source and target grids.
jaxace.CubicBSplinePlan
dataclass
¶
Compact fixed-grid plan: O(N+Q) geometry and reusable band factors.
plan(u) uses a band solve and four local entries per query. The computed
operator property explicitly materializes a dense Q×N operator (64 MiB
limit); it is neither cached nor used by ordinary plan application.
jaxace.prepare_cubic_b_spline_plan
¶
Prepare a compact fixed-grid plan for changing values.
CubicSplinePlan stores a dense n_knots × n_knots operator for the
natural-spline second derivatives, so storage is O(n_knots²). With the
current dense JAX solve, construction is O(n_knots³). Applying a completed
plan costs O(n_knots² + n_query) for one value vector and
O(n_knots² n_series + n_query n_series) for a matrix. It is intended for
moderate grids reused enough times to amortize construction.
CubicBSpline and CubicBSplinePlan use the same fixed not-a-knot basis as
AbstractCosmologicalEmulators.jl. Knot placement is derived from the source
sites and is not configurable. Extrapolation clamps to the nearest endpoint
by default; extrapolation="throw" and extrapolation="zero" are explicit
alternatives. Dynamic "throw" checks are unavailable whenever sites or queries
are traced, including jax.grad and jax.jvp without jax.jit. Use "clamp"
or "zero" for live geometry; a host-validated fixed throw plan can be compiled.
CubicBSplinePlan stores live collocation bands, reusable LU factors and a
four-entry query stencil: O(n_sites + n_query) retained geometry. Applying it
costs O((n_sites + n_query) * n_series). Forward and reverse solves reuse the
factorization; geometry derivatives remain live through the implicit solve.
Factor precision follows the source geometry, even if a later RHS has a higher
precision. Output dtype alone is not a guarantee of higher geometry accuracy.
plan.operator is now an explicit computed property, not a stored field.
It materializes the dense (n_query, n_sites) interpolation operator on each
access, subject to the 64 MiB guard. Callers wanting a dense repeated multiply
can materialize it once themselves. Ordinary plan(u) does not access it.
Internal PyTree layout has changed; rebuild plans and compiled functions rather
than relying on cross-version serialized internal layouts.
Public B-spline basis and coefficient API¶
CubicBSplineBasis accepts a full knot vector, or a domain and optional internal
knots. Endpoints have multiplicity four; internal multiplicity is at most three.
These low-level custom bases do not change the fixed not-a-knot policy of the
high-level interpolators. Basis/support indices are zero-based in Python.
jaxace.CubicBSplineBasis
dataclass
¶
Degree-three basis with explicit knots; indices are zero-based.
Supply either a full knot vector (positional or knot_vector=), or
domain=(lo, hi) and optional internal_knots. Under transformations,
finite ordered knots with the documented multiplicities are preconditions.
jaxace.knot_vector
¶
Return the complete stored knot vector, including repeated endpoints.
jaxace.basis_row
¶
Four local indices/weights, zero outside support; scalar query only.
jaxace.basis_stencil
¶
Local four-entry query rows; default domain checking is eager-only.
jaxace.basis_matrix
¶
Explicit dense basis matrix; ordinary interpolation need not allocate it.
jaxace.bspline_basis
¶
Return the basis used by a prepared spline or plan.
jaxace.bspline_coefficients
¶
Get spline coefficients or solve with a plan's existing factorization.
basis_row returns four indices and weights and is zero outside support.
basis_matrix explicitly materializes those rows. basis_stencil defaults to
extrapolation="throw", unlike the high-level constructors' "clamp" default.
Dynamic "throw" is unsupported under JAX transformations; use "clamp" or
"zero" for live geometry. Host-validated fixed throw plans can be compiled.
Nonfinite query coordinates are rejected eagerly in every policy.
bspline_coefficients(spline) returns stored coefficients;
bspline_coefficients(plan, u) solves with the existing factors.
bspline_basis(spline_or_plan) exposes the basis and preserves derivatives
through constructor composition. Raw LU leaves are structural, not independently
meaningful differentiable inputs.
The endpoint convention is intentional. The frozen merged-Julia/ForwardDiff
references exposed an upper-endpoint branch discrepancy caused by ordering a
Dual value against a plain boundary. Those raw results are preserved alongside
independent analytic interior-derivative references in tests/data/bspline_api;
the JAX API does not reproduce that outside-zero branch at equality. In that
frozen Julia version, the issue can change the Dual primal value under :zero
or reject an in-domain query under :throw; it is not merely a different
derivative convention. The fixtures describe that pinned version, not later
Julia fixes. The selected interior boundary derivatives are convention-dependent,
not two-sided derivatives of a smooth extension.
Chebyshev¶
jaxace.ChebyshevPlan
¶
Bases: NamedTuple
Plan for computing Chebyshev coefficients of a function evaluated at Chebyshev nodes.
Attributes:
| Name | Type | Description |
|---|---|---|
K |
Tuple[int, ...]
|
Tuple of polynomial degrees (K+1 nodes per dimension) |
nodes |
Tuple[ndarray, ...]
|
Tuple of evaluation nodes arrays |
dim |
Tuple[int, ...]
|
Tuple of target dimensions for decomposition |
jaxace.chebpoints
¶
Generate Chebyshev roots mapped to [x_min, x_max].
Matches AbstractCosmologicalEmulators.chebpoints
jaxace.prepare_chebyshev_plan
¶
prepare_chebyshev_plan(x_min: Union[float, Tuple[float, ...]], x_max: Union[float, Tuple[float, ...]], K: Union[int, Tuple[int, ...]], size_nd: Optional[Tuple[int, ...]] = None, dim: Union[int, Tuple[int, ...]] = 0) -> ChebyshevPlan
Precomputes the Chebyshev nodes required to compute coefficients.
K is the polynomial degree (K+1 nodes). For N-dimensional inputs, specify
the target dimensions dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_min
|
Union[float, Tuple[float, ...]]
|
Minimum x value(s) |
required |
x_max
|
Union[float, Tuple[float, ...]]
|
Maximum x value(s) |
required |
K
|
Union[int, Tuple[int, ...]]
|
Polynomial degree(s) |
required |
size_nd
|
Optional[Tuple[int, ...]]
|
Tuple representing input array shape (unused parameter kept for API parity) |
None
|
dim
|
Union[int, Tuple[int, ...]]
|
Target dimension(s) for Chebyshev decomposition (default 0) |
0
|
Returns:
| Type | Description |
|---|---|
ChebyshevPlan
|
ChebyshevPlan object containing nodes and settings |
jaxace.chebyshev_polynomials
¶
Computes the matrix of Chebyshev polynomials evaluated on x_grid,
mapped to [-1, 1] from [x_min, x_max].
Matches AbstractCosmologicalEmulators.chebyshev_polynomials functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_grid
|
ndarray
|
Grid of evaluation points |
required |
x_min
|
float
|
Input minimum domain |
required |
x_max
|
float
|
Input maximum domain |
required |
K
|
int
|
Polynomial degree |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Matrix of size (len(x_grid), K+1) |
jaxace.chebyshev_decomposition
¶
Computes Chebyshev coefficients for a function evaluated at Chebyshev nodes.
Fully supports batched N-dimensional JAX arrays across plan.dim using custom DCT-1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
ChebyshevPlan
|
ChebyshevPlan containing interpolation configuration |
required |
f_vals
|
ndarray
|
Array of function outputs evaluated exactly on plan.nodes along plan.dim (must have size K+1 along plan.dim) |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
N-Dimensional array of Chebyshev coefficients |