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.

The solver checks the CMB closure of each energy_balance, gradient and core_module call (ledger check of the CMB closure):

  • aragog.solver.entropy_solver.CMBClosureError, a RuntimeError, is raised when the node slope \((\partial T/\partial S)_P\) is not finite and positive.
  • Its subclass CMBLedgerMissError is raised for a ledger miss above 10 times its bound in 2 cases: solver.rtol is below \(10^{-8}\) (no repeat), or the one repeat of the call from its start at rtol = 1e-10 is not kept.
    • The run keeps the repeat only when its check ran and did not skip the call, and its miss is at most 10 times the bounds of both attempts (what happens after a miss).
    • A repeat that stops early, or raises CMBClosureError, CMBEddyFluxError or AcceptedStateRangeError, is not kept; any other error of the repeat propagates as it is.
    • Each repeat that ends logs one warning line with the refused miss and its outcome. An interrupt (KeyboardInterrupt) in the repeat logs no line and is not counted as a failed repeat.
  • After either error, and after any other error of the repeat, the solver puts back the solution it held at the start of the call. After a repeat that is not kept it also puts back the rtol, the tolerances, stop_early, the ledger counts and the lid state of the refused attempt.
  • A RuntimeError is raised in place of the repeat when the refused attempt changed the start state.
  • EntropySolver.cmb_ledger is a dict with the terms of the last checked call: r and bound (J in energy_balance and gradient, K in core_module), rel (dimensionless: the term \(\epsilon_\text{tab}\) of the bound) and excluded (true when the check was skipped). After a kept repeat it also holds repeat_of, the terms and the rtol of the refused solve, and the solution has cmb_ledger_repeat set to True. After a repeat that is not kept it holds the refused terms with their rtol, and the terms of the repeat under repeat (None when its check did not run). It is None after a call that the check does not cover.

aragog.solver.energy_stream evaluates the per-call energy integrals and the node checks over every accepted CVODE step in chunks of 2048 nodes while the solve runs. A node is passed on once CVODE has returned the output time after it, so the memory of a call grows with the steps of one output interval (at most max_steps), not with its step count.

The solver also checks the eddy diffusivity rule of the CMB basic node (Eddy diffusivity at the CMB node) in every NumPy EntropyState.update with convection on:

  • aragog.solver.entropy_state.check_cmb_convective_flux compares the convective flux of the CMB node with the 2 inputs of the rule. It requires the flux to equal the rule within \(10^{-12}\) relative, and it does not check a state with an input that is not finite.
  • The check takes the 2 inputs from the same mixing-length call that sets the eddy diffusivity of the CMB node, so it checks the value that this call gives the CMB node, not how the call computes the inputs. The test tests/test_cmb_eddy_diffusivity.py::test_cmb_rule_holds_on_random_states checks the rule itself: it computes the floor of node 0 from the melt fraction of node 0 and compares the NumPy update and the JAX function compute_mlt with the rule.
  • The check runs on the NumPy path: in the energy replay, in the NumPy right-hand side and in the update of the end state of each call. It does not run inside the JAX right-hand side.
  • On a failure it raises aragog.solver.entropy_state.CMBEddyFluxError, a RuntimeError, which names the part that fails, (i) to (iv).
  • EntropyState.cmb_eddy_diffusivity_inputs holds the 2 inputs of the last update: the mixing-length eddy diffusivity of node 1 before the floor and the floor of node 0, both in m\(^2\) s\(^{-1}\).

The mixing flux of EntropyState and of the JAX right-hand side takes the melt fraction of each cell from aragog.utilities.mixing_melt_fraction (Chemical mixing of melt fraction). Three constants of aragog.utilities set its form, in the lever-rule coordinate \(g = (S - S_\mathrm{sol})/(S_\mathrm{liq} - S_\mathrm{sol})\):

  • MIX_CLIP_EPS = \(10^{-3}\): the width of the smooth clip of \(g\) to \([0, 1]\).
  • MIX_TAIL_START = 0.01 and MIX_TAIL_END = 0.02: the cubic join to exactly 1 runs from \(g = 1.01\) to \(g = 1.02\), and the cubic join to exactly 0 from \(g = -0.01\) to \(g = -0.02\); the value and the slope are continuous at the ends of each join, the second derivative is not.

The result:

  • lies in \([0, 1]\) and never falls when \(g\) grows;
  • is exactly 0 for \(g \le -0.02\) and exactly 1 for \(g \ge 1.02\);
  • is NaN for a NaN or infinite \(g\), and for \(|g|\) above about \(10^{154}\), where \(g^2\) overflows.

phase_smoothing does not act on the mixing flux.

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
 95
 96
 97
 98
 99
100
101
102
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)

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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
38
39
40
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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
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
    self._cmb_node_phase = None
    self._cmb_ledger_counts = {'missed': 0, 'excluded': 0}
    self._cmb_ledger_repeats = {'repeated': 0, 'failed': 0}
    self.cmb_ledger = 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.

surface_temperature_bc property

Surface entropy [J/kg/K], surface temperature [K] and face half cell [m] of BC 5, the S_surf, outer_bc_value and surf_dr_half of a JAX BoundaryParams; None for the other outer modes. A changed outer_boundary_value is inverted first, and an invalid one raises ValueError.

temperature_staggered property

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

cmb_shell_surface_temperature()

Surface temperature [K] of the shell contrast of the core_module CMB law: the BC 5 surface temperature, else the surface_temperature setting, else NaN (the top cell stands in). A setting changed between calls is checked here.

Source code in src/aragog/solver/entropy_solver.py
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
def cmb_shell_surface_temperature(self) -> float:
    """Surface temperature [K] of the shell contrast of the core_module CMB law: the BC 5
    surface temperature, else the ``surface_temperature`` setting, else NaN (the top cell
    stands in). A setting changed between calls is checked here."""
    if self._outer_bc_kind == 5:
        self._refresh_surface_temperature()
        return float(self.state._surface_temperature_bc[1])
    value = self.evaluator.boundary_conditions._settings.surface_temperature
    check_surface_temperature(value)
    return math.nan if value is None else float(value)

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
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
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
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
@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
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
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
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
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
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
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 or self._n_lid:
        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=0 when rheology.enabled else 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.zeros_like(S_final) if self._rheology_enabled else 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)
    lid_out = {}
    if self._n_lid:
        lid_out['lid_handover_time'] = getattr(self, '_lid_handover_time', float('nan'))
        lid_out['lid_weight_max'] = float(getattr(sol, 'lid_weight_max', float('nan')))
    if self._n_lid and not self._lid_active:
        lid_out['lid_delta'] = lid_out['lid_E'] = 0.0
    elif self._n_lid:
        ev = self._lid_last
        lid_out = dict(
            lid_delta=ev.delta,
            lid_E=ev.E,
            lid_T_mean=ev.surf.T_m,
            lid_T_surface=ev.surf.T_s,
            lid_T_base=ev.T_b,
            lid_weight=ev.rates.w,
            lid_delta_eff=_lid.effective_thickness(ev.delta, ev.surf.s),
            lid_conductance=self._lid_k
            * max(_lid.shape(ev.surf.s)[0], _lid.LID_SLOPE_MIN)
            / ev.delta,
            lid_F_base=ev.F_b,
            lid_handover_time=lid_out['lid_handover_time'],
            lid_weight_max=lid_out['lid_weight_max'],
        )
    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(),
        )
    )
    _check_separation_sign(
        jgrav_b, rho_solid_b - rho_melt_b, ph._separation_viscosity, ph._separation_buoyancy
    )
    self._check_rheology_invariants()

    # 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 at the outer boundary (SPIDER's
    # atmosphere/temperature_surface); with the mush base and a live lid, the blend
    # w T_b + (1 - w) max(T_node, T_b), the melt side of the crust that outgassing reads.
    T_basic_final = np.asarray(self.state.phase_basic.temperature()).ravel()
    T_magma = float(T_basic_final[-1])
    if self._n_lid and self._lid_active and self._lid_mush:
        # melt side of the crust for outgassing; lid_T_surface reports the crust surface
        T_melt = self._lid_last.T_b
        w_lid = self._lid_last.rates.w
        T_magma = w_lid * T_melt + (1.0 - w_lid) * max(T_magma, T_melt)
    # 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.
    mass_heated = self._heated_mass(mass_stag)
    Q_radio_total = float(np.dot(np.asarray(self.state.heating_radio).ravel(), mass_heated))
    Q_tidal_total = float(np.dot(np.asarray(self.state.heating_tidal).ravel(), mass_heated))

    # 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 = 0.0 if self._rheology_enabled else 1.0

    # Heating flux
    area_surf = 4 * np.pi * float(r_basic[-1]) ** 2
    F_heat_total = float(np.dot(heating, mass_heated)) / 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 : n_stag + 2 + shell.n_cells]
        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_core_tol_J=step_integrals['core_tol'],
        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]),
        time=float(sol.t[-1]),
        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,
        **lid_out,
        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
