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 Holds the BC settings that EntropySolver reads, plus a standalone flux dispatch: surface (grey-body, UTBL, prescribed flux/T) and inner (prescribed flux/T). Core cooling (inner_boundary_condition = 1) is applied inside EntropySolver.
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: Core cooling (EntropySolver only; raises here) 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
204
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: Core cooling (EntropySolver only; raises here)
        2: Prescribed heat flux
        3: Prescribed temperature
    """
    if self._settings.inner_boundary_condition == 1:
        msg = 'inner_boundary_condition = 1 (core cooling) is applied by EntropySolver'
        raise NotImplementedError(msg)
    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]
        )

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
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
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
    self._warned: set[str] = set()
    self._batch_powers_calls: int = 0
    # 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
    # Output points CVODE returns per macro-step solve; a root ends the call early.
    self._cvode_output_points = self.parameters.solver.cvode_output_points
    # Maximum internal CVODE steps per output interval (SUNDIALS mxstep); exceeding it
    # returns CV_TOO_MUCH_WORK.
    self._max_steps = self.parameters.solver.max_steps
    # Optional per-solve core-temperature change limit [K]. When set,
    # a solve whose core temperature moves by more than this from the
    # solve-entry value at any point on the returned grid raises a flag
    # on the result. The flag is also raised, independent of this
    # limit, whenever any sampled core temperature is non-finite.
    self._tcore_change_limit = self.parameters.solver.tcore_change_limit
    # 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 the bower2018, energy_balance and core_module modes the solver state vector is longer than N; we strip the trailing extra rows 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.

The layout and the length of the state vector depend on the core BC mode (_dSdt_single lists the five), and this returns the derivative in the same layout.

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], one column of the length of the active core BC mode.

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
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
def dSdt(
    self,
    time: npt.NDArray | float,
    state_vec: npt.NDArray,
) -> npt.NDArray:
    """Time derivative of the full state vector.

    The layout and the length of the state vector depend on the
    core BC mode (``_dSdt_single`` lists the five), and this
    returns the derivative in the same layout.

    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],
        one column of the length of the active core BC mode.

    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
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
@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_core_temperature()

Return the most recent core temperature from the solver state.

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

Used by PROTEUS's retry ladder to snapshot the pre-solve T_core before a sequence of retry attempts and restore it on each retry, mirroring get_current_dSdr_cmb.

