Skip to content

aragog.jax

The aragog.jax package contains JAX-traceable replicas of the EOS, phase evaluator, and dSdt right-hand side. They are used to build an analytic Jacobian via jax.jacrev and feed it to SUNDIALS CVODE through the registered factory in aragog.solver.cvode_jax.

This module is loaded only when solver.use_jax_jacobian = true (the production default). The numpy path in aragog.solver.entropy_state remains the reference implementation and is exercised by the standalone tests; both must agree to numerical precision (see first-principles verification).

For when and why to opt into the JAX path, see CVODE and JAX-derived Jacobians.

Submodule Role
aragog.jax.eos EntropyEOS_JAX, the JAX-traceable P-S table loader, and PhaseState, the per-cell phase cache. Mirrors the public surface of aragog.eos.EntropyEOS.
aragog.jax.phase PhaseParams, MeshArrays, PhaseProperties, FluxOutput, compute_fluxes, compute_mlt, evaluate_phase. SPIDER-parity two-stage blend, mixing-length convection, and pure-functional flux assembly.
aragog.jax.solver BoundaryParams, SolveResult. The standalone JAX solve path used by the verification suite; in production the JAX path supplies only the Jacobian and CVODE drives the integration.
aragog.jax.nondim NonDimScales. Reference scales used to non-dimensionalise state and time before passing them to the integrator.

aragog.jax.eos

JAX-traceable P-S equation of state. Loads SPIDER-format two-phase tables and provides temperature, density, melt_fraction, and the latent-heat / phase-boundary derivatives via jax.jit-compatible bilinear interpolation.

eos

JAX-based entropy EOS layer for PALEOS P-S tables.

Drop-in replacement for aragog.eos.entropy.EntropyEOS using JAX arrays and jax.scipy.interpolate.RegularGridInterpolator. All methods are JIT-compilable and differentiable via jax.grad.

Table loading uses the existing numpy loader (disk I/O is not JIT-compiled). The loaded grids are converted to JAX arrays and stored as equinox Module fields so the entire EOS object is a valid JAX pytree.

Dependencies: jax, equinox (both already in PROTEUS ecosystem via atmodeller).

EntropyEOS_JAX(eos_dir)

Bases: Module

JAX-based entropy EOS from PALEOS P-S tables.

Drop-in replacement for aragog.eos.entropy.EntropyEOS with all lookups JIT-compilable and differentiable. Constructed from the same SPIDER-format table files.

Parameters:

Name Type Description Default
eos_dir Path or str

Directory containing the SPIDER-format P-S table files.

required
Notes

A non-finite input entropy (NaN, +inf or -inf) propagates as NaN through every entropy-derived output of compute_phase_state and the property methods below, keyed on the input entropy via jnp.isfinite(S), instead of raising or clamping to a finite value. latent_heat takes only pressure and stays finite. This keeps the lookups pure and safe under jax.jit and jax.vmap, where a Python raise is not possible. A finite entropy outside the table domain still clamps to the table edge; only non-finite entropy becomes NaN.

The numpy reference EOS handles non-finite entropy at two different entry points. The direct property lookups in aragog.eos.entropy (EntropyEOS.temperature and the others) never raise: a NaN entropy returns NaN and +-inf or a finite out-of-domain entropy clamps to the table edge, each with a log warning (strict_range defaults to False). The phase evaluator EntropyPhaseEvaluator._update_eos in aragog.eos.entropy_phase has an eager NaN backstop that raises RuntimeError when a lookup yields NaN, so a NaN entropy raises there while +-inf and finite out-of-domain entropy clamp to the edge. The JAX path uses NaN as the single sentinel across both, because it cannot raise under a transform.

Source code in src/aragog/jax/eos.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def __init__(self, eos_dir: Path | str):
    eos_dir = Path(eos_dir)
    if not eos_dir.is_dir():
        raise FileNotFoundError(f'EOS directory not found: {eos_dir}')

    logger.info('Loading JAX entropy EOS from %s', eos_dir)

    # Load tables from disk (numpy) and convert to JAX interpolators
    def _make_table(name: str, phase: str) -> _Table2D:
        if name == 'dTdPs':
            fname = f'adiabat_temp_grad_{phase}.dat'
        else:
            fname = f'{name}_{phase}.dat'
        t = _load_spider_ps_table(eos_dir / fname)
        return _Table2D(t['P'], t['S'], t['values'])

    self._temperature_solid = _make_table('temperature', 'solid')
    self._temperature_melt = _make_table('temperature', 'melt')
    self._density_solid = _make_table('density', 'solid')
    self._density_melt = _make_table('density', 'melt')
    self._heat_capacity_solid = _make_table('heat_capacity', 'solid')
    self._heat_capacity_melt = _make_table('heat_capacity', 'melt')
    self._dTdPs_solid = _make_table('dTdPs', 'solid')
    self._dTdPs_melt = _make_table('dTdPs', 'melt')

    # Phase boundaries
    sol = _load_spider_phase_boundary(eos_dir / 'solidus_P-S.dat')
    liq = _load_spider_phase_boundary(eos_dir / 'liquidus_P-S.dat')
    self._solidus = _PhaseBoundary1D(sol['P'], sol['S'])
    self._liquidus = _PhaseBoundary1D(liq['P'], liq['S'])

    # Domain bounds. P uses the temperature tables only (grid shape
    # reference for callers). S is the union across every loaded
    # table, so a value outside [S_min, S_max] is guaranteed to be
    # clamped by at least one table lookup below.
    self.P_min = min(self._temperature_solid.P_min, self._temperature_melt.P_min)
    self.P_max = max(self._temperature_solid.P_max, self._temperature_melt.P_max)
    self.S_min = min(
        self._temperature_solid.S_min,
        self._temperature_melt.S_min,
        self._density_solid.S_min,
        self._density_melt.S_min,
        self._heat_capacity_solid.S_min,
        self._heat_capacity_melt.S_min,
        self._dTdPs_solid.S_min,
        self._dTdPs_melt.S_min,
    )
    self.S_max = max(
        self._temperature_solid.S_max,
        self._temperature_melt.S_max,
        self._density_solid.S_max,
        self._density_melt.S_max,
        self._heat_capacity_solid.S_max,
        self._heat_capacity_melt.S_max,
        self._dTdPs_solid.S_max,
        self._dTdPs_melt.S_max,
    )

    logger.info(
        'JAX EOS loaded: P=[%.2e, %.2e] Pa, S=[%.0f, %.0f] J/kg/K',
        self.P_min,
        self.P_max,
        self.S_min,
        self.S_max,
    )

compute_phase_state(P, S, k_solid, k_liquid, matprop_smooth_width=0.0)

Single-pass SPIDER-parity phase evaluation (cp_blend='latent').

Bit-for-bit mirror of numpy EntropyPhaseEvaluator._update_eos with cp_blend='latent'. All properties share the same intermediates, and each is the smth-blend smth * mixed + (1 - smth) * single matching SPIDER combine_matprop (eos_composite.c:278-285).

Parameters:

Name Type Description Default
P Array

Pressure [Pa] and entropy [J/kg/K], same shape.

required
S Array

Pressure [Pa] and entropy [J/kg/K], same shape.

required
k_solid float

Single-phase thermal conductivities [W/m/K].

required
k_liquid float

Single-phase thermal conductivities [W/m/K].

required
matprop_smooth_width float

SPIDER's -matprop_smooth_width. 0.0 reproduces the sharp smth=1 inside [0,1] convention; 0.01 is the production setting.

0.0

Returns:

Type Description
PhaseState

All blended properties and shared intermediates.