1926
1927
1928
1929
1930
1931
1932
1933
1934
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()

jax_lid_params()

The sub-grid lid data of this solver for the JAX right-hand side (:class:aragog.jax.surface_lid.LidParams), from its EOS tables and mesh.

Source code in src/aragog/solver/entropy_solver.py
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
def jax_lid_params(self):
    """The sub-grid lid data of this solver for the JAX right-hand side
    (:class:`aragog.jax.surface_lid.LidParams`), from its EOS tables and mesh."""
    from aragog.jax import surface_lid as jl

    rheo, ph = self._lid_rheo, self.state.phase_staggered
    bc_held = self._lid_held_surface()
    bc_cap = self.evaluator.boundary_conditions._settings.lid_surface_flux_cap
    bc_slope = self.evaluator.boundary_conditions._settings.lid_surface_flux_slope
    if self._lid_const:
        raise ValueError(
            'the constant-property lid runs on the NumPy right-hand side only '
            '(the JAX right-hand side has no constant-property mode)'
        )
    if self._outer_bc_kind == 5:
        raise ValueError(
            'the lid under a fixed surface temperature (outer boundary 5) runs on the NumPy '
            'right-hand side only (the JAX lid has the grey-body surface)'
        )
    S_knots = self._lid_W_of_S.x
    hs = _lid.LidEnthalpy.table(S_knots, self._lid_W_of_S(S_knots), np.zeros(S_knots.size))
    on = rheo is not None
    part = self._lid_open_part()
    open_kw = {}
    if part is not None:
        L, Fp, G, Gl = part
        open_kw = dict(open_on=1.0, open_L=L, open_Fp=Fp, open_G=G, open_Gl=Gl)
        open_kw['open_T_m0'] = self._lid_open_T_m0()
    return jl.LidParams(
        e=jl.enthalpy(self._lid_hv, size=LID_TABLE_KNOTS),
        hs=jl.enthalpy(hs),
        P=self._lid_P,
        S_sol=self._lid_S_sol,
        T_sol=self._lid_T_sol,
        k=self._lid_k,
        emissivity=self._outer_bc_emiss,
        T_eq=self._outer_bc_T_eq,
        delta_on=self._lid_delta_on,
        delta_lo=self._lid_delta_lo,
        h_top=self._lid_h_top,
        area=self._lid_area,
        area_below=float(self._area_flat[-2]),
        volume_top=float(self._volume_flat[-1]),
        ra_crit=self._lid_ra_crit,
        convection=float(self._lid_convection),
        rheo=float(on),
        closure_lid=float(self._lid_handover_armed()),
        mush=float(self._lid_mush),
        flux=float(self._outer_bc_kind == 4),
        held=float(bc_held is not None),
        T_held=float(bc_held) if bc_held is not None else 0.0,
        capped=float(bc_held is not None and bc_cap is not None),
        cap=float(bc_cap) if bc_cap is not None else 0.0,
        slope=float(bc_slope) if bc_cap is not None and bc_slope else 0.0,
        phi_k=jl.enthalpy(self._lid_Phi_table) if self._lid_mush else jl.enthalpy(hs),
        fixed=float(on and rheo.lid_base_mode == 'fixed'),
        T_fixed=float(rheo.lid_base_temperature) if on else 0.0,
        contrast=float(rheo.lid_contrast_coeff) if on else 0.0,
        H_arr=self._lid_H if self._lid_H is not None else 1.0,
        phi_rheo=float(ph._phi_rheo),
        phi_width=float(ph._phi_width),
        **open_kw,
    )

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
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
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
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
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
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
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
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
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.
    """
    if _lid_slots(self):
        self._check_carried_lid()
    # 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).
    xi_cached = getattr(self, '_xi_pre_resolve', None)
    S_arr = self._remap_entropy_to_current_mesh(S_arr)
    # the lid start can refuse the state, so it runs before the state changes, and a refusal
    # puts back the one-shot remap grid for the next start
    try:
        lid_start = self._initial_lid(float(S_arr[-1]), S_arr) if _lid_slots(self) else None
    except ValueError:
        self._xi_pre_resolve = xi_cached
        raise

    # 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':
        # State [S_0, ..., S_{N-1}, dSdr_cmb]: the CMB gradient evolves by the bc.c:76-131 closure.
        # A cold start takes the one-sided difference of the bottom cells; a hot start keeps
        # the previous solution's gradient across 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(),
        )
    if lid_start is not None:
        self._S0 = np.concatenate([self._S0, lid_start])

set_initial_lid(delta, E_lid=None, handover_time=float('nan'))

Set the initial lid thickness [m] and energy [J/m^2] (a resume).

It holds in either order with set_initial_entropy, apart from a start that refuses the lid of the previous solution, and the phantom start of a new solver, which needs the top cell the full floor gap above the solidus and outside the heat-jump band (a handed-over lid over a solid top cell, or a lid in the slack of the step check, is refused there): a resume calls it first. With lid_mush_base a live lid set after set_initial_entropy is written into that start and checked when the solve starts, against the top cell of the start: below S_sol + LID_FLOOR_SLACK, not finite or in the heat-jump band, the solve refuses it and leaves the state as it was. Every start uses it until the next solve, which consumes it. With lid_mush_base a lid at or above 0.7 of the top cell hands over at the call start, and a lid the merge cannot take (the merged top cell or top node leaves the EOS table) is refused with its size; without it a lid above the growth stop (0.8 of the top cell) is refused. None clears the stored value: a later start then takes the lid of the previous solution, or the phantom lid (lid_delta_lo, linear profile). (0, 0) is a lid handed over to the mesh, which does not grow again; handover_time [yr] is then the lid_handover_time of the output, NaN if not known. A live lid has no hand-over time and clears the stored one. A 0-d real value (a scalar read from a NetCDF file) counts as a number; a masked-out value is refused.

Raises:

Type Description
ValueError

For a time that is neither NaN nor finite and >= 0, a time with a live or cleared lid, or a lid other than (0, 0) that is not finite with delta > 0.

Source code in src/aragog/solver/entropy_solver.py
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
def set_initial_lid(
    self,
    delta: float | None,
    E_lid: float | None = None,
    handover_time: float = float('nan'),
) -> None:
    """Set the initial lid thickness [m] and energy [J/m^2] (a resume).

    It holds in either order with ``set_initial_entropy``, apart from a start that refuses
    the lid of the previous solution, and the phantom start of a new solver, which needs the
    top cell the full floor gap above the solidus and outside the heat-jump band (a
    handed-over lid over a solid top cell, or a lid in the slack of the step check, is
    refused there): a resume calls it first. With ``lid_mush_base`` a live lid set after
    ``set_initial_entropy`` is written into that start and checked when the solve starts,
    against the top cell of the start: below ``S_sol + LID_FLOOR_SLACK``, not finite or in
    the heat-jump band, the solve refuses it and leaves the state as it was. Every start
    uses it until the next ``solve``, which consumes it.
    With ``lid_mush_base`` a lid at or above 0.7 of the top cell hands over at the call
    start, and a lid the merge cannot take (the merged top cell or top node leaves the EOS
    table) is refused with its size; without it a lid above the growth stop (0.8 of the top cell) is
    refused. ``None`` clears
    the stored value: a later start then takes the lid of the previous solution, or the
    phantom lid (``lid_delta_lo``, linear profile). ``(0, 0)`` is a lid handed over to the
    mesh, which does not grow again; ``handover_time`` [yr] is then the
    ``lid_handover_time`` of the output, NaN if not known. A live lid has no hand-over time
    and clears the stored one. A 0-d real value (a scalar read from a NetCDF file) counts as
    a number; a masked-out value is refused.

    Raises
    ------
    ValueError
        For a time that is neither NaN nor finite and >= 0, a time with a live or cleared
        lid, or a lid other than ``(0, 0)`` that is not finite with ``delta > 0``.
    """
    time_yr, delta_m, E = (_real_or_none(v) for v in (handover_time, delta, E_lid))
    known = time_yr is not None and not math.isnan(time_yr)
    if time_yr is None or (known and not 0.0 <= time_yr < math.inf):
        raise ValueError(
            f'set_initial_lid needs a hand-over time that is NaN or finite and >= 0, '
            f'got {handover_time!r}'
        )
    if delta is None and not known:
        self._lid_init = None
        return
    if delta is None:
        raise ValueError(
            'set_initial_lid takes a hand-over time only for a handed-over lid'
        )
    if delta_m is None or E is None:
        raise ValueError(f'set_initial_lid needs numbers, got {delta!r}, {E_lid!r}')
    if delta_m == 0.0 and E == 0.0:  # a lid handed over to the mesh
        self._lid_init = (0.0, 0.0)
    elif not math.isfinite(delta_m) or not math.isfinite(E) or delta_m <= 0:
        raise ValueError(
            f'set_initial_lid needs a finite delta > 0 and E_lid, got {delta}, {E_lid}'
        )
    elif known:
        raise ValueError(
            'set_initial_lid takes a hand-over time only for a handed-over lid'
        )
    else:
        self._lid_init = (delta_m, E)
    self._lid_handover_time = self._lid_start_handover_time = time_yr
    s0 = getattr(self, '_S0', None)
    if self._n_lid and s0 is not None and s0.size == self._n_core_state() + 2:
        s0[-2:] = self._lid_init

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
4127
4128
4129
4130
4131
4132
4133
4134
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, *, phase_params=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:

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. A factory that raises aragog.solver.cvode_jax.UnsupportedCoreBCError (bower2018, gradient) gives the NumPy RHS after a warning; any other exception it raises propagates out of solve().

required
phase_params PhaseParams

When supplied, validates immediately that phase_params.rheology matches self.parameters.phase_solid.rheology.

None
Source code in src/aragog/solver/entropy_solver.py
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
def set_jax_cvode_factory(self, factory, *, phase_params=None) -> 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. A factory that raises
        ``aragog.solver.cvode_jax.UnsupportedCoreBCError`` (bower2018,
        gradient) gives the NumPy RHS after a warning; any other
        exception it raises propagates out of ``solve()``.
    phase_params : PhaseParams, optional
        When supplied, validates immediately that ``phase_params.rheology``
        matches ``self.parameters.phase_solid.rheology``.
    """
    self._check_jax_factory_rheology(phase_params)
    self._check_jax_factory_rheology(factory)
    self._jax_cvode_factory = factory