Source code in src/aragog/solver/entropy_solver.py
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
def get_current_core_temperature(self) -> float | None:
    """Return the most recent core temperature from the solver state.

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

    Used by PROTEUS's retry ladder to snapshot the pre-solve
    T_core before a sequence of retry attempts and restore it on
    each retry, mirroring ``get_current_dSdr_cmb``.
    """
    return self._final_extra_state('T_core')

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 or core_module).

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
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
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`` or ``core_module``).

    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.
    """
    return self._final_extra_state('dSdr_cmb')

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
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
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.
    """
    self._sync_top_node()
    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 or self._core_bc == 'core_module'

    # solve() stores the integrals; a result set without solve() gets them here, before
    # the final-state refresh below that the rest of get_state() reads.
    step_integrals = sol.get('energy_integrals') or 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, _ = self._reconstruct_entropy(dSdr_final, S_surf_final)
    elif is_ext:
        S_final = sol.y[:n_stag, -1]
    else:
        S_final = sol.y[:, -1]

    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 through the RHS, so the boundary
    # fluxes are the ones the integrator applied; core_module zeroes the gradient
    # slot, so the CMB node is the bottom cell carried to the CMB pressure.
    y_diag = sol.y[:, -1].copy()
    if self._core_bc == 'core_module':
        y_diag[n_stag] = 0.0
    self._dSdt_single(sol.t[-1], y_diag)
    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()
    if self._core_bc == 'core_module':
        # Node 0 carries the applied closure: conduction across the thinner of the half
        # cell and the boundary layer.
        jcond_b[0], jconv_b[0], jgrav_b[0], jmix_b[0] = heat_flux[0], 0.0, 0.0, 0.0
    # Phase-boundary quantities at the basic nodes, for consumers that compute melt drainage.
    ph = self.state.phase_basic
    porosity_b, rho_solid_b, rho_melt_b, g_b = (
        np.array(x, dtype=float).ravel()
        for x in (
            ph.porosity(),
            *ph.phase_boundary_densities(),
            ph.gravitational_acceleration(),
        )
    )

    # Scalar quantities. M_mantle is the structural mass between the CMB
    # and the surface from the EOS mass integral, not the PALEOS rho_stag
    # used just below for per-cell output.
    mesh = self.evaluator.mesh
    M_mantle = float(
        np.diff(mesh.eos.get_mass_within_radii(self._r_basic_flat[[0, -1]]))[0]
    )
    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.
    T_core = self._core_temperature_from_column(sol.y[:, -1])
    # Per-solve core-temperature excursion: the largest change of the
    # core temperature from its solve-entry value over the returned
    # grid, with a flag set when it exceeds the configured limit or
    # when any sampled core temperature is non-finite.
    tcore_change_max, tcore_change_exceeded = self._core_temperature_excursion(sol)
    # 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 reported as the energy-conserving step-average
    # (trapezoidal time-mean over the call; integral equals step_dE_F_cmb_J).
    # Falls back to the end-of-step basic-node-0 value when the call has no
    # integrable trajectory. Sign positive-out-of-core into the mantle.
    F_cmb = step_integrals['F_cmb_step_avg']
    if F_cmb is None:
        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

    shell = self._core_shell()
    if shell is not None:
        y_end = np.asarray(sol.y[:, -1])
        t_shell_end = y_end[n_stag + 2 :]
        layer_base = float(shell.layer_base(t_shell_end, y_end[n_stag + 1]))
        t_top = float(shell.top_temperature(t_shell_end))
    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(Phi_global * M_mantle),
        M_mantle_solid=float((1.0 - Phi_global) * M_mantle),
        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_core_J=step_integrals['core'],
        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,
        cvode_flag=int(getattr(sol, 'cvode_flag', 0)),
        cvode_flag_name=str(getattr(sol, 'cvode_flag_name', 'N/A')),
        tcore_change_max=tcore_change_max,
        tcore_change_exceeded=tcore_change_exceeded,
        core_T_shell=None if shell is None else t_shell_end.copy(),
        core_layer_base=np.nan if shell is None else layer_base,
        core_T_top=np.nan if shell is None else t_top,
        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,
        porosity_b=porosity_b,
        rho_solid_b=rho_solid_b,
        rho_melt_b=rho_melt_b,
        g_b=g_b,
    )

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
1573
1574
1575
1576
1577
1578
1579
1580
1581
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
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
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_module).

Must be called BEFORE set_initial_entropy. If not called, the initial T_core defaults to the previous solution's final value (if any), else to the EOS temperature of the bottom cell's entropy in S_init, at the CMB pressure for core_module (no CMB flux at the start without a shell) and at the bottom-cell pressure for bower2018.

The value applies to every later call of set_initial_entropy. Pass None to clear it, restoring the hot-start behaviour; only a set value is checked against the mantle temperature at the CMB.

Source code in src/aragog/solver/entropy_solver.py
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
def set_initial_core_temperature(self, T_core_init: float | None) -> None:
    """Set the initial core temperature (``bower2018`` / ``core_module``).

    Must be called BEFORE ``set_initial_entropy``. If not called,
    the initial T_core defaults to the previous solution's final value
    (if any), else to the EOS temperature of the bottom cell's entropy
    in S_init, at the CMB pressure for ``core_module`` (no CMB flux at
    the start without a shell) and at the bottom-cell pressure for ``bower2018``.

    The value applies to every later call of ``set_initial_entropy``.
    Pass ``None`` to clear it, restoring the hot-start behaviour; only a
    set value is checked against the mantle temperature at the CMB.
    """
    self._T_core_init = None if T_core_init is None else float(T_core_init)

set_initial_dSdr_cmb(dSdr_cmb_init)