Source code in src/aragog/jax/eos.py
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
def compute_phase_state(
    self,
    P: jax.Array,
    S: jax.Array,
    k_solid: float,
    k_liquid: float,
    matprop_smooth_width: float = 0.0,
) -> PhaseState:
    """Single-pass SPIDER-parity phase evaluation (cp_blend='latent').

    Bit-for-bit mirror of numpy ``EntropyPhaseEvaluator._update_eos``
    with ``cp_blend='latent'``. All properties share the same
    intermediates, and each is the smth-blend
    ``smth * mixed + (1 - smth) * single`` matching SPIDER
    ``combine_matprop`` (eos_composite.c:278-285).

    Parameters
    ----------
    P, S : jax.Array
        Pressure [Pa] and entropy [J/kg/K], same shape.
    k_solid, k_liquid : float
        Single-phase thermal conductivities [W/m/K].
    matprop_smooth_width : float, default 0.0
        SPIDER's ``-matprop_smooth_width``. ``0.0`` reproduces the
        sharp ``smth=1`` inside [0,1] convention; ``0.01`` is the
        production setting.

    Returns
    -------
    PhaseState
        All blended properties and shared intermediates.
    """
    # ── Step 1: phase boundaries (computed ONCE) ────────────────
    S_sol = self.solidus_entropy(P)
    S_liq = self.liquidus_entropy(P)
    dS_phase = jnp.maximum(S_liq - S_sol, 1e-10)
    gphi = (S - S_sol) / dS_phase
    phi_arr = jnp.clip(gphi, 0.0, 1.0)

    # smth: matprop_smooth_width blend factor
    # (SPIDER util.c:get_smoothing). matprop_smooth_width is a static
    # Python float here, so the if-branch is resolved at trace time.
    if matprop_smooth_width > 0:
        smth = jnp.where(
            gphi > 0.5,
            1.0 - _tanh_weight_jax(gphi, 1.0, matprop_smooth_width),
            _tanh_weight_jax(gphi, 0.0, matprop_smooth_width),
        )
        sech2 = (
            1.0
            - jnp.tanh(jnp.where(gphi > 0.5, gphi - 1.0, gphi) / matprop_smooth_width) ** 2
        )
        dsmth_dg = jnp.where(gphi > 0.5, -0.5, 0.5) * sech2 / matprop_smooth_width
    else:
        smth = jnp.where((gphi >= 0.0) & (gphi <= 1.0), 1.0, 0.0)
        dsmth_dg = jnp.zeros_like(gphi)

    # ── Step 2: phase-boundary table evaluations (ONCE each) ────
    T_sol = self._lookup_at_phase_boundary('temperature', P, 'solid')
    T_liq = self._lookup_at_phase_boundary('temperature', P, 'melt')
    rho_sol = self._lookup_at_phase_boundary('density', P, 'solid')
    rho_liq = self._lookup_at_phase_boundary('density', P, 'melt')

    # ── Step 3: intermediate two-phase ('mixed') properties ─────
    dT_phase = jnp.maximum(T_liq - T_sol, 1e-10)
    T_avg = T_sol + 0.5 * dT_phase

    # T: linear blend
    T_mixed = phi_arr * T_liq + (1.0 - phi_arr) * T_sol

    # rho: harmonic mean
    inv_rho_mixed = phi_arr / jnp.maximum(rho_liq, 1.0) + (1.0 - phi_arr) / jnp.maximum(
        rho_sol, 1.0
    )
    rho_mixed = 1.0 / jnp.maximum(inv_rho_mixed, 1e-30)

    # alpha and Cp: latent-heat-augmented (SPIDER eos_composite.c:227-246).
    # The 100 J/kg/K floor on Cp_mixed is a defensive guard against
    # division-by-near-zero when the latent budget collapses
    # (dT_phase very large, or S_liq -> S_sol, or T_avg small near
    # the eutectic). MgSiO3 production runs are always well above
    # this floor; a triggering EOS is the signal that the upstream
    # property tables need clipping, not Aragog's runtime.
    alpha_mixed = (rho_sol - rho_liq) / dT_phase / jnp.maximum(rho_mixed, 1.0)
    Cp_mixed = jnp.maximum((S_liq - S_sol) / dT_phase * T_avg, 100.0)

    # dTdPs: analytical from intermediates
    dTdPs_mixed = (
        alpha_mixed * T_mixed / (jnp.maximum(rho_mixed, 1.0) * jnp.maximum(Cp_mixed, 100.0))
    )

    # cond: linear blend
    cond_mixed = phi_arr * k_liquid + (1.0 - phi_arr) * k_solid

    # ── Step 4: single-phase table evaluations (SPIDER 269-276) ──
    # Evaluate at S_sol/S_liq when mushy, at actual S otherwise.
    mushy = (phi_arr > 0) & (phi_arr < 1)
    S_for_solid = jnp.where(mushy, S_sol, S)
    S_for_melt = jnp.where(mushy, S_liq, S)

    # The ``gphi > 0.5`` switches below pick which pure-phase table to
    # evaluate when the cell is *outside* the mushy mask. This 0.5 is
    # a binary discriminator (gphi outside [0,1] is by definition
    # super-liquidus or sub-solidus), not the rheological critical
    # melt fraction; see ``PhaseParams.phi_rheo`` for the RCMF.
    def _table_lookup_blend(prop_name: str) -> jax.Array:
        solid_tbl, melt_tbl = self._get_tables(prop_name)
        v_sol = solid_tbl(P, S_for_solid)
        v_mel = melt_tbl(P, S_for_melt)
        return jnp.where(gphi > 0.5, v_mel, v_sol)

    T_single = _table_lookup_blend('temperature')
    rho_single = _table_lookup_blend('density')
    Cp_single = _table_lookup_blend('heat_capacity')
    dTdPs_single = _table_lookup_blend('dTdPs')
    # alpha from the thermodynamic identity, as the NumPy evaluator; thermal_exp is not read
    alpha_single = dTdPs_single * rho_single * Cp_single / jnp.maximum(T_single, 1.0)
    cond_single = jnp.where(gphi > 0.5, k_liquid, k_solid)

    # ── Step 5: combine_matprop blend (SPIDER 278-285) ──────────
    def _blend(mixed, single):
        return smth * mixed + (1.0 - smth) * single

    temperature = _blend(T_mixed, T_single)
    # (dT/dS)_P of that blend, with the pure-phase slope T/Cp in the single-phase term
    temperature_slope = (
        smth * jnp.where((gphi >= 0.0) & (gphi <= 1.0), (T_liq - T_sol) / dS_phase, 0.0)
        + (1.0 - smth) * jnp.where(mushy, 0.0, T_single / Cp_single)
        + (T_mixed - T_single) * dsmth_dg / dS_phase
    )
    density = _blend(rho_mixed, rho_single)
    heat_capacity = _blend(Cp_mixed, Cp_single)
    alpha_raw = _blend(alpha_mixed, alpha_single)
    dTdPs_val = _blend(dTdPs_mixed, dTdPs_single)
    thermal_conductivity = _blend(cond_mixed, cond_single)

    # Guard: clamp negative alpha (matches numpy line 309)
    eps_a = 1.0e-8
    thermal_expansivity = 0.5 * (
        alpha_raw + jnp.sqrt(alpha_raw * alpha_raw + eps_a * eps_a)
    )

    latent_heat = self.latent_heat(P)

    # A non-finite input entropy is otherwise masked to a finite value
    # by phi's clip and the tables' own edge-clamping. Propagate it as
    # NaN on every S-derived output instead. latent_heat takes only P,
    # so it stays finite.
    finite_S = jnp.isfinite(S)
    return PhaseState(
        temperature=jnp.where(finite_S, temperature, jnp.nan),
        density=jnp.where(finite_S, density, jnp.nan),
        heat_capacity=jnp.where(finite_S, heat_capacity, jnp.nan),
        thermal_expansivity=jnp.where(finite_S, thermal_expansivity, jnp.nan),
        dTdPs=jnp.where(finite_S, dTdPs_val, jnp.nan),
        thermal_conductivity=jnp.where(finite_S, thermal_conductivity, jnp.nan),
        melt_fraction=jnp.where(finite_S, phi_arr, jnp.nan),
        gphi=jnp.where(finite_S, gphi, jnp.nan),
        smth=jnp.where(finite_S, smth, jnp.nan),
        latent_heat=latent_heat,
        solidus_temperature=T_sol,
        temperature_slope=jnp.where(finite_S, temperature_slope, jnp.nan),
    )

dTdPs(P, S)

Adiabatic temperature gradient dT/dP|_S (P, S) [K/Pa].