solve(_floor_discard=None, _start=_CALL_START)

Run the BDF time integration of one call (see _solve_call).

A call that the CMB ledger check refuses (CMBLedgerMissError) at an rtol of at least 100 times _LEDGER_REPEAT_RTOL is solved once more from its start at that rtol, and the run keeps the repeat when its check ran, did not skip the call, and _repeat_keeps passes it: cmb_ledger then holds the repeat's terms and 'repeat_of' the refused ones, and the solution has cmb_ledger_repeat True. _cmb_ledger_repeats counts the repeats started and the failed ones (an interrupt is not a failed one). A floor-discard solve inside a call never repeats. A repeat that is not kept, stops early, or raises CMBClosureError, CMBEddyFluxError or AcceptedStateRangeError raises CMBLedgerMissError; its __cause__ and __context__ are the error of the repeat, whose __context__ is the refusal. Any other error of the repeat propagates as it is. The solver is then at the call start, with the rtol, stop_early, tolerances, ledger counts and lid state of the refused attempt, and cmb_ledger holds the refused terms with the repeat's (or None) under 'repeat'.

Raises:

Type Description
CMBLedgerMissError

When the call misses the ledger at an rtol below 100 times the repeat rtol, or its repeat is not kept.

RuntimeError

When the refused attempt changed the start state, so no repeat can run.

Source code in src/aragog/solver/entropy_solver.py
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
def solve(self, _floor_discard: str | None = None, _start: object = _CALL_START) -> None:
    """Run the BDF time integration of one call (see ``_solve_call``).

    A call that the CMB ledger check refuses (``CMBLedgerMissError``) at an rtol of at
    least 100 times ``_LEDGER_REPEAT_RTOL`` is solved once more from its start at that rtol,
    and the run keeps the repeat when its check ran, did not skip the call, and
    ``_repeat_keeps`` passes it: ``cmb_ledger`` then holds the repeat's terms and
    ``'repeat_of'`` the refused ones, and the solution has ``cmb_ledger_repeat`` True.
    ``_cmb_ledger_repeats`` counts the repeats started and the failed ones (an interrupt is
    not a failed one). A floor-discard solve inside a call never repeats. A repeat that is
    not kept, stops early, or raises ``CMBClosureError``, ``CMBEddyFluxError`` or
    ``AcceptedStateRangeError`` raises ``CMBLedgerMissError``; its ``__cause__`` and
    ``__context__`` are the error of the repeat, whose ``__context__`` is the refusal. Any
    other error of the repeat propagates as it is. The solver is then at the call start,
    with the rtol, ``stop_early``, tolerances, ledger counts and lid state of the refused
    attempt, and ``cmb_ledger`` holds the refused terms with the repeat's (or None) under
    ``'repeat'``.

    Raises
    ------
    CMBLedgerMissError
        When the call misses the ledger at an rtol below 100 times the repeat rtol, or its
        repeat is not kept.
    RuntimeError
        When the refused attempt changed the start state, so no repeat can run.
    """
    start = getattr(self, '_solution', None) if _start is _CALL_START else _start
    s0 = np.copy(getattr(self, '_S0', None))
    counts = dict(self._cmb_ledger_counts)
    try:
        self._solve_call(_floor_discard, start)
    except CMBLedgerMissError as miss:
        rtol = float(self.parameters.solver.rtol)
        # no division: a zero or NaN rtol re-raises the miss
        repeat_min = _LEDGER_REPEAT_RTOL / _LEDGER_REPEAT_MAX_RHO
        if _floor_discard is not None or not rtol >= repeat_min:
            raise
        self._repeat_call(miss, rtol, start, s0, counts)
        return
    if self._solution is not None:
        self._solution.cmb_ledger_repeat = False

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.time 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
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
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.time`` 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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
    self._surface_temperature_bc: tuple[float, float, float] | None = None
    check_convective_threshold(convective_threshold)
    self._convective_threshold = float(convective_threshold)
    self._bottom_up_grav_sep = bool(bottom_up_grav_sep)
    # Jgrav smoothing (none on Jmix): 'tanh' (default) is SPIDER's get_smoothing of width
    # matprop_smooth_width; 'cubic_hermite' is 16 gphi^2 (1 - gphi)^2 (0.32 at gphi = 0.83).
    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()
    self._radii_basic = np.asarray(mesh.basic.radii).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)
    self._last_viscous_velocity = np.zeros(n_basic)
    self._last_reynolds = np.zeros(n_basic)
    self._eta_eff_basic = np.zeros(n_basic)
    self._lid_state: dict | None = None
    self._time: float = 0.0

    # 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._cmb_kh_inputs = (0.0, 0.0)
    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._phi_mix_stag: npt.NDArray = np.zeros(n_staggered)  # cell fractions of Jmix
    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

    # Mesh-fixed phase-boundary cache at basic nodes: S_sol, S_liq, dS_fus, dP/dr, T_fus.
    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._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].

cmb_eddy_diffusivity_inputs property

(kh_mlt[1], floor[0]) of the last update, the inputs of the CMB node rule.

eta_eff_basic property

Solid effective viscosity at basic nodes [Pa s].

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.

lid_state property

Stagnant-lid diagnostic state dictionary from the last update, or None.

temperature_basic property

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

top_temperature property

Temperature at the outermost basic node [K].

basic_entropy(entropy, dSdr_cmb=None, entropy_basic=None)

