Skip to content

aragog.solver

The aragog.solver package contains the time-integration driver, the per-RHS state container, the boundary-condition handler, and the output dataclass.

The public surface re-exported from aragog.solver is:

Name Role
EntropySolver The ODE driver. Owns the integrator dispatch (Radau / BDF / CVODE), the nondimensionalisation layer, the retry-ladder hooks, and the SolverOutput post-processing.
EntropyState Per-RHS state container. Computes phase, density, \(T\), \(c_p\), \(\alpha\), \(k\), the four flux contributions, and the internal heating at each call.
BoundaryConditions Surface (grey-body, UTBL, prescribed flux/T) and inner (core cooling, prescribed flux/T) BC dispatch.
SolverOutput Dataclass returned by EntropySolver.get_state(). Carries the staggered-node profiles, basic-node fluxes, scalar diagnostics, the per-call energy integrals (step_dE_F_int_J, step_dE_F_cmb_J, step_dE_Q_radio_J, step_dE_Q_tidal_J, plus frozen-mass step_dE_Q_radio_cons_J/step_dE_Q_tidal_cons_J and the entropy-ODE solver residual step_solver_residual_J), the conservation-grade integrated mantle enthalpy E_state_cons (frozen-mass), and the integration status flag. See Energy diagnostics for the conservation-residual interpretation.
SECS_PER_YEAR Module-level constant scipy.constants.Julian_year (\(31{,}557{,}600\) s). The ODE is integrated in years; converting flux divergence (J/kg/K/s) to per-year requires this factor.

solver

Solver package for the Aragog interior dynamics model.

Provides the entropy-formulation solver (EntropySolver) and supporting classes (BoundaryConditions, EntropyState).

BoundaryConditions(_parameters, _mesh) dataclass

Boundary conditions

Args: parameters: Parameters mesh: Mesh

apply_flux_boundary_conditions(state)

Applies the boundary conditions to the state.

Args: state: The state to apply the boundary conditions to

Source code in src/aragog/solver/boundary.py
 98
 99
100
101
102
103
104
105
106
107
def apply_flux_boundary_conditions(self, state: State) -> None:
    """Applies the boundary conditions to the state.

    Args:
        state: The state to apply the boundary conditions to
    """
    self.apply_flux_inner_boundary_condition(state)
    self.apply_flux_outer_boundary_condition(state)
    logger.debug('temperature = %s', state.temperature_basic)
    logger.debug('heat_flux = %s', state.heat_flux)

apply_flux_inner_boundary_condition(state)

Applies the flux boundary condition to the state at the inner boundary.

Args: state: The state to apply the boundary conditions to

Equivalent to CORE_BC in C code. 1: Simple core cooling 2: Prescribed heat flux 3: Prescribed temperature

Source code in src/aragog/solver/boundary.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def apply_flux_inner_boundary_condition(self, state: State) -> None:
    """Applies the flux boundary condition to the state at the inner boundary.

    Args:
        state: The state to apply the boundary conditions to

    Equivalent to CORE_BC in C code.
        1: Simple core cooling
        2: Prescribed heat flux
        3: Prescribed temperature
    """
    if self._settings.inner_boundary_condition == 1:
        self.core_cooling(state)
    elif self._settings.inner_boundary_condition == 2:
        state.heat_flux[0, :] = self._settings.inner_boundary_value
    elif self._settings.inner_boundary_condition == 3:
        pass
        # raise NotImplementedError
    else:
        msg: str = f'inner_boundary_condition = {self._settings.inner_boundary_condition} is unknown'
        raise ValueError(msg)

apply_flux_outer_boundary_condition(state)

Applies the flux boundary condition to the state at the outer boundary.

Args: state: The state to apply the boundary conditions to

Equivalent to SURFACE_BC in C code. 1: Grey-body atmosphere 2: Zahnle steam atmosphere (not implemented) 4: Prescribed surface heat flux (atmosphere coupling) 5: Prescribed surface temperature

Source code in src/aragog/solver/boundary.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def apply_flux_outer_boundary_condition(self, state: State) -> None:
    """Applies the flux boundary condition to the state at the outer boundary.

    Args:
        state: The state to apply the boundary conditions to

    Equivalent to SURFACE_BC in C code.
        1: Grey-body atmosphere
        2: Zahnle steam atmosphere (not implemented)
        4: Prescribed surface heat flux (atmosphere coupling)
        5: Prescribed surface temperature
    """
    if self._settings.outer_boundary_condition == 1:
        self.grey_body(state)
    elif self._settings.outer_boundary_condition == 2:
        raise NotImplementedError
    elif self._settings.outer_boundary_condition == 4:
        state.heat_flux[-1, :] = self._settings.outer_boundary_value
    elif self._settings.outer_boundary_condition == 5:
        pass
    else:
        msg: str = f'outer_boundary_condition = {self._settings.outer_boundary_condition} is unknown'
        raise ValueError(msg)

apply_temperature_boundary_conditions(temperature, temperature_basic, dTdr)

Conforms the temperature and dTdr at the basic nodes to temperature boundary conditions.

Args: temperature: Temperature at the staggered nodes temperature_basic: Temperature at the basic nodes dTdr: Temperature gradient at the basic nodes

Source code in src/aragog/solver/boundary.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def apply_temperature_boundary_conditions(
    self, temperature: npt.NDArray, temperature_basic: npt.NDArray, dTdr: npt.NDArray
) -> None:
    """Conforms the temperature and dTdr at the basic nodes to temperature boundary conditions.

    Args:
        temperature: Temperature at the staggered nodes
        temperature_basic: Temperature at the basic nodes
        dTdr: Temperature gradient at the basic nodes
    """
    # Core-mantle boundary
    if self._settings.inner_boundary_condition == 3:
        temperature_basic[0, :] = self._settings.inner_boundary_value
        dTdr[0, :] = (
            2
            * (temperature[0, :] - temperature_basic[0, :])
            / self._mesh.basic.delta_mesh[0]
            * self._mesh.dxidr[0]
        )
    # Surface
    if self._settings.outer_boundary_condition == 5:
        temperature_basic[-1, :] = self._settings.outer_boundary_value
        dTdr[-1, :] = (
            2
            * (temperature_basic[-1, :] - temperature[-1, :])
            / self._mesh.basic.delta_mesh[-1]
            * self._mesh.dxidr[-1]
        )

apply_temperature_boundary_conditions_melt(melt_fraction, melt_fraction_basic, dphidr)

Conforms the melt fraction gradient dphidr at the basic nodes to temperature boundary conditions.

Args: melt_fraction: Melt fraction at the staggered nodes melt_fraction_basic: Melt fraction at the basic nodes dphidr: Melt fraction gradient at the basic nodes

Source code in src/aragog/solver/boundary.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def apply_temperature_boundary_conditions_melt(
    self, melt_fraction: npt.NDArray, melt_fraction_basic: npt.NDArray, dphidr: npt.NDArray
) -> None:
    """Conforms the melt fraction gradient dphidr at the basic nodes
       to temperature boundary conditions.

    Args:
        melt_fraction: Melt fraction at the staggered nodes
        melt_fraction_basic: Melt fraction at the basic nodes
        dphidr: Melt fraction gradient at the basic nodes
    """
    # Core-mantle boundary
    if self._settings.inner_boundary_condition == 3:
        dphidr[0, :] = (
            2
            * (melt_fraction[0, :] - melt_fraction_basic[0, :])
            / self._mesh.basic.delta_mesh[0]
            * self._mesh.dxidr[0]
        )
    # Surface
    if self._settings.outer_boundary_condition == 5:
        dphidr[-1, :] = (
            2
            * (melt_fraction_basic[-1, :] - melt_fraction[-1, :])
            / self._mesh.basic.delta_mesh[-1]
            * self._mesh.dxidr[-1]
        )

core_cooling(state)

Applies a core cooling heat flux according to Eq. (37) of Bower et al., 2018.

The core is modelled as a well-mixed reservoir with an effective temperature T_core = tfac_core_avg * T_cmb. The factor tfac_core_avg accounts for the adiabatic temperature gradient within the core (mass-weighted average core temperature / CMB temperature). Default 1.147 is for Earth-like parameters (Bower+2018, Table 2).

Parameters:

Name Type Description Default
state State

The state to apply the boundary condition to.

required
Source code in src/aragog/solver/boundary.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def core_cooling(self, state: State) -> None:
    """Applies a core cooling heat flux according to Eq. (37) of Bower et al., 2018.

    The core is modelled as a well-mixed reservoir with an effective
    temperature T_core = tfac_core_avg * T_cmb. The factor tfac_core_avg
    accounts for the adiabatic temperature gradient within the core
    (mass-weighted average core temperature / CMB temperature).
    Default 1.147 is for Earth-like parameters (Bower+2018, Table 2).

    Parameters
    ----------
    state : State
        The state to apply the boundary condition to.
    """
    # Core thermal capacity: C_core = rho_core * cp_core * V_core
    r_cmb = np.asarray(self._mesh.basic.radii).flat[0]
    core_capacity = (
        4
        / 3
        * np.pi
        * r_cmb**3
        * self._mesh.settings.core_density
        * self._settings.core_heat_capacity
    )

    # First mantle cell thermal capacity: C_cell = rho * cp * V_cell
    cap_stag = state.capacitance_staggered()  # rho * cp, may be float or array
    cap_first = np.asarray(cap_stag).flat[0]
    cell_capacity = np.asarray(self._mesh.basic.volume).flat[0] * cap_first

    # Geometric correction: area ratio between first interior face and CMB
    r_above = np.asarray(self._mesh.basic.radii).flat[1]
    radius_ratio = r_above / r_cmb

    # Core buffering factor (Bower+2018 Eq. 37):
    # alpha = (R_1/R_0)^2 / (1 + C_cell / (C_core * tfac))
    # When C_core >> C_cell: alpha -> (R_1/R_0)^2 (core tracks mantle)
    # When C_core << C_cell: alpha -> 0 (core absorbs all heat)
    tfac = self._settings.tfac_core_avg
    alpha = radius_ratio**2 / (cell_capacity / (core_capacity * tfac) + 1)

    state.heat_flux[0, :] = alpha * state.heat_flux[1, :]

grey_body(state)

Applies a grey body flux at the surface.