Set the initial CMB entropy gradient (energy_balance / core_module).

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
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
def set_initial_dSdr_cmb(self, dSdr_cmb_init: float | None) -> None:
    """Set the initial CMB entropy gradient (energy_balance / core_module).

    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; core_module uses length N+2 (dSdr_cmb and T_core) plus the shell temperatures of a stratified core. 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
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
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; ``core_module`` uses length N+2
    (``dSdr_cmb`` and ``T_core``) plus the shell temperatures of a
    stratified core. 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 = self._resolve_dSdr_cmb_init(S_arr, n_stag)
        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 in ('bower2018', 'core_module'):
        # Core temperature as an ODE state: bower2018 [S, T_core] (parity testing only),
        # core_module [S, dSdr_cmb, T_core] with T_core the core budget's state. The CMB
        # flux law takes T_core (the top shell cell with a shell) against the bottom cell.
        slots = EXTRA_STATE_SLOTS[core_bc]
        n_extra = len(slots)
        T_core_slot = n_stag + slots.index('T_core')
        T_core_init = getattr(self, '_T_core_init', None)
        t_core_override = T_core_init is not None
        if T_core_init is None:
            T_core_init = self.get_current_core_temperature()

        dSdr_cmb_init = None
        if 'dSdr_cmb' in slots:
            dSdr_cmb_init = self._resolve_dSdr_cmb_init(S_arr, n_stag)

        T_bottom_eos = None
        if (
            T_core_init is None or core_bc == 'core_module'
        ) and self.entropy_eos is not None:
            # core_module: the bottom cell at the CMB pressure, the mantle side of the
            # contrast of the flux law, so the default start without a shell has no flux.
            P_bot, S_bot = float(self._P_stag_flat[0]), float(S_arr[0])
            if core_bc == 'core_module':
                P_bot = float(getattr(self, '_P_basic_flat', self._P_stag_flat)[0])
            T_bottom_eos = float(
                np.asarray(
                    self.entropy_eos.temperature(np.array([P_bot]), np.array([S_bot]))
                ).item()
            )

        if T_core_init is None:
            if T_bottom_eos is not None:
                T_core_init = T_bottom_eos
            else:
                raise ValueError(
                    f"Cannot initialize core temperature for core_bc='{core_bc}': "
                    'entropy EOS is not available and no initial core temperature was provided.'
                )
        if (
            core_bc == 'core_module'
            and t_core_override
            and not getattr(self, '_t_core_offset_warned', False)
            and T_bottom_eos is not None
            and abs(T_core_init - T_bottom_eos) > 0.2 * max(T_bottom_eos, 1.0)
        ):
            # Once, for a supplied start: a hot start continues the run's own contrast.
            # Under a stiff base the flux relaxes a large offset only slowly.
            self._t_core_offset_warned = True
            logger.warning(
                'core_module: initial T_core=%.0f K differs from the '
                'mantle temperature at the CMB %.0f K by more than 20%%; '
                'the CMB flux relaxes the offset at the rate the basal '
                'boundary layer allows, which shifts inner-core nucleation timing.',
                T_core_init,
                T_bottom_eos,
            )
        shell = self._core_shell() if core_bc == 'core_module' else None
        self._S0 = np.empty(n_stag + n_extra + (0 if shell is None else shell.n_cells))
        self._S0[:n_stag] = S_arr
        self._S0[T_core_slot] = T_core_init
        if 'dSdr_cmb' in slots:
            self._S0[n_stag + slots.index('dSdr_cmb')] = float(dSdr_cmb_init)
        if shell is not None:
            self._S0[n_stag + n_extra :] = self._initial_shell(
                shell, T_core_init, t_core_override
            )
        logger.info(
            'Initial state (%s): S_min=%.0f, S_max=%.0f, T_core_init=%.0f K',
            core_bc,
            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_initial_shell_temperature(t_shell)

Set the shell temperatures [K] of a stratified core (a resume).

Must be called before set_initial_entropy. The profile applies to every later call of set_initial_entropy; None clears it, so the shell starts from the previous solution, or on the adiabat of the core without one.

Source code in src/aragog/solver/entropy_solver.py
2372
2373
2374
2375
2376
2377
2378
2379
def set_initial_shell_temperature(self, t_shell: npt.NDArray | None) -> None:
    """Set the shell temperatures [K] of a stratified core (a resume).

    Must be called before ``set_initial_entropy``. The profile applies to every later
    call of ``set_initial_entropy``; ``None`` clears it, so the shell starts from the
    previous solution, or on the adiabat of the core without one.
    """
    self._T_shell_init = None if t_shell is None else np.asarray(t_shell, dtype=float)

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. rhs_fn may optionally carry a step_powers(t_nodes, Y_nodes, aux) attribute for batched per-call energy power evaluation. 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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
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.
        ``rhs_fn`` may optionally carry a ``step_powers(t_nodes, Y_nodes, aux)``
        attribute for batched per-call energy power evaluation.
        May be None to disable the Option Z path even if the flag
        is on.
    """
    self._jax_cvode_factory = factory