Entropy at the basic nodes that update gives the basic phase evaluator.

The mesh transform of the staggered entropy (or a copy of entropy_basic); with dSdr_cmb the CMB node is the bottom cell carried to the CMB by that gradient, and with a set surface temperature (BC 5) the top node holds its entropy.

Parameters:

Name Type Description Default
entropy ndarray

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

required
dSdr_cmb float

Entropy gradient at the CMB [J/kg/K/m] (energy_balance and core_module).

None
entropy_basic ndarray

Entropy at the basic nodes (gradient mode), used in place of the transform.

None

Returns:

Type Description
ndarray

Entropy at the basic nodes [J/kg/K].

Source code in src/aragog/solver/entropy_state.py
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
def basic_entropy(
    self,
    entropy: npt.NDArray,
    dSdr_cmb: float | None = None,
    entropy_basic: npt.NDArray | None = None,
) -> npt.NDArray:
    """Entropy at the basic nodes that ``update`` gives the basic phase evaluator.

    The mesh transform of the staggered ``entropy`` (or a copy of ``entropy_basic``); with
    ``dSdr_cmb`` the CMB node is the bottom cell carried to the CMB by that gradient, and
    with a set surface temperature (BC 5) the top node holds its entropy.

    Parameters
    ----------
    entropy : ndarray
        Entropy at the staggered nodes [J/kg/K].
    dSdr_cmb : float, optional
        Entropy gradient at the CMB [J/kg/K/m] (energy_balance and core_module).
    entropy_basic : ndarray, optional
        Entropy at the basic nodes (gradient mode), used in place of the transform.

    Returns
    -------
    ndarray
        Entropy at the basic nodes [J/kg/K].
    """
    mesh = self._evaluator.mesh
    S = np.asarray(entropy).ravel()
    if entropy_basic is None:
        basic = getattr(mesh, 'entropy_at_basic_nodes', mesh.quantity_at_basic_nodes)
        entropy_basic = basic(S)
    S_b = np.array(entropy_basic, dtype=float).ravel()
    if dSdr_cmb is not None:
        r_basic = np.asarray(mesh.basic.radii).ravel()
        dr_offset = r_basic[0] - 0.5 * (r_basic[0] + r_basic[1])
        S_b[0] = float(S[0]) + float(dSdr_cmb) * dr_offset
    if self._surface_temperature_bc is not None:
        S_b[-1] = self._surface_temperature_bc[0]
    return S_b

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
1156
1157
1158
1159
1160
1161
1162
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
1197
1198
1199
1200
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)

set_surface_temperature(entropy, temperature, half_cell)

Prescribe the surface temperature (outer boundary condition 5).

Each update then sets the surface basic node to entropy and its gradient so that the conductive face flux is k (T_stag[-1] - T_node) / half_cell, with T_node the temperature of the node at entropy.

Parameters:

Name Type Description Default
entropy float

Entropy where T(P_s, S) is the prescribed temperature [J/kg/K].

required
temperature float

Prescribed surface temperature [K].

required
half_cell float

Distance of the surface face from the top cell, delta_mesh[-1] / dxidr[-1] / 2 [m].