When param_utbl is enabled, the surface radiating temperature is reduced to account for the ultra-thin thermal boundary layer at the magma ocean surface. The temperature drop across this unresolved boundary layer is parameterized as dT = b * T_surf^3 (Bower et al. 2018, Eq. 18), giving the cubic relation T_interior = T_surf + b * T_surf^3. The analytical solution (Cardano's formula) gives T_surf < T_interior.

Parameters:

Name Type Description Default
state State

The state to apply the boundary conditions to.

required
Source code in src/aragog/solver/boundary.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def grey_body(self, state: State) -> None:
    """Applies a grey body flux at the surface.

    When param_utbl is enabled, the surface radiating temperature is reduced
    to account for the ultra-thin thermal boundary layer at the magma ocean
    surface. The temperature drop across this unresolved boundary layer is
    parameterized as dT = b * T_surf^3 (Bower et al. 2018, Eq. 18), giving
    the cubic relation T_interior = T_surf + b * T_surf^3. The analytical
    solution (Cardano's formula) gives T_surf < T_interior.

    Parameters
    ----------
    state : State
        The state to apply the boundary conditions to.
    """
    t_top = state.top_temperature
    if self._settings.param_utbl:
        t_surf = self._utbl_tsurf(t_top)
    else:
        t_surf = t_top
    state.heat_flux[-1, :] = (
        self._settings.emissivity
        * sp_constants.Stefan_Boltzmann
        * (np.power(t_surf, 4) - self._settings.equilibrium_temperature**4)
    )

EntropySolver(parameters, entropy_eos=None)

Entropy-based interior dynamics solver.

Drop-in replacement for Solver (T-based) when using PALEOS P-S tables. Same interface: initialize() -> set_initial_entropy() -> solve(). PROTEUS can swap Solver for EntropySolver without changing the wrapper.

Parameters:

Name Type Description Default
parameters Parameters

Parsed configuration (same as T-based Solver).

required
entropy_eos EntropyEOS

Loaded P-S EOS tables.

None
Source code in src/aragog/solver/entropy_solver.py
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
def __init__(self, parameters: Parameters, entropy_eos: EntropyEOS | None = None):
    self.parameters = parameters
    self.entropy_eos = entropy_eos
    self.evaluator: object
    self.state: EntropyState
    self._solution: OptimizeResult
    self.stop_early: bool = False
    # Optional factory that builds JAX-derived CVODE callbacks.
    # Signature: factory(scales, core_bc_mode) -> (rhs_fn, jac_fn)
    # where ``scales`` is an aragog.jax.nondim.NonDimScales
    # instance built by ``_build_nondim_scales``. The factory is
    # registered by PROTEUS via ``set_jax_cvode_factory()`` when
    # ``config.interior_energetics.aragog.use_jax_jacobian`` is True.
    self._jax_cvode_factory = None
    # Number of output points CVODE returns per macro-step solve.
    # The per-call energy integrals trapezoidate the boundary fluxes
    # over this grid; the surface flux decays steeply within a long
    # call, so two endpoints under-resolve it (the F_int integral can
    # be tens of percent wrong over a multi-kyr step, which is the
    # dominant term in ``E_residual_cons_frac``). CVODE interpolates
    # these points from its own internal steps, so a finer output grid
    # sharpens the diagnostic without changing the integration, the
    # final state, or ``dt_actual``. Only the non-root path uses it;
    # when a phi-step-cap root fires the call already stops early.
    self._cvode_output_points = 65
    # Compression work [J] from the most recent structure re-solve.
    # When the planet contracts, the static pressure at each frozen
    # mass element rises, so the mantle enthalpy gains the adiabatic
    # compression term ``Sum mass (h(P_new, S) - h(P_old, S))`` at
    # fixed entropy. Exposed as an informational diagnostic only: the
    # coupler does NOT add it to the predicted energy. The conservation
    # residual differences the boundary-flux budget against the
    # entropy-transported heat (``step_dE_state_heat_J``, Sum rho T dS),
    # which is P-jump-agnostic, so no PdV energy is dropped from that
    # check and adding compression to the predicted side would
    # double-count. Zero for a static structure (P unchanged) and for
    # the first solve (no prior mesh).
    self._last_compression_J = 0.0
    # Staggered mass coordinates captured before a structure re-solve.
    # The carried entropy is interpolated from these onto the new mass
    # grid per parcel (``_remap_entropy_to_current_mesh``) so a parcel
    # keeps its entropy when the total mantle mass drifts across the
    # re-solve. One-shot: consumed by the next ``set_initial_entropy``.
    self._xi_pre_resolve = None

entropy_staggered property

Entropy at staggered nodes from the solution.

For bower2018 and energy_balance modes the solver state vector is N+1 in length; we strip the trailing extra row and return only the entropy block. For gradient mode, we reconstruct S from the gradient state.

solution property

Last solve_ivp result, or None if solve() has not been called yet. Returning None (instead of raising AttributeError) matters for the PROTEUS JAX dispatch path, where AragogJAXRunner handles the actual integration and the scipy EntropySolver lives only to hold Parameters / BC state โ€” its solve() is never invoked, so _solution is never set. Callers already handle sol is None.

staggered_mass_coordinates property

Lagrangian mass coordinate at each staggered node.

Labels each mass parcel independently of physical radius, which shifts when the structure re-solves. Used to carry the entropy field across a re-solve by parcel rather than by node index.

temperature_staggered property

Temperature at staggered nodes (derived from S via EOS).

dSdt(time, state_vec)

Time derivative of the full state vector.

For the bower2018 core BC the state vector is [S_0, ..., S_{N-1}, T_core] of length N+1, and this returns [dS/dt, dT_core/dt] of the same length.

For the quasi_steady BC the state vector is just [S_0, ..., S_{N-1}] of length N.

The integrator passes vectorized=False; this RHS handles the 1D path only.

Parameters:

Name Type Description Default
time float

Time [yr].

required
state_vec array

Solver state vector [J/kg/K for entropy, K for T_core]. Shape (N,) or (N+1,) only.

required

Returns:

Type Description
array

d(state_vec)/dt with the same shape as the input.

Source code in src/aragog/solver/entropy_solver.py
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
def dSdt(
    self,
    time: npt.NDArray | float,
    state_vec: npt.NDArray,
) -> npt.NDArray:
    """Time derivative of the full state vector.

    For the ``bower2018`` core BC the state vector is
    ``[S_0, ..., S_{N-1}, T_core]`` of length N+1, and this returns
    ``[dS/dt, dT_core/dt]`` of the same length.

    For the quasi_steady BC the state vector is just
    ``[S_0, ..., S_{N-1}]`` of length N.

    The integrator passes ``vectorized=False``; this RHS handles
    the 1D path only.

    Parameters
    ----------
    time : float
        Time [yr].
    state_vec : array
        Solver state vector [J/kg/K for entropy, K for T_core].
        Shape (N,) or (N+1,) only.

    Returns
    -------
    array
        d(state_vec)/dt with the same shape as the input.
    """
    return self._dSdt_single(time, state_vec)

from_file(filename, eos_dir, root='') classmethod

Create EntropySolver from a config file and EOS directory.

Parameters:

Name Type Description Default
filename str

Path to TOML configuration file.

required
eos_dir str

Path to directory with SPIDER-format P-S tables.

required
root str

Root directory for the config file.

''
Source code in src/aragog/solver/entropy_solver.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
@classmethod
def from_file(cls, filename: str, eos_dir: str, root: str = '') -> 'EntropySolver':
    """Create EntropySolver from a config file and EOS directory.

    Parameters
    ----------
    filename : str
        Path to TOML configuration file.
    eos_dir : str
        Path to directory with SPIDER-format P-S tables.
    root : str
        Root directory for the config file.
    """
    config_path = Path(root) / Path(filename)
    parameters = Parameters.from_file(config_path)
    entropy_eos = EntropyEOS(Path(eos_dir))
    return cls(parameters, entropy_eos)

get_current_dSdr_cmb()

Return the most recent CMB entropy gradient from the solver state.

Reads self._solution.y[n_stag, -1] (the final dSdr_cmb from the last accepted solve). Returns None when no solution exists yet, or when the state vector lacks the dSdr_cmb slot (core_bc other than energy_balance).

Used by PROTEUS's retry ladder to snapshot the pre-solve dSdr_cmb before a sequence of retry attempts and restore it on each retry, breaking the positive-feedback loop where a rejected attempt's final dSdr_cmb would otherwise become the next retry's hot-start IC and drive the boundary state further from the pre-solve value each time.

Source code in src/aragog/solver/entropy_solver.py
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
def get_current_dSdr_cmb(self) -> float | None:
    """Return the most recent CMB entropy gradient from the solver state.

    Reads ``self._solution.y[n_stag, -1]`` (the final dSdr_cmb from the
    last accepted solve). Returns ``None`` when no solution exists yet,
    or when the state vector lacks the dSdr_cmb slot (core_bc other
    than ``energy_balance``).

    Used by PROTEUS's retry ladder to snapshot the pre-solve
    dSdr_cmb before a sequence of retry attempts and restore it on
    each retry, breaking the positive-feedback loop where a
    rejected attempt's final dSdr_cmb would otherwise become the
    next retry's hot-start IC and drive the boundary state further
    from the pre-solve value each time.
    """
    n_stag = getattr(self, '_n_stag', None)
    prev_sol = getattr(self, '_solution', None)
    if (
        n_stag is None
        or prev_sol is None
        or getattr(prev_sol, 'y', None) is None
        or prev_sol.y.size == 0
        or prev_sol.y.shape[0] != n_stag + 1
    ):
        return None
    return float(prev_sol.y[n_stag, -1])

get_state()

Extract the solver state as a clean output dataclass.

This is the primary API for callers to retrieve results. It avoids the need to access solver internals (evaluator, mesh, state, phase objects).

Returns:

Type Description
SolverOutput

Dataclass containing all quantities needed by PROTEUS.

Source code in src/aragog/solver/entropy_solver.py
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
def get_state(self) -> SolverOutput:
    """Extract the solver state as a clean output dataclass.

    This is the primary API for callers to retrieve results. It
    avoids the need to access solver internals (evaluator, mesh,
    state, phase objects).

    Returns
    -------
    SolverOutput
        Dataclass containing all quantities needed by PROTEUS.
    """
    sol = self._solution
    eos = self.entropy_eos
    mesh = self.evaluator.mesh

    n_stag = self._n_stag
    energy_balance = self._core_bc == 'energy_balance'
    bower = self._core_bc == 'bower2018'
    gradient_mode = self._core_bc == 'gradient'
    is_ext = energy_balance or bower

    # Compute per-call energy integrals BEFORE refreshing state at
    # the final entropy. ``_compute_step_energy_integrals`` walks
    # the CVODE trajectory and calls state.update() at each
    # accepted sub-step; doing it before the final refresh keeps
    # the end-of-call snapshot (heat_flux, heating arrays, etc.)
    # consistent with what callers see in the rest of get_state().
    step_integrals = self._compute_step_energy_integrals()

    # Slice the final state vector.
    if gradient_mode:
        n_basic = n_stag + 1
        dSdr_final = sol.y[:n_basic, -1]
        S_surf_final = float(sol.y[n_basic, -1])
        S_final, S_basic_final = self._reconstruct_entropy(dSdr_final, S_surf_final)
        extra_final = None
    elif is_ext:
        S_final = sol.y[:n_stag, -1]
        extra_final = float(sol.y[n_stag, -1])
    else:
        S_final = sol.y[:, -1]
        extra_final = None

    P_stag = self._P_stag_flat
    r_basic = self._r_basic_flat
    r_stag = np.asarray(mesh.staggered.radii).ravel()
    vol = self._volume_flat

    if eos is not None:
        T_stag = np.asarray(eos.temperature(P_stag, S_final)).ravel()
        phi_stag = np.asarray(eos.melt_fraction(P_stag, S_final)).ravel()
        rho_stag = np.asarray(eos.density(P_stag, S_final)).ravel()
    else:
        # const_properties: analytical T, phi=1, rho=const
        pm = self.parameters.phase_mixed
        T_stag = pm.const_T_ref * np.exp((S_final - pm.const_S_ref) / pm.const_Cp)
        phi_stag = np.ones_like(S_final)
        rho_stag = np.full_like(S_final, pm.const_rho)

    # Refresh the state at the final entropy for derived quantities.
    if gradient_mode:
        self.state.update(S_final, sol.t[-1], dSdr=dSdr_final, entropy_basic=S_basic_final)
    elif energy_balance:
        self.state.update(S_final, sol.t[-1], dSdr_cmb=extra_final)
    else:
        self.state.update(S_final, sol.t[-1])
    visc_stag = np.asarray(self.state.phase_staggered.viscosity()).ravel()
    heat_flux = self.state.heat_flux.copy()
    heating = self.state.heating.copy()
    eddy_diff = self.state.eddy_diffusivity.copy()
    cap_stag = np.asarray(self.state.capacitance_staggered()).ravel()

    # Diagnostic snapshot from the post-integration state.update().
    jcond_b = self.state.jcond.copy()
    jconv_b = self.state.jconv.copy()
    jgrav_b = self.state.jgrav_heat.copy()
    jmix_b = self.state.jmix_heat.copy()
    dSdr_b = self.state.dSdr.copy()
    phi_basic_diag = self.state.phi_basic_diag.copy()
    T_basic_diag = self.state.T_basic_diag.copy()
    cp_basic_diag = self.state.cp_basic_diag.copy()
    rho_basic_diag = self.state.rho_basic_diag.copy()

    # Scalar quantities.
    # M_mantle uses the analytic A-W mass integral (matching
    # SPIDER's EOSAdamsWilliamson_GetMassWithinShell) when
    # eos_method=1. The discrete sum (rho_stag * vol) has O(h^2)
    # quadrature error vs the analytic integral, causing the
    # structure root finder to converge to a different R_int.
    # For eos_method=2 (external mesh), fall back to discrete sum.
    mesh = self.evaluator.mesh
    if hasattr(mesh.eos, 'get_mass_within_radii'):
        r_cmb = float(self._r_basic_flat[0])
        r_surf = float(self._r_basic_flat[-1])
        M_mantle = (
            mesh.eos.get_mass_within_radii(np.array([r_surf]))
            - mesh.eos.get_mass_within_radii(np.array([r_cmb]))
        ).item()
    else:
        rho_struct_stag = np.asarray(mesh.staggered_effective_density).ravel()
        mass_stag = rho_struct_stag * vol
        M_mantle = float(np.sum(mass_stag))
    mass_stag = rho_stag * vol  # PALEOS density for per-cell output
    # T_magma = top basic-node temperature, evaluated at
    # r = outer_boundary where P = surface_pressure. This matches
    # SPIDER's `atmosphere/temperature_surface` definition.
    # PROTEUS passes T_magma to the atmosphere module as the
    # interior-side surface boundary condition.
    T_basic_final = np.asarray(self.state.phase_basic.temperature()).ravel()
    T_magma = float(T_basic_final[-1])
    # Core temperature: bottom staggered cell (T_stag[0]).
    # SPIDER reports T_core = interior_o.temp[-1], the last
    # staggered node in its surface-to-CMB ordering. Aragog
    # orders CMB-to-surface, so [0] = CMB cell. Reading T_stag[0]
    # rather than evaluating T at the CMB basic node avoids a
    # systematic ~10 K offset from the half-cell pressure
    # difference and matches SPIDER's definition.
    if bower:
        T_core = extra_final  # bower2018: T_core integrated as ODE state
    else:
        T_core = float(T_stag[0])
    # Mass-weighted melt fraction = M_mantle_liquid / M_mantle.
    # MUST be mass-weighted, not volume-weighted, when
    # ``mass_coordinates = true``: the mesh is uniform in mass
    # coordinate, so deep high-density cells span small radial
    # intervals and have small volumes while surface low-density
    # cells are large. During bottom-up crystallisation the
    # surface stays liquid longest, so volume-weighted Phi stays
    # anchored near the surface value while the actual mantle has
    # crystallised, freezing the helpfile Phi and breaking
    # PROTEUS's stop-criterion + structure-update bookkeeping.
    # Matches the rootfn formula bit-for-bit.
    mass_total_for_phi = float(np.sum(mass_stag))
    if mass_total_for_phi > 0.0:
        Phi_global = float(np.sum(phi_stag * mass_stag) / mass_total_for_phi)
    else:
        Phi_global = float(np.mean(phi_stag))

    # Rheological front depth. ``phi_basic_stag_interp`` is the
    # staggered-phi interpolated to basic nodes -- distinct from the
    # EOS-evaluated ``phi_basic_diag`` captured for the diagnostic
    # output above, which is ``phase_basic.melt_fraction()``.
    phi_rheo = self.parameters.phase_mixed.rheological_transition_melt_fraction
    phi_basic_stag_interp = mesh.quantity_at_basic_nodes(phi_stag).ravel()
    # 0.99 / 0.01 bypass thresholds: short-circuit ``argmin`` when no
    # transition exists in the mantle (essentially-fully-liquid or
    # essentially-fully-solid). These mirror ``rheological_front`` in
    # ``output/diagnostics.py`` (now exposed as ``phi_high`` /
    # ``phi_low`` kwargs there). The ``argmin``-based search assumes
    # bottom-up crystallisation โ€” a middle-out solidification mode
    # would need a redefined RF concept (multiple crossings).
    if Phi_global > 0.99:
        rf = float(r_basic[0])
    elif Phi_global < 0.01:
        rf = float(r_basic[-1])
    else:
        idx = np.argmin(np.abs(phi_basic_stag_interp - phi_rheo))
        rf = float(r_basic[idx])
    R_outer = float(r_basic[-1])
    RF_depth = 1.0 - rf / R_outer if R_outer > 0 else 0.0

    # Thermal energy (sensible, for comparison with SPIDER).
    # Uses the real heat capacity Cp(P, S) from the EntropyEOS
    # phase evaluator so that E_th tracks the EOS internal energy
    # consistently with the solver state, rather than a fixed
    # reference Cp.
    Cp_stag = np.asarray(self.state.phase_staggered.heat_capacity()).ravel()
    E_th = float(np.sum(mass_stag * Cp_stag * T_stag))

    # Effective heat capacity (mass-weighted mean Cp)
    Cp_eff = float(np.sum(mass_stag * Cp_stag)) / max(M_mantle, 1.0)

    # EOS-consistent mantle integrated enthalpy [J]. Falls back
    # to NaN when no entropy EOS is loaded (e.g. const_properties
    # path), signalling to PROTEUS that the conservation diagnostic
    # is not available for this run.
    if eos is not None:
        from aragog.output.diagnostics import total_enthalpy

        E_state = total_enthalpy(eos, P_stag, S_final, mass_stag)
        # Conservation-grade integrated enthalpy with FROZEN
        # structural mass per shell. Same enthalpy table, but the
        # mass weighting matches the entropy ODE's frame so that
        # d/dt[E_state_cons] equals the divergence-of-flux budget
        # (with frozen-mass Q_*_cons) to numerical precision.
        mass_struct_stag = np.asarray(mesh.staggered_effective_density).ravel() * vol
        E_state_cons = total_enthalpy(eos, P_stag, S_final, mass_struct_stag)
    else:
        E_state = float('nan')
        E_state_cons = float('nan')

    # CMB heat flux: lower-boundary value of the basic-node heat
    # flux array. Sign convention follows the rest of Aragog,
    # positive-out-of-core when entering the mantle.
    F_cmb = float(heat_flux[0])

    # Mantle-integrated source powers [W] for the closed-mantle
    # energy balance dE/dt = -F_int*A_int + F_cmb*A_cmb + Q_radio +
    # Q_tidal. Each per-source heating array is in W/kg at staggered
    # nodes; mass-weighting recovers the total power.
    Q_radio_total = float(np.dot(np.asarray(self.state.heating_radio).ravel(), mass_stag))
    Q_tidal_total = float(np.dot(np.asarray(self.state.heating_tidal).ravel(), mass_stag))

    # Volumetric melt fraction (porosity-based)
    if eos is not None:
        rho_sol = np.asarray(
            eos._lookup_at_phase_boundary('density', P_stag, 'solid')
        ).ravel()
        rho_liq = np.asarray(
            eos._lookup_at_phase_boundary('density', P_stag, 'melt')
        ).ravel()
        rho_bulk = 1.0 / (
            phi_stag / np.where(rho_liq > 0, rho_liq, 1.0)
            + (1 - phi_stag) / np.where(rho_sol > 0, rho_sol, 1.0)
        )
        drho = rho_sol - rho_liq
        safe_drho = np.where(np.abs(drho) > 1e-10, drho, 1.0)
        porosity = np.clip((rho_sol - rho_bulk) / safe_drho, 0, 1)
        Phi_global_vol = float(np.sum(porosity * vol) / np.sum(vol))
    else:
        Phi_global_vol = 1.0  # const_properties: fully liquid

    # Heating flux
    area_surf = 4 * np.pi * float(r_basic[-1]) ** 2
    F_heat_total = float(np.dot(heating, mass_stag)) / area_surf

    return SolverOutput(
        S_final=S_final,
        T_stag=T_stag,
        phi_stag=phi_stag,
        rho_stag=rho_stag,
        visc_stag=visc_stag,
        P_stag=P_stag,
        r_basic=r_basic,
        r_stag=r_stag,
        vol=vol,
        mass_stag=mass_stag,
        heat_flux=heat_flux,
        heating=heating,
        eddy_diff=eddy_diff,
        cap_stag=cap_stag,
        T_magma=T_magma,
        T_core=T_core,
        Phi_global=Phi_global,
        Phi_global_vol=Phi_global_vol,
        M_mantle=M_mantle,
        M_mantle_liquid=float(np.sum(phi_stag * mass_stag)),
        M_mantle_solid=float(M_mantle - np.sum(phi_stag * mass_stag)),
        RF_depth=RF_depth,
        E_th=E_th,
        E_state=E_state,
        E_state_cons=E_state_cons,
        Cp_eff=Cp_eff,
        F_heat_total=F_heat_total,
        F_cmb=F_cmb,
        Q_radio_total=Q_radio_total,
        Q_tidal_total=Q_tidal_total,
        step_dE_F_int_J=step_integrals['F_int'],
        step_dE_F_cmb_J=step_integrals['F_cmb'],
        step_dE_Q_radio_J=step_integrals['Q_radio'],
        step_dE_Q_tidal_J=step_integrals['Q_tidal'],
        step_dE_Q_radio_cons_J=step_integrals['Q_radio_cons'],
        step_dE_Q_tidal_cons_J=step_integrals['Q_tidal_cons'],
        step_solver_residual_J=step_integrals['solver_residual'],
        # state_heat is the conservation-budget state term (Sum rho T dS);
        # compression is an informational PdV diagnostic from the preceding
        # structure re-solve, deliberately kept out of the predicted energy
        # to avoid double-counting the same work (see the SolverOutput field
        # comments and docs/Explanations/energy_diagnostics.md).
        step_dE_compression_J=float(getattr(self, '_last_compression_J', 0.0)),
        step_dE_state_heat_J=step_integrals['state_heat'],
        dt_actual=float(sol.t[-1] - sol.t[0]),
        status=sol.status,
        jcond_b=jcond_b,
        jconv_b=jconv_b,
        jgrav_b=jgrav_b,
        jmix_b=jmix_b,
        dSdr_b=dSdr_b,
        phi_basic=phi_basic_diag,
        T_basic=T_basic_diag,
        cp_basic=cp_basic_diag,
        rho_basic=rho_basic_diag,
    )

initialize()

Initialize mesh, boundary conditions, and entropy state.

Unlike the T-based Solver, we only need the mesh and BCs from the Evaluator. The T-based phase evaluators (which require solidus/liquidus files) are replaced by EntropyPhaseEvaluator.

Source code in src/aragog/solver/entropy_solver.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
def initialize(self) -> None:
    """Initialize mesh, boundary conditions, and entropy state.

    Unlike the T-based Solver, we only need the mesh and BCs from
    the Evaluator. The T-based phase evaluators (which require
    solidus/liquidus files) are replaced by EntropyPhaseEvaluator.
    """
    logger.info('Initializing EntropySolver')
    self._initialize_internals()

reset()

Reset for a new integration (PROTEUS coupling loop).

Re-reads the EOS mesh file if eos_method=2, then rebuilds the mesh, BCs, and entropy state. Matches Solver.reset().

Source code in src/aragog/solver/entropy_solver.py
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
def reset(self) -> None:
    """Reset for a new integration (PROTEUS coupling loop).

    Re-reads the EOS mesh file if eos_method=2, then rebuilds
    the mesh, BCs, and entropy state. Matches Solver.reset().
    """
    logger.info('Resetting EntropySolver')
    # Snapshot the pre-re-solve pressure, carried entropy and frozen
    # mass so the compression work across the mesh change can be
    # measured once the new mesh is built (see ``_last_compression_J``),
    # and the staggered mass coordinates so the carried entropy can be
    # remapped onto the new mass grid per parcel.
    P_old, S_old, mass_old = self._snapshot_for_compression()
    try:
        self._xi_pre_resolve = self.staggered_mass_coordinates.copy()
    except (AttributeError, TypeError):
        self._xi_pre_resolve = None
    if self.parameters.mesh.eos_method == 2 and self.parameters.mesh.eos_file:
        arr = np.loadtxt(self.parameters.mesh.eos_file)
        self.parameters.mesh.eos_radius = arr[:, 0]
        self.parameters.mesh.eos_pressure = arr[:, 1]
        self.parameters.mesh.eos_density = arr[:, 2]
        self.parameters.mesh.eos_gravity = arr[:, 3]
        _validate_eos_radius_range(self.parameters.mesh)
    self._initialize_internals()
    self._last_compression_J = self._compute_compression_work(P_old, S_old, mass_old)

set_initial_core_temperature(T_core_init)

Set the initial core temperature (bower2018 core_bc only).

Must be called BEFORE set_initial_entropy. If not called, the initial T_core defaults to the bottom-cell mantle temperature derived from S_init via the EOS.

Source code in src/aragog/solver/entropy_solver.py
1755
1756
1757
1758
1759
1760
1761
1762
def set_initial_core_temperature(self, T_core_init: float) -> None:
    """Set the initial core temperature (``bower2018`` core_bc only).

    Must be called BEFORE ``set_initial_entropy``. If not called,
    the initial T_core defaults to the bottom-cell mantle
    temperature derived from S_init via the EOS.
    """
    self._T_core_init = float(T_core_init)

set_initial_dSdr_cmb(dSdr_cmb_init)

Set the initial CMB entropy gradient (energy_balance mode only).

Must be called BEFORE set_initial_entropy. If not called, the initial dSdr_cmb is taken from the previous solution (if any), else from a one-sided FD of the staggered S_init at the bottom (which is zero for a uniform isentrope).

Pass None to clear a previously-set override, restoring the hot-start behaviour on the next call to set_initial_entropy. Used by PROTEUS's retry ladder to restore the pre-solve dSdr_cmb after a rejection, then release the override so the subsequent coupling step can hot-start from its own _solution normally.

Source code in src/aragog/solver/entropy_solver.py
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
def set_initial_dSdr_cmb(self, dSdr_cmb_init: float | None) -> None:
    """Set the initial CMB entropy gradient (energy_balance mode only).

    Must be called BEFORE ``set_initial_entropy``. If not called,
    the initial ``dSdr_cmb`` is taken from the previous solution
    (if any), else from a one-sided FD of the staggered S_init at
    the bottom (which is zero for a uniform isentrope).

    Pass ``None`` to clear a previously-set override, restoring
    the hot-start behaviour on the next call to
    ``set_initial_entropy``. Used by PROTEUS's retry ladder to
    restore the pre-solve dSdr_cmb after a rejection, then release
    the override so the subsequent coupling step can hot-start
    from its own ``_solution`` normally.
    """
    self._dSdr_cmb_init = None if dSdr_cmb_init is None else float(dSdr_cmb_init)

set_initial_entropy(S_init)

Set the initial entropy profile and (if used) initial T_core.

Parameters:

Name Type Description Default
S_init array or float

Entropy at staggered nodes [J/kg/K]. If scalar, sets uniform (isentropic) profile.

required
Notes

State vector length depends on the active core BC mode: quasi_steady uses length N; energy_balance and bower2018 use length N+1 (entropy block plus one extra state variable: dSdr_cmb or T_core respectively); gradient uses length N+2. For the bower2018 mode the initial T_core is taken from the bottom-cell mantle temperature derived from S_init via the EOS unless set_initial_core_temperature has been called first.

Source code in src/aragog/solver/entropy_solver.py
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
def set_initial_entropy(self, S_init: npt.NDArray | float) -> None:
    """Set the initial entropy profile and (if used) initial T_core.

    Parameters
    ----------
    S_init : array or float
        Entropy at staggered nodes [J/kg/K]. If scalar, sets uniform
        (isentropic) profile.

    Notes
    -----
    State vector length depends on the active core BC mode:
    ``quasi_steady`` uses length N; ``energy_balance`` and
    ``bower2018`` use length N+1 (entropy block plus one extra
    state variable: ``dSdr_cmb`` or ``T_core`` respectively);
    ``gradient`` uses length N+2. For the bower2018 mode the
    initial ``T_core`` is taken from the bottom-cell mantle
    temperature derived from ``S_init`` via the EOS unless
    ``set_initial_core_temperature`` has been called first.
    """
    # Prefer the cached _n_stag from _initialize_internals; fall
    # back to the mesh accessor for legacy callers that bypass it.
    if hasattr(self, '_n_stag') and self._n_stag is not None:
        n_stag = self._n_stag
    else:
        n_stag = self.evaluator.mesh.staggered.radii.shape[0]
        self._n_stag = n_stag

    if np.isscalar(S_init):
        S_arr = np.full(n_stag, float(S_init))
    else:
        S_arr = np.asarray(S_init, dtype=float)
        if len(S_arr) != n_stag:
            raise ValueError(f'S_init length {len(S_arr)} != mesh staggered nodes {n_stag}')

    # Carry the entropy onto the current mesh by mass parcel when a
    # structure re-solve changed the mass grid (no-op otherwise, and
    # always consumes the cached pre-resolve grid).
    S_arr = self._remap_entropy_to_current_mesh(S_arr)

    # Prefer the cached _core_bc from _initialize_internals.
    if hasattr(self, '_core_bc') and self._core_bc is not None:
        core_bc = self._core_bc
    else:
        core_bc = getattr(self.parameters.boundary_conditions, 'core_bc', 'quasi_steady')
        self._core_bc = core_bc
    logger.debug('set_initial_entropy: core_bc=%r, n_stag=%d', core_bc, n_stag)

    if core_bc == 'energy_balance':
        # SPIDER bit-parity core BC (energy_balance mode).
        # State = [S_0, ..., S_{N-1}, dSdr_cmb]
        # The boundary state dSdr_cmb is the entropy gradient at
        # the CMB basic node (mirror of SPIDER's dSdxi[ind_cmb]).
        # Its time derivative is set by the bc.c:76-131 formula
        # in _dSdt_single from the actual physical heat flux.
        #
        # Cold-start dSdr_cmb_init: use the finite-difference
        # estimate from the staggered cells (one-sided forward
        # difference, since there's no cell below the CMB).
        # The boundary state will then evolve from this to its
        # quasi-equilibrium value over the first few coupling
        # steps as the energy balance constraint kicks in.
        #
        # Hot-start dSdr_cmb_init: preserve from the previous
        # solution if available, so the integrated boundary state
        # survives PROTEUS coupling resets.
        dSdr_cmb_init = getattr(self, '_dSdr_cmb_init', None)
        if dSdr_cmb_init is None:
            # Hot start: preserve from previous solution if shape matches
            prev_sol = getattr(self, '_solution', None)
            if (
                prev_sol is not None
                and getattr(prev_sol, 'y', None) is not None
                and prev_sol.y.size > 0
                and prev_sol.y.shape[0] == n_stag + 1
            ):
                dSdr_cmb_init = float(prev_sol.y[n_stag, -1])
                logger.info(
                    'Preserved dSdr_cmb from previous solve: %.3e J/kg/K/m',
                    dSdr_cmb_init,
                )
        if dSdr_cmb_init is None:
            # Cold start: one-sided FD of S_init at the bottom.
            # dSdr_cmb โ‰ˆ (S_stag[1] - S_stag[0]) / (r_stag[1] - r_stag[0])
            # For a uniform S_init this is exactly zero, which
            # is the correct neutral-buoyancy starting point.
            if n_stag >= 2:
                r_basic = np.asarray(self.evaluator.mesh.basic.radii).ravel()
                r_stag_0 = 0.5 * (r_basic[0] + r_basic[1])
                r_stag_1 = 0.5 * (r_basic[1] + r_basic[2])
                dSdr_cmb_init = (float(S_arr[1]) - float(S_arr[0])) / max(
                    r_stag_1 - r_stag_0, 1.0
                )
            else:
                dSdr_cmb_init = 0.0
            logger.info(
                'Cold-start dSdr_cmb from FD: %.3e J/kg/K/m',
                dSdr_cmb_init,
            )
        self._S0 = np.empty(n_stag + 1)
        self._S0[:n_stag] = S_arr
        self._S0[n_stag] = float(dSdr_cmb_init)
        logger.info(
            'Initial state (energy_balance): S_min=%.0f, S_max=%.0f, dSdr_cmb_init=%.3e',
            S_arr.min(),
            S_arr.max(),
            dSdr_cmb_init,
        )
    elif core_bc == 'bower2018':
        # Core temperature as ODE state variable (conduction-only
        # flux). State = [S, T_core]. Available for parity testing
        # only; not recommended for production runs.
        T_core_init = getattr(self, '_T_core_init', None)
        if T_core_init is None:
            prev_sol = getattr(self, '_solution', None)
            if (
                prev_sol is not None
                and getattr(prev_sol, 'y', None) is not None
                and prev_sol.y.size > 0
                and prev_sol.y.shape[0] == n_stag + 1
            ):
                T_core_init = float(prev_sol.y[n_stag, -1])
        if T_core_init is None:
            P_bottom = float(self._P_stag_flat[0])
            T_core_init = float(
                np.asarray(
                    self.entropy_eos.temperature(np.array([P_bottom]), np.array([S_arr[0]]))
                ).item()
            )
        self._S0 = np.empty(n_stag + 1)
        self._S0[:n_stag] = S_arr
        self._S0[n_stag] = T_core_init
        logger.info(
            'Initial state (bower2018): S_min=%.0f, S_max=%.0f, T_core_init=%.0f K',
            S_arr.min(),
            S_arr.max(),
            T_core_init,
        )
    elif core_bc == 'gradient':
        # Gradient-based formulation mirroring SPIDER's dS/dxi state.
        # State = [dS/dr at N+1 basic nodes, S_surf], length N+2.
        # S at staggered nodes is reconstructed by cumulative sum
        # at each RHS evaluation, providing the global smoothing
        # that prevents BDF overshoot at the solidus.
        mesh = self.evaluator.mesh
        dSdr_init = mesh.d_dr_at_basic_nodes(S_arr).ravel()
        n_basic = len(dSdr_init)
        S_surf = float(S_arr[-1])
        self._S0 = np.empty(n_basic + 1)
        self._S0[:n_basic] = dSdr_init
        self._S0[n_basic] = S_surf
        # Verify roundtrip
        S_check, _ = self._reconstruct_entropy(dSdr_init, S_surf)
        roundtrip_err = float(np.max(np.abs(S_check - S_arr)))
        logger.info(
            'Initial state (gradient): dSdr range [%.3e, %.3e] J/kg/K/m, '
            'S_surf=%.1f, roundtrip err=%.2e J/kg/K',
            dSdr_init.min(),
            dSdr_init.max(),
            S_surf,
            roundtrip_err,
        )
    else:
        # quasi_steady BC: state = [S_0, ..., S_{N-1}]
        self._S0 = S_arr
        logger.info(
            'Initial entropy (quasi_steady BC): S_min=%.0f, S_max=%.0f J/kg/K',
            S_arr.min(),
            S_arr.max(),
        )

set_jax_cvode_factory(factory)

Register a factory that produces JAX-derived CVODE callbacks.

The factory is called inside solve() when use_jax_jacobian is enabled in the config. It is given the current nondim scaling spec (NonDimScales) and core-BC mode and must return the (rhs_fn, jac_fn) pair accepted by scikits.odes CVODE.

Parameters:

Name Type Description Default
factory callable

factory(scales, core_bc_mode) -> (rhs_fn, jac_fn) where scales is an aragog.jax.nondim.NonDimScales instance. May be None to disable the Option Z path even if the flag is on.

required
Source code in src/aragog/solver/entropy_solver.py
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def set_jax_cvode_factory(self, factory) -> None:
    """Register a factory that produces JAX-derived CVODE callbacks.

    The factory is called inside ``solve()`` when ``use_jax_jacobian``
    is enabled in the config. It is given the current nondim scaling
    spec (NonDimScales) and core-BC mode and must return the
    ``(rhs_fn, jac_fn)`` pair accepted by scikits.odes CVODE.

    Parameters
    ----------
    factory : callable
        ``factory(scales, core_bc_mode) -> (rhs_fn, jac_fn)`` where
        ``scales`` is an ``aragog.jax.nondim.NonDimScales`` instance.
        May be None to disable the Option Z path even if the flag
        is on.
    """
    self._jax_cvode_factory = factory

solve()

Run the BDF time integration.

Source code in src/aragog/solver/entropy_solver.py
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
def solve(self) -> None:
    """Run the BDF time integration."""
    start_time = self.parameters.solver.start_time
    end_time = self.parameters.solver.end_time
    # Absolute tolerance floor (1e-8) matches SPIDER's atol=rtol.
    # Tight tolerance is necessary to resolve the crystallisation
    # front and prevent cumulative integration error during long
    # solidification runs.
    atol_base = max(self.parameters.solver.atol, 1.0e-8)
    rtol = self.parameters.solver.rtol

    # Phase-aware atol: tight during crystallization, relaxed
    # only when fully solid.
    try:
        n_stag = self._n_stag
        if self._core_bc == 'gradient':
            # Gradient mode: reconstruct S to compute phi0
            n_basic = n_stag + 1
            dSdr0 = self._S0[:n_basic]
            S_surf0 = float(self._S0[n_basic])
            S0_block, _ = self._reconstruct_entropy(dSdr0, S_surf0)
        elif self._state_is_extended:
            S0_block = self._S0[:n_stag]
        else:
            S0_block = self._S0
        phi0 = float(
            np.asarray(self.entropy_eos.melt_fraction(self._P_stag_flat, S0_block)).mean()
        )
        phi0 = max(0.0, min(1.0, phi0))
    except Exception:
        phi0 = 1.0

    if phi0 > 0.01:
        atol_scale = 1.0
        max_step = 100.0  # years
    else:
        atol_scale = 10.0
        max_step = np.inf

    # phi_cap_anchor stores the step-cap anchor dict for the SUNDIALS
    # rootfn / scipy event, or None when no cap is armed. Initialised
    # here so the consumer at the bottom of solve() never hits an
    # UnboundLocalError when the EOS branch below is skipped (e.g. the
    # const_properties path with no EOS).
    phi_cap_anchor = None

    # Tighten max_step when ANY cell is near a phase boundary and arm the
    # step caps. Runs whenever the entropy EOS is loaded, independent of
    # the mean melt fraction: the temperature and entropy caps must stay
    # active in the deep-solid regime (mean melt fraction below 0.01),
    # where a cell can still cool on the solid adiabat well below the
    # solidus and the melt-fraction cap is blind. When a cell's entropy is
    # within the configured phase-boundary entropy margin (default
    # 200 J/kg/K) of either phase boundary, OR sits inside the mushy band,
    # max_step is reduced to 1 yr to give CVODE enough resolution to
    # handle the phase-boundary stiffness gradually.
    if self.entropy_eos is not None:
        entropy_margin = _resolve_entropy_margin(
            getattr(self.parameters.energy, 'phase_boundary_entropy_margin', None)
        )
        # S0_block is staggered (length n_stag). For per-cell
        # phase-boundary check we use the staggered S directly
        # against the staggered-pressure phase boundaries.
        P_stag = self._P_stag_flat
        S_liq_stag = np.asarray(self.entropy_eos.liquidus_entropy(P_stag)).ravel()
        S_sol_stag = np.asarray(self.entropy_eos.solidus_entropy(P_stag)).ravel()
        S_arr_stag = np.asarray(S0_block).ravel()
        margin_to_liq = S_arr_stag - S_liq_stag  # > 0 means above liquidus
        margin_to_sol = S_arr_stag - S_sol_stag  # > 0 means above solidus
        near_liq = np.any(np.abs(margin_to_liq) < entropy_margin)
        near_sol = np.any(np.abs(margin_to_sol) < entropy_margin)
        in_mushy = np.any((margin_to_liq < 0.0) & (margin_to_sol > 0.0))
        # Keep the original CMB-only check too as a backstop
        P_cmb = float(self._P_basic_flat[0])
        S_liq = float(self.entropy_eos.liquidus_entropy(np.array([P_cmb])).item())
        S_sol = float(self.entropy_eos.solidus_entropy(np.array([P_cmb])).item())
        S0_block_cmb = float(S0_block[0])
        if _phase_boundary_max_step_clamp(
            near_liq,
            near_sol,
            in_mushy,
            cmb_margin_to_liq=S0_block_cmb - S_liq,
            cmb_margin_to_sol=S0_block_cmb - S_sol,
            entropy_margin=entropy_margin,
        ):
            max_step = 1.0

        # Per-call step caps as a SUNDIALS root function. Build the
        # anchor metadata here (per-cell melt fraction, temperature and
        # entropy at solve entry); the rootfn instance is constructed
        # below once the nondim state_scale is known. CVODE returns at
        # the exact time the tightest active cap is reached, enforced by
        # the integrator's own trajectory rather than a start-time rate
        # estimate. The per-cell melt-fraction term catches a deep cell
        # crossing the two-phase window in one step (a negligible move in
        # the global mean but the source of the crystallisation-onset
        # core-temperature jump). The melt-fraction derivative saturates
        # once a cell is fully solid, so it cannot bound the temperature
        # drop on the solid adiabat just below the solidus; the optional
        # temperature and entropy caps bound |ฮ”T| and |ฮ”S| per cell
        # directly. All armed caps share one rootfn (g is the minimum
        # margin). Armed as soon as any cell is inside, near, or below the
        # two-phase window so the caps stay active through the solid
        # adiabat. The caps are skipped in gradient core_bc mode, where the
        # state vector holds entropy gradients rather than entropies and
        # the per-cell EOS lookups would be dimensionally meaningless.
        phi_step_cap = _resolve_step_cap(
            getattr(self.parameters.energy, 'phi_step_cap', None)
        )
        temp_step_cap = _resolve_step_cap(
            getattr(self.parameters.energy, 'temperature_step_cap', None)
        )
        entropy_step_cap = _resolve_step_cap(
            getattr(self.parameters.energy, 'entropy_step_cap', None)
        )
        any_cap = phi_step_cap > 0.0 or temp_step_cap > 0.0 or entropy_step_cap > 0.0
        below_solidus = bool(np.any(margin_to_sol < 0.0))
        gradient_mode = getattr(self, '_core_bc', None) == 'gradient'
        if gradient_mode and any_cap:
            logger.info('step caps are not supported in gradient core_bc mode; not armed')
        if (
            any_cap
            and not gradient_mode
            and (near_liq or near_sol or in_mushy or below_solidus)
        ):
            try:
                rho_stag_init = np.asarray(
                    self.entropy_eos.density(self._P_stag_flat, S_arr_stag)
                ).ravel()
                phi_stag_init = np.asarray(
                    self.entropy_eos.melt_fraction(self._P_stag_flat, S_arr_stag)
                ).ravel()
                mass_stag_init = rho_stag_init * self._volume_flat
                mass_total_init = float(np.sum(mass_stag_init))
                if mass_total_init > 0.0:
                    phi0_global = float(
                        np.sum(mass_stag_init * phi_stag_init) / mass_total_init
                    )
                    T0_stag_init = None
                    if temp_step_cap > 0.0:
                        T0_stag_init = np.asarray(
                            self.entropy_eos.temperature(self._P_stag_flat, S_arr_stag)
                        ).ravel()
                    phi_cap_anchor = {
                        'cap_phi': phi_step_cap,
                        'phi0_global': phi0_global,
                        'phi0_cell': phi_stag_init,
                        'cap_T': temp_step_cap,
                        'T0_cell': T0_stag_init,
                        'cap_S': entropy_step_cap,
                        'S0_cell': S_arr_stag.copy(),
                    }
                    logger.debug(
                        'step caps armed (CVODE rootfn): phi=%.3g, T=%.3g K, S=%.3g '
                        'J/kg/K (global ฮฆ0=%.4f)',
                        phi_step_cap,
                        temp_step_cap,
                        entropy_step_cap,
                        phi0_global,
                    )
            except Exception as exc:
                logger.warning(
                    'step-cap rootfn anchor failed (%s); proceeding without cap',
                    exc,
                )

    # External per-call atol scale factor (PROTEUS retry ladder
    # opts in by setting solver._atol_sf before solve()). Default
    # 1.0 leaves behaviour unchanged for callers that don't set it.
    atol_sf_external = float(getattr(self, '_atol_sf', 1.0))
    atol = atol_base * atol_scale * atol_sf_external

    logger.info(
        'EntropySolver: integrating from %.2e to %.2e yr '
        '(Phi_init=%.3f, atol_scale=%.1fx, atol_sf=%.1fx, atol=%.2e, rtol=%.2e)',
        start_time,
        end_time,
        phi0,
        atol_scale,
        atol_sf_external,
        atol,
        rtol,
    )

    # โ”€โ”€ Nondimensionalise state, time, and tolerances โ”€โ”€
    # All state components become O(1) after dividing by their
    # reference scales, so scalar atol works uniformly and the
    # BDF solver no longer needs to resolve 9+ significant digits
    # on an O(1000) state variable. The physics code in
    # _dSdt_single stays in physical units; only the solver
    # interface scales in and out.
    # NonDimScales is the single source of truth for nondim
    # scaling, consumed by both the scipy/CVODE wrapper here and
    # the JAX factory. ``__post_init__`` enforces the contract
    # ``rhs_scale = t_ref / state_scale``.
    scales = self._build_nondim_scales()
    S_ref = self._S_ref
    t_ref = scales.t_ref
    n_s = self._n_stag
    _state_scale = scales.state_scale
    _rhs_scale = scales.rhs_scale

    S0_nd = self._S0 / _state_scale
    start_nd = start_time / t_ref
    end_nd = end_time / t_ref
    max_step_nd = max_step / t_ref if np.isfinite(max_step) else max_step

    # Per-component atol in nondim units. Each state component
    # has its own nondim scale (S_ref for entropy, dSdr_ref for
    # dSdr_cmb in energy_balance mode, dSdr_ref for all gradient
    # components in gradient mode). Dividing atol by _state_scale
    # element-wise gives the same physical tolerance on every
    # component, regardless of its nondim scale. A scalar
    # atol_nd = atol/S_ref would force ~10^8x tighter physical
    # tolerance on dSdr_cmb, choking the step size and
    # suppressing the entropy cooling rate enough to prevent
    # solidification.
    atol_nd = atol / _state_scale

    def _rhs_nondim(t_nd, y_nd):
        """Nondim wrapper: scale state to physical, call physics, scale RHS back."""
        dydt_phys = self._dSdt_single(
            t_nd * t_ref,
            y_nd * _state_scale,
        )
        return dydt_phys * _rhs_scale

    logger.info(
        'Nondimensionalisation: S_ref=%.3f t_ref=%.3e yr '
        'atol_nd min/max=[%.2e, %.2e] S0_nd range [%.4f, %.4f]',
        S_ref,
        t_ref,
        float(np.min(atol_nd)),
        float(np.max(atol_nd)),
        S0_nd[:n_s].min(),
        S0_nd[:n_s].max(),
    )

    # BDF integration with phase-aware max_step constraint.
    jac_sparsity = self._build_jac_sparsity()

    # โ”€โ”€ melt-fraction cap rootfn / event construction โ”€โ”€
    # Build the SUNDIALS rootfn (CVODE path) and the equivalent
    # solve_ivp event (scipy fallback) only when the cap is armed.
    # Both consume nondim ``y`` and rescale via ``_state_scale``
    # before reading the EOS. The phase-boundary max_step=1 yr
    # clamp set above is preserved; the cap is an ADDITIONAL
    # guardrail anchored at the per-cell and global melt fractions at
    # solve entry.
    events = None
    phi_cap_rootfn = None
    if phi_cap_anchor is not None:
        a = phi_cap_anchor
        try:
            cap_kw = dict(
                eos=self.entropy_eos,
                P_stag=self._P_stag_flat,
                volume=self._volume_flat,
                n_stag=self._n_stag,
                phi0_global=a['phi0_global'],
                cap=a['cap_phi'],
                state_scale=_state_scale,
                phi0_per_cell=a['phi0_cell'],
                cap_temperature=a['cap_T'],
                T0_per_cell=a['T0_cell'],
                cap_entropy=a['cap_S'],
                S0_per_cell=a['S0_cell'],
            )
            phi_cap_rootfn = _PhiCapRootFunction(**cap_kw)
            events = [_phi_cap_event_factory(**cap_kw)]
        except Exception as exc:
            logger.warning(
                'step-cap rootfn instantiation failed (%s); integrating without cap',
                exc,
            )
            phi_cap_rootfn = None
            events = None

    # Integrator dispatch. SUNDIALS CVODE (via scikits.odes) is
    # the same solver SPIDER uses and is the recommended choice
    # for production-grade stiff integration: scipy's BDF and
    # Radau collapse their step size to machine epsilon at the
    # crystallisation front and abort with `Required step size
    # is less than spacing between numbers` because scipy's
    # Newton iterator cannot converge through the stiff phase
    # transition. CVODE's modified-Newton with cached Jacobian
    # factorisation handles the discontinuity cleanly. Scipy
    # solve_ivp (Radau or BDF) is kept as a fallback for systems
    # without scikits.odes available.
    solver_method = getattr(self.parameters.energy, 'solver_method', 'cvode')
    # Warn when CVODE was requested but scikits.odes is not
    # importable: the fallback to scipy Radau is a substantial
    # change in solver behaviour (no modified-Newton, no cached
    # Jacobian factorisation) and a silent fallback would let a
    # broken environment masquerade as a physics regression.
    if solver_method == 'cvode' and not _CVODE_AVAILABLE:
        logger.warning(
            'EntropySolver: solver_method="cvode" requested but '
            'scikits.odes is not installed; falling back to scipy '
            'Radau. Install scikits-odes to enable the production '
            'CVODE path (same solver SPIDER uses).'
        )
    use_cvode = solver_method == 'cvode' and _CVODE_AVAILABLE
    if use_cvode:
        # Option Z: build JAX-derived CVODE callbacks when the
        # factory is registered AND the config flag is on. The
        # factory re-creates the (rhs_fn, jac_fn) pair per solve
        # call (JIT recompile cost applies; the same JAX tracing
        # cache is hit on matching signatures, so cost collapses
        # after the first call within a Python process lifetime).
        cvode_rhs_override = None
        cvode_jacfn = None
        use_jax_jac = (
            getattr(self.parameters.energy, 'use_jax_jacobian', False)
            and self._jax_cvode_factory is not None
        )
        if use_jax_jac:
            try:
                # Pass the NonDimScales instance, which bundles
                # the internal nondim contract.
                cvode_rhs_override, cvode_jacfn = self._jax_cvode_factory(
                    scales,
                    self._core_bc,
                )
                logger.info(
                    'EntropySolver: option Z active '
                    '(JAX analytic Jacobian + JAX RHS via scikits.odes)'
                )
            except Exception as exc:  # pragma: no cover - fallback path
                logger.warning(
                    'EntropySolver: JAX CVODE factory failed (%s); '
                    'falling back to numpy RHS + FD Jacobian',
                    exc,
                )
                cvode_rhs_override = None
                cvode_jacfn = None

        if cvode_rhs_override is None:
            logger.info('EntropySolver: using CVODE (solver_method=cvode)')
        self._solution = self._solve_cvode(
            start_time=start_nd,
            end_time=end_nd,
            y0=S0_nd,
            atol=atol_nd,
            rtol=rtol,
            max_step=max_step_nd,
            rhs=_rhs_nondim,
            cvode_rhs_fn_override=cvode_rhs_override,
            cvode_jacfn=cvode_jacfn,
            phi_cap_rootfn=phi_cap_rootfn,
        )
    else:
        method = 'Radau' if solver_method != 'bdf' else 'BDF'
        logger.info('EntropySolver: using scipy %s', method)
        self._solution = solve_ivp(
            _rhs_nondim,
            (start_nd, end_nd),
            S0_nd,
            method=method,
            vectorized=False,
            dense_output=False,
            atol=atol_nd,
            rtol=rtol,
            jac_sparsity=jac_sparsity,
            max_step=max_step_nd,
            events=events,
        )

    # โ”€โ”€ Restore physical units โ”€โ”€
    sol = self._solution
    if sol.t is not None:
        sol.t = np.asarray(sol.t, dtype=float) * t_ref
    if sol.y is not None:
        sol_y = np.asarray(sol.y, dtype=float)
        if sol_y.ndim == 2:
            sol.y = sol_y * _state_scale[:, np.newaxis]
        else:
            sol.y = sol_y * _state_scale

    # ฮ”ฮฆ_global cap-fire log, emitted with PHYSICAL time. The
    # CVODE path attaches ``cap_fired`` etc. to the result inside
    # ``_solve_cvode``; the scipy fallback exposes the same signal
    # via ``sol.t_events`` (non-empty when the terminal event
    # fired). Logging here (after the t_ref restoration) keeps
    # operator-facing messages in physical years rather than the
    # nondim time the rootfn sees internally.
    if getattr(sol, 'cap_fired', False) and sol.t is not None:
        t_root_phys = float(sol.t[-1])
        logger.info(
            'ฮ”ฮฆ_global cap: CVODE rootfn fired at '
            't=%.3e yr after %d evals; cap=%.3g, '
            'ฮฆ_global(start)=%.4f',
            t_root_phys,
            int(getattr(sol, 'cap_evals', 0)),
            float(getattr(sol, 'cap_value', 0.0)),
            float(getattr(sol, 'cap_phi0', 0.0)),
        )
    elif (
        getattr(sol, 't_events', None) is not None
        and len(sol.t_events) > 0
        and len(sol.t_events[0]) > 0
    ):
        t_event_phys = float(sol.t_events[0][0]) * t_ref
        logger.info(
            'ฮ”ฮฆ_global cap: scipy event fired at t=%.3e yr (terminal=True)',
            t_event_phys,
        )

    # Diagnostic logging: internal BDF step statistics (in physical yr)
    if sol.t is not None and len(sol.t) > 1:
        dt_internal = np.diff(sol.t)
        logger.info(
            'EntropySolver: %d internal steps, %d RHS evals, '
            'dt_min=%.2e yr, dt_max=%.2e yr, dt_med=%.2e yr',
            len(sol.t),
            sol.nfev,
            dt_internal.min(),
            dt_internal.max(),
            np.median(dt_internal),
        )
        logger.info(
            'EntropySolver: phase-boundary cache hits=%d misses=%d',
            self.state._pb_cache_hits,
            self.state._pb_cache_misses,
        )
        self.state._pb_cache_hits = 0
        self.state._pb_cache_misses = 0

    if self._solution.status == 0:
        logger.info('EntropySolver: integration completed successfully.')
        self.stop_early = False
    elif self._solution.status == 1:
        # Termination event (liquidus crossing at CMB cell).
        # Integration succeeded up to the event time.
        t_event = self._solution.t[-1]
        logger.info(
            'EntropySolver: liquidus-crossing event at t=%.2e yr '
            '(stopped %.1f yr before end_time). Bottom cell reached '
            'onset of crystallization.',
            t_event,
            end_time - t_event,
        )
        self.stop_early = False
    else:
        logger.error(
            'EntropySolver: integration failed (status=%d): %s',
            self._solution.status,
            self._solution.message,
        )
        self.stop_early = True

write_netcdf(path, *, time=None, description=None)

Convenience wrapper: self.get_state().to_netcdf(path).

Designed for the standalone solver script: build the solver, call solve(), then dump the final state as a NetCDF4 file.

Parameters:

Name Type Description Default
path str or Path

Destination NetCDF4 file (overwrites if it exists).

required
time float

Simulation time at which this snapshot was taken [yr]. Defaults to SolverOutput.dt_actual if omitted.

None
description str

Free-form description string written as the dataset's description global attribute.

None
See Also

SolverOutput.to_netcdf : underlying writer with the full schema.

Source code in src/aragog/solver/entropy_solver.py
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
def write_netcdf(
    self,
    path: str | Path,
    *,
    time: float | None = None,
    description: str | None = None,
) -> None:
    """Convenience wrapper: ``self.get_state().to_netcdf(path)``.

    Designed for the standalone solver script: build the solver,
    call ``solve()``, then dump the final state as a NetCDF4 file.

    Parameters
    ----------
    path : str or Path
        Destination NetCDF4 file (overwrites if it exists).
    time : float, optional
        Simulation time at which this snapshot was taken [yr].
        Defaults to ``SolverOutput.dt_actual`` if omitted.
    description : str, optional
        Free-form description string written as the dataset's
        ``description`` global attribute.

    See Also
    --------
    SolverOutput.to_netcdf : underlying writer with the full schema.
    """
    # Forward only when the caller supplied a description; otherwise
    # let ``to_netcdf``'s default take effect so the two entry points
    # stamp the same string into ``ds.description``.
    kwargs: dict[str, str] = {}
    if description is not None:
        kwargs['description'] = description
    self.get_state().to_netcdf(path, time=time, **kwargs)

EntropyState(evaluator, phase_staggered, phase_basic, conduction=True, convection=True, gravitational_separation=False, mixing=False, radionuclides=False, tidal=False, tidal_array=None, eddy_diffusivity_thermal=1.0, eddy_diffusivity_chemical=1.0, kappah_floor=0.0, bottom_up_grav_sep=True, phase_smoothing='tanh')

Stores and updates the thermodynamic state using entropy.

The key difference from State: the prognostic variable is S(r,t), not T(r,t). All properties are looked up from (P, S) via the EntropyPhaseEvaluator. Convective transport is driven by dS/dr (entropy gradient), not by the superadiabatic T gradient.

Parameters:

Name Type Description Default
evaluator Evaluator

Contains mesh and boundary conditions.

required
phase EntropyPhaseEvaluator

Entropy-based phase evaluator with (P,S) lookups.

required
settings dict

Energy settings (conduction, convection, mixing, etc.)

required
Source code in src/aragog/solver/entropy_state.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def __init__(
    self,
    evaluator: Evaluator,
    phase_staggered: EntropyPhaseEvaluator,
    phase_basic: EntropyPhaseEvaluator,
    conduction: bool = True,
    convection: bool = True,
    gravitational_separation: bool = False,
    mixing: bool = False,
    radionuclides: bool = False,
    tidal: bool = False,
    tidal_array: list | None = None,
    eddy_diffusivity_thermal: float = 1.0,
    eddy_diffusivity_chemical: float = 1.0,
    kappah_floor: float = 0.0,
    bottom_up_grav_sep: bool = True,
    phase_smoothing: str = 'tanh',
):
    self._evaluator = evaluator
    self.phase_staggered = phase_staggered
    self.phase_basic = phase_basic
    self._conduction = conduction
    self._convection = convection
    self._grav_sep = gravitational_separation
    self._mixing = mixing
    self._radionuclides = radionuclides
    self._tidal = tidal
    self._tidal_array = (
        tidal_array if tidal_array is not None and len(tidal_array) > 0 else [0.0]
    )
    self._eddy_diff_thermal = eddy_diffusivity_thermal
    self._eddy_diff_chem = eddy_diffusivity_chemical
    self._kappah_floor = kappah_floor
    self._bottom_up_grav_sep = bool(bottom_up_grav_sep)
    # Phase-boundary smoothing method for Jgrav and Jmix.
    # 'tanh' (default): SPIDER's get_smoothing(matprop_smooth_width=0.01, gphi).
    #   Two-branch tanh, smth=1.0 across [0.05, 0.95]. Production setting;
    #   matches SPIDER once material properties agree to <0.01%.
    # 'cubic_hermite': 16*gphi^2*(1-gphi)^2. Intermediate-phi damping
    #   (smth=0.32 at gphi=0.83). Fallback for cases where residual EOS
    #   mismatch would otherwise cause a CMB drain; not a production
    #   setting.
    if phase_smoothing not in ('cubic_hermite', 'tanh'):
        raise ValueError(
            f"phase_smoothing must be 'cubic_hermite' or 'tanh', got {phase_smoothing!r}"
        )
    self._phase_smoothing = phase_smoothing

    mesh = evaluator.mesh
    n_basic = mesh.basic.radii.size
    n_staggered = mesh.staggered.radii.size

    # Cache flattened (1D) mesh arrays to avoid repeated
    # np.asarray(...).flatten() calls in the hot path.
    # The mesh stores (N,1) column vectors; we flatten once here.
    self._mixing_length = np.asarray(mesh.basic.mixing_length).ravel()
    self._mixing_length_sq = np.asarray(mesh.basic.mixing_length_squared).ravel()
    self._mixing_length_cu = np.asarray(mesh.basic.mixing_length_cubed).ravel()

    # Allocate state arrays (all 1D).
    self._entropy_staggered = np.zeros(n_staggered)
    self._entropy_basic = np.zeros(n_basic)
    self._dSdr = np.zeros(n_basic)
    self._dphidr = np.zeros(n_basic)
    self._eddy_diffusivity = np.zeros(n_basic)
    self._heat_flux = np.zeros(n_basic)
    self._mass_flux = np.zeros(n_basic)
    self._is_convective = np.zeros(n_basic, dtype=bool)

    # Per-component flux decomposition at basic nodes for diagnostic
    # output. These mirror the accumulations into ``_heat_flux`` below
    # so each term can be written to NetCDF independently.
    self._jcond = np.zeros(n_basic)
    self._jconv = np.zeros(n_basic)
    self._jgrav_heat = np.zeros(n_basic)
    self._jmix_heat = np.zeros(n_basic)

    # Per-source heating decomposition at staggered nodes [W/kg].
    # Stashed alongside the cumulative ``_heating`` so the energy-
    # conservation diagnostic can sum each source over cell mass to
    # report total radiogenic / tidal power in W, without re-running
    # the heating assembly. Mirrors the per-component flux
    # decomposition above.
    self._heating_radio = np.zeros(n_staggered)
    self._heating_tidal = np.zeros(n_staggered)

    # Basic-node EOS state snapshots (populated in update()).
    self._phi_basic_diag = np.zeros(n_basic)
    self._T_basic_diag = np.zeros(n_basic)
    self._cp_basic_diag = np.zeros(n_basic)
    self._rho_basic_diag = np.zeros(n_basic)

    # Phase-boundary entropy cache at staggered nodes. P_stag is
    # fixed for the lifetime of the solve, so S_sol(P_stag) and
    # S_liq(P_stag) are constants. Caching them avoids ~230k
    # scipy interpolator calls per 10-yr PROTEUS step (two per
    # RHS eval) that otherwise dominate the BDF hot path.
    self._P_stag_cached_id: int = -1
    self._S_sol_stag: npt.NDArray = np.zeros(n_staggered)
    self._S_liq_stag: npt.NDArray = np.zeros(n_staggered)
    self._dS_phase_stag: npt.NDArray = np.ones(n_staggered)
    self._pb_cache_hits: int = 0
    self._pb_cache_misses: int = 0

    # Phase-boundary cache at basic nodes for the mixing-flux
    # computation (``_jmix_spider_heat`` in update()). Like the
    # staggered cache, these are mesh-fixed: the basic-node
    # pressure profile doesn't change within a solve.
    # Cached: S_sol/S_liq, their P-derivatives, dP/dr, and
    # T_fus = ยฝ(T_sol + T_liq).
    self._P_basic_cached_id: int = -1
    self._S_sol_basic: npt.NDArray = np.zeros(n_basic)
    self._S_liq_basic: npt.NDArray = np.zeros(n_basic)
    self._dS_phase_basic: npt.NDArray = np.ones(n_basic)
    self._dS_sol_dP_basic: npt.NDArray = np.zeros(n_basic)
    self._dS_liq_dP_basic: npt.NDArray = np.zeros(n_basic)
    self._dP_dr_basic: npt.NDArray = np.zeros(n_basic)
    self._T_fus_basic: npt.NDArray = np.zeros(n_basic)

    # One-shot flags: emit each transient-guard warning at most
    # once per EntropyState instance. Without throttling, a
    # non-standard EOS that triggers a floor produces one warning
    # per RHS call (1000s per coupling step) and floods the log.
    # The complementary load-time scan in
    # ``EntropySolver._check_eos_floors`` flags the same Cp condition
    # before any RHS call; these runtime guards exist to catch
    # transient floor activations from out-of-bounds (P, S) lookups
    # that the static load-time scan cannot anticipate.
    #
    # The kappa_h floor at the rheological transition
    # (``self._eddy_diffusivity = np.maximum(..., kh_floor)`` in
    # update()) is *intentional design*, not a transient guard, and
    # is deliberately silent: it fires by construction at every RHS
    # call inside the mushy band.
    self._cp_floor_warned: bool = False  # conduction Cp >= 100 J/kg/K
    self._cp_mlt_floor_warned: bool = False  # MLT Cp >= 1 J/kg/K
    self._dS_phase_stag_floor_warned: bool = False  # S_liq - S_sol >= 1 J/kg/K (staggered)
    self._dS_phase_basic_floor_warned: bool = False  # S_liq - S_sol >= 1 J/kg/K (basic)

bottom_temperature property

Temperature at the innermost basic node [K].

heating property

Total internal heating [W/kg] at staggered nodes.

heating_radio property

Radiogenic heating contribution [W/kg] at staggered nodes.

heating_tidal property

Tidal heating contribution [W/kg] at staggered nodes.

temperature_basic property

Temperature at basic nodes (derived from S via EOS).

top_temperature property

Temperature at the outermost basic node [K].

capacitance_staggered()

Capacitance for entropy equation: rho * T [kg K / m^3].

The entropy equation is: rho * T * dS/dt = -div(F) + sources. Compare T-formulation: rho * Cp * dT/dt = -div(F) + sources.

Source code in src/aragog/solver/entropy_state.py
1034
1035
1036
1037
1038
1039
1040
def capacitance_staggered(self) -> npt.NDArray:
    """Capacitance for entropy equation: rho * T [kg K / m^3].

    The entropy equation is: rho * T * dS/dt = -div(F) + sources.
    Compare T-formulation: rho * Cp * dT/dt = -div(F) + sources.
    """
    return self.phase_staggered.capacitance()

dTdr()

Temperature gradient at basic nodes (from T profile, for BCs).

Source code in src/aragog/solver/entropy_state.py
1061
1062
1063
1064
def dTdr(self) -> npt.NDArray:
    """Temperature gradient at basic nodes (from T profile, for BCs)."""
    T_stag = self.phase_staggered.temperature()
    return self._evaluator.mesh.d_dr_at_basic_nodes(T_stag)

update(entropy, time, dSdr_cmb=None, dSdr=None, entropy_basic=None)

Update the state from the entropy profile.

Parameters:

Name Type Description Default
entropy array

Entropy at staggered nodes [J/kg/K].

required
time float

Current time [yr].

required
dSdr_cmb float

energy_balance mode: override the CMB boundary gradient with the value from the extended state vector.

None
dSdr array

Gradient-mode: provide dS/dr at all basic nodes directly, bypassing the FD transform. Shape (N+1,).

None
entropy_basic array

Gradient-mode: provide S at all basic nodes directly, bypassing the quantity transform. Shape (N+1,).

None
Source code in src/aragog/solver/entropy_state.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
def update(
    self,
    entropy: npt.NDArray,
    time: FloatOrArray,
    dSdr_cmb: float | None = None,
    dSdr: npt.NDArray | None = None,
    entropy_basic: npt.NDArray | None = None,
) -> None:
    """Update the state from the entropy profile.

    Parameters
    ----------
    entropy : array
        Entropy at staggered nodes [J/kg/K].
    time : float
        Current time [yr].
    dSdr_cmb : float, optional
        energy_balance mode: override the CMB boundary gradient
        with the value from the extended state vector.
    dSdr : array, optional
        Gradient-mode: provide dS/dr at all basic nodes directly,
        bypassing the FD transform. Shape (N+1,).
    entropy_basic : array, optional
        Gradient-mode: provide S at all basic nodes directly,
        bypassing the quantity transform. Shape (N+1,).
    """
    mesh = self._evaluator.mesh

    S = np.asarray(entropy).ravel()
    self._entropy_staggered = S
    if entropy_basic is not None:
        self._entropy_basic = np.asarray(entropy_basic).ravel()
    else:
        self._entropy_basic = mesh.quantity_at_basic_nodes(S).ravel()
    if dSdr is not None:
        self._dSdr = np.asarray(dSdr).ravel()
    else:
        # Entropy gradient at basic nodes (uniform dxi spacing).
        #
        # Replaces Aragog's ``mesh.d_dr_at_basic_nodes(S)`` which
        # used a dense transform matrix with a 3-point second-order
        # boundary extrapolation scaled by dxi/dr. That stencil
        # overshoots catastrophically at the CMB when the
        # crystallisation front creates a kink in the staggered S
        # profile: the extrapolated dS/dr[0] reached 10^7x the
        # physically correct value, producing a 2.6e10 W/m^2 Jtot
        # spike at the CMB basic node that drained the bottom
        # staggered cell's entropy to the solidus in one coupling
        # step.
        #
        # SPIDER computes dSdxi as a simple centered difference in
        # UNIFORM xi-space between adjacent staggered cells
        # (ic.c:443-446), then applies the chain rule dS/dr =
        # dSdxi * dxi/dr. At boundaries SPIDER copies the nearest
        # interior value (ic.c:450: ``arr_dSdxi_b[CMB] =
        # arr_dSdxi_b[CMB-1]``). The uniform-xi spacing makes the
        # denominator constant, bounding the gradient to the actual
        # inter-cell entropy difference regardless of the spatial
        # mesh non-uniformity.
        xi_s = np.asarray(mesh.staggered.mass_radii).ravel()
        dxi_s = xi_s[1:] - xi_s[:-1]
        n_basic = mesh.basic.radii.size
        dSdxi = np.zeros(n_basic)
        dSdxi[1:-1] = (S[1:] - S[:-1]) / dxi_s
        # Boundary values: SPIDER evolves dSdxi at the CMB and
        # surface as state variables via the core energy balance
        # ODE (bc.c:76, set_cmb_entropy_gradient_update). At the
        # CMB, this drives dSdxi toward ~0 (core acts as a thermal
        # reservoir in quasi-equilibrium): on a representative
        # Earth-mantle solidification trajectory SPIDER's
        # dSdxi[CMB] is roughly seven orders of magnitude smaller
        # than the first interior node. In Aragog's quasi_steady
        # mode (no core energy balance ODE), we approximate this
        # by setting the boundary gradients to zero, which is the
        # steady-state limit of SPIDER's evolved boundary gradient.
        # SPIDER bc.c convention: boundary gradients copy from the
        # adjacent interior node. In energy_balance mode, the CMB
        # gradient is overridden later by the state-vector value.
        dSdxi[0] = dSdxi[1]  # CMB: copy from first interior
        dSdxi[-1] = dSdxi[-2]  # surface: copy from last interior
        dxidr = np.asarray(mesh.dxidr).ravel()
        self._dSdr = dSdxi * dxidr

    # energy_balance mode: override the boundary entropy gradient
    # with the state-vector value. Must happen BEFORE the
    # phase_basic update so the bottom basic node uses the
    # boundary entropy.
    if dSdr_cmb is not None:
        r_basic = np.asarray(mesh.basic.radii).ravel()
        r_stag_0 = 0.5 * (r_basic[0] + r_basic[1])
        dr_offset = r_basic[0] - r_stag_0
        self._dSdr[0] = float(dSdr_cmb)
        self._entropy_basic[0] = float(S[0]) + float(dSdr_cmb) * dr_offset

    # Update phase evaluators with current (P, S)
    self.phase_staggered.set_entropy(S)
    self.phase_staggered.update()
    self.phase_basic.set_entropy(self._entropy_basic)
    self.phase_basic.update()

    # Melt-fraction gradient for gravitational separation and mixing.
    #
    # Clamped lever-rule melt fraction:
    #     phi = clip((S - S_sol) / (S_liq - S_sol), 0, 1)
    # Per-cell clipping gives dphi/dr = 0 in pure-phase cells
    # (no phase separation in pure liquid or solid), with a
    # well-defined gradient at the crystallisation front.
    #
    # Evaluated from cached EOS lookups (S_sol, S_liq) rather than
    # self.phase_staggered.melt_fraction() to avoid IEEE roundoff
    # noise that destabilises the BDF Jacobian. Cached arrays are
    # byte-identical throughout the solve.
    self._ensure_phase_boundary_cache()
    gphi = (S - self._S_sol_stag) / self._dS_phase_stag
    _smooth_clip(gphi, 0.0, 1.0, eps=1.0e-3)
    # phi_smoothclipped is computed but unused: the mixing flux
    # evaluates directly from dSdr and dP/dr (see below).

    # โ”€โ”€ MLT from entropy gradient โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    # Convection is unstable when dS/dr < 0 (entropy decreasing
    # outward). The convective driver itself uses the smoothed
    # max(-dSdr, 0) below, which is C^infinity in dSdr, so the
    # velocity arrays are never hard-masked at the marginal-stability
    # boundary (a hard mask there would break CVODE's higher-order BDF
    # predictor). `_is_convective` is the hard dS/dr < 0 gate applied
    # only to the additive eddy-diffusivity floor (see the kappa_h
    # floor block below), which deliberately accepts a flux-derivative
    # kink at dS/dr = 0 in exchange for keeping the floor out of
    # stably-stratified cells.
    self._is_convective = self._dSdr < 0

    # Buoyancy: convert entropy gradient to effective thermal
    # buoyancy |superadiabatic| = alpha * T * |dS/dr| / Cp.
    # Use the smoothed max(-dSdr, 0), which replaces the
    # `np.abs(dSdr)` + `mask[~convective] = 0` pair with a single
    # C^infinity expression. For dSdr << 0: reduces to -dSdr
    # (unstable profile, full convection drive). For dSdr >> 0:
    # smoothly reduces to 0 (stable profile, no convection).
    alpha = np.asarray(self.phase_basic.thermal_expansivity()).ravel()
    T = np.asarray(self.phase_basic.temperature()).ravel()
    Cp = np.asarray(self.phase_basic.heat_capacity()).ravel()
    g = np.asarray(self.phase_basic.gravitational_acceleration()).ravel()

    # eps=1e-30 is intentionally near-zero: at double precision this
    # gives a hard max(-x, 0) without the kink smoothing. The original
    # eps=1e-8 inflated |dSdr| by 15% when gradients were O(eps) at
    # isentropic ICs, causing 7% kh error. SPIDER uses a hard if/else
    # threshold, so the near-zero eps matches SPIDER's behavior. If
    # CVODE stability requires smoothing, increase to ~1e-20.
    conv_drive = _smooth_abs_neg(self._dSdr, eps=1.0e-30)
    Cp_safe_mlt = self._maybe_warn_cp_floor(
        Cp,
        floor=1.0,
        site='MLT',
        consequence=(
            'eddy-diffusivity velocity prefactor is biased upward at those points'
        ),
        flag_name='_cp_mlt_floor_warned',
    )
    effective_superadiabatic = alpha * T * conv_drive / Cp_safe_mlt
    velocity_prefactor = g * effective_superadiabatic

    # Viscous velocity (Re <= Re_crit). No boolean masking needed:
    # velocity_prefactor already vanishes smoothly for stable
    # (dSdr > 0) cells via conv_drive.
    mixing_length = self._mixing_length
    mixing_length_cubed = self._mixing_length_cu
    mixing_length_squared = self._mixing_length_sq
    nu = np.asarray(self.phase_basic.kinematic_viscosity()).ravel()

    viscous_velocity = velocity_prefactor * mixing_length_cubed / (18.0 * nu)

    # Inviscid velocity (Re > Re_crit). Add a tiny eps^2 inside the
    # sqrt to avoid the sqrt-kink at velocity_sq = 0; the value is
    # negligibly different from sqrt(max(x, 0)) for any physical
    # inviscid_velocity_sq.
    inviscid_velocity_sq = velocity_prefactor * mixing_length_squared / 16.0
    inviscid_velocity = np.sqrt(inviscid_velocity_sq + 1.0e-20)

    # Reynolds number
    reynolds = viscous_velocity * mixing_length / nu

    # Smooth blend between regimes (tanh transition at Re_crit).
    # blend_width = 0.01 * RE_CRIT: at Re โ‰ช RE_CRIT (solid regime,
    # Re ~ 1e-26), tanh saturates to -1 within machine precision so
    # the inviscid contribution is exactly zero. The blend width
    # must stay well below RE_CRIT (5x narrower than 0.2 * RE_CRIT
    # is sufficient): a wider blend leaks inviscid_weight ~ 5e-5
    # at Re=0; multiplied by inviscid_velocity ~ 1 m/s and mixing
    # length ~ 7e5 m that yields k_h ~ 20 m^2/s in solid layers
    # (vs SPIDER's hard if-else giving k_h ~ 1e-7), which makes
    # max(k_h_raw, kappah_floor) sit on the raw value rather than
    # the phase-modulated floor and creates a metastable
    # equilibrium for dSdr_cmb and a phi=0 oscillation.
    # 1% of RE_CRIT. This is a numerics-tunable (NOT a smoothing-width
    # config knob and NOT the matprop_smooth_width above): a wider
    # blend leaks a non-zero inviscid_weight into solid layers and
    # creates the metastable equilibrium described in the comment
    # block above. Not exposed via config because the safe range is
    # narrow.
    blend_width = 0.01 * RE_CRIT
    inviscid_weight = 0.5 * (1.0 + np.tanh((reynolds - RE_CRIT) / max(blend_width, 1e-30)))
    # Raw eddy diffusivity (before thermal scaling and floor)
    kh_raw = (
        (1.0 - inviscid_weight) * viscous_velocity + inviscid_weight * inviscid_velocity
    ) * mixing_length

    # Apply eddy_diffusivity_thermal scaling (SPIDER convention:
    # positive = scale factor, negative = fixed constant)
    if self._eddy_diff_thermal > 0:
        self._eddy_diffusivity = self._eddy_diff_thermal * kh_raw
    else:
        self._eddy_diffusivity = np.full_like(kh_raw, -self._eddy_diff_thermal)

    # Chemical eddy diffusivity uses raw kh (before floor and thermal scaling),
    # matching SPIDER's matprop.c lines 318-325
    if self._eddy_diff_chem > 0:
        self._kappac = self._eddy_diff_chem * kh_raw
    else:
        self._kappac = np.full_like(kh_raw, -self._eddy_diff_chem)

    # kappa_h floor (phase-dependent, modulated by melt fraction), gated
    # to convectively-unstable cells. Production PROTEUS runs use
    # kappah_floor = 10 m^2/s (PROTEUS schema default). The phi-modulated
    # floor f_floor = tanh_weight(phi, phi_rheo, phi_width) ramps from 0
    # in solid layers to ~1 in mushy/liquid layers, where MLT can
    # otherwise numerically freeze when the entropy gradient gets small.
    # The ``self._is_convective`` (dS/dr < 0) gate confines the floor to
    # cells that are actually convecting: a stably-stratified, just-frozen
    # mushy cell at the crystallisation front must NOT receive a floored
    # eddy diffusivity, because the signed convective flux
    # rho*T*kappa_h*(-dS/dr) would then inject a spurious sign-flipped
    # flux that pins the cell sub-solidus. SPIDER has no kappa_h floor, so
    # floor = 0 in stratified layers is the SPIDER-consistent limit. The
    # transition is anchored on the rheological critical melt fraction so
    # the floor turns on where Costa-blended viscosity drops. Mirrored in
    # the JAX twin jax/phase.py.
    if self._kappah_floor > 0.0:
        phi_basic = np.asarray(self.phase_basic.melt_fraction()).flatten()
        from aragog.utilities import tanh_weight

        phi_rheo = float(getattr(self.phase_basic, '_phi_rheo', 0.4))
        phi_width = float(getattr(self.phase_basic, '_phi_width', 0.15))
        f_floor = tanh_weight(phi_basic, phi_rheo, phi_width)
        self._eddy_diffusivity = apply_kappah_floor(
            self._eddy_diffusivity,
            self._kappah_floor,
            f_floor,
            self._is_convective,
        )

    # Mirror SPIDER energy.c:220-223: at the CMB basic node, use
    # the eddy diffusivity from one node above rather than the
    # boundary-extrapolated value. SPIDER does this because kappah
    # is a nonlinear function of the entropy gradient, and the
    # boundary extrapolation can over- or under-estimate it relative
    # to the interior value. Borrowing from the first interior node
    # avoids this artifact and aligns the CMB convective flux with
    # SPIDER's treatment.
    if len(self._eddy_diffusivity) >= 2:
        self._eddy_diffusivity[0] = self._eddy_diffusivity[1]

    # โ”€โ”€ Compute fluxes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    rho = np.asarray(self.phase_basic.density()).ravel()
    k = np.asarray(self.phase_basic.thermal_conductivity()).ravel()

    self._heat_flux = np.zeros_like(self._entropy_basic)
    self._mass_flux = np.zeros_like(self._entropy_basic)
    # Reset per-component diagnostic buffers for this update() pass.
    self._jcond = np.zeros_like(self._entropy_basic)
    self._jconv = np.zeros_like(self._entropy_basic)
    self._jgrav_heat = np.zeros_like(self._entropy_basic)
    self._jmix_heat = np.zeros_like(self._entropy_basic)

    # Ensure mesh dP/dr is populated (needed by conduction and mixing).
    # The cache is computed lazily from the mesh pressure profile and
    # only needs refreshing when the mesh changes.
    if self._conduction or self._mixing:
        self._ensure_basic_phase_boundary_cache()

    if self._conduction:
        # Conductive heat flux:
        #   F_cond = -k * [(T/Cp) * dS/dr + dT/dr|_adiabat]
        #
        # The total temperature gradient decomposes into a
        # superadiabatic part (proportional to the entropy gradient)
        # and an adiabatic part. The adiabatic gradient is computed
        # from the EOS table (dTdPs) rather than the thermodynamic
        # identity (-g*alpha*T/Cp), ensuring consistency with the
        # EOS property lookups at phase boundaries.
        #
        # Cp_safe clamps Cp from below at 100 J/kg/K to guard the
        # T/Cp factor against pathological EOS lookups. Production
        # MgSiO3 EOS stays well above this floor (typical Cp ~ 1000+
        # J/kg/K, latent-blend Cp_eff in mushy zone goes higher
        # still). If the floor activates, the superadiabatic term is
        # silently inflated relative to the true T/Cp. Static checks
        # on the loaded EOS table happen at load time in
        # ``EntropySolver._check_eos_floors``; this runtime guard
        # catches transient floor activations from out-of-bounds
        # (P, S) queries the static scan cannot anticipate. The
        # warning is throttled to one fire per EntropyState instance
        # to avoid log spam over thousands of RHS calls per step.
        Cp_safe = self._maybe_warn_cp_floor(
            Cp,
            floor=100.0,
            site='conduction',
            consequence=('F_cond superadiabatic term is biased upward at those points'),
            flag_name='_cp_floor_warned',
        )
        superadiabatic = (T / Cp_safe) * self._dSdr
        # Adiabatic gradient from EOS table: dT/dr|_ad = dTdPs * dPdr
        # where dPdr comes from the mesh pressure profile
        # (Adams-Williamson), not from -rho_material*g. Using the
        # mesh dPdr is essential because structural density differs
        # from EOS material density.
        dTdPs = np.asarray(self.phase_basic.dTdPs()).ravel()
        dTdrs_ad = dTdPs * self._dP_dr_basic
        self._jcond = -k * (superadiabatic + dTdrs_ad)
        self._heat_flux += self._jcond

    if self._convection:
        # F_conv = rho * T * kappa_h * (-dS/dr)
        # This is the entropy flux: positive when dS/dr < 0 (unstable)
        self._jconv = rho * T * self._eddy_diffusivity * (-self._dSdr)
        self._heat_flux += self._jconv

    if self._grav_sep:
        phi_b = np.asarray(self.phase_basic.melt_fraction()).ravel()
        v_rel = np.asarray(self.phase_basic.relative_velocity()).ravel()
        jgrav = rho * phi_b * (1.0 - phi_b) * v_rel

        # SPIDER-analogue phase-boundary smoothing.
        #
        # Purpose: at the first crystallisation step the raw mass
        # flux rho * phi * (1-phi) * v_rel can drain the CMB
        # cell's entropy off the PALEOS P-S table in one coupling
        # step, because the Stokes-regime permeability at
        # grain_size = 0.1 m gives v_rel of several m/s and
        # phi * (1-phi) ~ 5e-3 at phi = 0.995 is not enough
        # damping on its own.
        #
        # SPIDER avoids this via
        # `smth = get_smoothing(matprop_smooth_width, gphi)` where
        # gphi is the UN-truncated two-phase fraction
        #     gphi = (S - S_sol(P)) / (S_liq(P) - S_sol(P))
        # at the STAGGERED cell immediately BELOW the interface
        # (JGRAV_BOTTOM_UP, SPIDER/energy.c:523-533). gphi exceeds
        # 1 for pure liquid and goes negative for pure solid, so
        # `smth` drops cleanly to 0 on both sides, killing Jgrav
        # at any interface whose lower neighbour is in a pure
        # phase. Aragog's bookkeeping phi is clamped to [0,1] by
        # the EOS lookup so we recompute gphi here from the
        # staggered-cell entropy against the solidus/liquidus
        # entropies.
        #
        # Phase-boundary smoothing for gravitational separation.
        # Uses the same cubic Hermite ``16*gphi^2*(1-gphi)^2`` as
        # the Jmix term below. Both Jgrav and Jmix MUST use the
        # same smoothing function so their relative balance is
        # internally consistent.
        #
        # SPIDER uses a tanh (get_smoothing, width=0.01) for both,
        # which gives smth=1.0 across most of [0.05, 0.95]. This
        # works in SPIDER because all material properties match
        # exactly, producing a precise Jtot cancellation. In Aragog,
        # residual EOS interpolation differences create a small Jtot
        # imbalance that the full-strength tanh amplifies into a
        # CMB cell drain. The cubic Hermite provides intermediate-
        # phi damping (smth=0.32 at gphi=0.83 vs tanh=1.0) that
        # gives Aragog the margin it needs. Once all audit items
        # (1.1, 1.2) are resolved and material properties match
        # SPIDER to 0.01%, the smoothing can be switched to tanh.
        if self._bottom_up_grav_sep:
            gphi_stag = (self._entropy_staggered - self._S_sol_stag) / self._dS_phase_stag

            if self._phase_smoothing == 'tanh':
                # SPIDER tanh-smoothing width. Defaults to 0.01 (SPIDER
                # ``matprop_smooth_width`` convention); pulls from the
                # phase evaluator when configured non-zero so a single
                # config knob drives both EOS and Jgrav/Jmix smoothing.
                smw = (
                    float(getattr(self.phase_basic, '_matprop_smooth_width', 0.0)) or 1.0e-2
                )
                smth_stag = _spider_get_smoothing(gphi_stag, smooth_width=smw)
            else:
                gphi_clip = _smooth_clip(gphi_stag, 0.0, 1.0, eps=1.0e-3)
                smth_stag = 16.0 * gphi_clip**2 * (1.0 - gphi_clip) ** 2

            # Bottom-up: basic node i (interface between staggered
            # i-1 and i) sees the smoothing of staggered i-1 (the
            # cell BELOW).
            smth_basic = np.ones_like(jgrav)
            smth_basic[1:-1] = smth_stag[:-1]
            jgrav = jgrav * smth_basic

        self._mass_flux += jgrav

    # Zero mass fluxes at boundaries (SPIDER convention: no mass
    # transfer across CMB or surface, energy.c lines 282-285, 423-426)
    self._mass_flux[0] = 0.0
    self._mass_flux[-1] = 0.0
    self._jgrav_heat = self._mass_flux * np.asarray(self.phase_basic.latent_heat()).ravel()
    self._heat_flux += self._jgrav_heat

    if self._mixing:
        # Mixing flux from phase-change-driven chemical diffusion.
        # Computed directly as a heat flux (not via mass_flux * L):
        #     Jmix_heat = -kappac * rho * T_fus * bracket * smth
        # where the bracket is the effective chemical potential gradient:
        #     bracket = dS/dr - [phi*dS_liq/dP + (1-phi)*dS_sol/dP] * dP/dr
        # and smth (tanh or cubic Hermite) zeroes the flux outside the
        # mushy band (0 <= gphi <= 1). The bracket is computed directly
        # from gradients rather than from dphi/dr, keeping the RHS
        # smooth in pure-phase regions.
        self._ensure_basic_phase_boundary_cache()
        phi_basic_clipped = np.asarray(self.phase_basic.melt_fraction()).ravel()
        bracket = (
            self._dSdr
            - (
                phi_basic_clipped * self._dS_liq_dP_basic
                + (1.0 - phi_basic_clipped) * self._dS_sol_dP_basic
            )
            * self._dP_dr_basic
        )
        # Smoothing: same method as Jgrav (controlled by
        # self._phase_smoothing) for internal consistency.
        gphi_basic = (self._entropy_basic - self._S_sol_basic) / self._dS_phase_basic
        if self._phase_smoothing == 'tanh':
            # Same matprop_smooth_width as the Jgrav site above; one
            # config knob drives both inline smoothings to keep them
            # consistent across the mass-flux assembly.
            smw = float(getattr(self.phase_basic, '_matprop_smooth_width', 0.0)) or 1.0e-2
            smth_basic_mix = _spider_get_smoothing(gphi_basic, smooth_width=smw)
        else:
            gphi_basic_clip = _smooth_clip(gphi_basic, 0.0, 1.0, eps=1.0e-3)
            smth_basic_mix = 16.0 * gphi_basic_clip**2 * (1.0 - gphi_basic_clip) ** 2
        jmix_spider_heat = (
            -self._kappac * rho * self._T_fus_basic * bracket * smth_basic_mix
        )
        # Zero at the actual boundaries (no mass transfer across
        # CMB or surface)
        jmix_spider_heat[0] = 0.0
        jmix_spider_heat[-1] = 0.0
        self._jmix_heat = jmix_spider_heat
        self._heat_flux += self._jmix_heat

    # Snapshot basic-node EOS quantities for diagnostics. rho, T,
    # Cp are already evaluated above for the flux/MLT terms.
    self._rho_basic_diag = rho
    self._T_basic_diag = T
    self._cp_basic_diag = Cp
    self._phi_basic_diag = np.asarray(self.phase_basic.melt_fraction()).ravel()

    # โ”€โ”€ Internal heating (power per unit mass [W/kg]) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    # Sources: radiogenic + tidal only. The volumetric work done by
    # phase segregation against the pressure gradient is already
    # implicit in the divergence of the ฮ”h-weighted mass-flux
    # contributions to ``_heat_flux``: by definition ฮ”h = ฮ”u + Pยทฮ”v,
    # and on a hydrostatic column โˆ‚ฮ”h/โˆ‚r โŠƒ ฮ”vยทโˆ‚P/โˆ‚r = โˆ’ฯgยทฮ”v, so
    # โˆ’โˆ‚/โˆ‚r(jยทฮ”h) โŠƒ +ฯยทgยทฮ”vยทj already carries the volumetric-work
    # quantity. Adding an explicit ฮฆ_vol source on top would
    # double-count. The Bower 2018 entropy form has no such source
    # either.
    n_stag = len(self._entropy_staggered)
    self._heating = np.zeros(n_stag)
    self._heating_radio = np.zeros(n_stag)
    self._heating_tidal = np.zeros(n_stag)

    if self._radionuclides:
        radio = 0.0
        for r in self._evaluator.radionuclides:
            radio += r.get_heating(time)
        self._heating += radio
        self._heating_radio[:] = radio

    if self._tidal:
        if len(self._tidal_array) == 1:
            tidal_term = np.full(n_stag, self._tidal_array[0])
        elif len(self._tidal_array) == n_stag:
            tidal_term = np.array(self._tidal_array)
        else:
            tidal_term = np.zeros(n_stag)
        self._heating += tidal_term
        self._heating_tidal[:] = tidal_term

SolverOutput(S_final, T_stag, phi_stag, rho_stag, visc_stag, P_stag, r_basic, r_stag, vol, mass_stag, heat_flux, heating, eddy_diff, cap_stag, jcond_b, jconv_b, jgrav_b, jmix_b, dSdr_b, phi_basic, T_basic, cp_basic, rho_basic, T_magma, T_core, Phi_global, Phi_global_vol, M_mantle, M_mantle_liquid, M_mantle_solid, RF_depth, E_th, E_state, E_state_cons, Cp_eff, F_heat_total, F_cmb, Q_radio_total, Q_tidal_total, step_dE_F_int_J, step_dE_F_cmb_J, step_dE_Q_radio_J, step_dE_Q_tidal_J, step_dE_Q_radio_cons_J, step_dE_Q_tidal_cons_J, step_solver_residual_J, step_dE_compression_J, step_dE_state_heat_J, dt_actual, status) dataclass

Complete output from one EntropySolver integration step.

This dataclass is the public contract between Aragog and PROTEUS. All quantities needed by the coupling wrapper are included here, so callers never need to reach into solver internals.

to_netcdf(path, *, time=None, description='Aragog SolverOutput snapshot')

Write this solver snapshot to a NetCDF4 file.

Produces a self-contained file that captures the full SolverOutput dataclass: scalar diagnostics, staggered-node profiles (entropy, temperature, melt fraction, density, viscosity, ...), basic-node profiles (heat flux, per-component flux decomposition, ...), and run-level metadata (Aragog version, optional simulation time, status code). All fields carry CF-style units and long_name attributes so the file is interpretable without consulting the source.

Designed for the standalone solver path: a script that builds an EntropySolver, runs solve(), and wants a portable record of the final state. PROTEUS-coupled runs do not use this; they assemble their own per-iteration helpfile rows on the wrapper side. The two writers are independent on purpose so the standalone schema can evolve without breaking PROTEUS.

Parameters:

Name Type Description Default
path str or Path

Destination NetCDF4 file. Overwrites if the file exists.

required
time float

Simulation time at which this snapshot was taken [yr]. Stored as the scalar time variable; defaults to the integrated step duration dt_actual if not supplied (the standalone solver does not carry an absolute clock).

None
description str

Free-form description string written to the dataset's description global attribute.

'Aragog SolverOutput snapshot'
Notes
  • Uses netCDF4 directly (already a hard dependency); no xarray import to keep startup lean.
  • All array fields are written as f8 (float64). The integer status field is stored as i4.
  • Reading back: netCDF4.Dataset(path) or xarray.open_dataset(path) both work; the file follows the CF-1.8 attribute convention.
Source code in src/aragog/solver/entropy_solver.py
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def to_netcdf(
    self,
    path: str | Path,
    *,
    time: float | None = None,
    description: str = 'Aragog SolverOutput snapshot',
) -> None:
    """Write this solver snapshot to a NetCDF4 file.

    Produces a self-contained file that captures the full
    ``SolverOutput`` dataclass: scalar diagnostics, staggered-node
    profiles (entropy, temperature, melt fraction, density,
    viscosity, ...), basic-node profiles (heat flux, per-component
    flux decomposition, ...), and run-level metadata (Aragog
    version, optional simulation time, status code). All fields
    carry CF-style ``units`` and ``long_name`` attributes so the
    file is interpretable without consulting the source.

    Designed for the standalone solver path: a script that builds
    an ``EntropySolver``, runs ``solve()``, and wants a portable
    record of the final state. PROTEUS-coupled runs do *not* use
    this; they assemble their own per-iteration helpfile rows on
    the wrapper side. The two writers are independent on purpose
    so the standalone schema can evolve without breaking PROTEUS.

    Parameters
    ----------
    path : str or Path
        Destination NetCDF4 file. Overwrites if the file exists.
    time : float, optional
        Simulation time at which this snapshot was taken [yr].
        Stored as the scalar ``time`` variable; defaults to the
        integrated step duration ``dt_actual`` if not supplied
        (the standalone solver does not carry an absolute clock).
    description : str, optional
        Free-form description string written to the dataset's
        ``description`` global attribute.

    Notes
    -----
    - Uses ``netCDF4`` directly (already a hard dependency); no
      xarray import to keep startup lean.
    - All array fields are written as ``f8`` (float64). The
      integer ``status`` field is stored as ``i4``.
    - Reading back: ``netCDF4.Dataset(path)`` or
      ``xarray.open_dataset(path)`` both work; the file follows the
      CF-1.8 attribute convention.
    """
    from datetime import datetime, timezone

    import netCDF4 as nc

    from aragog import __version__

    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)

    with nc.Dataset(path, mode='w') as ds:
        ds.description = description
        ds.aragog_version = __version__
        ds.created_utc = datetime.now(timezone.utc).isoformat(timespec='seconds')
        ds.Conventions = 'CF-1.8'

        n_stag = int(np.asarray(self.S_final).size)
        n_basic = int(np.asarray(self.r_basic).size)
        ds.createDimension('staggered', n_stag)
        ds.createDimension('basic', n_basic)

        def _scalar(
            name: str,
            value: float | int,
            units: str,
            long_name: str,
            *,
            fill_value_nan: bool = False,
        ) -> None:
            dtype = 'i4' if isinstance(value, (int, np.integer)) else 'f8'
            # CF convention: ``_FillValue`` must be set at variable
            # creation time, not after, otherwise netCDF4 raises
            # AttributeError. Pass it via the ``fill_value`` kwarg of
            # createVariable.
            if fill_value_nan and dtype == 'f8':
                v = ds.createVariable(name, dtype, fill_value=np.nan)
            else:
                v = ds.createVariable(name, dtype)
            v.units = units
            v.long_name = long_name
            v[...] = value

        def _arr(name: str, value, dim: str, units: str, long_name: str) -> None:
            arr = np.asarray(value, dtype=np.float64).ravel()
            v = ds.createVariable(name, 'f8', (dim,))
            v.units = units
            v.long_name = long_name
            v[:] = arr

        # Time stamp: prefer caller-supplied absolute time, else
        # fall back to the per-call duration.
        t_value = float(time) if time is not None else float(self.dt_actual)
        _scalar('time', t_value, 'yr', 'Simulation time of snapshot')

        # โ”€โ”€ Scalar diagnostics โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        _scalar('T_magma', self.T_magma, 'K', 'Surface (magma) temperature')
        _scalar('T_core', self.T_core, 'K', 'Core-mantle boundary temperature')
        _scalar(
            'Phi_global',
            self.Phi_global,
            '1',
            'Mass-weighted global mantle melt fraction (M_liq / M_mantle)',
        )
        _scalar(
            'Phi_global_vol',
            self.Phi_global_vol,
            '1',
            'Porosity-derived volume melt fraction (V_liq / V_mantle)',
        )
        _scalar('M_mantle', self.M_mantle, 'kg', 'Total mantle mass')
        _scalar('M_mantle_liquid', self.M_mantle_liquid, 'kg', 'Liquid mantle mass')
        _scalar('M_mantle_solid', self.M_mantle_solid, 'kg', 'Solid mantle mass')
        _scalar('RF_depth', self.RF_depth, '1', 'Dimensionless rheological-front depth')
        _scalar('E_th', self.E_th, 'J', 'Thermal energy proxy (legacy sum m*Cp_apparent*T)')
        # E_state and E_state_cons are documented to be NaN on the
        # ``const_properties`` path (no entropy EOS attached). Mark
        # them with ``_FillValue = NaN`` so xarray correctly treats
        # an absent value as intentional missing data rather than a
        # silent corrupted float.
        _scalar(
            'E_state',
            self.E_state,
            'J',
            'EOS-consistent integrated mantle enthalpy',
            fill_value_nan=True,
        )
        _scalar(
            'E_state_cons',
            self.E_state_cons,
            'J',
            'Conservation-grade integrated enthalpy with frozen structural mass',
            fill_value_nan=True,
        )
        _scalar('Cp_eff', self.Cp_eff, 'J kg-1 K-1', 'Mass-weighted mean heat capacity')
        _scalar('F_heat_total', self.F_heat_total, 'W m-2', 'Total internal heating flux')
        _scalar('F_cmb', self.F_cmb, 'W m-2', 'Heat flux at the CMB (positive out of core)')
        _scalar(
            'Q_radio_total', self.Q_radio_total, 'W', 'Mantle-integrated radiogenic power'
        )
        _scalar('Q_tidal_total', self.Q_tidal_total, 'W', 'Mantle-integrated tidal power')
        _scalar(
            'step_dE_F_int_J',
            self.step_dE_F_int_J,
            'J',
            'Per-call surface heat-loss energy',
        )
        _scalar(
            'step_dE_F_cmb_J', self.step_dE_F_cmb_J, 'J', 'Per-call CMB heat-gain energy'
        )
        _scalar(
            'step_dE_Q_radio_J', self.step_dE_Q_radio_J, 'J', 'Per-call radiogenic energy'
        )
        _scalar('step_dE_Q_tidal_J', self.step_dE_Q_tidal_J, 'J', 'Per-call tidal energy')
        _scalar(
            'step_dE_Q_radio_cons_J',
            self.step_dE_Q_radio_cons_J,
            'J',
            'Per-call radiogenic energy (frozen-mass weighting)',
        )
        _scalar(
            'step_dE_Q_tidal_cons_J',
            self.step_dE_Q_tidal_cons_J,
            'J',
            'Per-call tidal energy (frozen-mass weighting)',
        )
        _scalar(
            'step_solver_residual_J',
            self.step_solver_residual_J,
            'J',
            'Per-call entropy-ODE balance residual',
        )
        _scalar(
            'step_dE_compression_J',
            self.step_dE_compression_J,
            'J',
            'Per-call compression work from the structure re-solve',
        )
        _scalar(
            'step_dE_state_heat_J',
            self.step_dE_state_heat_J,
            'J',
            'Per-call entropy-transported heat content change (EOS quadrature)',
        )
        _scalar('dt_actual', self.dt_actual, 'yr', 'Actual integration time of this step')
        _scalar('status', int(self.status), '1', 'Solver status code (0 = success)')

        # โ”€โ”€ Staggered-node profiles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        _arr('r_stag', self.r_stag, 'staggered', 'm', 'Radius at staggered nodes')
        _arr('P_stag', self.P_stag, 'staggered', 'Pa', 'Pressure at staggered nodes')
        _arr('S_final', self.S_final, 'staggered', 'J kg-1 K-1', 'Specific entropy')
        _arr('T_stag', self.T_stag, 'staggered', 'K', 'Temperature at staggered nodes')
        _arr(
            'phi_stag',
            self.phi_stag,
            'staggered',
            '1',
            'Melt mass fraction at staggered nodes',
        )
        _arr('rho_stag', self.rho_stag, 'staggered', 'kg m-3', 'Density at staggered nodes')
        _arr(
            'visc_stag',
            self.visc_stag,
            'staggered',
            'Pa s',
            'Dynamic viscosity at staggered nodes',
        )
        _arr('vol', self.vol, 'staggered', 'm3', 'Per-shell volume')
        _arr('mass_stag', self.mass_stag, 'staggered', 'kg', 'Per-shell mass')
        _arr('heating', self.heating, 'staggered', 'W kg-1', 'Internal heating rate')
        _arr('cap_stag', self.cap_stag, 'staggered', 'kg K m-3', 'Capacitance rho*T')

        # โ”€โ”€ Basic-node profiles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        _arr('r_basic', self.r_basic, 'basic', 'm', 'Radius at basic nodes')
        _arr('heat_flux', self.heat_flux, 'basic', 'W m-2', 'Total radial heat flux')
        _arr('eddy_diff', self.eddy_diff, 'basic', 'm2 s-1', 'Eddy thermal diffusivity')
        _arr('jcond_b', self.jcond_b, 'basic', 'W m-2', 'Conductive heat flux')
        _arr('jconv_b', self.jconv_b, 'basic', 'W m-2', 'Convective (MLT) heat flux')
        _arr(
            'jgrav_b',
            self.jgrav_b,
            'basic',
            'W m-2',
            'Gravitational-separation heat-flux contribution',
        )
        _arr('jmix_b', self.jmix_b, 'basic', 'W m-2', 'SPIDER-parity phase-mixing flux')
        _arr('dSdr_b', self.dSdr_b, 'basic', 'J kg-1 K-1 m-1', 'Radial entropy gradient')
        _arr('phi_basic', self.phi_basic, 'basic', '1', 'Melt mass fraction at basic nodes')
        _arr('T_basic', self.T_basic, 'basic', 'K', 'Temperature at basic nodes')
        _arr(
            'cp_basic',
            self.cp_basic,
            'basic',
            'J kg-1 K-1',
            'Heat capacity at basic nodes',
        )
        _arr('rho_basic', self.rho_basic, 'basic', 'kg m-3', 'Density at basic nodes')