solve(_floor_discard=None)

Run the BDF time integration.

A successful solve also stores the per-call energy integrals on the result as energy_integrals (see _compute_step_energy_integrals); a failed one stores zeros. _floor_discard (internal) refuses the call with that warning: a call whose floor root returns a state below the EOS table, or stops at the call start, is solved again this way, so it returns its start state.

Source code in src/aragog/solver/entropy_solver.py
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
def solve(self, _floor_discard: str | None = None) -> None:
    """Run the BDF time integration.

    A successful solve also stores the per-call energy integrals on the result as
    ``energy_integrals`` (see ``_compute_step_energy_integrals``); a failed one stores
    zeros. ``_floor_discard`` (internal) refuses the call with that warning: a call whose
    floor root returns a state below the EOS table, or stops at the call start, is solved
    again this way, so it returns its start state.
    """
    wall_start = time.perf_counter()
    self._sync_top_node()  # the EOS may have changed since the reset
    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

    # Step-cap anchor of the root or event, None when no cap is armed (the floor arms the
    # root without it); set here for the paths without an EOS, such as const_properties.
    phi_cap_anchor = None
    floor, floor_refused = None, False
    rate_mode = False

    # Runs whenever the entropy EOS is loaded: the T and S caps stay armed in the deep solid,
    # where the phi cap is blind. A cell within the margin of a boundary or in the mushy band
    # tightens max_step: 1 yr for 'fixed', CVODE segments for 'rate'.
    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])
        cap_set = getattr(self.parameters.energy, 'phase_boundary_cap', None)
        cap_mode = cap_set or 'rate'
        # Staggered cells plus the CMB cell at the CMB-pressure boundaries.
        rate_liq = np.append(S_liq_stag, S_liq)
        rate_sol = np.append(S_sol_stag, S_sol)
        w = float(getattr(self.parameters.phase_mixed, 'matprop_smooth_width', 0.0))
        rate_delta = max(3.0 * w * float(np.max(rate_liq - rate_sol)), _RATE_CAP_MIN_DELTA)
        use_cvode = (
            getattr(self.parameters.energy, 'solver_method', 'cvode') == 'cvode'
            and _CVODE_AVAILABLE
        )
        segment_margin = _segment_arming_margin(
            entropy_margin, rate_delta, cap_mode, self._core_bc, use_cvode
        )

        def clamps(margin):
            return _phase_boundary_max_step_clamp(
                np.any(np.abs(margin_to_liq) < margin),
                np.any(np.abs(margin_to_sol) < margin),
                in_mushy,
                cmb_margin_to_liq=S0_block_cmb - S_liq,
                cmb_margin_to_sol=S0_block_cmb - S_sol,
                entropy_margin=margin,
            )

        if clamps(entropy_margin) or (
            segment_margin > entropy_margin and clamps(segment_margin)
        ):
            rate_mode = cap_mode == 'rate' and self._core_bc != 'gradient'
            max_step = 1.0
            if cap_mode == 'rate' and not rate_mode:
                self._warn_once(
                    'gradient',
                    'phase_boundary_cap="rate" is not used by the gradient core; '
                    'max_step 1 yr',
                    logging.WARNING if cap_set else logging.INFO,
                )

        # 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,
                )

        # EOS floor: a root ends the call at S_min + m, or S_min + m/2 for a start below
        # S_min + m; closer starts are decided by _floor_start_level.
        floor_margin = _resolve_step_cap(
            getattr(self.parameters.energy, 'eos_floor_margin', EOS_FLOOR_MARGIN_DEFAULT)
        )
        S_tab = float(self.entropy_eos.S_min)
        if floor_margin >= float(self.entropy_eos.S_max) - S_tab:
            raise ValueError(
                f'eos_floor_margin {floor_margin!r} J/kg/K must be below the entropy '
                f'span of the EOS tables, {float(self.entropy_eos.S_max) - S_tab!r}'
            )
        if _floor_discard is not None:
            floor_refused, end_time = True, start_time
            logger.warning(_floor_discard)
        elif floor_margin > 0.0 and not gradient_mode and end_time > start_time:
            mesh = self.evaluator.mesh
            floor_w = np.asarray(mesh._quantity_transform)[-1]
            if mesh.top_node == 'limited':  # the node stays in the table with its cells
                floor_w = np.eye(1, floor_w.size, floor_w.size - 1).ravel()
            level, refuse = _floor_start_level(
                floor_w,
                S_arr_stag,
                lambda: np.ravel(self._dSdt_single(start_time, self._S0))[: self._n_stag],
                S_tab,
                floor_margin,
                end_time - start_time,
            )
            if level is not None:
                floor = dict(
                    floor_weights=floor_w, floor_level=level, floor_margin=floor_margin
                )
            elif refuse:
                floor_refused, end_time = True, start_time
                s_floor = _floor_entropy(floor_w, S_arr_stag)
                band, half = 2.0e-6 * floor_margin, 0.5 * (s_floor + S_tab)
                if s_floor <= S_tab:
                    why = 'at or below the table minimum'
                elif s_floor <= S_tab + band and not S_tab < half < s_floor:
                    why = 'no level fits between it and the table minimum'
                elif s_floor <= S_tab + band:
                    why = f'counts as at the table minimum (within {band:.2g} J/kg/K) and falls'
                else:
                    why = (
                        f'at most {0.5 * floor_margin:.1f} J/kg/K above it, falls too fast'
                    )
                logger.warning(
                    'EOS floor: entropy %.9g J/kg/K at the call start, %+.3e J/kg/K from the '
                    'table minimum %.9g J/kg/K, %s; the call does not advance',
                    s_floor,
                    s_floor - S_tab,
                    S_tab,
                    why,
                )

    # 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()
    _offset = scales.state_offset
    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 - _offset) / _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 + _offset,
        )
        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 or floor is not None:
        a = phi_cap_anchor or {}
        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.get('phi0_global', 0.0),
                cap=a.get('cap_phi', 0.0),
                state_scale=_state_scale,
                phi0_per_cell=a.get('phi0_cell'),
                cap_temperature=a.get('cap_T', 0.0),
                T0_per_cell=a.get('T0_cell'),
                cap_entropy=a.get('cap_S', 0.0),
                S0_per_cell=a.get('S0_cell'),
                **(floor or {}),
            )
            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
    self._cvode_step_powers_batch = None
    if use_cvode:
        # Build JAX-derived CVODE callbacks when the factory is registered
        # and use_jax_jacobian is active. Callbacks reuse cached functions.
        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,
                )
                self._cvode_step_powers_batch = getattr(
                    cvode_rhs_override, 'step_powers', None
                )
                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)')
        cvode_kw = dict(
            atol=atol_nd,
            rtol=rtol,
            rhs=_rhs_nondim,
            cvode_rhs_fn_override=cvode_rhs_override,
            cvode_jacfn=cvode_jacfn,
            phi_cap_rootfn=phi_cap_rootfn,
        )
        spans = end_time > start_time
        D = self.state._convective_threshold
        if spans and D > 0.0:
            self._warn_once(
                'threshold',
                f'convective_threshold {D:.1e} > 0: kappa_h jumps at dS/dr = 0, which can '
                'stall CVODE at a node whose gradient stays near 0, also at rtol 1e-8; '
                'see the heat transport docs',
            )
        if spans and rtol > _CVODE_TOL_LIMIT:
            atol_cfg = self.parameters.solver.atol
            loose = atol_cfg > _CVODE_TOL_LIMIT and self._core_bc == 'energy_balance'
            note = (
                f'; the configured solver.atol {atol_cfg:.1e} adds to this' if loose else ''
            )
            self._warn_once(
                'cvode_tol',
                f'CVODE at solver.rtol {rtol:.1e}: an rtol above 1e-8 can lock CVODE '
                'at the convective switch (convective mask and kappa_h floor; in test runs '
                'at convective_threshold = 0 '
                'with atol = rtol and the initial entropy drawn per run: 12 of 1133 at 1e-6, '
                '0 of 1026 at 1e-8, and 0 of 80 at 1e-5 but about 12 times more RHS '
                f'evaluations than at 1e-8; see the solver tuning docs){note}. '
                'Use 1e-8, the Aragog default, for rtol and atol',
            )
        if rate_mode:
            if spans and rtol > _RATE_CAP_RTOL_LIMIT:
                self._warn_once(
                    'rtol',
                    f'phase_boundary_cap="rate" at rtol {rtol:.1e}: its accuracy is measured '
                    'at rtol 1e-8',
                )

            def _rate_h(t_nd, y_nd):
                try:
                    y = np.asarray(y_nd, dtype=float) * _state_scale + _offset
                    S = y[:n_s]
                    dSdt = np.asarray(self._dSdt_single(t_nd * t_ref, y)).ravel()[:n_s]
                    rho = np.asarray(self.entropy_eos.density(self._P_stag_flat, S)).ravel()
                    h = _rate_phase_boundary_max_step(
                        np.append(S, S[0]),
                        np.append(dSdt, dSdt[0]),
                        rate_liq,
                        rate_sol,
                        np.append(rho * self._volume_flat, 0.0),
                        rate_delta,
                    )
                except Exception as exc:
                    logger.warning(
                        'rate cap: dS/dt evaluation failed (%s); max_step 1 yr', exc
                    )
                    h = 1.0
                return h / t_ref

            def _rate_roots(y_nd, inside):
                return _PhaseBoundarySegmentRoot(
                    rate_liq,
                    rate_sol,
                    y_nd,
                    rate_delta,
                    inside,
                    _state_scale,
                    n_s,
                    cap=phi_cap_rootfn,
                )

            self._solution = self._solve_cvode_segments(
                start_time=start_nd,
                end_time=end_nd,
                y0=S0_nd,
                h_at=_rate_h,
                roots_at=_rate_roots,
                t_ref=t_ref,
                h_min=1.0 / t_ref,
                **cvode_kw,
            )
        else:
            self._solution = self._solve_cvode(
                start_time=start_nd,
                end_time=end_nd,
                y0=S0_nd,
                max_step=max_step_nd,
                **cvode_kw,
            )
    else:
        shell = self._core_shell() is not None
        if shell and solver_method == 'radau':
            raise ValueError(
                "a stratified core_module needs solver_method 'cvode' or 'bdf': Radau "
                'takes minutes per call on the stiff mixing of the resolved shell'
            )
        method = 'BDF' if solver_method == 'bdf' or shell else 'Radau'
        logger.info('EntropySolver: using scipy %s', method)
        if rate_mode:
            self._warn_once(
                'scipy',
                'phase_boundary_cap="rate" needs CVODE; max_step 1 yr with scipy',
                logging.WARNING if cap_set else logging.INFO,
            )
        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] + _offset[:, np.newaxis]
        else:
            sol.y = sol_y * _state_scale + _offset
    trace = sol.get('energy_trace')
    if trace is not None:
        sol.energy_trace = self._physical_trace(trace, t_ref, _state_scale, _offset)
    if floor_refused:
        sol.status = 1
        sol.message = 'EOS floor: the call does not advance'
    elif floor is not None and sol.status >= 0 and sol.t is not None and len(sol.t):
        t_end = float(np.asarray(sol.t)[-1])
        ys = [np.asarray(sol.y, dtype=float)]
        if trace is not None:
            ys.append(np.asarray(sol.energy_trace[1], dtype=float))
        S_all = np.concatenate([y[:n_s] for y in ys], axis=1)
        low = min(float(np.min(floor['floor_weights'] @ S_all)), float(S_all.min()))
        if low < S_tab:
            return self.solve(
                _floor_discard=(
                    f'EOS floor: the call with level S_min {floor["floor_level"] - S_tab:+.3e} '
                    f'J/kg/K put the floor entropy at S_min {low - S_tab:+.3e} J/kg/K at '
                    f'{t_end - start_time:.6g} yr after the call start {start_time:.9g} yr '
                    f'(table minimum {S_tab:.9g} J/kg/K); the call is discarded and does not '
                    'advance'
                )
            )
        if t_end <= float(np.asarray(sol.t)[0]):  # the returned start, after the time scale
            return self.solve(
                _floor_discard=(
                    f'EOS floor: the root of level S_min {floor["floor_level"] - S_tab:+.3e} '
                    f'J/kg/K fell at the call start t={start_time:.9g} yr; the call does not '
                    'advance'
                )
            )

    # Step-cap-fire log, in physical time (after the t_ref restoration
    # above) and naming whichever margin actually bound: read from
    # ``sol.cap_label`` on the CVODE path, from the event closure's
    # ``binding_cap`` on the scipy fallback path.
    cap_display_names = {
        'phi': 'ΔΦ_global',
        'temperature': 'ΔT',
        'entropy': 'ΔS',
        'eos_floor': 'EOS floor',
    }
    if getattr(sol, 'cap_fired', False) and sol.t is not None:
        t_root_phys = float(sol.t[-1])
        cap_label = getattr(sol, 'cap_label', None)
        if cap_label is None:
            # The terminating rootfn call raised, so which cap bound is
            # unknown; report that rather than guessing 'phi'.
            logger.info(
                'step cap fired at t=%.3e yr after %d evals; '
                'binding cap unknown (EOS lookup failed on the terminating call)',
                t_root_phys,
                int(getattr(sol, 'cap_evals', 0)),
            )
        else:
            cap_name = cap_display_names.get(cap_label, 'ΔΦ_global')
            if cap_label == 'phi':
                logger.info(
                    '%s cap: CVODE rootfn fired at '
                    't=%.3e yr after %d evals; cap=%.3g, '
                    'Φ_global(start)=%.4f',
                    cap_name,
                    t_root_phys,
                    int(getattr(sol, 'cap_evals', 0)),
                    float(getattr(sol, 'cap_value', 0.0)),
                    float(getattr(sol, 'cap_phi0', 0.0)),
                )
            else:
                floor_fired = cap_label == 'eos_floor'
                logger.log(
                    logging.WARNING if floor_fired else logging.INFO,
                    '%s cap: CVODE rootfn fired at t=%.3e yr after %d evals; %s',
                    cap_name,
                    t_root_phys,
                    int(getattr(sol, 'cap_evals', 0)),
                    f'level={sol.cap_value:.6g}'
                    if floor_fired
                    else f'cap={sol.cap_value:.3g}',
                )
    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
        event_label = getattr(events[0], 'binding_cap', None) if events else None
        if event_label is None:
            logger.info(
                'step cap fired at t=%.3e yr (terminal=True); '
                'binding cap unknown (EOS lookup failed on the terminating call)',
                t_event_phys,
            )
        else:
            cap_name = cap_display_names.get(event_label, 'ΔΦ_global')
            logger.log(
                logging.WARNING if event_label == 'eos_floor' else logging.INFO,
                '%s cap: scipy event fired at t=%.3e yr (terminal=True)%s',
                cap_name,
                t_event_phys,
                f'; level={floor["floor_level"]:.6g}' if event_label == 'eos_floor' else '',
            )

    # 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)
        cvode_nst = getattr(sol, 'cvode_nst', None)
        cvode_nfe = getattr(sol, 'cvode_nfe', None)
        if use_cvode and cvode_nst is not None:
            logger.info(
                'EntropySolver: %d internal steps, %d RHS evals, '
                'output grid dt_min=%.2e yr, dt_max=%.2e yr, dt_med=%.2e yr',
                cvode_nst,
                cvode_nfe,
                dt_internal.min(),
                dt_internal.max(),
                np.median(dt_internal),
            )
        else:
            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

    self._log_solution_outcome(self.parameters.solver.end_time)
    if self.stop_early:
        sol.energy_integrals = dict(_ZERO_ENERGY_INTEGRALS)
        return
    budget = getattr(self, '_core_module_budget', None)
    if self._core_bc == 'core_module' and budget is not None:
        from aragog.core.regime import refuse_unmodelled_regime

        # every accepted step of the call, not only the output points
        t_core = (sol.get('energy_trace') or (sol.t, sol.y))[1][self._n_stag + 1]
        refuse_unmodelled_regime(budget, t_core)
    t_solved = time.perf_counter()
    sol.energy_integrals = self._compute_step_energy_integrals()
    logger.info(
        'EntropySolver: energy integrals in %.2f s (solve %.2f s)',
        time.perf_counter() - t_solved,
        t_solved - wall_start,
    )

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
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
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', convective_threshold=CONVECTIVE_THRESHOLD_DEFAULT)

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
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
325
326
327
328
329
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',
    convective_threshold: float = CONVECTIVE_THRESHOLD_DEFAULT,
):
    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
    check_convective_threshold(convective_threshold)
    self._convective_threshold = float(convective_threshold)
    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