required
Source code in src/aragog/solver/entropy_state.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def set_surface_temperature(
    self, entropy: float, temperature: float, half_cell: float
) -> None:
    """Prescribe the surface temperature (outer boundary condition 5).

    Each update then sets the surface basic node to ``entropy`` and its gradient so that the
    conductive face flux is ``k (T_stag[-1] - T_node) / half_cell``, with ``T_node`` the
    temperature of the node at ``entropy``.

    Parameters
    ----------
    entropy : float
        Entropy where ``T(P_s, S)`` is the prescribed temperature [J/kg/K].
    temperature : float
        Prescribed surface temperature [K].
    half_cell : float
        Distance of the surface face from the top cell, ``delta_mesh[-1] / dxidr[-1] / 2``
        [m].
    """
    self._surface_temperature_bc = (float(entropy), float(temperature), float(half_cell))

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
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
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
    t_arr = np.asarray(time, dtype=float)
    self._time = float(t_arr.flat[0]) if t_arr.size > 0 else 0.0
    self._entropy_basic = self.basic_entropy(S, dSdr_cmb, entropy_basic)
    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: the CMB gradient is the state-vector value
    if dSdr_cmb is not None:
        self._dSdr[0] = float(dSdr_cmb)

    # 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()
    if self._surface_temperature_bc is not None:
        self._match_surface_gradient()

    self._ensure_phase_boundary_cache()

    # ── 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
    if self._surface_temperature_bc is not None:
        floor_mask[-1] = False  # no floor at a surface held at its temperature

    # 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 = np.abs(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()
    rheo = getattr(self.phase_basic, '_rheology', None)
    rheo_enabled = rheo is not None and rheo.enabled

    def q_factor(theta):
        """Viscous mixing-length factor (l_v / l)^4 [-] at the basic nodes."""
        return np.asarray(
            _viscous_mixing_length_factor_core(
                radii=self._radii_basic,
                r_in=float(self._radii_basic[0]),
                r_out=float(self._radii_basic[-1]),
                mixing_length=mixing_length,
                bottom_slope=rheo.mlt_bottom_slope,
                theta=theta,
                s_top_inf=rheo.s_top_inf,
                c_theta=rheo.c_theta,
                xp=np,
            )
        ).ravel()

    q_mlt_1 = q_factor(None) if rheo_enabled else 1.0

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

    # 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

    def mlt(nu_, q_mlt):
        """Viscous velocity, Reynolds number, and thermal and chemical eddy diffusivities."""
        q_025 = q_mlt**0.25
        u_visc = velocity_prefactor * mixing_length_cubed * q_mlt**0.75 / (18.0 * nu_)
        re = u_visc * mixing_length * q_025 / nu_
        w_inv = 0.5 * (1.0 + np.tanh((re - RE_CRIT) / max(blend_width, 1e-30)))
        kh_raw = (
            (1.0 - w_inv) * (u_visc * q_025) + w_inv * inviscid_velocity
        ) * mixing_length

        # eddy_diffusivity_thermal scaling (SPIDER convention: positive = scale
        # factor, negative = fixed constant)
        if self._eddy_diff_thermal > 0:
            eddy = self._eddy_diff_thermal * kh_raw
        else:
            eddy = 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:
            kappac = self._eddy_diff_chem * kh_raw
        else:
            kappac = np.full_like(kh_raw, -self._eddy_diff_chem)

        kh_mlt_1 = float(eddy[1]) if len(eddy) >= 2 else 0.0
        kh_floor_0 = 0.0
        # 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()
            phi_rheo = float(getattr(self.phase_basic, '_phi_rheo', 0.4))
            phi_width = float(getattr(self.phase_basic, '_phi_width', 0.15))
            if rheo_enabled:
                f_floor = zero_anchored_weight(tanh_weight, phi_basic, phi_rheo, phi_width)
            else:
                f_floor = tanh_weight(phi_basic, phi_rheo, phi_width)
            eddy = apply_kappah_floor(eddy, self._kappah_floor, f_floor, floor_mask)
            kh_floor_0 = float(self._kappah_floor * f_floor[0] * floor_mask[0])

        # CMB basic node: the mixing-length value of node 1 (SPIDER energy.c 220-223),
        # or the floor of node 0 under its own mask, whichever is larger.
        if len(eddy) >= 2:
            eddy[0] = np.maximum(kh_mlt_1, kh_floor_0)
        self._cmb_kh_inputs = (kh_mlt_1, kh_floor_0)
        return u_visc, re, eddy, kappac

    viscous_velocity, reynolds, self._eddy_diffusivity, self._kappac = mlt(nu, q_mlt_1)

    self._last_viscous_velocity = viscous_velocity
    self._last_reynolds = reynolds

    # ── 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 rheo_enabled:
        eta_diff_b = np.asarray(self.phase_basic.eta_diff()).ravel()
        phi_b_rheo = np.asarray(self.phase_basic.melt_fraction()).ravel()
        if rheo.stress_closure_mode == 'local':
            self._lid_state = None
            tau_y_b = np.asarray(self.phase_basic.tau_y()).ravel()
            eta_eff_b = _compute_effective_viscosity_core(
                eta_diff=eta_diff_b,
                stress_closure_mode='local',
                unyielded_velocity=viscous_velocity,
                mixing_length=q_mlt_1**0.25 * mixing_length,
                tau_y=tau_y_b,
                xp=np,
            )
        else:
            T_sol_b = self.phase_basic.solidus_temperature()
            T_sol_b_arr = np.asarray(T_sol_b).ravel() if T_sol_b is not None else None
            mu_mix_pass1 = np.asarray(self.phase_basic.viscosity()).ravel()
            kappa_th_b = k / (rho * np.maximum(Cp, 100.0))
            p_b_pos = np.maximum(np.asarray(self.phase_basic.pressure).ravel(), 0.0)
            lid_state = _compute_stagnant_lid_state_core(
                radii=self._radii_basic,
                temperature=T,
                pressure=p_b_pos,
                convective_flux=self._jconv,
                total_flux=self._jcond + self._jconv,
                solidus_temperature=T_sol_b_arr,
                melt_fraction=phi_b_rheo,
                params=rheo,
                viscosity_solid=self.phase_basic._visc_solid,
                phi_rheo=self.phase_basic._phi_rheo,
                phi_width=self.phase_basic._phi_width,
                unyielded_velocity=viscous_velocity,
                viscosity_mixture=mu_mix_pass1,
                density=rho,
                gravity=np.abs(g),
                thermal_expansivity=alpha,
                thermal_diffusivity=kappa_th_b,
                xp=np,
            )
            self._lid_state = lid_state
            eta_eff_b = _compute_effective_viscosity_core(
                eta_diff=eta_diff_b,
                tau_d=lid_state['tau_d_lid'],
                tau_y_lid=lid_state['tau_y_lid'],
                stress_closure_mode='lid',
                w_lid=lid_state['w_lid'],
                eta_i=lid_state['eta_i'],
                xp=np,
            )
        self._eta_eff_basic = np.asarray(eta_eff_b).ravel()
        mu_pass2 = np.asarray(
            self.phase_basic.blend_viscosity_with_solid(self._eta_eff_basic)
        ).ravel()
        self.phase_basic._viscosity_val = mu_pass2
        self.phase_basic._rheology_viscosity_dirty = False
        viscous_velocity, reynolds, self._eddy_diffusivity, self._kappac = mlt(
            mu_pass2 / rho,
            q_factor(None if rheo.stress_closure_mode == 'local' else lid_state['theta']),
        )
        self._last_viscous_velocity = viscous_velocity
        self._last_reynolds = reynolds
        if self._convection:
            self._jconv = rho * T * self._eddy_diffusivity * (-self._dSdr)
        self._heat_flux = self._jcond + self._jconv
    else:
        self._lid_state = None

    if self._convection and self._jconv.size >= 2:
        kh_mlt_1, kh_floor_0 = self._cmb_kh_inputs
        check_cmb_convective_flux(
            jconv_0=self._jconv[0],
            rho_t_0=rho[0] * T[0],
            dsdr_0=self._dSdr[0],
            kh_mlt_1=kh_mlt_1,
            kh_floor_0=kh_floor_0,
            threshold=self._convective_threshold,
        )

    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 JGRAV_BOTTOM_UP (energy.c:523-533): the weight of the unclipped gphi of the cell
        # below each face stops Jgrav where that cell is pure melt or solid (no CMB drain).
        if self._bottom_up_grav_sep:
            gphi_stag = (self._entropy_staggered - self._S_sol_stag) / self._dS_phase_stag

            if self._phase_smoothing == 'tanh':
                # Width from matprop_smooth_width of the evaluator (0.01 when 0), so one
                # setting drives both the property blend and the Jgrav 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)
                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:
        # Bower et al. (2018) Eq. 9 with T_fus: Jmix = -kappa_c rho T_fus dS_fus dphi/dr, with
        # dphi/dr from the cell fractions on the dS/dr stencil: continuous in S.
        self._ensure_basic_phase_boundary_cache()
        # Cell melt fraction from the cached phase boundaries rather than
        # phase_staggered.melt_fraction(), whose round-off noise unsettles the Jacobian.
        self._phi_mix_stag = mixing_melt_fraction(
            (self._entropy_staggered - self._S_sol_stag) / self._dS_phase_stag
        )
        xi_s = np.asarray(mesh.staggered.mass_radii).ravel()
        dphidr = np.zeros_like(self._dSdr)
        dphidr[1:-1] = np.diff(self._phi_mix_stag) / np.diff(xi_s)
        dphidr *= np.asarray(mesh.dxidr).ravel()
        jmix = -self._kappac * rho * self._T_fus_basic * self._dS_phase_basic * dphidr
        # Zero at the actual boundaries (no mass transfer across
        # CMB or surface)
        jmix[0] = 0.0
        jmix[-1] = 0.0
        self._jmix_heat = jmix
        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, time, 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'), step_core_tol_J=float('nan'), lid_delta=float('nan'), lid_E=float('nan'), lid_T_mean=float('nan'), lid_T_surface=float('nan'), lid_T_base=float('nan'), lid_weight=float('nan'), lid_delta_eff=float('nan'), lid_conductance=float('nan'), lid_F_base=float('nan'), lid_handover_time=float('nan'), lid_weight_max=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 SolverOutput.time, the time of the stored state.

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
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
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
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
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
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
        ``SolverOutput.time``, the time of the stored state.
    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: the caller's time if given, else the time of the state.
        t_value = float(time) if time is not None else float(self.time)
        _scalar('time', t_value, 'yr', 'Simulation time of snapshot')

        # ── Scalar diagnostics ──────────────────────────────────
        _scalar(
            'T_magma',
            self.T_magma,
            'K',
            'Surface (magma) temperature; with the mush base and a live lid w T_b + (1 - w) max(T_node, T_b)',
        )
        _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_core_tol_J',
            self.step_core_tol_J,
            'J',
            'Tolerance scale of the per-call core energy change',
            fill_value_nan=True,
        )
        _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,
        )
        if np.isfinite(self.lid_delta):  # 0 after the hand-over, NaN with the lid off
            for name, unit, text in _LID_OUTPUT_FIELDS:
                _scalar(name, getattr(self, name), unit, text, 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', 'phase-mixing heat 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')

mixing_melt_fraction(gphi, xp=np)

Cell melt fraction of the mixing flux.

The lever-rule coordinate is clipped to [0, 1] with the sqrt smooth clip of bandwidth MIX_CLIP_EPS, which keeps a small tail beyond each phase boundary (smooth_clip gives its size). Between the distances MIX_TAIL_START and MIX_TAIL_END beyond a boundary the cubic smoothstep blends the tail to exactly 1 above the liquidus and to exactly 0 below the solidus, with a continuous value and slope, so 2 pure-melt or 2 pure-solid cells have no mixing flux between them. Between the 2 joins the result is the smooth clip unchanged.

Parameters:

Name Type Description Default
gphi float or ndarray

Lever-rule coordinate (S - S_sol) / (S_liq - S_sol), not clipped [-].

required
xp module

Array backend (numpy or jax.numpy).

numpy

Returns:

Type Description
float or ndarray

Melt fraction in [0, 1], non-decreasing in gphi [-]. NaN for a NaN or infinite gphi, and for |gphi| above about 1e154, where gphi**2 overflows.

Source code in src/aragog/utilities.py
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
def mixing_melt_fraction(gphi: FloatOrArray, xp: Any = np) -> Any:
    """Cell melt fraction of the mixing flux.

    The lever-rule coordinate is clipped to [0, 1] with the sqrt smooth clip of bandwidth
    ``MIX_CLIP_EPS``, which keeps a small tail beyond each phase boundary (``smooth_clip``
    gives its size). Between the distances ``MIX_TAIL_START`` and ``MIX_TAIL_END`` beyond a
    boundary the cubic smoothstep blends the tail to exactly 1 above the liquidus and to exactly
    0 below the solidus, with a continuous value and slope, so 2 pure-melt or 2 pure-solid cells
    have no mixing flux between them. Between the 2 joins the result is the smooth clip unchanged.

    Parameters
    ----------
    gphi : float or ndarray
        Lever-rule coordinate ``(S - S_sol) / (S_liq - S_sol)``, not clipped [-].
    xp : module, default numpy
        Array backend (``numpy`` or ``jax.numpy``).

    Returns
    -------
    float or ndarray
        Melt fraction in ``[0, 1]``, non-decreasing in ``gphi`` [-]. NaN for a NaN or infinite
        ``gphi``, and for ``|gphi|`` above about 1e154, where ``gphi**2`` overflows.
    """
    phi = smooth_clip(gphi, xp=xp)
    width = MIX_TAIL_END - MIX_TAIL_START
    x = xp.clip((gphi - 1.0 - MIX_TAIL_START) / width, 0.0, 1.0)
    y = xp.clip((-gphi - MIX_TAIL_START) / width, 0.0, 1.0)
    melt = 1.0 - (1.0 - x * x * (3.0 - 2.0 * x)) * (1.0 - phi)
    return xp.where(x > 0.0, melt, (1.0 - y * y * (3.0 - 2.0 * y)) * phi)

check_cmb_convective_flux(*, jconv_0, rho_t_0, dsdr_0, kh_mlt_1, kh_floor_0, threshold, rtol=1e-12)

Check the convective flux at the CMB basic node against the inputs of its rule.

The CMB node takes kh[0] = max(kh_mlt_1, kh_floor_0), so its convective flux J = -rho T kh[0] dS/dr[0] must satisfy, with g = dS/dr[0] and D the convective threshold:

(i) for g >= D: |J| <= rho T kh_mlt_1 |g| (no floor of node 1 crosses a stable CMB); (ii) for g < D: |J| >= rho T kh_floor_0 |g| (node 0 keeps its own floor); (iii) J g <= 0 (no flux against its own gradient); (iv) J = -rho T max(kh_mlt_1, kh_floor_0) g (the rule itself).

kh_floor_0 is already 0 where g >= D. Parts (i) to (iii) name the failure; (iv) also catches a flux between the bounds of (i) and (ii).

A state with a non-finite input is not checked.

Parameters:

Name Type Description Default
jconv_0 float

Convective heat flux at the CMB node [W m^-2].

required
rho_t_0 float

Density times temperature at the CMB node [kg K m^-3].

required
dsdr_0 float

Entropy gradient at the CMB node [J kg^-1 K^-1 m^-1].

required
kh_mlt_1 float

Mixing-length eddy diffusivity of node 1 before the floor [m^2 s^-1].

required
kh_floor_0 float

Floor of node 0 under its own mask [m^2 s^-1].

required
threshold float

Convective threshold D [J kg^-1 K^-1 m^-1].

required
rtol float

Relative tolerance of parts (i), (ii) and (iv).

1e-12

Raises:

Type Description
CMBEddyFluxError

If a part of the invariant fails; the message names the part.

Source code in src/aragog/solver/entropy_state.py
120
121
122
123
124
125
126
127
128
129
130
131
132
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def check_cmb_convective_flux(
    *,
    jconv_0: float,
    rho_t_0: float,
    dsdr_0: float,
    kh_mlt_1: float,
    kh_floor_0: float,
    threshold: float,
    rtol: float = 1.0e-12,
) -> None:
    """Check the convective flux at the CMB basic node against the inputs of its rule.

    The CMB node takes ``kh[0] = max(kh_mlt_1, kh_floor_0)``, so its convective flux
    ``J = -rho T kh[0] dS/dr[0]`` must satisfy, with ``g = dS/dr[0]`` and ``D`` the
    convective threshold:

    (i) for ``g >= D``: ``|J| <= rho T kh_mlt_1 |g|`` (no floor of node 1 crosses a
        stable CMB);
    (ii) for ``g < D``: ``|J| >= rho T kh_floor_0 |g|`` (node 0 keeps its own floor);
    (iii) ``J g <= 0`` (no flux against its own gradient);
    (iv) ``J = -rho T max(kh_mlt_1, kh_floor_0) g`` (the rule itself).

    ``kh_floor_0`` is already 0 where ``g >= D``. Parts (i) to (iii) name the failure; (iv)
    also catches a flux between the bounds of (i) and (ii).

    A state with a non-finite input is not checked.

    Parameters
    ----------
    jconv_0 : float
        Convective heat flux at the CMB node [W m^-2].
    rho_t_0 : float
        Density times temperature at the CMB node [kg K m^-3].
    dsdr_0 : float
        Entropy gradient at the CMB node [J kg^-1 K^-1 m^-1].
    kh_mlt_1 : float
        Mixing-length eddy diffusivity of node 1 before the floor [m^2 s^-1].
    kh_floor_0 : float
        Floor of node 0 under its own mask [m^2 s^-1].
    threshold : float
        Convective threshold ``D`` [J kg^-1 K^-1 m^-1].
    rtol : float, optional
        Relative tolerance of parts (i), (ii) and (iv).

    Raises
    ------
    CMBEddyFluxError
        If a part of the invariant fails; the message names the part.
    """
    if not np.all(np.isfinite((jconv_0, rho_t_0, dsdr_0, kh_mlt_1, kh_floor_0))):
        return
    j, g = float(jconv_0), float(dsdr_0)
    if j * g > 0.0:
        part = '(iii) failed, flux against its gradient'
    elif g >= threshold and abs(j) > rho_t_0 * kh_mlt_1 * abs(g) * (1.0 + rtol):
        part = '(i) failed, flux above kh_mlt[1]'
    elif g < threshold and abs(j) < rho_t_0 * kh_floor_0 * abs(g) * (1.0 - rtol):
        part = '(ii) failed, flux below floor[0]'
    elif abs(j + rho_t_0 * max(kh_mlt_1, kh_floor_0) * g) > rtol * abs(j):
        part = '(iv) failed, flux differs from the rule'
    else:
        return
    raise CMBEddyFluxError(
        f'CMB invariant {part}: J={j:.6e} W/m2, dS/dr[0]={g:.6e}, '
        f'kh_mlt[1]={kh_mlt_1:.6e}, floor[0]={kh_floor_0:.6e}'
    )

CMBEddyFluxError

Bases: RuntimeError

The convective flux at the CMB basic node breaks the rule of its eddy diffusivity.

energy_stream

Per-call energy integrals and node checks, evaluated in bounded chunks while CVODE steps.

The quadrature nodes of a call are every accepted CVODE step, every output point and, on a fired root, the root-search points below the root. They pass through three stages:

  1. CallNodes filters the nodes of one CVODE call to increasing times up to the call end and brackets them by the start and end states.
  2. SolveNodes joins the calls of one solve, keeps the last of each run of nodes that round to the same physical time, converts them to physical units and collects them in chunks of CHUNK nodes.
  3. The consumers (EnergyQuadrature, TableGuard, DomainCheck, FloorMin, RegimeCheck) take one chunk at a time and keep only running sums, extremes and the last node.

So the memory of a call is bounded by the steps of one output interval (at most max_steps, which wait in CallNodes) and one chunk, not by its step count. The nodes, their order and the arithmetic per node are those of a stored trace; only the trapezoid sums are added chunk by chunk. A consumer stores its first error and raises it after the solve, never inside a CVODE callback.

CMBLedger(solver, core=False)

Running form of the CMB closure check of EntropySolver._check_cmb_ledger.

add takes the nodes of a chunk with the CMB power p [W] (energy_balance and gradient) or the core-top change d [K] (core_module, core True) and keeps the end-point temperatures of the CMB node, the largest s w, rel and the exclusion flag, the scale and the every-other-node trapezoid; finish applies the bound. A node slope that is not finite and positive is kept in error for finish.

Source code in src/aragog/solver/energy_stream.py
350
351
352
353
354
355
356
357
358
359
360
361
def __init__(self, solver: EntropySolver, core: bool = False):
    self.s, self.core = solver, core
    self.ev = getattr(solver, '_cmb_node_phase', None)
    self.tol = getattr(solver, '_call_tol', None)  # set by solve()
    self.error: Exception | None = None
    self.n = self.n_slots = 0
    self.t0 = self.t1 = self.T0 = self.T1 = math.nan
    self.sw_max = self.rel = -math.inf
    self.excluded = False
    self.scale = self.q2 = self.d_max = 0.0
    self.d0 = self.d1 = math.nan
    self.prev = self.even = None  # (t [s], p [W]) of the last node and of the last even one

finish(q)

Check the call with its CMB heat q [J] (energy_balance and gradient).

Source code in src/aragog/solver/energy_stream.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def finish(self, q: float) -> None:
    """Check the call with its CMB heat ``q`` [J] (energy_balance and gradient)."""
    from aragog.solver.entropy_solver import CMBLedgerMissError

    s = self.s
    s.cmb_ledger = None
    if self.ev is None or self.tol is None or self.n < 2 or not self.t1 > self.t0:
        return
    if self.error is not None:
        raise self.error
    atol, rtol = self.tol
    nst = self.n - 1
    floor = np.sqrt(self.n_slots) * nst * self.sw_max
    if not self.core:
        C = float(s._core_cp * s._core_tfac * s._core_M)
        q2 = self.q2
        if nst % 2:  # the last node closes the every-other-node trapezoid
            q2 += float(
                np.trapezoid([self.even[1], self.prev[1]], [self.even[0], self.prev[0]])
            )
        r, extra = C * (self.T1 - self.T0) + q, abs(q - q2) / 3.0
        floor *= C
    else:
        r = (self.T1 - self.T0) - (self.d1 - self.d0)
        extra = np.sqrt(self.n_slots) * nst * (atol + rtol * self.d_max)
    bound = self.rel * self.scale + extra + floor
    s.cmb_ledger = {'r': r, 'bound': bound, 'rel': self.rel, 'excluded': self.excluded}
    counts = s._cmb_ledger_counts
    if self.excluded:
        counts['excluded'] += 1
        logger.warning(
            'EntropySolver: CMB closure check skipped for the call to t = %.6e yr: the node '
            'table slope is <= 1e-6 of the closure slope (padded or clamped cell); %d call(s) '
            'skipped so far',
            self.t1,
            counts['excluded'],
        )
        return
    counts['missed'] += int(abs(r) > bound)
    if abs(r) > 10.0 * bound:
        raise CMBLedgerMissError(
            f'CMB closure fault in the call to t = {self.t1:.6e} yr: ledger miss {r:.6g} '
            f'is above 10x the solver bound {bound:.6g} ({"K" if self.core else "J"})'
        )
    if abs(r) > bound:
        logger.warning(
            'EntropySolver: CMB closure ledger miss %.6g above the bound %.6g in the call '
            'to t = %.6e yr; %d call(s) missed so far',
            r,
            bound,
            self.t1,
            counts['missed'],
        )

CallNodes(sink, t0, y0, t_out, start=True)

Quadrature nodes of one CVODE call, passed to sink in increasing time.

Nodes later than the call end and nodes not later than the previous kept node are dropped; the rest are bracketed by the start state (unless start is False, when the previous call's end state is the same node) and the end state. The call end is known only when the call returns: it is the root, or an output time of t_out that CVODE reached. CVODE returns an output time once a step that passes it ends without a root, so a node at or before the last output time passed by the step before the latest one is final and is passed on; the later nodes, at most the steps of one output interval, wait for end. A node at the time of a waiting node is never kept and is dropped at once.

Source code in src/aragog/solver/energy_stream.py
75
76
77
78
79
80
81
82
83
84
85
def __init__(self, sink, t0: float, y0: npt.NDArray, t_out, start: bool = True):
    self.sink = sink
    self.last = float(t0)
    self.t_out = np.asarray(t_out, dtype=float).ravel()
    self._wait: deque[tuple[float, npt.NDArray]] = deque()
    self._t_max = self._t_before = -math.inf  # latest and previous running time maxima
    self._done = self.last  # nodes at or before this time are final
    self.count = 0  # nodes passed on
    self.recorded, self.latest = 0, None  # root-function states seen, the last of them
    if start:
        self._emit(self.last, np.array(y0, dtype=float).ravel())

end(t, y)

Close the call with its result times t and states y (n_state, n_t).

Source code in src/aragog/solver/energy_stream.py
110
111
112
113
114
115
116
117
118
def end(self, t: npt.NDArray, y: npt.NDArray) -> None:
    """Close the call with its result times ``t`` and states ``y`` (n_state, n_t)."""
    t_end = float(t[-1])
    while self._wait:
        tk, yk = self._wait.popleft()
        if self.last < tk <= t_end:
            self._emit(tk, yk)
    if self.last < t_end:
        self._emit(t_end, np.array(y[:, -1], dtype=float))

record(t, y)

Record the state the root function sees at time t.

Source code in src/aragog/solver/energy_stream.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def record(self, t: float, y: npt.ArrayLike) -> None:
    """Record the state the root function sees at time ``t``."""
    t, y = float(t), np.array(y, dtype=float)
    self.recorded += 1
    self.latest = (t, y)
    if t <= self.last or t == self._t_max:
        return
    if t > self._t_max:
        self._t_before, self._t_max = self._t_max, t
        k = int(np.searchsorted(self.t_out, self._t_before, side='right')) - 1
        if k >= 0:
            self._done = max(self._done, float(self.t_out[k]))
    self._wait.append((t, y))
    while self._wait and self._wait[0][0] <= self._done:
        tk, yk = self._wait.popleft()
        if tk > self.last:
            self._emit(tk, yk)

DomainCheck(solver, domain, tol, k_cmb)

EOS lookup points outside the valid table window (EntropySolver._eos_domain_failure).

Keeps the count of states, the count of points more than tol table S cells outside and the worst such point; k_cmb is the state row of the CMB gradient, if there is one.

Source code in src/aragog/solver/energy_stream.py
269
270
271
272
273
274
275
276
def __init__(self, solver: EntropySolver, domain, tol: float, k_cmb: int | None):
    self.s, self.domain, self.tol, self.k_cmb = solver, domain, tol, k_cmb
    self.widths = (
        float(solver.state.phase_staggered._matprop_smooth_width),
        float(solver.state.phase_basic._matprop_smooth_width),
    )
    self.n_states = self.n_out = 0
    self.worst = None

EnergyQuadrature(solver)

Per-call energy integrals [J] and the per-node invariant checks, chunk by chunk.

The running form of EntropySolver._compute_step_energy_integrals: per chunk the powers come from the JAX batch (or, without it, from _step_powers at each node), the trapezoid sums carry the last node of the previous chunk, and the core heat change, its tolerance scale, the CMB ledger (CMBLedger) and the largest lid weight are kept the same way.

Each check keeps its first failure, with the node index in the whole call, and result raises them in the order of a stored trace (_ORDER, then the CMB ledger): the batch checks of the whole call, then the per-node checks of the loop, then the core capacity. After a failure the later chunks run only the checks that come before it. When the batch fails on a chunk, that chunk and all later ones use _step_powers with its per-node checks; the earlier chunks keep their batch powers and batch checks, since their nodes are gone, and a warning names them.

Source code in src/aragog/solver/energy_stream.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def __init__(self, solver: EntropySolver):
    self.s = solver
    self.n = 0
    self.errors: dict[str, Exception] = {}
    self.batch_fn = None
    self.prev = None  # (t, powers, C_eff, d_core) of the last node
    self.sums = np.zeros(7)
    self.span_s = 0.0
    self.first = self.last = None  # (t, y, change) of the first and last node
    self.grown_max = self.w_max = -math.inf
    self.core_heat = 0.0
    self.core_tol = 0.0
    self.last_batch = self.used_batch = False
    self.skip = False
    self.ledger = None

result(sol)

The integrals of the call; raises the first failed check.

Source code in src/aragog/solver/energy_stream.py
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
def result(self, sol) -> dict[str, float | None]:
    """The integrals of the call; raises the first failed check."""
    from aragog.solver.entropy_solver import _ZERO_ENERGY_INTEGRALS

    s = self.s
    if self.first is None or self.skip:
        return dict(_ZERO_ENERGY_INTEGRALS)
    if self.used_batch:
        s._batch_powers_calls += 1
    logger.info(
        'EntropySolver: evaluated energy powers via %s (%d nodes)',
        'JAX batch path' if self.used_batch else 'numpy loop fallback',
        self.n,
    )
    if self.n_lid:  # largest delta / cap - 1 over the accepted states with a lid
        sol.lid_cap_excess = (
            self.grown_max / self.cap - 1.0 if self.grown_max > -math.inf else math.nan
        )
    t_last, y_last, _ = self.last
    counters = (s.state._pb_cache_hits, s.state._pb_cache_misses)
    try:
        self._raise('rheo_range')
        if self.last_batch:
            s._dSdt_single(t_last, y_last)
        self._raise('lid_table', 'lid_floor', 'lid_thickness', 'loop')
        if self.last_batch:
            if s._n_lid and s._lid_active:
                s._check_lid_step(self.lid_lo, self.n - 1, t_last)
            if self.check_rheo:
                s._check_rheology_step_invariants(
                    self.rheo, step_idx=self.n - 1, time_yr=t_last
                )
    finally:
        s.state._pb_cache_hits, s.state._pb_cache_misses = counters
    if self.n_lid:
        sol.lid_weight_max = self.w_max

    state_heat = s._step_heat_content(
        s._stag_entropy(sol.y[:, 0]), s._stag_entropy(sol.y[:, -1])
    )
    if s._n_lid:
        state_heat += s._lid_heat_change(sol.y[:, 0], sol.y[:, -1])
    step_dE_F_cmb = float(self.sums[1])
    if self.core_bc in ('energy_balance', 'gradient'):
        s._check_cmb_ledger(q=step_dE_F_cmb, ledger=self.ledger)
    denom = 4.0 * np.pi * float(s._r_basic_flat[0]) ** 2 * self.span_s
    f_cmb_step_avg = step_dE_F_cmb / denom if denom > 0.0 else None

    step_dE_core, step_core_tol = 0.0, float('nan')
    n_stag = getattr(s, '_n_stag', 0)
    t_first, y_first, c_first = self.first
    if self.core:
        self._raise('core')
        d_last = self.last[2] - c_first
        if self.budget.stratification:
            shell = self.budget.shell
            step_dE_core = self.core_heat + float(
                shell.heat_change(d_last[1 : 1 + shell.n_cells])
            )
        else:
            step_dE_core = self.budget.heat_change(float(y_first[n_stag + 1]), d_last[0])
        if t_last > t_first:  # a call that does not advance has no scale
            step_core_tol = self.core_tol
        s._check_cmb_ledger(q=step_dE_F_cmb, ledger=self.ledger)
    elif self.core_bc == 'bower2018':
        C_core = getattr(s, '_core_cap', None)
        if C_core is None:
            p = s.parameters
            rho_c = float(p.mesh.core_density)
            cp_c = float(p.boundary_conditions.core_heat_capacity)
            vol_c = 4.0 / 3.0 * np.pi * float(s._r_basic_flat[0]) ** 3
            C_core = vol_c * rho_c * cp_c
        step_dE_core = float(C_core * (float(y_last[n_stag]) - float(y_first[n_stag])))

    return {
        'F_int': float(self.sums[0]),
        'F_cmb': step_dE_F_cmb,
        'F_cmb_step_avg': f_cmb_step_avg,
        'Q_radio': float(self.sums[2]),
        'Q_tidal': float(self.sums[3]),
        'Q_radio_cons': float(self.sums[4]),
        'Q_tidal_cons': float(self.sums[5]),
        'solver_residual': float(self.sums[6]),
        'state_heat': state_heat,
        'core': step_dE_core,
        'core_tol': step_core_tol,
    }

FloorMin(solver, weights)

Smallest floor entropy and smallest cell entropy over the nodes (the EOS floor check).

Source code in src/aragog/solver/energy_stream.py
313
314
315
def __init__(self, solver: EntropySolver, weights: npt.NDArray):
    self.n_s, self.w = solver._n_stag, weights
    self.low = math.inf

ListSink()

Collects nondimensional nodes; the trace of a CVODE call made outside solve.

Source code in src/aragog/solver/energy_stream.py
48
49
def __init__(self):
    self.t, self.y = [], []

arrays()

Node times and states (n_state, n), or None without nodes.

Source code in src/aragog/solver/energy_stream.py
55
56
57
58
59
def arrays(self) -> tuple[npt.NDArray, npt.NDArray] | None:
    """Node times and states (n_state, n), or None without nodes."""
    if not self.t:
        return None
    return np.array(self.t), np.array(self.y).T

RegimeCheck(solver, budget)

refuse_unmodelled_regime on the T_core of every node; keeps its first error.

Source code in src/aragog/solver/energy_stream.py
326
327
328
def __init__(self, solver: EntropySolver, budget):
    self.row, self.budget = solver._n_stag + 1, budget
    self.error = None

SolveNodes(consumers, t_ref, scale, offset, change_from, lid=False, keep=False)

Joined nodes of one solve, in physical units, handed to the consumers in chunks.

Of each run of nondimensional times that round to the same year the last node is kept; nodes at an equal nondimensional time (the two states of a lid hand-over) are all kept. Each state becomes y_nd * scale + offset; the rows from change_from on are also passed as y_nd * scale, their change from the call start. With a sub-grid lid the lid energy is set to 0 where the lid thickness is 0.

Parameters:

Name Type Description Default
consumers list

Objects with add(t, y, change).

required
t_ref float

Time scale [yr].

required
scale ndarray

State scale and offset per row.

required
offset ndarray

State scale and offset per row.

required
change_from int

First row of the changes.

required
lid bool

The state ends with the lid thickness and energy.

False
keep bool

Also keep every node (for tests); see kept.

False
Source code in src/aragog/solver/energy_stream.py
146
147
148
149
150
151
152
153
154
155
156
def __init__(self, consumers, t_ref, scale, offset, change_from, lid=False, keep=False):
    self.consumers = consumers
    self.t_ref = float(t_ref)
    self.scale = np.reshape(np.asarray(scale, dtype=float), (-1, 1))
    self.offset = np.reshape(np.asarray(offset, dtype=float), (-1, 1))
    self.change_from, self.lid, self.keep = change_from, lid, keep
    self._prev = None
    self._t: list[float] = []
    self._y: list[npt.NDArray] = []
    self._kept: list[tuple] = []
    self.n = 0

close()

Pass on the last node and the partial chunk.

Source code in src/aragog/solver/energy_stream.py
190
191
192
193
194
195
def close(self) -> None:
    """Pass on the last node and the partial chunk."""
    if self._prev is not None:
        self._push(*self._prev)
        self._prev = None
    self._flush()

kept()

The kept nodes (t, y) and their states times the scale, without the offset.

Source code in src/aragog/solver/energy_stream.py
197
198
199
200
201
202
203
def kept(self) -> tuple[tuple[npt.NDArray, npt.NDArray], npt.NDArray]:
    """The kept nodes ``(t, y)`` and their states times the scale, without the offset."""
    if not self._kept:
        w = self.scale.shape[0]
        return (np.empty(0), np.empty((w, 0))), np.empty((w, 0))
    t, y, c = zip(*self._kept, strict=True)
    return (np.concatenate(t), np.concatenate(y, axis=1)), np.concatenate(c, axis=1)

TableGuard(solver)

First node with a cell entropy outside the EOS tables (EntropySolver._eos_table_failure).

bad holds its time [yr] and message; with strict_accepted_range on, error also holds the AcceptedStateRangeError the solve raises.

Source code in src/aragog/solver/energy_stream.py
230
231
232
233
234
def __init__(self, solver: EntropySolver):
    self.s = solver
    self.t0 = None
    self.bad = None
    self.error: Exception | None = None

feed(consumers, t_pts, y_pts, change=None)

Pass a stored trace (t_pts, y_pts) (physical) to consumers chunk by chunk.

Source code in src/aragog/solver/energy_stream.py
206
207
208
209
210
211
212
213
214
215
def feed(consumers, t_pts, y_pts, change=None) -> None:
    """Pass a stored trace ``(t_pts, y_pts)`` (physical) to ``consumers`` chunk by chunk."""
    t_pts = np.atleast_1d(np.asarray(t_pts, dtype=float))
    y_pts = np.asarray(y_pts, dtype=float)
    if y_pts.ndim == 1:
        y_pts = y_pts.reshape(-1, 1)
    for a in range(0, t_pts.size, CHUNK):
        c = None if change is None else change[:, a : a + CHUNK]
        for consumer in consumers:
            consumer.add(t_pts[a : a + CHUNK], y_pts[:, a : a + CHUNK], c)