Source code in src/aragog/jax/eos.py
650
651
652
def dTdPs(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Adiabatic temperature gradient dT/dP|_S (P, S) [K/Pa]."""
    return self._lookup_phase_weighted('dTdPs', P, S)

density(P, S)

Density rho(P, S) [kg/m^3], matching numpy EntropyEOS.density.

  • Mushy zone (0 < phi < 1): harmonic mean of end-member densities evaluated at phase-boundary entropies (Lever Rule, SPIDER eos_composite.c:236-237).
  • Pure phase (phi = 0 or phi = 1): evaluate the active single- phase table at the actual S (clamped by the table itself). SPIDER combine_matprop(smth=0, mixed, single) selects the single-phase branch in this regime. Using the harmonic-mean form unconditionally biases the fully-molten density relative to the numpy EntropyEOS.
Source code in src/aragog/jax/eos.py
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
def density(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Density rho(P, S) [kg/m^3], matching numpy EntropyEOS.density.

    - Mushy zone (0 < phi < 1): harmonic mean of end-member
      densities evaluated at phase-boundary entropies (Lever Rule,
      SPIDER ``eos_composite.c:236-237``).
    - Pure phase (phi = 0 or phi = 1): evaluate the active single-
      phase table at the actual S (clamped by the table itself).
      SPIDER ``combine_matprop(smth=0, mixed, single)`` selects the
      single-phase branch in this regime. Using the harmonic-mean
      form unconditionally biases the fully-molten density
      relative to the numpy EntropyEOS.
    """
    phi = self.melt_fraction(P, S)
    mushy = (phi > 0) & (phi < 1)

    solid_table, melt_table = self._get_tables('density')

    # Mushy zone: harmonic mean at phase boundaries
    rho_sol_boundary = self._lookup_at_phase_boundary('density', P, 'solid')
    rho_liq_boundary = self._lookup_at_phase_boundary('density', P, 'melt')
    inv_rho_mushy = phi / jnp.maximum(rho_liq_boundary, 1.0) + (1.0 - phi) / jnp.maximum(
        rho_sol_boundary, 1.0
    )
    rho_mushy = 1.0 / jnp.maximum(inv_rho_mushy, 1e-30)

    # Single-phase: evaluate at actual S (clamped by the table). Pick
    # the melt table for phi >= 0.5, solid otherwise (matches numpy).
    # NOTE: this 0.5 is a binary table-selector for the non-mushy
    # fallback only — outside the mushy band phi is essentially 0 or
    # 1 by construction. It is NOT the rheological critical melt
    # fraction (RCMF). The RCMF lives in
    # ``EntropyPhaseEvaluator._phi_rheo`` / ``PhaseParams.phi_rheo``
    # and drives the viscosity tanh blend separately.
    rho_solid_single = solid_table(P, S)
    rho_melt_single = melt_table(P, S)
    rho_single = jnp.where(phi >= 0.5, rho_melt_single, rho_solid_single)

    # A non-finite S is otherwise masked to a finite value by the
    # table's edge-clamping; propagate it as NaN instead.
    return jnp.where(jnp.isfinite(S), jnp.where(mushy, rho_mushy, rho_single), jnp.nan)

entropy_at_temperature(P, T)

Entropy [J/kg/K] at scalar pressure P where temperature(P, S) = T.

A fixed 60-step bisection over the tables' entropy range (its edge where T lies beyond the range), plus a term that is zero in value and carries the implicit derivatives dS/dT = 1 / (dT/dS) and dS/dP = -(dT/dP) / (dT/dS), which are zero where dT/dS is below 1e-12 |T|; NaN for a NaN P or T.

Source code in src/aragog/jax/eos.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def entropy_at_temperature(self, P: jax.Array, T: jax.Array) -> jax.Array:
    """Entropy [J/kg/K] at scalar pressure ``P`` where ``temperature(P, S) = T``.

    A fixed 60-step bisection over the tables' entropy range (its edge where ``T`` lies
    beyond the range), plus a term that is zero in value and carries the implicit
    derivatives ``dS/dT = 1 / (dT/dS)`` and ``dS/dP = -(dT/dP) / (dT/dS)``, which are zero
    where ``dT/dS`` is below ``1e-12 |T|``; NaN for a NaN ``P`` or ``T``.
    """
    solid, melt = self._get_tables('temperature')
    span = (jnp.minimum(solid.S_min, melt.S_min), jnp.maximum(solid.S_max, melt.S_max))
    t_fixed = jax.lax.stop_gradient(T)
    p_fixed = jax.lax.stop_gradient(P)

    def body(_, bracket):
        lo, hi = bracket
        mid = 0.5 * (lo + hi)
        below = self.temperature(p_fixed, mid) < t_fixed
        return jnp.where(below, mid, lo), jnp.where(below, hi, mid)

    lo, hi = jax.lax.fori_loop(0, 60, body, (jnp.asarray(span[0]), jnp.asarray(span[1])))
    s_root = jax.lax.stop_gradient(0.5 * (lo + hi))
    slope = jax.lax.stop_gradient(jax.grad(self.temperature, argnums=1)(p_fixed, s_root))
    # inside a flat band of the tables the slope is rounding, below 1e-16 |T|
    slope = jnp.where(slope > 1e-12 * jnp.abs(t_fixed), slope, jnp.inf)
    inside = (self.temperature(p_fixed, span[0]) < t_fixed) & (
        t_fixed < self.temperature(p_fixed, span[1])
    )
    zero = (T - t_fixed) - (self.temperature(P, s_root) - self.temperature(p_fixed, s_root))
    s = jnp.where(inside, s_root + zero / slope, s_root)
    return jnp.where(jnp.isnan(P + T), jnp.nan, s)

heat_capacity(P, S)

Specific heat capacity Cp(P, S) [J/kg/K].

Source code in src/aragog/jax/eos.py
646
647
648
def heat_capacity(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Specific heat capacity Cp(P, S) [J/kg/K]."""
    return self._lookup_phase_weighted('heat_capacity', P, S)

latent_heat(P)

Latent heat L(P) = T_fus x (S_liq - S_sol) [J/kg].

Source code in src/aragog/jax/eos.py
654
655
656
657
658
659
660
661
def latent_heat(self, P: jax.Array) -> jax.Array:
    """Latent heat L(P) = T_fus x (S_liq - S_sol) [J/kg]."""
    S_sol = self.solidus_entropy(P)
    S_liq = self.liquidus_entropy(P)
    T_sol = self._lookup_at_phase_boundary('temperature', P, 'solid')
    T_liq = self._lookup_at_phase_boundary('temperature', P, 'melt')
    T_fus = 0.5 * (T_sol + T_liq)
    return T_fus * jnp.maximum(S_liq - S_sol, 1.0)

liquidus_entropy(P)

Liquidus entropy S_liq(P) [J/kg/K].

Source code in src/aragog/jax/eos.py
469
470
471
def liquidus_entropy(self, P: jax.Array) -> jax.Array:
    """Liquidus entropy S_liq(P) [J/kg/K]."""
    return self._liquidus(P)

material_expansivity(P, S)

Thermal expansivity [1/K] of the phases, without the phase-change term.

The volume-weighted blend rho sum_i x_i alpha_i / rho_i of each phase's rho cp |dT/dP|_S / T at its own entropy, with x_i the Lever-rule mass fractions and rho the harmonic mixture density of density.

Source code in src/aragog/jax/eos.py
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def material_expansivity(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Thermal expansivity [1/K] of the phases, without the phase-change term.

    The volume-weighted blend ``rho sum_i x_i alpha_i / rho_i`` of each phase's
    ``rho cp |dT/dP|_S / T`` at its own entropy, with ``x_i`` the Lever-rule mass fractions
    and ``rho`` the harmonic mixture density of ``density``.
    """
    phi = self.melt_fraction(P, S)
    melt = phi / self._lookup_at_phase_boundary('density', P, 'melt')
    volume = melt / (
        melt + (1.0 - phi) / self._lookup_at_phase_boundary('density', P, 'solid')
    )
    return self._lookup_phase_weighted(
        ('density', 'heat_capacity', 'dTdPs', 'temperature'),
        P,
        S,
        per_phase=lambda rho, cp, dTdPs, T: rho * cp * jnp.abs(dTdPs) / jnp.maximum(T, 1.0),
        melt_weight=volume,
    )

melt_fraction(P, S)

Melt fraction phi from position between solidus and liquidus.

phi = 0 for S <= S_sol, phi = 1 for S >= S_liq, linear between.

Source code in src/aragog/jax/eos.py
473
474
475
476
477
478
479
480
481
482
def melt_fraction(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Melt fraction phi from position between solidus and liquidus.

    phi = 0 for S <= S_sol, phi = 1 for S >= S_liq, linear between.
    """
    S_sol = self.solidus_entropy(P)
    S_liq = self.liquidus_entropy(P)
    dS = jnp.maximum(S_liq - S_sol, 1e-10)
    phi = jnp.clip((S - S_sol) / dS, 0.0, 1.0)
    return jnp.where(jnp.isfinite(S), phi, jnp.nan)

solidus_entropy(P)

Solidus entropy S_sol(P) [J/kg/K].

Source code in src/aragog/jax/eos.py
465
466
467
def solidus_entropy(self, P: jax.Array) -> jax.Array:
    """Solidus entropy S_sol(P) [J/kg/K]."""
    return self._solidus(P)

temperature(P, S)

Temperature T(P, S) [K].

Source code in src/aragog/jax/eos.py
569
570
571
def temperature(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Temperature T(P, S) [K]."""
    return self._lookup_phase_weighted('temperature', P, S)

thermal_expansivity(P, S)

Thermal expansivity alpha(P, S) [1/K].

Derived: alpha = rho * Cp * |dTdPs| / T.

Source code in src/aragog/jax/eos.py
683
684
685
686
687
688
689
690
691
692
def thermal_expansivity(self, P: jax.Array, S: jax.Array) -> jax.Array:
    """Thermal expansivity alpha(P, S) [1/K].

    Derived: alpha = rho * Cp * |dTdPs| / T.
    """
    T = self.temperature(P, S)
    rho = self.density(P, S)
    Cp = self.heat_capacity(P, S)
    dTdPs_val = self.dTdPs(P, S)
    return rho * Cp * jnp.abs(dTdPs_val) / jnp.maximum(T, 1.0)

PhaseState

Bases: NamedTuple

Material properties at (P, S) following SPIDER eos_composite.c convention.

All scalar properties (T, rho, Cp, alpha, dTdPs, k) result from a smth-blend between two-phase mixed values (analytical formulas at the phase boundaries) and single table values (looked up at the actual P and at S_sol or S_liq when mushy). This matches numpy EntropyPhaseEvaluator._update_eos step-for-step.

aragog.jax.phase

Phase-aware property evaluation and flux assembly. evaluate_phase performs the SPIDER two-stage tanh blend at one cell; compute_fluxes is the pure-functional RHS that returns heat flux at basic nodes, internal heating at staggered nodes, eddy diffusivity, and capacitance.

phase

JAX phase evaluator and flux computation for the entropy solver.

Pure-functional replacements for entropy_phase.py (phase properties) and entropy_state.py (MLT convection, heat/mass fluxes). All functions are JIT-compilable and differentiable.

The numpy versions mutate state arrays in-place. The JAX versions take arrays in and return NamedTuples out, with no side effects.

Dependencies: jax, equinox (already in PROTEUS ecosystem via atmodeller).

PhaseParams(phi_rheo=0.4, phi_width=0.15, viscosity_solid=1e+21, viscosity_liquid=0.1, grain_size=0.001, k_solid=4.0, k_liquid=2.0, matprop_smooth_width=0.0, conduction=True, convection=True, grav_sep=False, mixing=False, eddy_diff_thermal=1.0, eddy_diff_chemical=1.0, kappah_floor=0.0, bottom_up_grav_sep=True, phase_smoothing='tanh', phase_smoothing_width=0.01, separation_viscosity=SEPARATION_VISCOSITY_DEFAULT, convective_threshold=CONVECTIVE_THRESHOLD_DEFAULT, separation_buoyancy=SEPARATION_BUOYANCY_DEFAULT, rheology=None)

Bases: Module

Static parameters for phase evaluation and flux computation.

Constructed once from config, passed as args to JIT-compiled functions. All fields are scalars or 1D JAX arrays.

Source code in src/aragog/jax/phase.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def __init__(
    self,
    phi_rheo: float = 0.4,
    phi_width: float = 0.15,
    viscosity_solid: float = 1e21,
    viscosity_liquid: float = 1e-1,
    grain_size: float = 1e-3,
    k_solid: float = 4.0,
    k_liquid: float = 2.0,
    matprop_smooth_width: float = 0.0,
    conduction: bool = True,
    convection: bool = True,
    grav_sep: bool = False,
    mixing: bool = False,
    eddy_diff_thermal: float = 1.0,
    eddy_diff_chemical: float = 1.0,
    kappah_floor: float = 0.0,
    bottom_up_grav_sep: bool = True,
    phase_smoothing: str = 'tanh',
    phase_smoothing_width: float = 0.01,
    separation_viscosity: str = SEPARATION_VISCOSITY_DEFAULT,
    convective_threshold: float = CONVECTIVE_THRESHOLD_DEFAULT,
    separation_buoyancy: str = SEPARATION_BUOYANCY_DEFAULT,
    rheology: SolidRheologyParams | None = None,
):
    self.phi_rheo = phi_rheo
    self.phi_width = phi_width
    self.log10_visc_solid = jnp.log10(viscosity_solid)
    self.log10_visc_liquid = jnp.log10(viscosity_liquid)
    self.grain_size = grain_size
    self.k_solid = k_solid
    self.k_liquid = k_liquid
    self.matprop_smooth_width = matprop_smooth_width
    self.conduction = float(conduction)
    self.convection = float(convection)
    self.grav_sep = float(grav_sep)
    self.mixing = float(mixing)
    self.eddy_diff_thermal = eddy_diff_thermal
    self.eddy_diff_chemical = eddy_diff_chemical
    self.kappah_floor = kappah_floor
    check_convective_threshold(convective_threshold)
    self.convective_threshold = float(convective_threshold)
    self.bottom_up_grav_sep = float(bottom_up_grav_sep)
    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_tanh = 1.0 if phase_smoothing == 'tanh' else 0.0
    self.phase_smoothing_width = float(phase_smoothing_width)
    if separation_viscosity not in SEPARATION_VISCOSITY_MODES:
        raise ValueError(
            f'separation_viscosity must be one of {SEPARATION_VISCOSITY_MODES}, '
            f'got {separation_viscosity!r}'
        )
    # Explicit dispatch: a third mode added to SEPARATION_VISCOSITY_MODES
    # must fail here rather than silently fall back to 'melt'.
    if separation_viscosity == 'mixture':
        self.separation_viscosity_mixture = 1.0
    elif separation_viscosity == 'melt':
        self.separation_viscosity_mixture = 0.0
    else:
        raise ValueError(f'unhandled separation_viscosity {separation_viscosity!r}')
    if separation_buoyancy not in SEPARATION_BUOYANCY_MODES:
        raise ValueError(
            f'separation_buoyancy must be one of {SEPARATION_BUOYANCY_MODES}, '
            f'got {separation_buoyancy!r}'
        )
    self.separation_buoyancy_mixture = {'mixture': 1.0, 'solid': 0.0}[separation_buoyancy]
    rheo_obj = merge_rheology(rheology, {})
    rheo_obj.__post_init__()
    check_viscosity_ceiling(viscosity_solid, rheo_obj)
    if rheo_obj.enabled:
        if not np.isfinite(viscosity_solid) or viscosity_solid <= 0.0:
            raise ValueError('viscosity_solid must be finite and positive')
        if not np.isfinite(phi_rheo) or not (0.0 <= float(phi_rheo) <= 1.0):
            raise ValueError('phi_rheo must lie in [0, 1]')
        if not np.isfinite(phi_width) or float(phi_width) <= 0.0:
            raise ValueError('phi_width must be finite and positive')
    self.rheology = rheo_obj

from_parameters(parameters, **overrides) classmethod

Construct PhaseParams from a Parameters object, with optional keyword overrides.

Parameters:

Name Type Description Default
parameters Parameters

Parsed Aragog runtime parameter container holding phase_solid, phase_liquid, phase_mixed, and energy sub-containers.

required
**overrides Any

Optional keyword arguments overriding individual :class:PhaseParams constructor fields within their valid domains.

{}

Returns:

Type Description
PhaseParams

Validated static material and transport parameter bundle.

Raises:

Type Description
(TypeError, ValueError)

If any extracted or overridden parameter violates the domain or rheology ceiling checks of :class:PhaseParams.

Source code in src/aragog/jax/phase.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
@classmethod
def from_parameters(cls, parameters: Any, **overrides: Any) -> 'PhaseParams':
    """Construct ``PhaseParams`` from a ``Parameters`` object, with optional keyword overrides.

    Parameters
    ----------
    parameters : Parameters
        Parsed Aragog runtime parameter container holding ``phase_solid``,
        ``phase_liquid``, ``phase_mixed``, and ``energy`` sub-containers.
    **overrides : Any
        Optional keyword arguments overriding individual :class:`PhaseParams`
        constructor fields within their valid domains.

    Returns
    -------
    PhaseParams
        Validated static material and transport parameter bundle.

    Raises
    ------
    TypeError, ValueError
        If any extracted or overridden parameter violates the domain or
        rheology ceiling checks of :class:`PhaseParams`.
    """
    kwargs: dict[str, Any] = {
        'phi_rheo': float(parameters.phase_mixed.rheological_transition_melt_fraction),
        'phi_width': float(parameters.phase_mixed.rheological_transition_width),
        'viscosity_solid': float(parameters.phase_solid.viscosity),
        'viscosity_liquid': float(parameters.phase_liquid.viscosity),
        'grain_size': float(parameters.phase_mixed.grain_size),
        'k_solid': float(parameters.phase_solid.thermal_conductivity),
        'k_liquid': float(parameters.phase_liquid.thermal_conductivity),
        'matprop_smooth_width': float(parameters.phase_mixed.matprop_smooth_width),
        'conduction': bool(parameters.energy.conduction),
        'convection': bool(parameters.energy.convection),
        'grav_sep': bool(parameters.energy.gravitational_separation),
        'mixing': bool(parameters.energy.mixing),
        'eddy_diff_thermal': float(parameters.energy.eddy_diffusivity_thermal),
        'eddy_diff_chemical': float(parameters.energy.eddy_diffusivity_chemical),
        'kappah_floor': float(parameters.energy.kappah_floor),
        'bottom_up_grav_sep': bool(parameters.energy.bottom_up_grav_sep),
        'phase_smoothing': str(parameters.energy.phase_smoothing),
        'phase_smoothing_width': (
            float(parameters.phase_mixed.matprop_smooth_width) or 1.0e-2
        ),
        'separation_viscosity': str(parameters.phase_mixed.separation_viscosity),
        'convective_threshold': float(parameters.energy.convective_threshold),
        'separation_buoyancy': str(
            getattr(
                parameters.phase_mixed, 'separation_buoyancy', SEPARATION_BUOYANCY_DEFAULT
            )
        ),
        'rheology': getattr(parameters.phase_solid, 'rheology', None),
    }
    kwargs.update(overrides)
    return cls(**kwargs)

MeshArrays(d_dr_matrix, quantity_matrix, area, volume, radii_basic, mixing_length, mixing_length_sq, mixing_length_cu, radii_stag, P_stag, P_basic, gravity, dP_dr_basic=None, gravity_stag=None, top_limited=False, top_ratio=1.0, top_bounds=(-jnp.inf, jnp.inf), *, validate_rheology=False)

Bases: Module

Static mesh geometry arrays, converted from numpy Mesh once.

All arrays are 1D JAX arrays. The transform matrices are 2D.

from P_basic and radii_basic via numpy gradient (matches entropy_state._dP_dr_basic = np.gradient(P_basic, r_basic)).

Source code in src/aragog/jax/phase.py
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def __init__(
    self,
    d_dr_matrix,
    quantity_matrix,
    area,
    volume,
    radii_basic,
    mixing_length,
    mixing_length_sq,
    mixing_length_cu,
    radii_stag,
    P_stag,
    P_basic,
    gravity,
    dP_dr_basic=None,
    gravity_stag=None,
    top_limited=False,
    top_ratio=1.0,
    top_bounds=(-jnp.inf, jnp.inf),
    *,
    validate_rheology: bool = False,
):
    """Custom init so callers that predate the dP_dr_basic field
    keep working. When ``dP_dr_basic`` is not supplied we derive it
    from ``P_basic`` and ``radii_basic`` via numpy gradient (matches
    ``entropy_state._dP_dr_basic = np.gradient(P_basic, r_basic)``).
    """
    self.d_dr_matrix = d_dr_matrix
    self.quantity_matrix = quantity_matrix
    self.area = area
    self.volume = volume
    self.radii_basic = radii_basic
    self.mixing_length = mixing_length
    self.mixing_length_sq = mixing_length_sq
    self.mixing_length_cu = mixing_length_cu
    self.radii_stag = radii_stag
    self.P_stag = P_stag
    self.P_basic = P_basic
    self.gravity = gravity
    if dP_dr_basic is None:
        import numpy as _np

        dP_dr_basic = jnp.asarray(
            _np.gradient(_np.asarray(P_basic), _np.asarray(radii_basic))
        )
    self.dP_dr_basic = dP_dr_basic
    # Default ``gravity_stag`` to a midpoint average of ``gravity``
    # so callers that don't supply a per-staggered profile still
    # see a reasonable approximation. ``from_numpy_mesh`` overrides
    # this with the EOS-interpolated value at staggered radii
    # whenever the column is available.
    if gravity_stag is None:
        g_arr = jnp.asarray(gravity)
        gravity_stag = 0.5 * (g_arr[:-1] + g_arr[1:])
    self.gravity_stag = jnp.asarray(gravity_stag)
    self.top_limited, self.top_ratio = bool(top_limited), float(top_ratio)
    self.top_bounds = jnp.asarray(top_bounds, dtype=float)
    if validate_rheology:
        self.validate_for_rheology()

from_numpy_mesh(mesh, *, validate_rheology=False) staticmethod

Build from a numpy Aragog Mesh object.

Source code in src/aragog/jax/phase.py
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
489
490
491
492
493
494
495
496
497
498
499
@staticmethod
def from_numpy_mesh(mesh, *, validate_rheology: bool = False) -> 'MeshArrays':
    """Build from a numpy Aragog Mesh object."""
    P_basic_arr = np.asarray(mesh.basic_pressure).ravel()
    r_basic_arr = np.asarray(mesh.basic.radii).ravel()
    r_stag_arr = np.asarray(mesh.staggered.radii).ravel()
    return MeshArrays(
        d_dr_matrix=jnp.asarray(mesh._d_dr_transform),
        quantity_matrix=jnp.asarray(mesh._quantity_transform),
        area=jnp.asarray(np.asarray(mesh.basic.area).ravel()),
        volume=jnp.asarray(np.asarray(mesh.basic.volume).ravel()),
        radii_basic=jnp.asarray(r_basic_arr),
        radii_stag=jnp.asarray(r_stag_arr),
        mixing_length=jnp.asarray(np.asarray(mesh.basic.mixing_length).ravel()),
        mixing_length_sq=jnp.asarray(np.asarray(mesh.basic.mixing_length_squared).ravel()),
        mixing_length_cu=jnp.asarray(np.asarray(mesh.basic.mixing_length_cubed).ravel()),
        P_stag=jnp.asarray(np.asarray(mesh.staggered_pressure).ravel()),
        P_basic=jnp.asarray(P_basic_arr),
        # SPIDER-parity dP/dr at basic nodes via numpy gradient (matches
        # entropy_state._dP_dr_basic = np.gradient(P_basic, r_basic)).
        dP_dr_basic=jnp.asarray(np.gradient(P_basic_arr, r_basic_arr)),
        # Per-node gravity profile when the external mesh file
        # carries eos_gravity (UserDefinedEOS / Zalmoxis path),
        # else scalar broadcast. The per-node array is aligned to
        # the same basic-node grid as area / volume / mixing_length,
        # so the MLT buoyancy cascade in compute_mlt picks up the
        # radial dependence without any downstream broadcasting
        # change. Scalar fallback chain:
        # mesh.eos._gravitational_acceleration (AdamsWilliamsonEOS),
        # mesh.settings.gravitational_acceleration (external EOS
        # without the private attribute), then 9.81 m/s^2.
        gravity=_build_gravity_array(mesh, r_stag=False),
        # Same construction at the staggered radii. Mirrors numpy's
        # entropy_solver.py ``g_stag = np.interp(r_stag, eos_radius,
        # eos_gravity)`` (with scalar fallback). Aligned to the
        # staggered grid.
        gravity_stag=_build_gravity_array(mesh, r_stag=True),
        top_limited=getattr(mesh, 'top_node', 'linear') == 'limited',
        top_ratio=getattr(mesh, 'top_ratio', 1.0),
        top_bounds=getattr(mesh, 'top_bounds', (-np.inf, np.inf)),
        validate_rheology=validate_rheology,
    )

validate_for_rheology()

Validate static mesh invariants required when solid-state rheology is enabled.

Returns:

Type Description
None

Returns None when all mesh invariants hold.

Raises:

Type Description
ValueError

If eager radii_basic [m] has fewer than 3 nodes or is not finite, strictly positive, and strictly increasing; if mixing_length [m] is non-finite or negative; if P_basic or P_stag [Pa] is non-finite or below -1.0 Pa; or if gravity [m/s^2] is non-finite or non-positive.

Source code in src/aragog/jax/phase.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
def validate_for_rheology(self) -> None:
    """Validate static mesh invariants required when solid-state rheology is enabled.

    Returns
    -------
    None
        Returns ``None`` when all mesh invariants hold.

    Raises
    ------
    ValueError
        If eager ``radii_basic`` [m] has fewer than 3 nodes or is not finite,
        strictly positive, and strictly increasing; if ``mixing_length`` [m]
        is non-finite or negative; if ``P_basic`` or ``P_stag`` [Pa] is
        non-finite or below ``-1.0`` Pa; or if ``gravity`` [m/s^2] is
        non-finite or non-positive.
    """
    if not isinstance(self.radii_basic, jax.core.Tracer):
        r_b = np.asarray(self.radii_basic, dtype=float).ravel()
        if (
            r_b.size < 3
            or not np.all(np.isfinite(r_b))
            or r_b[0] <= 0.0
            or not np.all(np.diff(r_b) > 0.0)
        ):
            raise ValueError(
                'basic-node radii must be finite, positive, and strictly increasing with >= 3 nodes'
            )
    if not isinstance(self.mixing_length, jax.core.Tracer):
        ml = np.asarray(self.mixing_length, dtype=float).ravel()
        if not np.all(np.isfinite(ml)) or np.any(ml < 0.0):
            raise ValueError('basic-node mixing_length must be finite and non-negative')
    if not isinstance(self.P_basic, jax.core.Tracer):
        p_b = np.asarray(self.P_basic, dtype=float).ravel()
        if not np.all(np.isfinite(p_b)) or np.any(p_b < -1.0):
            raise ValueError(
                'pressure at basic and staggered nodes must be finite and >= -1.0 Pa'
            )
    if not isinstance(self.P_stag, jax.core.Tracer):
        p_s = np.asarray(self.P_stag, dtype=float).ravel()
        if not np.all(np.isfinite(p_s)) or np.any(p_s < -1.0):
            raise ValueError(
                'pressure at basic and staggered nodes must be finite and >= -1.0 Pa'
            )
    if not isinstance(self.gravity, jax.core.Tracer):
        g_b = np.asarray(self.gravity, dtype=float).ravel()
        if not np.all(np.isfinite(g_b)) or np.any(g_b <= 0.0):
            raise ValueError('gravity at basic nodes must be finite and positive')

PhaseProperties

Bases: NamedTuple

Material properties at a set of mesh nodes.

FluxOutput

Bases: NamedTuple

Output from the flux computation at basic nodes.

compute_fluxes(S_stag, time, eos, params, mesh, heating_rate, S_basic_cmb_override=None, dSdr_cmb_override=None, surface_temperature=None)

Compute all heat and mass fluxes from the entropy profile.

This is the physics kernel called by the ODE RHS. It is a pure function: no mutation, no side effects, fully JIT-compilable.

Parameters:

Name Type Description Default
S_stag Array

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

required
time float

Current time [yr] (used for radionuclide heating).

required
eos EntropyEOS_JAX

JAX EOS tables.

required
params PhaseParams

Static material parameters and transport flags.

required
mesh MeshArrays

Mesh geometry and transform matrices.

required
heating_rate Array

Internal heating rate at staggered nodes [W/kg] (radionuclide + tidal, pre-computed by caller).

required
S_basic_cmb_override float or None

Optional override for the entropy at the CMB basic node (basic-node index 0). Used by the energy_balance and core_module core BCs, which reconstruct S_basic[0] from the state-tracked dSdr_cmb via S[0] + dSdr_cmb * (r_basic[0] - r_stag[0]). When None, the standard quantity_matrix mapping is used.

None
dSdr_cmb_override float or None

Optional override for the entropy gradient at the CMB basic node (dSdr[0]). Used by the energy_balance and core_module core BCs, where dSdr_cmb is a state-tracked variable. When None, the standard d_dr_matrix mapping is used.

None
surface_temperature tuple or None

(S_surf, dr_half) of a prescribed surface temperature (outer BC 5): the surface node takes S_surf [J/kg/K], which sets its temperature, and the gradient of :func:_matched_surface_gradient. When None, the surface copy convention is used.

None

Returns:

Type Description
FluxOutput

Heat flux, mass flux, eddy diffusivity, heating.

Source code in src/aragog/jax/phase.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
def compute_fluxes(
    S_stag: jax.Array,
    time: float,
    eos: EntropyEOS_JAX,
    params: PhaseParams,
    mesh: MeshArrays,
    heating_rate: jax.Array,
    S_basic_cmb_override=None,
    dSdr_cmb_override=None,
    surface_temperature=None,
) -> FluxOutput:
    """Compute all heat and mass fluxes from the entropy profile.

    This is the physics kernel called by the ODE RHS. It is a pure
    function: no mutation, no side effects, fully JIT-compilable.

    Parameters
    ----------
    S_stag : jax.Array
        Entropy at staggered nodes [J/kg/K].
    time : float
        Current time [yr] (used for radionuclide heating).
    eos : EntropyEOS_JAX
        JAX EOS tables.
    params : PhaseParams
        Static material parameters and transport flags.
    mesh : MeshArrays
        Mesh geometry and transform matrices.
    heating_rate : jax.Array
        Internal heating rate at staggered nodes [W/kg]
        (radionuclide + tidal, pre-computed by caller).
    S_basic_cmb_override : float or None
        Optional override for the entropy at the CMB basic node
        (basic-node index 0). Used by the energy_balance and
        core_module core BCs, which reconstruct S_basic[0] from the state-tracked
        dSdr_cmb via S[0] + dSdr_cmb * (r_basic[0] - r_stag[0]).
        When None, the standard quantity_matrix mapping is used.
    dSdr_cmb_override : float or None
        Optional override for the entropy gradient at the CMB
        basic node (dSdr[0]). Used by the energy_balance and
        core_module core BCs, where dSdr_cmb is a state-tracked variable. When None,
        the standard d_dr_matrix mapping is used.
    surface_temperature : tuple or None
        ``(S_surf, dr_half)`` of a prescribed surface temperature (outer BC 5): the surface
        node takes ``S_surf`` [J/kg/K], which sets its temperature, and the gradient of
        :func:`_matched_surface_gradient`. When None, the surface copy convention is used.

    Returns
    -------
    FluxOutput
        Heat flux, mass flux, eddy diffusivity, heating.
    """
    # Interpolate entropy to basic nodes and compute gradient
    S_basic = entropy_at_basic_nodes(mesh, S_stag)
    dSdr = mesh.d_dr_matrix @ S_stag

    # SPIDER ic.c:450 boundary-copy convention for dSdr at the surface
    # (mirrors numpy entropy_state.py:390 ``dSdxi[-1] = dSdxi[-2]``).
    # The d_dr_matrix gives a linear-extrapolation gradient at the top
    # basic node, but the SPIDER convention is to copy the adjacent
    # interior value. Without this, the surface dSdr can flip sign
    # relative to numpy, blowing up kappa_h and dS/dt at the second-
    # to-last staggered cell. The CMB side has its own override path
    # via ``dSdr_cmb_override``, so the surface copy here is the only
    # one needed at this layer.
    dSdr = dSdr.at[-1].set(dSdr[-2])

    # Apply energy_balance overrides at the CMB basic node.
    # Done as separate jax.lax.cond branches so the function remains
    # JIT-compatible regardless of whether the overrides are None or
    # JAX scalars. We use jnp.where with a static bool flag passed
    # through from the caller via the optional argument.
    if S_basic_cmb_override is not None:
        S_basic = S_basic.at[0].set(S_basic_cmb_override)
    if dSdr_cmb_override is not None:
        dSdr = dSdr.at[0].set(dSdr_cmb_override)
    else:
        # Mirror numpy entropy_state.py:389 ``dSdxi[0] = dSdxi[1]`` for the modes without a
        # boundary-state override; energy_balance and core_module pass one above.
        dSdr = dSdr.at[0].set(dSdr[1])

    if surface_temperature is not None:
        S_basic = S_basic.at[-1].set(surface_temperature[0])

    # Phase properties at basic nodes only; the fluxes need no staggered-node properties.
    phase_basic = evaluate_phase(eos, params, mesh.P_basic, S_basic)
    if surface_temperature is not None:
        t_top_cell = evaluate_phase(eos, params, mesh.P_stag[-1:], S_stag[-1:]).temperature[0]
        dSdr = _matched_surface_gradient(
            dSdr, surface_temperature[1], t_top_cell, phase_basic, mesh
        )

    # MLT eddy diffusivity
    kappa_h, kappa_c, _, u_visc_1, q_025_1 = compute_mlt(
        dSdr,
        phase_basic,
        mesh,
        params,
        theta=None,
        return_aux=True,
        return_q_025=True,
        surface_floor=surface_temperature is None,
    )

    # Basic node properties
    rho = phase_basic.density
    T = phase_basic.temperature
    Cp = phase_basic.heat_capacity
    k = phase_basic.thermal_conductivity
    dTdPs_basic = phase_basic.dTdPs

    # Heat flux components (multiply by flag to enable/disable)
    heat_flux = jnp.zeros_like(S_basic)

    # Conduction (SPIDER decomposition matching numpy entropy_state):
    #   F_cond = -k * [(T/Cp) * dS/dr + dT/dr|_adiabat]
    # where the adiabatic gradient is dT/dr|_ad = dTdPs * dPdr_basic
    # (EOS-table dT/dP|_S times the structural Adams-Williamson dP/dr).
    # This avoids the noise from finite-differencing T_stag and matches
    # SPIDER's eos-consistent conduction at phase boundaries.
    # Cp floor (100 J/kg/K) parity with numpy entropy_state.update. A
    # logger.warning inside this jit-compiled RHS would only fire
    # during tracing, not on actual data; the equivalent diagnostic
    # is emitted at load time by EntropySolver._check_eos_floors,
    # plus a once-per-instance runtime warning on the numpy path.
    Cp_safe = jnp.maximum(Cp, 100.0)
    superadiabatic = (T / Cp_safe) * dSdr
    dT_dr_adiabat = dTdPs_basic * mesh.dP_dr_basic
    jcond = params.conduction * (-k * (superadiabatic + dT_dr_adiabat))
    jconv = params.convection * (rho * T * kappa_h * (-dSdr))

    lid_state = None
    if params.rheology.enabled:
        kappa_th_b = k / (rho * Cp_safe)
        visc_solid = 10.0**params.log10_visc_solid
        eta_diff_b = (
            phase_basic.eta_diff
            if phase_basic.eta_diff is not None
            else jnp.full_like(T, visc_solid)
        )
        tau_y_b = (
            phase_basic.tau_y if phase_basic.tau_y is not None else jnp.full_like(T, jnp.inf)
        )
        if params.rheology.stress_closure_mode == 'local':
            lid_state = None
            eta_eff_b = _compute_effective_viscosity_core(
                eta_diff=eta_diff_b,
                stress_closure_mode='local',
                unyielded_velocity=u_visc_1,
                mixing_length=q_025_1 * mesh.mixing_length,
                tau_y=tau_y_b,
                xp=jnp,
            )
        else:
            lid_state = _compute_stagnant_lid_state_core(
                radii=mesh.radii_basic,
                temperature=T,
                pressure=jnp.maximum(mesh.P_basic, 0.0),
                convective_flux=jconv,
                total_flux=jcond + jconv,
                solidus_temperature=phase_basic.solidus_temperature,
                melt_fraction=phase_basic.melt_fraction,
                params=params.rheology,
                viscosity_solid=visc_solid,
                phi_rheo=params.phi_rheo,
                phi_width=params.phi_width,
                unyielded_velocity=u_visc_1,
                viscosity_mixture=phase_basic.viscosity,
                density=rho,
                gravity=jnp.abs(mesh.gravity),
                thermal_expansivity=phase_basic.thermal_expansivity,
                thermal_diffusivity=kappa_th_b,
                xp=jnp,
            )
            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=jnp,
            )
        log10_eta_eff = jnp.log10(jnp.maximum(eta_eff_b, jnp.finfo(float).tiny))
        mu_pass2 = blend_viscosity_with_solid_jax(
            phase_basic.melt_fraction, phase_basic.smth, log10_eta_eff, params
        )
        phase_basic = phase_basic._replace(
            viscosity=mu_pass2, kinematic_viscosity=mu_pass2 / rho
        )
        theta_pass2 = (
            None if params.rheology.stress_closure_mode == 'local' else lid_state['theta']
        )
        kappa_h, kappa_c = compute_mlt(
            dSdr,
            phase_basic,
            mesh,
            params,
            theta=theta_pass2,
            surface_floor=surface_temperature is None,
        )
        jconv = params.convection * (rho * T * kappa_h * (-dSdr))

    heat_flux = heat_flux + jcond
    heat_flux = heat_flux + jconv

    # Mass flux for gravitational separation and mixing
    mass_flux = jnp.zeros_like(S_basic)

    # Gravitational separation.
    #
    # Raw Stokes/permeability-driven mass flux:
    #     jgrav_raw = rho * phi * (1 - phi) * v_rel
    # SPIDER analogue smoothing (SPIDER/energy.c:523-533,
    # JGRAV_BOTTOM_UP + get_smoothing): multiply jgrav_raw by a bounded
    # polynomial of an UN-truncated two-phase fraction
    #     gphi = (S - S_sol(P)) / (S_liq(P) - S_sol(P))
    # evaluated at the staggered cell immediately BELOW the interface.
    # The polynomial `16 * gphi^2 * (1 - gphi)^2` (clipped to [0, 1])
    # vanishes cleanly at both pure phases and has bounded derivatives
    # everywhere, unlike SPIDER's tanh smoothing. This is the scipy-
    # path fix from entropy_state.py mirrored here so the JAX backend
    # doesn't reproduce the pre-fix CMB drain at first crystallisation.
    phi_b = phase_basic.melt_fraction
    v_rel = relative_velocity(
        eos,
        params,
        mesh.P_basic,
        rho,
        phi_b,
        mesh.gravity,
        phase_basic.viscosity,
    )
    jgrav_raw = rho * phi_b * (1.0 - phi_b) * v_rel

    # gphi at STAGGERED nodes (cell below each basic interface)
    S_sol_stag = eos.solidus_entropy(mesh.P_stag)
    S_liq_stag = eos.liquidus_entropy(mesh.P_stag)
    dS_stag = jnp.maximum(S_liq_stag - S_sol_stag, 1.0)
    gphi_stag = (S_stag - S_sol_stag) / dS_stag

    smth_stag = phase_boundary_smoothing(gphi_stag, params)

    # Map staggered smoothing to basic-node interfaces: interior basic
    # node i (1..N-2) sees the smoothing of staggered node i-1 (the
    # cell BELOW). Boundary basic nodes (0 and -1) use smth = 1 as a
    # placeholder because the mass flux at those indices is zeroed a
    # few lines below anyway. Lengths: staggered has N entries, basic
    # has N+1; smth_stag[:-1] supplies the N-1 interior interfaces
    # plus the two boundaries, totalling N+1.
    smth_basic = jnp.concatenate(
        [
            jnp.array([1.0]),
            smth_stag[:-1],
            jnp.array([1.0]),
        ]
    )

    # `bottom_up_grav_sep = 1.0` selects the smoothed flux, 0.0 selects
    # the raw flux (for reproducing the pre-fix drain in regression
    # tests).
    jgrav_smoothed = jgrav_raw * smth_basic
    jgrav = (
        params.bottom_up_grav_sep * jgrav_smoothed
        + (1.0 - params.bottom_up_grav_sep) * jgrav_raw
    )
    mass_flux = mass_flux + params.grav_sep * jgrav

    # Zero mass fluxes at boundaries (SPIDER convention)
    mass_flux = mass_flux.at[0].set(0.0)
    mass_flux = mass_flux.at[-1].set(0.0)

    # Add latent heat transport from mass flux
    heat_flux = heat_flux + mass_flux * phase_basic.latent_heat

    # Mixing heat flux, Bower et al. (2018) Eq. 9 with T_fus: Jmix = -kappa_c rho L dphi/dr,
    # L = T_fus dS_fus (numpy forms the product, equal to round-off), dphi/dr from cell fractions.
    dphidr = mesh.d_dr_matrix @ mixing_melt_fraction(gphi_stag, xp=jnp)
    jmix_heat = -kappa_c * rho * phase_basic.latent_heat * dphidr
    # Zero at CMB and surface (no mass/heat transfer across those boundaries)
    jmix_heat = jmix_heat.at[0].set(0.0)
    jmix_heat = jmix_heat.at[-1].set(0.0)
    heat_flux = heat_flux + params.mixing * jmix_heat

    return FluxOutput(
        heat_flux=heat_flux,
        mass_flux=mass_flux,
        eddy_diffusivity=kappa_h,
        heating=heating_rate,
        jmix_heat=jmix_heat,
        T_lid_iso=lid_state['T_lid_iso'] if lid_state is not None else None,
    )

compute_mlt(dSdr, phase_basic, mesh, params, theta=None, return_aux=False, return_q_025=False, surface_floor=True)

Compute MLT eddy diffusivity from the entropy gradient.

Parameters:

Name Type Description Default
dSdr Array

Entropy gradient at basic nodes [J/kg/K/m].

required
phase_basic PhaseProperties

Material properties at basic nodes.

required
mesh MeshArrays

Mesh geometry.

required
params PhaseParams

Static parameters.

required
theta Array or float

Frank-Kamenetskii contrast for viscous mixing-length rescaling.

None
return_aux bool

When True, also return (reynolds, viscous_velocity) as the third and fourth elements of the returned tuple.

False
return_q_025 bool

When True together with return_aux, also append q_mlt**0.25 as the fifth element of the returned tuple.

False
surface_floor bool

False under a prescribed surface temperature (outer BC 5): the kappa_h floor does not act at the surface node.

True

Returns:

Type Description
tuple of jax.Array

(kappa_h, kappa_c) when return_aux is False; (kappa_h, kappa_c, reynolds, viscous_velocity) when True (or 5-tuple with q_025 when return_q_025 is True).

Source code in src/aragog/jax/phase.py
 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
def compute_mlt(
    dSdr: jax.Array,
    phase_basic: PhaseProperties,
    mesh: MeshArrays,
    params: PhaseParams,
    theta: jax.Array | float | None = None,
    return_aux: bool = False,
    return_q_025: bool = False,
    surface_floor: bool = True,
) -> tuple[jax.Array, ...]:
    """Compute MLT eddy diffusivity from the entropy gradient.

    Parameters
    ----------
    dSdr : jax.Array
        Entropy gradient at basic nodes [J/kg/K/m].
    phase_basic : PhaseProperties
        Material properties at basic nodes.
    mesh : MeshArrays
        Mesh geometry.
    params : PhaseParams
        Static parameters.
    theta : jax.Array or float, optional
        Frank-Kamenetskii contrast for viscous mixing-length rescaling.
    return_aux : bool, default False
        When True, also return ``(reynolds, viscous_velocity)`` as the
        third and fourth elements of the returned tuple.
    return_q_025 : bool, default False
        When True together with ``return_aux``, also append ``q_mlt**0.25``
        as the fifth element of the returned tuple.
    surface_floor : bool
        False under a prescribed surface temperature (outer BC 5): the kappa_h floor does
        not act at the surface node.

    Returns
    -------
    tuple of jax.Array
        ``(kappa_h, kappa_c)`` when ``return_aux`` is False;
        ``(kappa_h, kappa_c, reynolds, viscous_velocity)`` when True
        (or 5-tuple with ``q_025`` when ``return_q_025`` is True).
    """
    alpha = phase_basic.thermal_expansivity
    T = phase_basic.temperature
    Cp = phase_basic.heat_capacity
    nu = phase_basic.kinematic_viscosity

    # |dS/dr| as 0.5*(|x| + sqrt(x^2 + eps^2)): equal to |x| for |x| >> eps, with a
    # finite gradient at x = 0, where the backward pass of jnp.abs can give NaN.
    eps_abs = 1.0e-30
    abs_dSdr_safe = 0.5 * (jnp.abs(dSdr) + jnp.sqrt(dSdr * dSdr + eps_abs * eps_abs))
    # An unstable node is driven by at least the gradient D (convective_threshold).
    drive = jnp.maximum(abs_dSdr_safe, params.convective_threshold)
    effective_superadiabatic = alpha * T * drive / jnp.maximum(Cp, 1.0)
    velocity_prefactor = jnp.abs(mesh.gravity) * effective_superadiabatic

    # Hard masks matching the numpy reference: the mixing-length drive acts where
    # dS/dr < 0, the floor where dS/dr < D (convective_threshold).
    conv_mask = jnp.where(dSdr < 0.0, 1.0, 0.0)
    floor_mask = jnp.where(dSdr < params.convective_threshold, 1.0, 0.0)
    if not surface_floor:  # a surface held at its temperature (outer BC 5) gets no floor
        floor_mask = floor_mask.at[-1].set(0.0)

    eps_sqrt = 1.0e-20
    inviscid_velocity_sq = (velocity_prefactor * mesh.mixing_length_sq / 16.0) * conv_mask
    inviscid_velocity = jnp.sqrt(inviscid_velocity_sq + eps_sqrt)

    blend_width = 0.01 * RE_CRIT
    if params.rheology.enabled:
        q_mlt = _viscous_mixing_length_factor_core(
            radii=mesh.radii_basic,
            r_in=mesh.radii_basic[0],
            r_out=mesh.radii_basic[-1],
            mixing_length=mesh.mixing_length,
            bottom_slope=params.rheology.mlt_bottom_slope,
            theta=theta,
            s_top_inf=params.rheology.s_top_inf,
            c_theta=params.rheology.c_theta,
            xp=jnp,
        )
        q_025, q_075 = _mlt_factor_powers(q_mlt)
    else:
        q_025 = q_075 = jnp.ones_like(dSdr)
    viscous_velocity = (
        velocity_prefactor * mesh.mixing_length_cu * q_075 / (18.0 * nu)
    ) * conv_mask
    reynolds = viscous_velocity * mesh.mixing_length * q_025 / nu
    inviscid_weight = 0.5 * (
        1.0 + jnp.tanh((reynolds - RE_CRIT) / jnp.maximum(blend_width, 1e-30))
    )
    kh_raw = (
        (1.0 - inviscid_weight) * (viscous_velocity * q_025)
        + inviscid_weight * inviscid_velocity
    ) * mesh.mixing_length

    # Thermal eddy diffusivity (SPIDER convention: positive=scale, negative=constant)
    kappa_h = jnp.where(
        params.eddy_diff_thermal > 0,
        params.eddy_diff_thermal * kh_raw,
        jnp.full_like(kh_raw, -params.eddy_diff_thermal),
    )

    # Chemical eddy diffusivity (from raw kh, before floor)
    kappa_c = jnp.where(
        params.eddy_diff_chemical > 0,
        params.eddy_diff_chemical * kh_raw,
        jnp.full_like(kh_raw, -params.eddy_diff_chemical),
    )

    # Melt-fraction-modulated kappa_h floor on cells with dS/dr < D only; see
    # solver/entropy_state.py:apply_kappah_floor for why cells with
    # dS/dr >= D keep their raw value.
    phi_basic = phase_basic.melt_fraction
    if params.rheology.enabled:
        f_floor = zero_anchored_weight(
            tanh_weight, phi_basic, params.phi_rheo, params.phi_width, jnp
        )
    else:
        f_floor = tanh_weight(phi_basic, params.phi_rheo, params.phi_width)
    kh_floor = params.kappah_floor * f_floor * floor_mask
    kappa_h_mlt = kappa_h
    kappa_h = jnp.maximum(kappa_h, kh_floor)

    # 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; numpy twin: EntropyState.update.
    kappa_h = kappa_h.at[0].set(jnp.maximum(kappa_h_mlt[1], kh_floor[0]))

    if return_aux:
        if return_q_025:
            return kappa_h, kappa_c, reynolds, viscous_velocity, q_025
        return kappa_h, kappa_c, reynolds, viscous_velocity
    return kappa_h, kappa_c

evaluate_phase(eos, params, P, S, *, include_rheology=True)

Compute all material properties at (P, S) nodes.

Parameters:

Name Type Description Default
eos EntropyEOS_JAX

JAX EOS tables.

required
params PhaseParams

Static material parameters.

required
P Array

Pressure [Pa], 1D.

required
S Array

Entropy [J/kg/K], 1D.

required
include_rheology bool

When True and params.rheology.enabled is True, evaluate Arrhenius diffusion-creep viscosity and Byerlee yield stress for the solid branch.

True

Returns:

Type Description
PhaseProperties

All material properties at the given nodes.

Source code in src/aragog/jax/phase.py
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
def evaluate_phase(
    eos: EntropyEOS_JAX,
    params: PhaseParams,
    P: jax.Array,
    S: jax.Array,
    *,
    include_rheology: bool = True,
) -> PhaseProperties:
    """Compute all material properties at (P, S) nodes.

    Parameters
    ----------
    eos : EntropyEOS_JAX
        JAX EOS tables.
    params : PhaseParams
        Static material parameters.
    P : jax.Array
        Pressure [Pa], 1D.
    S : jax.Array
        Entropy [J/kg/K], 1D.
    include_rheology : bool, default True
        When True and ``params.rheology.enabled`` is True, evaluate
        Arrhenius diffusion-creep viscosity and Byerlee yield stress
        for the solid branch.

    Returns
    -------
    PhaseProperties
        All material properties at the given nodes.
    """
    # SPIDER-parity single-pass evaluation: T, rho, Cp, alpha, dTdPs, k
    # all derived from one shared (S_sol, S_liq, gphi, smth, phase-boundary)
    # cache, with the smth-blend mixed<->single matching numpy
    # EntropyPhaseEvaluator._update_eos.
    state = eos.compute_phase_state(
        P,
        S,
        k_solid=params.k_solid,
        k_liquid=params.k_liquid,
        matprop_smooth_width=params.matprop_smooth_width,
    )
    phi = state.melt_fraction

    eta_diff = None
    tau_y = None
    w_blend = tanh_weight(phi, params.phi_rheo, params.phi_width)
    phi_thresh = params.rheology.phi_visc_single if params.rheology.enabled else 0.5
    visc_solid_weight = state.smth * (1.0 - w_blend) + (1.0 - state.smth) * jnp.where(
        phi > phi_thresh, 0.0, 1.0
    )
    if params.rheology.enabled and include_rheology:
        visc_solid = 10.0**params.log10_visc_solid
        p_pos = jnp.maximum(P, 0.0)
        eta_diff = _compute_arrhenius_viscosity_core(
            state.temperature,
            p_pos,
            viscosity_solid=visc_solid,
            g_homologous=params.rheology.g_homologous,
            solidus_temperature=state.solidus_temperature,
            t_sol_0=params.rheology.t_sol_0,
            dt_sol_dp=params.rheology.dt_sol_dp,
            arrhenius_t_ref=params.rheology.arrhenius_t_ref,
            r_gas=R_GAS,
            viscosity_max_log10=params.rheology.viscosity_max_log10,
            water_prefactor=params.rheology.water_prefactor,
            xp=jnp,
            activation_energy=params.rheology.activation_energy,
            activation_volume=params.rheology.activation_volume,
            activation_volume_decay_pressure=params.rheology.activation_volume_decay_pressure,
        )
        tau_y = _compute_yield_stress_core(
            p_pos,
            yield_stress_c=params.rheology.yield_stress_c,
            yield_stress_mu=params.rheology.yield_stress_mu,
            yield_stress_max=params.rheology.yield_stress_max,
            xp=jnp,
        )
        log10_eta_solid = jnp.log10(jnp.maximum(eta_diff, jnp.finfo(float).tiny))
        viscosity = blend_viscosity_with_solid_jax(phi, state.smth, log10_eta_solid, params)
    else:
        viscosity = blend_viscosity_with_solid_jax(
            phi, state.smth, params.log10_visc_solid, params
        )
    kinematic_viscosity = viscosity / state.density

    # Capacitance for entropy equation
    capacitance = state.density * state.temperature

    return PhaseProperties(
        temperature=state.temperature,
        density=state.density,
        heat_capacity=state.heat_capacity,
        thermal_expansivity=state.thermal_expansivity,
        dTdPs=state.dTdPs,
        melt_fraction=phi,
        viscosity=viscosity,
        kinematic_viscosity=kinematic_viscosity,
        thermal_conductivity=state.thermal_conductivity,
        latent_heat=state.latent_heat,
        capacitance=capacitance,
        solidus_temperature=state.solidus_temperature,
        eta_diff=eta_diff,
        tau_y=tau_y,
        smth=state.smth,
        temperature_slope=state.temperature_slope,
        visc_solid_weight=visc_solid_weight,
    )

aragog.jax.solver

Standalone JAX solve path used by the verification suite. The production path uses CVODE driven by aragog.solver.entropy_solver and only borrows the Jacobian from jax.jacrev; this module's solve_entropy is kept for parity tests and gradient-based sensitivity studies.

solver

JAX ODE solver for the entropy equation (research-only).

Direct-JAX integration of the entropy equation via diffrax Kvaerno5 (5th-order ESDIRK, A-L stable). The RHS applies boundary conditions, computes flux divergence, and adds internal heating, all in pure JAX.

Not production-ready: the diffrax ESDIRK solvers (kvaerno3, kvaerno5) stall at the first crystallisation step on the cubic-Hermite J_grav smoothing in coupled Earth-mantle runs. Kept for autodiff development. The production JAX integration path is the CVODE Option-Z path in aragog/solver/cvode_jax.py, selected by setting EnergyParams.use_jax_jacobian = True (PROTEUS-side backend="jax"), which uses CVODE for time stepping and JAX only for the analytic Jacobian.

Dependencies: jax, equinox, diffrax, lineax (transitive via diffrax).

BoundaryParams(*, outer_bc_type, outer_bc_value, emissivity, T_eq, inner_bc_type, inner_bc_value, core_density, core_heat_capacity, tfac_core_avg, cmb_area=0.0, core_M=0.0, cmb_dr_cmb=0.0, param_utbl=False, param_utbl_const=0.0, S_surf=None, surf_dr_half=0.0, lid=None)

Bases: Module

Boundary condition configuration as a JAX pytree.

Surface BC types: 1 = grey-body (F = emissivity * sigma * (T^4 - T_eq^4)) 4 = prescribed flux (from atmosphere module) 5 = prescribed temperature: the surface node takes the entropy S_surf, which sets the surface temperature, and the face flux is the kernel flux at the half-cell gradient over surf_dr_half; outer_bc_value [K] is only compared with the temperature of S_surf (:func:check_surface_temperature), so a new temperature needs a new S_surf (EntropySolver.surface_temperature_bc)

CMB BC types: 0 = insulating (F = 0) 1 = core cooling (Bower+2018 Eq. 37) 2 = prescribed flux 3 = prescribed temperature (preserve conduction-derived flux) 5 = energy_balance (SPIDER bc.c formula with (dS/dT)_P): F_cmb derived from the boundary entropy gradient (state-tracked dSdr_cmb). Used by dSdt_energy_balance.

All float fields are stored as JAX arrays (not Python floats) to avoid JIT recompilation when values change between coupling steps.

Energy-balance constants are optional (default 0); only used when inner_bc_type == 5 via dSdt_energy_balance.

Source code in src/aragog/jax/solver.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def __init__(
    self,
    *,
    outer_bc_type,
    outer_bc_value,
    emissivity,
    T_eq,
    inner_bc_type,
    inner_bc_value,
    core_density,
    core_heat_capacity,
    tfac_core_avg,
    cmb_area=0.0,
    core_M=0.0,
    cmb_dr_cmb=0.0,
    param_utbl=False,
    param_utbl_const=0.0,
    S_surf=None,
    surf_dr_half=0.0,
    lid=None,
):
    if outer_bc_type == 5 and not (
        S_surf is not None
        and np.isfinite(float(S_surf))
        and 0.0 < float(outer_bc_value) < np.inf
        and 0.0 < float(surf_dr_half) < np.inf
    ):
        raise ValueError(
            'outer_bc_type 5 needs a finite S_surf, an outer_bc_value > 0 K and a '
            'surf_dr_half > 0 m, all finite (EntropySolver.surface_temperature_bc), got '
            f'{S_surf}, {outer_bc_value}, {surf_dr_half}'
        )
    if outer_bc_type == 5 and param_utbl:
        raise ValueError('param_utbl is a grey-body correction; set it false with type 5')
    self.outer_bc_type = outer_bc_type
    self.outer_bc_value = jnp.asarray(outer_bc_value, dtype=jnp.float64)
    self.S_surf = jnp.asarray(0.0 if S_surf is None else S_surf, dtype=jnp.float64)
    self.surf_dr_half = jnp.asarray(surf_dr_half, dtype=jnp.float64)
    self.emissivity = jnp.asarray(emissivity, dtype=jnp.float64)
    self.T_eq = jnp.asarray(T_eq, dtype=jnp.float64)
    self.inner_bc_type = inner_bc_type
    self.inner_bc_value = jnp.asarray(inner_bc_value, dtype=jnp.float64)
    self.core_density = jnp.asarray(core_density, dtype=jnp.float64)
    self.core_heat_capacity = jnp.asarray(core_heat_capacity, dtype=jnp.float64)
    self.tfac_core_avg = jnp.asarray(tfac_core_avg, dtype=jnp.float64)
    self.cmb_area = jnp.asarray(cmb_area, dtype=jnp.float64)
    self.core_M = jnp.asarray(core_M, dtype=jnp.float64)
    self.cmb_dr_cmb = jnp.asarray(cmb_dr_cmb, dtype=jnp.float64)
    self.param_utbl = bool(param_utbl)
    self.param_utbl_const = jnp.asarray(param_utbl_const, dtype=jnp.float64)
    self.lid = lid

SolveResult

Bases: NamedTuple

Output from solve_entropy.

aragog.jax.nondim

Reference scales used internally to non-dimensionalise the state vector and time before they enter the integrator. The triplet (state_scale, rhs_scale, t_ref) is built from EntropySolver._S_ref, _dSdr_ref, and _t_ref_yr; it is not user-configurable.

nondim

Nondimensional scaling spec shared by the numpy and JAX RHS paths.

Single source of truth for the (state_scale, rhs_scale, t_ref) triplet and the state offset that scales physical-units state into the BDF integrator's O(1) work space. Built once by the EntropySolver, consumed by both the scipy/CVODE wrapper (entropy_solver.py) and the JAX CVODE factory (cvode_jax.py).

Internal contract enforced by __post_init__:

rhs_scale = t_ref / state_scale          (per component)
state_scale > 0, rhs_scale > 0, t_ref > 0
state_scale.shape == rhs_scale.shape

By construction, every NonDimScales instance enforces the internal contract (rhs_scale = t_ref / state_scale, all positive, shapes matching) inside its __post_init__ before any caller can use it. The two callers that consume an instance --- the scipy/CVODE wrapper in entropy_solver.py and the JAX CVODE factory in cvode_jax.py --- therefore do NOT need to re-check those invariants on entry.

NonDimScales(state_scale, t_ref, rhs_scale=None, state_offset=None) dataclass

Per-component nondim scales for the entropy solver state vector.

Parameters:

Name Type Description Default
state_scale (ndarray, shape(n))

Physical-units scale per state component: y_phys = y_nd * state_scale. Different components can have different scales (entropy in J/kg/K, dSdr in J/kg/K/m, T_core in K), so the scale is per-element.

required
t_ref float

Time scale: t_phys = t_nd * t_ref. Same value for every state component.

required
rhs_scale (ndarray, shape(n) or None)

Optional precomputed RHS scale dydt_nd = dydt_phys * rhs_scale. If None, derived as t_ref / state_scale automatically. When provided, must satisfy the contract or __post_init__ raises.

None
state_offset (ndarray, shape(n) or None)

Physical offset per state component, y_phys = y_nd * state_scale + state_offset, so that a component is integrated as its change from the offset; None means zero. The core_module mode offsets its temperatures by their values at the start of the call.

None

n property

Number of state-vector components.