1011
1012
1013
1014
1015
1016
1017
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
1038
1039
1040
1041
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 and core_module modes: 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
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
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 and core_module modes: 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:
        basic = getattr(mesh, 'entropy_at_basic_nodes', mesh.quantity_at_basic_nodes)
        self._entropy_basic = np.ravel(basic(S))
    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 and core_module: override the boundary entropy gradient with the
    # state-vector value, 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 ────────────────────────────────
    # The drive below acts only where dS/dr < 0; the floor applies while dS/dr < D
    # (convective_threshold). D = 0 gives the dS/dr < 0 switch for both.
    self._is_convective = self._dSdr < 0.0
    floor_mask = self._dSdr < self._convective_threshold

    # Buoyancy |superadiabatic| = alpha * T * max(-dS/dr, 0) / Cp, at least alpha*T*D/Cp
    # on unstable nodes.
    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()

    conv_drive = np.maximum(
        _smooth_abs_neg(self._dSdr, eps=1.0e-30),
        self._convective_threshold * self._is_convective,
    )
    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 is 0 on stable 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)

    # Melt-fraction-modulated kappa_h floor on cells with dS/dr < D only (see
    # apply_kappah_floor for why cells with dS/dr >= D keep their raw value).
    # 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,
            floor_mask,
        )

    # 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)
        # Positive when dS/dr < 0, negative on stable nodes with the floor (0 <= dS/dr < D)
        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, porosity_b, rho_solid_b, rho_melt_b, g_b, 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_core_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, cvode_flag=0, cvode_flag_name='N/A', tcore_change_max=0.0, tcore_change_exceeded=False, core_T_shell=None, core_layer_base=float('nan'), core_T_top=float('nan')) 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. status 0 (success) and 1 (stop at a step-cap event) are successful runs, any other status is a failure; failed tells the two apart.

failed property

Whether the integration failed (a status other than 0 and 1).

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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
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',
            'Step-average 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_core_J', self.step_dE_core_J, 'J', 'Per-call core energy change')
        _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', _STATUS_DESCRIPTION)
        _scalar(
            'cvode_flag',
            int(self.cvode_flag),
            '1',
            'Raw CVODE return flag (0 SUCCESS, -1 TOO_MUCH_WORK, '
            '-4 CONV_FAILURE); scipy solve_ivp path reports 0',
        )
        ds.cvode_flag_name = self.cvode_flag_name
        _scalar(
            'tcore_change_max',
            float(self.tcore_change_max),
            'K',
            'Largest per-solve core-temperature change from solve entry',
        )
        if self.core_T_shell is not None:
            ds.createDimension('shell', int(np.asarray(self.core_T_shell).size))
            _arr('core_T_shell', self.core_T_shell, 'shell', 'K', 'Core shell temperatures')
        _scalar(
            'core_layer_base',
            self.core_layer_base,
            'm',
            'Base of the stable core layer',
            fill_value_nan=True,
        )
        _scalar(
            'core_T_top',
            self.core_T_top,
            'K',
            'Temperature at the top of the core shell',
            fill_value_nan=True,
        )
        _scalar(
            'tcore_change_exceeded',
            int(self.tcore_change_exceeded),
            '1',
            'Flag (0/1): per-solve core-temperature change exceeds the '
            'limit, or a sampled core temperature is non-finite',
        )

        # ── 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')
        _arr(
            'porosity_b',
            self.porosity_b,
            'basic',
            '1',
            'Density-derived porosity at basic nodes',
        )
        _arr(
            'rho_solid_b',
            self.rho_solid_b,
            'basic',
            'kg m-3',
            'Solid density at the phase boundary at basic nodes',
        )
        _arr(
            'rho_melt_b',
            self.rho_melt_b,
            'basic',
            'kg m-3',
            'Melt density at the phase boundary at basic nodes',
        )
        _arr('g_b', self.g_b, 'basic', 'm s-2', 'Gravitational acceleration at basic nodes')