Skip to content

proteus.interior_struct.zalmoxis

The PROTEUS-side wrapper around the Zalmoxis interior structure module. This module builds the call-time configuration dict, calls zalmoxis.solver.main(), writes the Aragog mesh file, and validates the schema contract on zalmoxis_output.dat.

For the conceptual overview of how Zalmoxis is integrated into PROTEUS, see the Zalmoxis coupling explainer. For the practical TOML recipe, see the Zalmoxis coupling how-to.

ZalmoxisMissingEOSFilesError

Bases: RuntimeError, MissingReferenceData

A layer's configured EOS identifier names a table file absent on disk.

get_zalmoxis_output_filepath(outdir)

Returns the output file path for Zalmoxis data. Args: outdir (str): Output directory. Returns: str: Path to the output file.

Source code in src/proteus/interior_struct/zalmoxis.py
231
232
233
234
235
236
237
238
def get_zalmoxis_output_filepath(outdir: str):
    """Returns the output file path for Zalmoxis data.
    Args:
        outdir (str): Output directory.
    Returns:
        str: Path to the output file.
    """
    return os.path.join(outdir, 'data', 'zalmoxis_output.dat')

validate_zalmoxis_output_schema(output_path, hf_row, rtol_radius=1e-06, rtol_mass=0.05, mantle_mass_ref=None)

Verify zalmoxis_output.dat is consistent with hf_row scalars.

The file is the contract Aragog reads inside solver.reset() (eos_method=2). This check confirms the file's last r matches hf_row['R_int'], and that the mantle mass matches hf_row['M_int'] - hf_row['M_core']. Catches file I/O corruption, column-order mistakes, truncation, encoding drift, and Aragog/Zalmoxis schema desync at the file handover boundary.

The mantle mass is taken from mantle_mass_ref when the caller supplies it: the structure's accumulator total mass_enclosed[-1] minus the exact core-mass target cmb_mass. Re-integrating the coarse output nodes with a grid trapezoid instead diverges from the sub-grid-substepped RK45 integral across the steep interior density profile, reaching ~10% at high planet mass, which would false-reject a structure that actually conserves mass. With the reference supplied, part (b) reduces to a check that the core-mantle split point is well resolved: the residual it measures is the CMB-node snap overshoot mass_enclosed[cmb_index] - cmb_mass relative to the mantle mass, a fraction of one boundary shell. File-density-column corruption is caught downstream by Aragog's EOS-vs-mesh consistency at solver.reset(); the radius check (part (a)) catches truncation and column swaps directly. When no reference is supplied the check falls back to the grid-trapezoidal shell-sum.

Parameters:

Name Type Description Default
output_path str

Path to the just-written zalmoxis_output.dat.

required
hf_row dict

PROTEUS hf_row holding the scalar truth (R_int, M_int, M_core).

required
rtol_radius float

Relative tolerance for the top-of-mantle vs. R_int check. Default 1e-6: the file's last r and hf_row['R_int'] come from the same variable in zalmoxis_solver, so equality is exact modulo float-string round-trip noise. Tight tolerance catches truncation, last-line corruption, and column-swap bugs at the bit level.

1e-06
rtol_mass float

Relative tolerance for the integrated mantle mass vs. M_int - M_core. Default 5e-2 (5%) reflects two stacked sources of legitimate mismatch: (a) integrator-method difference: Zalmoxis' mass_enclosed is the ODE state from RK45 with sub-grid substepping, while the schema check re-integrates via a grid-trapezoidal shell-sum. On stiff CHILI density profiles this shows about 0.8 to 2.0 %. (b) blend_mesh_files post-write modifies the file in place but does not update hf_row scalars. When blending fires with alpha < 1 (capping large R-shifts), the file's integrated mass can drift up to about 5% from the unblended hf_row['M_int'], so this check has to tolerate it. 5e-2 keeps a >2x margin over the worst legitimate noise while still catching gross corruption (column swap, truncation, byte-flip) at >>5 %. The tight mass-conservation contract (<0.1 %) lives in the wrapper-level mass-anchor check on hf_row['M_int'] / hf_row['M_int_target'], not here.

0.05

Raises:

Type Description
RuntimeError

On any violation (file unreadable, wrong shape, radius mismatch, mass mismatch). Caller (the wrapper's except-block) catches this and routes through the fall-back path.

Source code in src/proteus/interior_struct/zalmoxis.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
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
def validate_zalmoxis_output_schema(
    output_path: str,
    hf_row: dict,
    rtol_radius: float = 1e-6,
    rtol_mass: float = 5e-2,
    mantle_mass_ref: float | None = None,
) -> None:
    """Verify zalmoxis_output.dat is consistent with hf_row scalars.

    The file is the contract Aragog reads inside ``solver.reset()``
    (eos_method=2). This check confirms the file's last r matches
    ``hf_row['R_int']``, and that the mantle mass matches
    ``hf_row['M_int'] - hf_row['M_core']``.
    Catches file I/O corruption, column-order mistakes, truncation,
    encoding drift, and Aragog/Zalmoxis schema desync at the file
    handover boundary.

    The mantle mass is taken from ``mantle_mass_ref`` when the caller supplies
    it: the structure's accumulator total ``mass_enclosed[-1]`` minus the exact
    core-mass target ``cmb_mass``. Re-integrating the coarse output nodes with a
    grid trapezoid instead diverges from the sub-grid-substepped RK45 integral
    across the steep interior density profile, reaching ~10% at high planet mass,
    which would false-reject a structure that actually conserves mass. With the
    reference supplied, part (b) reduces to a check that the core-mantle split
    point is well resolved: the residual it measures is the CMB-node snap
    overshoot ``mass_enclosed[cmb_index] - cmb_mass`` relative to the mantle
    mass, a fraction of one boundary shell. File-density-column corruption is
    caught downstream by Aragog's EOS-vs-mesh consistency at ``solver.reset()``;
    the radius check (part (a)) catches truncation and column swaps directly.
    When no reference is supplied the check falls back to the grid-trapezoidal
    shell-sum.

    Parameters
    ----------
    output_path : str
        Path to the just-written ``zalmoxis_output.dat``.
    hf_row : dict
        PROTEUS hf_row holding the scalar truth (R_int, M_int, M_core).
    rtol_radius : float
        Relative tolerance for the top-of-mantle vs. R_int check.
        Default 1e-6: the file's last r and ``hf_row['R_int']`` come
        from the same variable in zalmoxis_solver, so equality is
        exact modulo float-string round-trip noise. Tight tolerance
        catches truncation, last-line corruption, and column-swap
        bugs at the bit level.
    rtol_mass : float
        Relative tolerance for the integrated mantle mass vs.
        ``M_int - M_core``. Default 5e-2 (5%) reflects two stacked
        sources of legitimate mismatch:
        (a) integrator-method difference: Zalmoxis' ``mass_enclosed``
        is the ODE state from RK45 with sub-grid substepping, while
        the schema check re-integrates via a grid-trapezoidal
        shell-sum. On stiff CHILI density profiles this shows
        about 0.8 to 2.0 %.
        (b) ``blend_mesh_files`` post-write modifies the file in
        place but does not update hf_row scalars. When blending fires
        with alpha < 1 (capping large R-shifts), the file's integrated
        mass can drift up to about 5% from the unblended
        hf_row['M_int'], so this check has to tolerate it.
        5e-2 keeps a >2x margin over the worst legitimate noise
        while still catching gross corruption (column swap,
        truncation, byte-flip) at >>5 %. **The tight mass-conservation
        contract (<0.1 %) lives in the wrapper-level mass-anchor
        check on hf_row['M_int'] / hf_row['M_int_target']**, not here.

    Raises
    ------
    RuntimeError
        On any violation (file unreadable, wrong shape, radius
        mismatch, mass mismatch). Caller (the wrapper's except-block)
        catches this and routes through the fall-back path.
    """
    try:
        data = np.loadtxt(output_path)
    except Exception as exc:
        raise RuntimeError(
            'zalmoxis_output.dat schema violation: could not reload '
            f'the just-written file ({output_path}): {exc}'
        )
    if data.size == 0 or data.ndim != 2 or data.shape[1] != 5:
        raise RuntimeError(
            'zalmoxis_output.dat schema violation: unexpected shape '
            f'{data.shape if data.size else "empty"} '
            f'(expected (N, 5)) for {output_path}'
        )

    r_file = data[:, 0]
    rho_file = data[:, 2]

    # (a) top-of-mantle radius == hf_row['R_int']
    r_top = float(r_file[-1])
    r_int_hf = float(hf_row.get('R_int', 0.0))
    if r_int_hf > 0:
        r_rel = abs(r_top / r_int_hf - 1.0)
        if r_rel > rtol_radius:
            raise RuntimeError(
                'zalmoxis_output.dat schema violation: top-of-mantle '
                f'r={r_top:.6e} from file differs from '
                f'hf_row[R_int]={r_int_hf:.6e} '
                f'(rel={r_rel:.3e} > {rtol_radius:.1e})'
            )

    # (b) mantle integrated mass == hf_row['M_int'] - hf_row['M_core'].
    # Prefer the structure's own RK45 accumulator mantle mass when the
    # caller supplies it (mantle_mass_ref). That value is the sub-grid
    # substepped ODE integral, exact to the solver tolerance. Re-integrating
    # the coarse output nodes with a grid trapezoid instead diverges from it
    # across the steep core-mantle density jump (the CMB-node snap attributes
    # a whole boundary shell to one side), reaching ~10% at high planet mass,
    # which would false-reject a structure that actually conserves mass. Only
    # when no reference is available do we fall back to the grid-trapezoidal
    # shell-sum (4/3 pi (r2^3 - r1^3) * rho_avg).
    if mantle_mass_ref is not None:
        mantle_mass = float(mantle_mass_ref)
        mass_source = 'accumulator'
    else:
        shells = (
            (4.0 / 3.0)
            * np.pi
            * (r_file[1:] ** 3 - r_file[:-1] ** 3)
            * 0.5
            * (rho_file[1:] + rho_file[:-1])
        )
        mantle_mass = float(np.sum(shells))
        mass_source = 'trapezoid'
    M_int_hf = float(hf_row.get('M_int', 0.0))
    M_core_hf = float(hf_row.get('M_core', 0.0))
    expected_mantle = M_int_hf - M_core_hf
    if expected_mantle > 0:
        m_rel = abs(mantle_mass / expected_mantle - 1.0)
        log.debug(
            'zalmoxis mass-closure: mantle split m_rel=%.3e (%s, rtol_mass=%.1e)',
            m_rel,
            mass_source,
            rtol_mass,
        )
        if m_rel > rtol_mass:
            raise RuntimeError(
                'zalmoxis_output.dat schema violation: '
                f'mantle mass ({mass_source})={mantle_mass:.6e} kg '
                'differs from hf_row[M_int - M_core]='
                f'{expected_mantle:.6e} kg '
                f'(rel={m_rel:.3e} > {rtol_mass:.1e})'
            )

zalmoxis_mesh_gaps(output_path, hf_row)

Compare a mesh file's radial bounds with a helpfile row.

The tolerance is that of Aragog's EntropySolver.reset(), max(1 m, 1e-9 * (R_int - R_core)), applied to both bounds in both directions; an 11-digit helpfile rounds the radii by at most 5e-5 m below 1e7 m and 5e-4 m up to 1e8 m.

Parameters:

Name Type Description Default
output_path str

Path to zalmoxis_output.dat, its .prev backup or a saved copy.

required
hf_row dict

Helpfile row holding R_core and R_int [m].

required

Returns:

Type Description
tuple of float or None

(file r[0] - R_core, file r[-1] - R_int, tolerance) in metres, or None unless the file ends with a newline and holds at least two finite 5-column rows with strictly increasing radii.

Source code in src/proteus/interior_struct/zalmoxis.py
387
388
389
390
391
392
393
394
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
def zalmoxis_mesh_gaps(output_path: str, hf_row: dict) -> tuple[float, float, float] | None:
    """Compare a mesh file's radial bounds with a helpfile row.

    The tolerance is that of Aragog's ``EntropySolver.reset()``,
    ``max(1 m, 1e-9 * (R_int - R_core))``, applied to both bounds in both
    directions; an 11-digit helpfile rounds the radii by at most 5e-5 m below
    1e7 m and 5e-4 m up to 1e8 m.

    Parameters
    ----------
    output_path : str
        Path to ``zalmoxis_output.dat``, its ``.prev`` backup or a saved copy.
    hf_row : dict
        Helpfile row holding ``R_core`` and ``R_int`` [m].

    Returns
    -------
    tuple of float or None
        ``(file r[0] - R_core, file r[-1] - R_int, tolerance)`` in metres, or
        None unless the file ends with a newline and holds at least two finite
        5-column rows with strictly increasing radii.
    """
    try:
        text = Path(output_path).read_text()
        data = np.loadtxt(text.splitlines(), ndmin=2) if text.strip() else None
    except (OSError, ValueError):
        return None
    if data is None:
        return None
    r = data[:, 0]
    if (
        not text.endswith('\n')
        or data.shape[1] != 5
        or r.size < 2
        or not np.isfinite(data).all()
        or (np.diff(r) <= 0).any()
    ):
        return None
    atol = max(1.0, 1.0e-9 * (hf_row['R_int'] - hf_row['R_core']))
    return r[0] - hf_row['R_core'], r[-1] - hf_row['R_int'], atol

copy_zalmoxis_output(src, dst)

Copy through a temporary file, so dst is never partial if the process stops.

Source code in src/proteus/interior_struct/zalmoxis.py
429
430
431
432
433
434
435
436
437
def copy_zalmoxis_output(src: str, dst: str) -> None:
    """Copy through a temporary file, so ``dst`` is never partial if the process stops."""
    tmp = dst + '.tmp'
    try:
        shutil.copy2(src, tmp)
        os.replace(tmp, dst)
    except BaseException:
        Path(tmp).unlink(missing_ok=True)
        raise

save_zalmoxis_output_snapshot(outdir, time)

Copy zalmoxis_output.dat to data/<time>_zalmoxis.dat.

The copy is written only next to the row's <time>_int.nc, so archiving and pruning treat it as part of that snapshot.

Parameters:

Name Type Description Default
outdir str

Run output directory.

required
time float

Simulated time of the helpfile row being written [yr].

required
Source code in src/proteus/interior_struct/zalmoxis.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def save_zalmoxis_output_snapshot(outdir: str, time: float) -> None:
    """Copy ``zalmoxis_output.dat`` to ``data/<time>_zalmoxis.dat``.

    The copy is written only next to the row's ``<time>_int.nc``, so archiving
    and pruning treat it as part of that snapshot.

    Parameters
    ----------
    outdir : str
        Run output directory.
    time : float
        Simulated time of the helpfile row being written [yr].
    """
    src = get_zalmoxis_output_filepath(outdir)
    data = os.path.join(outdir, 'data')
    if os.path.isfile(src) and os.path.isfile(snapshot_path_for_time(data, time, '_int.nc')):
        copy_zalmoxis_output(
            src, os.path.join(data, format_subyear_time(time) + '_zalmoxis.dat')
        )

build_volatile_profile(hf_row, mantle_eos)

Build a VolatileProfile from helpfile volatile masses.

Computes per-phase (liquid/solid) mass fractions for dissolved volatiles that have Zalmoxis EOS tables. Returns None if no volatiles are dissolved or if the mantle liquid/solid masses are unavailable.

Ownership of the liquid/solid split: the coupled PROTEUS path takes the per-phase masses from the outgassing chemistry (CALLIOPE/Aragog equilibrium via the helpfile), which already solved solubility. Zalmoxis's own partition_rule hook is a structure-side idealization for standalone Zalmoxis runs with no chemistry coupled; it is deliberately not used here.

Parameters:

Name Type Description Default
hf_row dict

Current helpfile row with volatile mass keys (e.g. H2O_kg_liquid, H2O_kg_solid) and mantle mass keys: M_mantle with Phi_global (preferred, structural), or M_mantle_liquid and M_mantle_solid as a fallback.

required
mantle_eos str

Primary mantle EOS identifier (e.g. 'PALEOS:MgSiO3').

required

Returns:

Type Description
VolatileProfile or None

Profile with per-phase fractions, or None if not applicable.

Source code in src/proteus/interior_struct/zalmoxis.py
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def build_volatile_profile(hf_row: dict, mantle_eos: str):
    """Build a VolatileProfile from helpfile volatile masses.

    Computes per-phase (liquid/solid) mass fractions for dissolved volatiles
    that have Zalmoxis EOS tables. Returns None if no volatiles are dissolved
    or if the mantle liquid/solid masses are unavailable.

    Ownership of the liquid/solid split: the coupled PROTEUS path takes
    the per-phase masses from the outgassing chemistry (CALLIOPE/Aragog
    equilibrium via the helpfile), which already solved solubility.
    Zalmoxis's own ``partition_rule`` hook is a structure-side
    idealization for standalone Zalmoxis runs with no chemistry coupled;
    it is deliberately not used here.

    Parameters
    ----------
    hf_row : dict
        Current helpfile row with volatile mass keys (e.g. ``H2O_kg_liquid``,
        ``H2O_kg_solid``) and mantle mass keys: ``M_mantle`` with
        ``Phi_global`` (preferred, structural), or ``M_mantle_liquid`` and
        ``M_mantle_solid`` as a fallback.
    mantle_eos : str
        Primary mantle EOS identifier (e.g. ``'PALEOS:MgSiO3'``).

    Returns
    -------
    VolatileProfile or None
        Profile with per-phase fractions, or None if not applicable.
    """
    from zalmoxis.mixing import VolatileProfile

    # Denominators: the melt concentration must be taken against the same
    # reservoir the chemistry used and the structure carries. CALLIOPE
    # dissolves into M_mantle * Phi_global, and the structure integrates
    # the (structural) mantle mass, so split the structural M_mantle by
    # Phi_global. Aragog's M_mantle_liquid/M_mantle_solid use its PALEOS
    # EOS cell masses instead, ~7% denser than the wet structural mantle,
    # which diluted w_liquid and lost the same fraction of dissolved
    # water from the structure. Fall back to the per-phase masses when
    # the structural fields are absent (e.g. minimal test rows).
    M_mantle = float(hf_row.get('M_mantle', 0.0))
    Phi_global = float(hf_row.get('Phi_global', float('nan')))
    if M_mantle > 0 and np.isfinite(Phi_global):
        Phi_global = min(max(Phi_global, 0.0), 1.0)
        M_liq = Phi_global * M_mantle
        M_sol = (1.0 - Phi_global) * M_mantle
    else:
        M_liq = float(hf_row.get('M_mantle_liquid', 0.0))
        M_sol = float(hf_row.get('M_mantle_solid', 0.0))

    # Need mantle mass data to compute fractions
    if M_liq + M_sol <= 0:
        return None

    w_liquid = {}
    w_solid = {}
    has_nonzero = False

    for species, eos_name in VOLATILE_EOS_MAP.items():
        kg_liq = float(hf_row.get(f'{species}_kg_liquid', 0.0))
        kg_sol = float(hf_row.get(f'{species}_kg_solid', 0.0))

        # Only include species with meaningful dissolved mass
        if kg_liq + kg_sol <= 0:
            continue

        # Mass fraction in liquid phase
        w_l = kg_liq / M_liq if M_liq > 0 else 0.0
        # Mass fraction in solid phase
        w_s = kg_sol / M_sol if M_sol > 0 else 0.0

        w_liquid[eos_name] = w_l
        w_solid[eos_name] = w_s
        has_nonzero = True

    if not has_nonzero:
        return None

    # Normalize: total volatile fraction in each phase must not exceed 0.95
    # (at least 5% silicate). Clamp proportionally if sum exceeds the limit.
    for w_dict in (w_liquid, w_solid):
        total = sum(w_dict.values())
        max_volatile_frac = 0.95
        if total > max_volatile_frac:
            scale = max_volatile_frac / total
            for k in w_dict:
                w_dict[k] *= scale

    log.info(
        'Built VolatileProfile: liquid=%s, solid=%s',
        {k: f'{v:.4f}' for k, v in w_liquid.items()},
        {k: f'{v:.4f}' for k, v in w_solid.items()},
    )

    return VolatileProfile(
        w_liquid=w_liquid,
        w_solid=w_solid,
        primary_component=mantle_eos,
    )

extend_mantle_eos_with_volatiles(mantle_eos, volatile_profile)

Extend a single-component mantle EOS string with volatile components.

If a VolatileProfile is provided and the mantle EOS is a single component, this adds the volatile EOS components with small placeholder fractions. The actual fractions are overridden at each ODE step by the VolatileProfile.

Parameters:

Name Type Description Default
mantle_eos str

Base mantle EOS string (e.g. 'PALEOS:MgSiO3').

required
volatile_profile VolatileProfile or None

Profile containing volatile EOS component names.

required

Returns:

Type Description
str

Extended EOS string (e.g. 'PALEOS:MgSiO3:0.98+PALEOS:H2O:0.01+Chabrier:H:0.01'), or the original string if no extension needed.

Source code in src/proteus/interior_struct/zalmoxis.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def extend_mantle_eos_with_volatiles(mantle_eos: str, volatile_profile) -> str:
    """Extend a single-component mantle EOS string with volatile components.

    If a VolatileProfile is provided and the mantle EOS is a single component,
    this adds the volatile EOS components with small placeholder fractions.
    The actual fractions are overridden at each ODE step by the VolatileProfile.

    Parameters
    ----------
    mantle_eos : str
        Base mantle EOS string (e.g. ``'PALEOS:MgSiO3'``).
    volatile_profile : VolatileProfile or None
        Profile containing volatile EOS component names.

    Returns
    -------
    str
        Extended EOS string (e.g.
        ``'PALEOS:MgSiO3:0.98+PALEOS:H2O:0.01+Chabrier:H:0.01'``),
        or the original string if no extension needed.
    """
    if volatile_profile is None:
        return mantle_eos

    # Don't modify if already multi-component
    if '+' in mantle_eos:
        return mantle_eos

    # Collect all volatile EOS components from the profile
    all_vol_components = set()
    for d in (volatile_profile.w_liquid, volatile_profile.w_solid):
        all_vol_components.update(d.keys())

    if not all_vol_components:
        return mantle_eos

    # Build extended string with small placeholder fractions
    # (actual fractions set by VolatileProfile at each radius)
    n_vol = len(all_vol_components)
    placeholder = 0.01  # 1% each
    primary_frac = max(0.5, 1.0 - n_vol * placeholder)
    parts = [f'{mantle_eos}:{primary_frac:.4f}']
    for comp in sorted(all_vol_components):
        parts.append(f'{comp}:{placeholder:.4f}')

    extended = '+'.join(parts)
    log.info('Extended mantle EOS: %s -> %s', mantle_eos, extended)
    return extended

solve_superliquidus_adiabat(config, hf_row)

Memoised super-liquidus anchor solve, see _solve_superliquidus_adiabat.

A failure of the integration with ValueError, KeyError, IndexError, ArithmeticError or RuntimeError (common.ANCHOR_NUMERICAL_ERRORS) is raised as a chained InitialConditionError that names the type and P_cmb. NotImplementedError, RecursionError and UnicodeError (common.ANCHOR_PASSTHROUGH_ERRORS), and every other type such as TypeError, AttributeError, OSError or MemoryError, propagate unchanged and are not memoised. An InitialConditionError from the solve is raised as is. Both are memoised under the same key as a success, as a copy without traceback, so repeated structure solves at one P_cmb do not repeat a failing scan.

Parameters:

Name Type Description Default
config Config

PROTEUS configuration.

required
hf_row dict or None

Helpfile row; hf_row['P_cmb'] is used when populated.

required

Returns:

Type Description
dict

See _solve_superliquidus_adiabat.

Raises:

Type Description
InitialConditionError

See _solve_superliquidus_adiabat; also for a numerical failure of the integration (chained). A memoised failure is raised again with the same message, chained to the stored copy.

FileNotFoundError

If an EOS or melting-curve file is missing.

Source code in src/proteus/interior_struct/zalmoxis.py
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
def solve_superliquidus_adiabat(config: Config, hf_row: dict | None) -> dict:
    """Memoised super-liquidus anchor solve, see ``_solve_superliquidus_adiabat``.

    A failure of the integration with ``ValueError``, ``KeyError``,
    ``IndexError``, ``ArithmeticError`` or ``RuntimeError``
    (``common.ANCHOR_NUMERICAL_ERRORS``) is raised as a chained
    ``InitialConditionError`` that names the type and P_cmb.
    ``NotImplementedError``, ``RecursionError`` and ``UnicodeError``
    (``common.ANCHOR_PASSTHROUGH_ERRORS``), and every other type such as
    ``TypeError``, ``AttributeError``, ``OSError`` or ``MemoryError``,
    propagate unchanged and are not memoised. An ``InitialConditionError``
    from the solve is raised as is. Both are memoised under the same key as
    a success, as a copy without traceback, so repeated structure solves at
    one P_cmb do not repeat a failing scan.

    Parameters
    ----------
    config : Config
        PROTEUS configuration.
    hf_row : dict or None
        Helpfile row; ``hf_row['P_cmb']`` is used when populated.

    Returns
    -------
    dict
        See ``_solve_superliquidus_adiabat``.

    Raises
    ------
    InitialConditionError
        See ``_solve_superliquidus_adiabat``; also for a numerical failure of
        the integration (chained). A memoised failure is raised again with
        the same message, chained to the stored copy.
    FileNotFoundError
        If an EOS or melting-curve file is missing.
    """
    from proteus.interior_energetics.common import (
        ANCHOR_NUMERICAL_ERRORS,
        ANCHOR_PASSTHROUGH_ERRORS,
        InitialConditionError,
    )
    from proteus.utils.structure_estimate import resolve_P_cmb

    P_cmb = resolve_P_cmb(hf_row, config)[0]
    key = _superliq_cache_key(config, P_cmb)
    if key in _SUPERLIQ_FAILED:
        first = _SUPERLIQ_FAILED[key]
        raise InitialConditionError(str(first)) from first
    try:
        return _solve_superliquidus_adiabat(config, hf_row)
    except InitialConditionError as exc:
        _SUPERLIQ_FAILED[key] = InitialConditionError(str(exc))
        raise
    except (ZalmoxisMissingEOSFilesError, *ANCHOR_PASSTHROUGH_ERRORS):
        raise
    except ANCHOR_NUMERICAL_ERRORS as exc:
        msg = (
            f'liquidus_super: the PALEOS P-T anchor failed at P_cmb={P_cmb / 1e9:.0f} GPa '
            f'({type(exc).__name__}: {exc}).'
        )
        _SUPERLIQ_FAILED[key] = InitialConditionError(msg)
        raise InitialConditionError(msg) from exc

load_zalmoxis_configuration(config, hf_row, temperature_mode_override=None, external_temperature_source=False)

Loads the model configuration for Zalmoxis and calculates the dry mass of the planet based on the total mass and the mass of volatiles. Args: config (Config): The configuration object containing the Zalmoxis parameters. hf_row (dict): A dictionary containing the mass of volatiles and other parameters. temperature_mode_override: Optional local override for config.planet.temperature_mode. Lets callers force a different structure-solve mode (e.g. 'adiabatic' for SPIDER coupling with T-dependent mantle EOS) without mutating the shared Config object. When None, falls back to config.planet.temperature_mode. external_temperature_source: True when the caller passes an external temperature function or array so the structure solve follows an evolved T(r) instead of the internal temperature-mode dispatch. In 'liquidus_super' mode this lets cmb_temperature reuse the last solved super-liquidus anchor rather than re-solving it, since the anchor is not consumed when an external source drives the solve. Returns: dict: A dictionary containing the Zalmoxis configuration parameters.

Source code in src/proteus/interior_struct/zalmoxis.py
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
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
def load_zalmoxis_configuration(
    config: Config,
    hf_row: dict,
    temperature_mode_override: str | None = None,
    external_temperature_source: bool = False,
):
    """Loads the model configuration for Zalmoxis and calculates the dry mass of the planet based on the total mass and the mass of volatiles.
    Args:
        config (Config): The configuration object containing the Zalmoxis parameters.
        hf_row (dict): A dictionary containing the mass of volatiles and other parameters.
        temperature_mode_override: Optional local override for
            ``config.planet.temperature_mode``. Lets callers force a different
            structure-solve mode (e.g. 'adiabatic' for SPIDER coupling with
            T-dependent mantle EOS) without mutating the shared Config object.
            When None, falls back to ``config.planet.temperature_mode``.
        external_temperature_source: True when the caller passes an external
            temperature function or array so the structure solve follows an
            evolved T(r) instead of the internal temperature-mode dispatch. In
            'liquidus_super' mode this lets ``cmb_temperature`` reuse the last
            solved super-liquidus anchor rather than re-solving it, since the
            anchor is not consumed when an external source drives the solve.
    Returns:
        dict: A dictionary containing the Zalmoxis configuration parameters.
    """

    # The Zalmoxis solver consumes core_frac as a mass fraction and does
    # not read core_frac_mode. Warn if a radius fraction was requested, so
    # the user is not surprised by the mass-fraction interpretation.
    if config.interior_struct.core_frac_mode == 'radius':
        log.warning(
            'interior_struct.core_frac_mode = "radius" has no effect with the '
            'zalmoxis module: core_frac (%.3f) is interpreted as a mass '
            'fraction. Use core_frac_mode = "mass", or switch to the dummy or '
            'spider module if a radius fraction is intended.',
            config.interior_struct.core_frac,
        )

    # Setup target planet mass (input parameter) as the total mass of the planet (dry mass + volatiles) [kg],
    # plus the volatile mass impacts and escape moved, which mass_tot (rock anchor) leaves out.
    from proteus.interior_struct.common import volatile_mass_change

    total_planet_mass = config.planet.mass_tot * M_earth + volatile_mass_change(hf_row)

    log.debug(
        'Total target planet mass (dry mass + volatiles): %s kg '
        'with EOS: core=%s, mantle=%s, ice=%s',
        total_planet_mass,
        config.interior_struct.zalmoxis.core_eos,
        config.interior_struct.zalmoxis.mantle_eos,
        config.interior_struct.zalmoxis.ice_layer_eos or 'none',
    )

    # Volatile mass (O included) excluded from the structure target: the full inventory
    # with dry_mantle, else only the atmosphere, since the wet-mantle EOS holds the dissolved
    # mass. Element columns absent before the first inventory count as zero (.get below).
    dry_mantle = config.interior_struct.zalmoxis.dry_mantle
    M_volatiles = 0.0
    for e in element_list:
        if dry_mantle:
            M_volatiles += float(hf_row.get(e + '_kg_total', 0.0))
        else:
            M_volatiles += float(hf_row.get(e + '_kg_atm', 0.0))

    log.debug(f'Volatile mass: {M_volatiles} kg')
    log.debug(
        'Mass budget: total=%.6e kg (%.4f M_earth), volatiles=%.6e kg (%.2f%%)',
        total_planet_mass,
        total_planet_mass / M_earth,
        M_volatiles,
        100.0 * M_volatiles / total_planet_mass if total_planet_mass > 0 else 0,
    )

    # Calculate the target planet mass (dry mass) by subtracting the mass of volatiles from the total planet mass
    planet_mass = total_planet_mass - M_volatiles

    log.debug(f'Target planet mass (dry mass): {planet_mass} kg ')

    # Build per-layer EOS config dict from PROTEUS config fields
    layer_eos_config = {
        'core': config.interior_struct.zalmoxis.core_eos,
        'mantle': config.interior_struct.zalmoxis.mantle_eos,
    }
    if config.interior_struct.zalmoxis.ice_layer_eos is not None:
        layer_eos_config['ice_layer'] = config.interior_struct.zalmoxis.ice_layer_eos

    # This dict only sees the dry layer_eos_config here; zalmoxis_solver
    # rebuilds it after extend_mantle_eos_with_volatiles adds a
    # dissolved-volatile component, so that component gets the real mzf too.
    mzf = config.interior_struct.zalmoxis.mushy_zone_factor
    mushy_zone_factors = _build_mushy_zone_factors(layer_eos_config, mzf)

    zc = config.interior_struct.zalmoxis
    log.debug(
        'Zalmoxis config: num_layers=%d, outer_solver=%s, tol_outer=%.1e, '
        'tol_inner=%.1e, use_jax=%s, use_anderson=%s',
        zc.num_levels,
        zc.outer_solver,
        zc.solver_tol_outer,
        zc.solver_tol_inner,
        zc.use_jax,
        zc.use_anderson,
    )

    # Core fraction. The Zalmoxis solver consumes `core_mass_fraction`
    # literally as a mass fraction and does not read `core_frac_mode`, so
    # `core_frac` is always interpreted as a mass fraction here regardless
    # of the mode. `core_frac_mode = "radius"` is only honoured by the
    # dummy and spider structure modules; a warning is emitted above when
    # it is combined with zalmoxis.

    # 'liquidus_super' can read the mantle EOS table here before
    # zalmoxis_solver's own pre-flight check runs, raising a bare
    # FileNotFoundError. That check never inspects the melting-curve
    # directory a WolfBower2018/RTPress100TPa mantle also needs, so a
    # missing one re-raises unconverted here and in zalmoxis_solver itself.
    try:
        cmb_temperature = _resolve_zalmoxis_cmb_temperature(
            config,
            hf_row,
            temperature_mode_override or config.planet.temperature_mode,
            external_temperature_source=external_temperature_source,
        )
    except FileNotFoundError:
        check_zalmoxis_eos_files(layer_eos_config, load_zalmoxis_material_dictionaries())
        raise

    return {
        'planet_mass': planet_mass,
        'core_mass_fraction': config.interior_struct.core_frac,
        'core_frac_mode': config.interior_struct.core_frac_mode,
        'mantle_mass_fraction': config.interior_struct.zalmoxis.mantle_mass_fraction,
        # For the structure solve, 'accretion' and 'isentropic' both reduce
        # to 'adiabatic' inside Zalmoxis. Zalmoxis only solves the structure
        # (M-R via hydrostatic + EOS); the entropy IC for Aragog/SPIDER is
        # set independently from config.planet.ini_entropy. 'accretion'
        # delays White+Li T-profile until after structure converges;
        # 'isentropic' (CHILI protocol) means the energetics solver
        # consumes ini_entropy, not the Zalmoxis T-profile, so the choice
        # of structure-solve T is decoupled from the IC. 'adiabatic_from_cmb'
        # is passed through to Zalmoxis with the CMB-anchor temperature so
        # the structure-side T(r) integrates upward from T_cmb at R_cmb,
        # matching the entropy that the energetics solver receives via
        # compute_initial_entropy. 'liquidus_super' maps to
        # 'adiabatic_from_cmb' here, with cmb_temperature derived from the
        # Fei+2021 liquidus at the converged P_cmb (or a Noack & Lasbleis
        # (2020) mass-aware P_cmb estimate on the very first call before
        # Zalmoxis has populated P_cmb) plus delta_T_super. The anchor is
        # recomputed against the converged P_cmb on the next structure
        # iteration. temperature_mode_override lets SPIDER coupling force
        # adiabatic without mutating the shared Config object (see proteus
        # rules §"Config mutability").
        'temperature_mode': _resolve_zalmoxis_temperature_mode(
            temperature_mode_override or config.planet.temperature_mode
        ),
        'surface_temperature': config.planet.tsurf_init,
        'cmb_temperature': cmb_temperature,
        'center_temperature': config.planet.tcenter_init,
        'temp_profile_file': None,
        'layer_eos_config': layer_eos_config,
        'mushy_zone_factor': mzf,
        'mushy_zone_factors': mushy_zone_factors,
        'num_layers': config.interior_struct.zalmoxis.num_levels,
        'target_surface_pressure': _get_target_surface_pressure(config, hf_row),
        # Solver tolerances and iteration limits
        'tolerance_outer': config.interior_struct.zalmoxis.solver_tol_outer,
        'tolerance_inner': config.interior_struct.zalmoxis.solver_tol_inner,
        'max_iterations_outer': config.interior_struct.zalmoxis.solver_max_iter_outer,
        'max_iterations_inner': config.interior_struct.zalmoxis.solver_max_iter_inner,
        # JAX diffrax structure path and Anderson Picard acceleration both
        # default on. See Zalmoxis.use_jax and use_anderson in config._struct.
        'use_jax': config.interior_struct.zalmoxis.use_jax,
        'use_anderson': config.interior_struct.zalmoxis.use_anderson,
        # outer mass-radius solver dispatch ('newton' default |
        # 'picard'). When 'newton', Zalmoxis uses Newton + brentq
        # bracketing on f(R) = M(R) - M_target instead of the
        # damped-Picard fixed-point loop. Newton requires tight
        # integrator tolerances; we auto-apply newton_relative_tolerance
        # / newton_absolute_tolerance when the Newton path is selected.
        'outer_solver': config.interior_struct.zalmoxis.outer_solver,
        # Newton-specific knobs (newton_max_iter, newton_tol) AND
        # tightened integrator tolerances are passed ONLY when the
        # Newton path is selected. Picard runs see the dict without
        # any Newton keys and without tightened tolerances, so a
        # future Zalmoxis guard against unknown keys would not break
        # Picard callers.
        **(
            {
                'newton_max_iter': (config.interior_struct.zalmoxis.newton_max_iter),
                'newton_tol': config.interior_struct.zalmoxis.newton_tol,
                'relative_tolerance': (
                    config.interior_struct.zalmoxis.newton_relative_tolerance
                ),
                'absolute_tolerance': (
                    config.interior_struct.zalmoxis.newton_absolute_tolerance
                ),
            }
            if config.interior_struct.zalmoxis.outer_solver == 'newton'
            else {}
        ),
    }

load_zalmoxis_material_dictionaries()

Build an EOS registry dict with file paths pointing to FWL_DATA.

Returns the same dict format as Zalmoxis EOS_REGISTRY, but with every eos_file path resolved to its fwl-io dataset directory in FWL_DATA instead of ZALMOXIS_ROOT/data/. The data root is the one download_zalmoxis_eos() fetches into, so Zalmoxis, when called from PROTEUS, reads the files that were fetched.

Returns:

Type Description
dict

Flat dict keyed by EOS identifier string (e.g. "Seager2007:iron", "PALEOS:MgSiO3", "Chabrier:H").

Source code in src/proteus/interior_struct/zalmoxis.py
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
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
1791
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
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
def load_zalmoxis_material_dictionaries():
    """Build an EOS registry dict with file paths pointing to FWL_DATA.

    Returns the same dict format as Zalmoxis ``EOS_REGISTRY``, but with
    every ``eos_file`` path resolved to its fwl-io dataset directory in
    ``FWL_DATA`` instead of ``ZALMOXIS_ROOT/data/``. The data root is the one
    ``download_zalmoxis_eos()`` fetches into, so Zalmoxis, when called from
    PROTEUS, reads the files that were fetched.

    Returns
    -------
    dict
        Flat dict keyed by EOS identifier string (e.g.
        ``"Seager2007:iron"``, ``"PALEOS:MgSiO3"``, ``"Chabrier:H"``).
    """
    root = GetFWLData()
    seager_dir = dataset_dir(EOS_SEAGER_2007, data_root=root)

    _seager_iron = {'eos_file': str(seager_dir / 'eos_seager07_iron.txt')}
    _seager_silicate = {'eos_file': str(seager_dir / 'eos_seager07_silicate.txt')}
    _seager_water = {'eos_file': str(seager_dir / 'eos_seager07_water.txt')}

    # Wolf & Bower 2018
    wb_dir = dataset_dir(EOS_WOLF_BOWER_2018, data_root=root)
    _wb_melted = {
        'eos_file': str(wb_dir / 'density_melt.dat'),
        'adiabat_grad_file': str(wb_dir / 'adiabat_temp_grad_melt.dat'),
    }
    _wb_solid = {'eos_file': str(wb_dir / 'density_solid.dat')}

    # RTPress 100 TPa
    rt_dir = dataset_dir(EOS_RTPRESS_100TPA, data_root=root)
    _rt_melted = {
        'eos_file': str(rt_dir / 'density_melt.dat'),
        'adiabat_grad_file': str(rt_dir / 'adiabat_temp_grad_melt.dat'),
    }

    # PALEOS 2-phase MgSiO3 (separate solid/liquid, Zenodo 19680050): the
    # 150 pts/decade (default) and 600 pts/decade (highres) pairs share one dataset.
    paleos2ph_dir = dataset_dir(EOS_PALEOS_MGSIO3, data_root=root)
    paleos2ph_hr_dir = paleos2ph_dir
    _paleos2ph_melted = {
        'eos_file': str(paleos2ph_dir / 'paleos_mgsio3_tables_pt_proteus_liquid.dat'),
        'format': 'paleos',
    }
    _paleos2ph_solid = {
        'eos_file': str(paleos2ph_dir / 'paleos_mgsio3_tables_pt_proteus_solid.dat'),
        'format': 'paleos',
    }
    _paleos2ph_melted_highres = {
        'eos_file': str(
            paleos2ph_hr_dir / 'paleos_mgsio3_tables_pt_proteus_liquid_highres.dat'
        ),
        'format': 'paleos',
    }
    _paleos2ph_solid_highres = {
        'eos_file': str(paleos2ph_hr_dir / 'paleos_mgsio3_tables_pt_proteus_solid_highres.dat'),
        'format': 'paleos',
    }

    # PALEOS unified tables, one dataset per material
    _paleos_iron = {
        'eos_file': str(
            dataset_dir(EOS_PALEOS_IRON, data_root=root) / 'paleos_iron_eos_table_pt.dat'
        ),
        'format': 'paleos_unified',
    }
    _paleos_mgsio3 = {
        'eos_file': str(
            dataset_dir(EOS_PALEOS_MGSIO3_UNIFIED, data_root=root)
            / 'paleos_mgsio3_eos_table_pt.dat'
        ),
        'format': 'paleos_unified',
    }
    _paleos_h2o = {
        'eos_file': str(
            dataset_dir(EOS_PALEOS_H2O, data_root=root) / 'paleos_water_eos_table_pt.dat'
        ),
        'format': 'paleos_unified',
    }

    # Chabrier H/He
    chabrier_dir = dataset_dir(EOS_CHABRIER_2021, data_root=root)
    _chabrier_h = {
        'eos_file': str(chabrier_dir / 'EOS_Chabrier2021_HHe' / 'chabrier2021_H.dat'),
        'format': 'paleos_unified',
    }

    # PALEOS-API live tabulation entries. These carry only a GridSpec at
    # build time; the dispatch layer (``zalmoxis.eos.paleos_api_cache``)
    # mutates them in place on first density query to populate ``eos_file``
    # and rewrite ``format`` to the downstream value (``paleos_unified`` or
    # ``paleos``). Cache keys are SHA+grid-hash under
    # ``$ZALMOXIS_ROOT/data/EOS_PALEOS_API/``; cold-cache cost is a one-time
    # generator run (see ``zalmoxis.eos.paleos_api``).
    from zalmoxis.eos.paleos_api import (
        make_default_grid_h2o,
        make_default_grid_iron,
        make_default_grid_mgsio3,
    )

    _paleos_api_iron = {
        'format': 'paleos_api',
        'material': 'iron',
        'grid_spec': make_default_grid_iron(),
    }
    _paleos_api_mgsio3 = {
        'format': 'paleos_api',
        'material': 'mgsio3',
        'grid_spec': make_default_grid_mgsio3(),
    }
    _paleos_api_h2o = {
        'format': 'paleos_api',
        'material': 'h2o',
        'grid_spec': make_default_grid_h2o(),
        'h2o_table_path': None,
    }
    _paleos_api_2ph_mgsio3_melted = {
        'format': 'paleos_api_2phase',
        'material': 'mgsio3',
        'side': 'liquid',
        'grid_spec': make_default_grid_mgsio3(),
    }
    _paleos_api_2ph_mgsio3_solid = {
        'format': 'paleos_api_2phase',
        'material': 'mgsio3',
        'side': 'solid',
        'grid_spec': make_default_grid_mgsio3(),
    }

    return {
        # Seager2007 static
        'Seager2007:iron': {'core': _seager_iron},
        'Seager2007:MgSiO3': {'mantle': _seager_silicate},
        'Seager2007:H2O': {'ice_layer': _seager_water},
        # Wolf & Bower 2018 T-dependent
        'WolfBower2018:MgSiO3': {
            'core': _seager_iron,
            'melted_mantle': _wb_melted,
            'solid_mantle': _wb_solid,
        },
        # RTPress 100 TPa extended melt + WB2018 solid
        'RTPress100TPa:MgSiO3': {
            'core': _seager_iron,
            'melted_mantle': _rt_melted,
            'solid_mantle': _wb_solid,
        },
        # PALEOS 2-phase MgSiO3 (Zenodo 19680050; 150 pts/decade default,
        # 600 pts/decade as -highres variant for sensitivity tests).
        'PALEOS-2phase:MgSiO3': {
            'core': _seager_iron,
            'melted_mantle': _paleos2ph_melted,
            'solid_mantle': _paleos2ph_solid,
        },
        'PALEOS-2phase:MgSiO3-highres': {
            'core': _seager_iron,
            'melted_mantle': _paleos2ph_melted_highres,
            'solid_mantle': _paleos2ph_solid_highres,
        },
        # PALEOS unified
        'PALEOS:iron': _paleos_iron,
        'PALEOS:MgSiO3': _paleos_mgsio3,
        'PALEOS:H2O': _paleos_h2o,
        # PALEOS-API live-tabulated (dispatch populates eos_file on demand)
        'PALEOS-API:iron': _paleos_api_iron,
        'PALEOS-API:MgSiO3': _paleos_api_mgsio3,
        'PALEOS-API:H2O': _paleos_api_h2o,
        'PALEOS-API-2phase:MgSiO3': {
            'core': _seager_iron,
            'melted_mantle': _paleos_api_2ph_mgsio3_melted,
            'solid_mantle': _paleos_api_2ph_mgsio3_solid,
        },
        # Chabrier H/He
        'Chabrier:H': _chabrier_h,
    }

resolve_paleos_api(key, entry)

Materialise a PALEOS-API registry entry in place, once per process.

A resolve runs git to read the paleos version, and the EOS check runs before every structure solve on a fresh registry, so resolved entries are kept by key. A kept entry whose tables were removed is resolved again, which rebuilds them.

Parameters:

Name Type Description Default
key str

Registry key of the entry, e.g. 'PALEOS-API-2phase:MgSiO3'.

required
entry dict

Its registry entry, updated in place with the table paths.

required

Raises:

Type Description
ZalmoxisMissingEOSFilesError

When the paleos package is not installed, since the resolver's worker pool would then restart forever instead of failing.

Source code in src/proteus/interior_struct/zalmoxis.py
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
def resolve_paleos_api(key: str, entry: dict) -> None:
    """Materialise a PALEOS-API registry entry in place, once per process.

    A resolve runs git to read the paleos version, and the EOS check runs before
    every structure solve on a fresh registry, so resolved entries are kept by key.
    A kept entry whose tables were removed is resolved again, which rebuilds them.

    Parameters
    ----------
    key : str
        Registry key of the entry, e.g. ``'PALEOS-API-2phase:MgSiO3'``.
    entry : dict
        Its registry entry, updated in place with the table paths.

    Raises
    ------
    ZalmoxisMissingEOSFilesError
        When the paleos package is not installed, since the resolver's worker pool
        would then restart forever instead of failing.
    """
    cached = _PALEOS_API_RESOLVED.pop(key, None)
    if cached and all(os.path.isfile(p) for p in _table_paths(cached)):
        _PALEOS_API_RESOLVED[key] = cached
        entry.update(copy.deepcopy(cached))
        return
    if not _paleos_installed():
        raise ZalmoxisMissingEOSFilesError(
            f'PALEOS-API tables not built:\n  {key} (the paleos package is not installed)\n'
            f'{_PALEOS_API_FIX}'
        )
    from zalmoxis.eos.paleos_api_cache import resolve_registry_entry

    resolve_registry_entry(entry)
    _PALEOS_API_RESOLVED[key] = copy.deepcopy(entry)

check_zalmoxis_eos_files(layer_eos_config, mat_dicts, paleos_companions=False)

Fail fast when a selected EOS table file is missing on disk.

Walks the registry entries selected by layer_eos_config and collects every referenced table path that does not exist, then raises one actionable error. Without this check the solver emits one read error per shell and ends in a non-convergence failure that hides the real cause. PALEOS-API entries (live tabulation) are materialised here, so a failed build stops the run before any solve.

Parameters:

Name Type Description Default
layer_eos_config dict

Per-layer EOS identifier strings ('core', 'mantle', ...).

required
mat_dicts dict

EOS registry from :func:load_zalmoxis_material_dictionaries.

required
paleos_companions bool

Also require the :func:paleos_companion_keys of the mantle.

False

Raises:

Type Description
ZalmoxisMissingEOSFilesError

If any selected EOS table file is missing, naming every missing path and the command that downloads them.

Source code in src/proteus/interior_struct/zalmoxis.py
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
def check_zalmoxis_eos_files(
    layer_eos_config: dict, mat_dicts: dict, paleos_companions: bool = False
) -> None:
    """Fail fast when a selected EOS table file is missing on disk.

    Walks the registry entries selected by ``layer_eos_config`` and
    collects every referenced table path that does not exist, then
    raises one actionable error. Without this check the solver emits
    one read error per shell and ends in a non-convergence failure that
    hides the real cause. PALEOS-API entries (live tabulation) are
    materialised here, so a failed build stops the run before any solve.

    Parameters
    ----------
    layer_eos_config : dict
        Per-layer EOS identifier strings (``'core'``, ``'mantle'``, ...).
    mat_dicts : dict
        EOS registry from :func:`load_zalmoxis_material_dictionaries`.
    paleos_companions : bool
        Also require the :func:`paleos_companion_keys` of the mantle.

    Raises
    ------
    ZalmoxisMissingEOSFilesError
        If any selected EOS table file is missing, naming every missing
        path and the command that downloads them.
    """
    from zalmoxis.eos.dispatch import _is_paleos_api

    selected = [
        (role, key)
        for role, identifier in layer_eos_config.items()
        for key in eos_components(identifier)
    ]
    if paleos_companions:
        companions = paleos_companion_keys(layer_eos_config.get('mantle', ''))
        selected += [('mantle', key) for key in companions]
    missing: set[str] = set()
    unbuilt: set[str] = set()
    for layer_role, key in selected:
        entry = mat_dicts.get(key)
        if entry is None:
            # Unknown identifiers fail later with a registry error.
            continue
        api = key in _PALEOS_API_RESOLVED or _is_paleos_api(entry)
        if api:
            try:
                resolve_paleos_api(key, entry)
            except ZalmoxisMissingEOSFilesError:
                unbuilt.add(f'{key} (the paleos package is not installed)')
                continue
            except Exception as exc:
                unbuilt.add(f'{key} ({type(exc).__name__}: {exc})')
                continue
        # Nested entries map layer roles to flat entries; their 'core' sub-entry
        # counts only for the core role or when it is the only sub-entry.
        if 'eos_file' in entry:
            subentries = [entry]
        else:
            has_other_roles = any(role != 'core' for role in entry)
            subentries = [
                sub
                for role, sub in entry.items()
                if role != 'core' or layer_role == 'core' or not has_other_roles
            ]
        for sub in subentries:
            if not isinstance(sub, dict):
                continue
            for field in ('eos_file', 'adiabat_grad_file'):
                path = sub.get(field)
                if path and not os.path.isfile(path) and api:
                    # A generated table removed since it was built is built again.
                    _PALEOS_API_RESOLVED.pop(key, None)
                    unbuilt.add(f'{key} ({path} not found)')
                elif path and not os.path.isfile(path):
                    missing.add(path)
    parts = []
    if missing:
        parts.append(
            f'Interior EOS table file(s) not found:\n  {"\n  ".join(sorted(missing))}\n'
            'Download them with '
            '`proteus get interiordata --config-path <config.toml>`, '
            f'or run `proteus start` once without --offline. {RELOCATE_HINT}'
        )
    if unbuilt:
        parts.append(
            f'PALEOS-API tables not built:\n  {"\n  ".join(sorted(unbuilt))}\n{_PALEOS_API_FIX}'
        )
    if parts:
        raise ZalmoxisMissingEOSFilesError('\n'.join(parts))

energetics_entry(mantle_eos, mat_dicts)

Energetics key of a mantle EOS and its registry entry (empty when absent).

Source code in src/proteus/interior_struct/zalmoxis.py
2031
2032
2033
2034
def energetics_entry(mantle_eos: str, mat_dicts: dict) -> tuple[str | None, dict]:
    """Energetics key of a mantle EOS and its registry entry (empty when absent)."""
    key = energetics_eos_key(mantle_eos)
    return key, mat_dicts.get(key or '', {})

require_paleos_tables(config, outdir)

Stop the run before any solve when a table of its EOS set is missing.

Requires every table file of the core, mantle and ice-layer EOS and, for a mantle with a PALEOS component, the MgSiO3 2-phase pair; a resumed SPIDER run that keeps its P-S tables is held only to its layer tables. The liquidus_super initial adiabat requires the pair for any mantle. With dry_mantle = false the dissolved-volatile tables are also required. A mantle with a non-MgSiO3 component gets one WARNING that names the tables its energetics and its liquidus_super initial adiabat use.

Parameters:

Name Type Description Default
config Config

Configuration object with struct.zalmoxis settings.

required
outdir str

The run output directory.

required

Raises:

Type Description
ZalmoxisMissingEOSFilesError

Naming every missing file and the command that downloads it.

Source code in src/proteus/interior_struct/zalmoxis.py
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
def require_paleos_tables(config: Config, outdir: str) -> None:
    """Stop the run before any solve when a table of its EOS set is missing.

    Requires every table file of the core, mantle and ice-layer EOS and,
    for a mantle with a PALEOS component, the MgSiO3 2-phase pair; a resumed
    SPIDER run that keeps its P-S tables is held only to its layer tables. The
    liquidus_super initial adiabat requires the pair for any mantle. With
    ``dry_mantle = false`` the dissolved-volatile tables are also required. A
    mantle with a non-MgSiO3 component gets one WARNING that names the tables
    its energetics and its liquidus_super initial adiabat use.

    Parameters
    ----------
    config : Config
        Configuration object with struct.zalmoxis settings.
    outdir : str
        The run output directory.

    Raises
    ------
    ZalmoxisMissingEOSFilesError
        Naming every missing file and the command that downloads it.
    """
    zc = config.interior_struct.zalmoxis
    layers = {'core': zc.core_eos, 'mantle': zc.mantle_eos}
    if zc.ice_layer_eos is not None:
        layers['ice_layer'] = zc.ice_layer_eos
    if not zc.dry_mantle:
        # Dissolved volatiles join the mantle EOS during the run.
        layers['volatiles'] = '+'.join(VOLATILE_EOS_MAP.values())
    mat_dicts = load_zalmoxis_material_dictionaries()
    # Runs before the accreted mass is restored: no mass check and no report here.
    kept = config.params.resume and _resumed_ps_tables(outdir, None)
    liquidus_super = config.planet.temperature_mode == 'liquidus_super'
    if liquidus_super:
        layers['anchor'] = twophase_registry_key(zc.mantle_eos)
    # Aragog re-solves the initial condition on the pair when the mesh changes.
    check_zalmoxis_eos_files(
        layers,
        mat_dicts,
        paleos_companions=not kept or config.interior_energetics.module == 'aragog',
    )
    components = eos_components(zc.mantle_eos)
    mixture = len(set(components)) > 1
    if all(is_mgsio3(c) for c in components):
        return
    uses = []
    if config.interior_energetics.module in ('spider', 'aragog'):
        if not generates_paleos_tables(config.interior_struct):
            uses.append(
                'the energetics use the eos_dir P-S tables (by default Wolf and Bower 2018) '
                'and the melting_dir curves'
            )
        else:
            uses.append(
                'the energetics and melting curves are PALEOS MgSiO3 '
                f'({energetics_eos_key(zc.mantle_eos)}, solidus = '
                f'{zc.mushy_zone_factor:.2f} x PALEOS liquidus)'
            )
    if liquidus_super:
        uses.append('the liquidus_super initial adiabat is solved on the MgSiO3 2-phase tables')
    if uses:
        head = (
            'the non-MgSiO3 components enter only the structure density; '
            if mixture
            else 'the structure uses its density, while '
        )
        log.warning('mantle_eos=%s: %s%s', zc.mantle_eos, head, '; '.join(uses))

resolve_2phase_mgsio3_paths(mantle_eos, mat_dicts, required=False)

Return the 2-phase MgSiO3 table paths, stopping on a missing one when required.

Parameters:

Name Type Description Default
mantle_eos str

Configured mantle EOS.

required
mat_dicts dict

Zalmoxis material dictionaries.

required
required bool

Raise instead of returning None for a missing table. The initial-condition solves that read the pair always set it, the surface-entropy lookup sets it for a generated PALEOS table set, and the P-S export leaves it off.

False

Returns:

Type Description
tuple[str | None, str | None]

See :func:_twophase_mgsio3_paths.

Raises:

Type Description
ZalmoxisMissingEOSFilesError

If required and a table of the pair is not available.

Source code in src/proteus/interior_struct/zalmoxis.py
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
def resolve_2phase_mgsio3_paths(mantle_eos: str, mat_dicts: dict, required: bool = False):
    """Return the 2-phase MgSiO3 table paths, stopping on a missing one when required.

    Parameters
    ----------
    mantle_eos : str
        Configured mantle EOS.
    mat_dicts : dict
        Zalmoxis material dictionaries.
    required : bool
        Raise instead of returning None for a missing table. The initial-condition
        solves that read the pair always set it, the surface-entropy lookup sets it
        for a generated PALEOS table set, and the P-S export leaves it off.

    Returns
    -------
    tuple[str | None, str | None]
        See :func:`_twophase_mgsio3_paths`.

    Raises
    ------
    ZalmoxisMissingEOSFilesError
        If ``required`` and a table of the pair is not available.
    """
    paths = _twophase_mgsio3_paths(mantle_eos, mat_dicts)
    if required and None in paths:
        missing = [p for p, ok in zip(('solid', 'liquid'), paths) if ok is None]
        key = twophase_registry_key(mantle_eos)
        fix = (
            _PALEOS_API_FIX
            if key.startswith('PALEOS-API')
            else 'Download them with `proteus get interiordata --config-path <config.toml>`. '
            + RELOCATE_HINT
        )
        raise ZalmoxisMissingEOSFilesError(
            f'PALEOS 2-phase MgSiO3 tables {key} not available: {", ".join(missing)}. {fix}'
        )
    return paths

load_zalmoxis_solidus_liquidus_functions(mantle_eos, config)

Loads the solidus and liquidus functions for Zalmoxis based on the mantle EOS.

Melting curves are needed for two purposes: 1. Temperature-dependent density in the mushy zone (WolfBower2018, RTPress). 2. phi(r) blending in VolatileProfile (any EOS with dissolved volatiles).

The curves follow the energetics key of the mantle EOS (:func:proteus.utils.helper.energetics_eos_key), the same key as the energetics. For WolfBower2018/RTPress100TPa, loads SPIDER-format P-T files from FWL_DATA. For PALEOS unified and PALEOS-2phase, the liquidus comes from the analytic Belonoshko+2005 / Fei+2021 curve (Zalmoxis 'PALEOS-liquidus') which is the basis Zalmoxis uses for MgSiO3 phase separation, and the solidus is derived as T_sol = T_liq * mushy_zone_factor. This keeps the curves used for phi-blending and 2-phase nabla_ad consistent with the unified PALEOS density-interpolation phase boundaries.

Parameters:

Name Type Description Default
mantle_eos str

Mantle EOS string (e.g. "WolfBower2018:MgSiO3", "PALEOS:MgSiO3", "PALEOS-2phase:MgSiO3").

required
config Config

PROTEUS configuration object.

required

Returns:

Type Description
tuple or None

(solidus_func, liquidus_func) callable P [Pa] -> T [K], or None.

Source code in src/proteus/interior_struct/zalmoxis.py
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
def load_zalmoxis_solidus_liquidus_functions(mantle_eos: str, config: Config):
    """Loads the solidus and liquidus functions for Zalmoxis based on the mantle EOS.

    Melting curves are needed for two purposes:
    1. Temperature-dependent density in the mushy zone (WolfBower2018, RTPress).
    2. phi(r) blending in VolatileProfile (any EOS with dissolved volatiles).

    The curves follow the energetics key of the mantle EOS
    (:func:`proteus.utils.helper.energetics_eos_key`), the same key as the
    energetics. For WolfBower2018/RTPress100TPa, loads SPIDER-format P-T files from FWL_DATA.
    For PALEOS unified and PALEOS-2phase, the liquidus comes from the analytic
    Belonoshko+2005 / Fei+2021 curve (Zalmoxis ``'PALEOS-liquidus'``) which is
    the basis Zalmoxis uses for MgSiO3 phase separation, and the solidus is
    derived as T_sol = T_liq * mushy_zone_factor. This keeps the curves used
    for phi-blending and 2-phase nabla_ad consistent with the unified PALEOS
    density-interpolation phase boundaries.

    Parameters
    ----------
    mantle_eos : str
        Mantle EOS string (e.g. ``"WolfBower2018:MgSiO3"``, ``"PALEOS:MgSiO3"``,
        ``"PALEOS-2phase:MgSiO3"``).
    config : Config
        PROTEUS configuration object.

    Returns
    -------
    tuple or None
        (solidus_func, liquidus_func) callable P [Pa] -> T [K], or None.
    """
    key = energetics_eos_key(mantle_eos) or ''
    if key.startswith(TDEP_EOS_PREFIXES):
        return get_zalmoxis_melting_curves(config)

    # PALEOS unified and 2-phase share the analytic PALEOS-liquidus (Belonoshko+2005 /
    # Fei+2021), with solidus = mushy_zone_factor x liquidus. The 2-phase nabla_ad needs
    # both curves, and without them the unified path falls back to phi = 0.5.
    if key.startswith(PALEOS_EOS_PREFIXES):
        try:
            from zalmoxis.melting_curves import (
                derive_solidus_from_liquidus,
                get_solidus_liquidus_functions,
            )

            _, liquidus_func = get_solidus_liquidus_functions(
                solidus_id='Stixrude14-solidus',  # required by API but unused; solidus is built below as mushy_zone_factor * liquidus (constant depression of the PALEOS liquidus)
                liquidus_id='PALEOS-liquidus',
            )
            mzf = config.interior_struct.zalmoxis.mushy_zone_factor
            solidus_func = derive_solidus_from_liquidus(liquidus_func, mzf)
            log.info(
                'PALEOS melting curves (%s): liquidus from PALEOS, '
                'solidus = liquidus * %.2f (mushy_zone_factor)',
                mantle_eos,
                mzf,
            )
            return solidus_func, liquidus_func
        except Exception as e:
            log.warning('Could not load PALEOS melting curves: %s', e)
            return None

    return None

scale_temperature_profile_for_aragog(config, mantle_radii, mantle_temperature_profile)

Scales the temperature profile obtained from Zalmoxis to match the number of levels required by Aragog. Args: config (Config): The configuration object containing the configuration parameters. mantle_radii (np.ndarray): The radial positions of the mantle layers from Zalmoxis. mantle_temperature_profile (np.ndarray): The temperature profile of the mantle layers from Zalmoxis. Returns: np.ndarray: The scaled temperature profile matching the number of levels in Aragog.

Source code in src/proteus/interior_struct/zalmoxis.py
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
def scale_temperature_profile_for_aragog(
    config: Config, mantle_radii: np.ndarray, mantle_temperature_profile: np.ndarray
):
    """Scales the temperature profile obtained from Zalmoxis to match the number of levels required by Aragog.
    Args:
        config (Config): The configuration object containing the configuration parameters.
        mantle_radii (np.ndarray): The radial positions of the mantle layers from Zalmoxis.
        mantle_temperature_profile (np.ndarray): The temperature profile of the mantle layers from Zalmoxis.
    Returns:
        np.ndarray: The scaled temperature profile matching the number of levels in Aragog.
    """

    # Number of levels in Aragog mesh
    mesh_grid_size = config.interior_energetics.num_levels - 1

    # Create new evenly spaced radial positions for Aragog
    radii_to_interpolate = np.linspace(mantle_radii[0], mantle_radii[-1], mesh_grid_size)

    # Cubic interpolation onto the Aragog radial mesh
    cubic_interp = interp1d(mantle_radii, mantle_temperature_profile, kind='cubic')
    return cubic_interp(radii_to_interpolate)

write_spider_mesh_file(outdir, mantle_radii, mantle_pressure, mantle_density, mantle_gravity, num_basic)

Write an external mesh file for SPIDER from Zalmoxis mantle profiles.

Interpolates the Zalmoxis mantle arrays onto uniformly-spaced SPIDER basic and staggered nodes, then writes the mesh file in the format expected by SPIDER's SetMeshFromExternalFile().

Parameters:

Name Type Description Default
outdir str

PROTEUS output directory (file is written to outdir/data/).

required
mantle_radii ndarray

Radial positions from CMB to surface, ascending [m].

required
mantle_pressure ndarray

Pressure at each radius [Pa].

required
mantle_density ndarray

Density at each radius [kg/m^3].

required
mantle_gravity ndarray

Gravity magnitude at each radius [m/s^2] (positive).

required
num_basic int

Number of SPIDER basic nodes (shell boundaries).

required

Returns:

Type Description
str

Path to the written mesh file.

Source code in src/proteus/interior_struct/zalmoxis.py
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
def write_spider_mesh_file(
    outdir: str,
    mantle_radii: np.ndarray,
    mantle_pressure: np.ndarray,
    mantle_density: np.ndarray,
    mantle_gravity: np.ndarray,
    num_basic: int,
) -> str:
    """Write an external mesh file for SPIDER from Zalmoxis mantle profiles.

    Interpolates the Zalmoxis mantle arrays onto uniformly-spaced SPIDER
    basic and staggered nodes, then writes the mesh file in the format
    expected by SPIDER's ``SetMeshFromExternalFile()``.

    Parameters
    ----------
    outdir : str
        PROTEUS output directory (file is written to ``outdir/data/``).
    mantle_radii : np.ndarray
        Radial positions from CMB to surface, ascending [m].
    mantle_pressure : np.ndarray
        Pressure at each radius [Pa].
    mantle_density : np.ndarray
        Density at each radius [kg/m^3].
    mantle_gravity : np.ndarray
        Gravity magnitude at each radius [m/s^2] (positive).
    num_basic : int
        Number of SPIDER basic nodes (shell boundaries).

    Returns
    -------
    str
        Path to the written mesh file.
    """
    num_staggered = num_basic - 1
    R_surf = float(mantle_radii[-1])
    R_cmb = float(mantle_radii[0])

    # Basic nodes: uniform spacing from surface to CMB (descending r)
    r_b = np.linspace(R_surf, R_cmb, num_basic)
    # Staggered nodes: midpoints between consecutive basic nodes
    r_s = 0.5 * (r_b[:-1] + r_b[1:])

    # Interpolate Zalmoxis profiles onto node positions
    # mantle_radii is ascending, np.interp requires ascending xp
    P_b = np.interp(r_b, mantle_radii, mantle_pressure)
    rho_b = np.interp(r_b, mantle_radii, mantle_density)
    g_b = np.interp(r_b, mantle_radii, mantle_gravity)

    P_s = np.interp(r_s, mantle_radii, mantle_pressure)
    rho_s = np.interp(r_s, mantle_radii, mantle_density)
    g_s = np.interp(r_s, mantle_radii, mantle_gravity)

    # Negate gravity for SPIDER convention (inward-pointing, negative)
    g_b = -np.abs(g_b)
    g_s = -np.abs(g_s)

    # Write mesh file
    mesh_path = os.path.join(outdir, 'data', 'spider_mesh.dat')
    with open(mesh_path, 'w') as f:
        f.write(f'# {num_basic} {num_staggered}\n')
        for i in range(num_basic):
            f.write(f'{r_b[i]:.15e} {P_b[i]:.15e} {rho_b[i]:.15e} {g_b[i]:.15e}\n')
        for i in range(num_staggered):
            f.write(f'{r_s[i]:.15e} {P_s[i]:.15e} {rho_s[i]:.15e} {g_s[i]:.15e}\n')

    log.info(
        'Wrote SPIDER mesh file: %s (%d basic + %d staggered nodes)',
        mesh_path,
        num_basic,
        num_staggered,
    )

    return mesh_path

read_ps_cache_pointer(outdir)

Return the shared PS-cache table directory recorded for outdir.

Reads the pointer written by :func:_write_ps_cache_pointer. Used by the resume path to locate PROTEUS_PS_CACHE_DIR tables that live outside the run directory.

Parameters:

Name Type Description Default
outdir str

The run output directory.

required

Returns:

Type Description
str or None

The recorded table directory, or None when the pointer is absent, unreadable, or empty.

Source code in src/proteus/interior_struct/zalmoxis.py
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
def read_ps_cache_pointer(outdir: str) -> str | None:
    """Return the shared PS-cache table directory recorded for `outdir`.

    Reads the pointer written by :func:`_write_ps_cache_pointer`. Used by
    the resume path to locate PROTEUS_PS_CACHE_DIR tables that live outside
    the run directory.

    Parameters
    ----------
    outdir : str
        The run output directory.

    Returns
    -------
    str or None
        The recorded table directory, or None when the pointer is absent,
        unreadable, or empty.
    """

    pointer = os.path.join(outdir, 'data', PS_CACHE_POINTER_NAME)
    if not os.path.isfile(pointer):
        return None
    try:
        with open(pointer) as f:
            cache_dir = f.read().strip()
    except OSError:
        return None
    return cache_dir or None

generate_spider_tables(config, outdir)

Generate P-S EOS tables and phase boundaries from PALEOS data.

Produces P-S lookup tables for density, temperature, heat capacity, thermal expansion, and adiabatic gradient, plus solidus/liquidus phase boundaries in S(P) format. These are consumed by the entropy-IC verify in Aragog (and by SPIDER if the structure module is SPIDER).

Supports two PALEOS layouts:

  1. paleos_unified (e.g. PALEOS:MgSiO3): the structural backbone is the single unified P-T table covering both phases plus mushy zone, while the per-phase property surfaces are built from the sibling two-phase solid + liquid tables, so the densities stay resolved across the melting-curve discontinuity. The solidus is derived from mushy_zone_factor * liquidus (default 0.8, the constant Stixrude 2014 solidus/liquidus ratio applied to the PALEOS liquidus); the liquidus is the analytic PALEOS Belonoshko+2005 / Fei+2021 curve.
  2. PALEOS-2phase:<solid> (e.g. PALEOS-2phase:MgSiO3): separate solid + liquid PALEOS tables. The solidus is derived exactly as in the unified layout, mushy_zone_factor * liquidus (default 0.8); the two-phase tables additionally supply the latent-heat entropy gap between the liquid-table entropy at the liquidus and the solid-table entropy at the derived solidus.

For non-PALEOS EOS types (WolfBower2018, RTPress100TPa), returns None and the caller is expected to fall back on pre-existing SPIDER tables. A PALEOS mantle with a missing table raises instead.

Parameters:

Name Type Description Default
config Config

Configuration object with struct.zalmoxis settings.

required
outdir str

Output directory. Tables are written to outdir/data/spider_eos/, or, when the PROTEUS_PS_CACHE_DIR environment variable is set, to a subdirectory of it named after the sanitised :func:_ps_cache_key string, which independent runs with the same key share.

required

Returns:

Type Description
dict or None

Keys 'eos_dir', 'solidus_path', 'liquidus_path' with absolute paths. Returns None if the mantle EOS is not PALEOS.

Raises:

Type Description
ZalmoxisMissingEOSFilesError

When a table of a PALEOS mantle or its MgSiO3 2-phase pair is missing.

Source code in src/proteus/interior_struct/zalmoxis.py
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
def generate_spider_tables(config: Config, outdir: str):
    """Generate P-S EOS tables and phase boundaries from PALEOS data.

    Produces P-S lookup tables for density, temperature, heat capacity,
    thermal expansion, and adiabatic gradient, plus solidus/liquidus phase
    boundaries in S(P) format. These are consumed by the entropy-IC verify
    in Aragog (and by SPIDER if the structure module is SPIDER).

    Supports two PALEOS layouts:

    1. ``paleos_unified`` (e.g. ``PALEOS:MgSiO3``): the structural backbone is
       the single unified P-T table covering both phases plus mushy zone, while
       the per-phase property surfaces are built from the sibling two-phase
       solid + liquid tables, so the densities stay resolved across the melting-curve
       discontinuity. The solidus is derived from ``mushy_zone_factor *
       liquidus`` (default 0.8, the constant Stixrude 2014 solidus/liquidus
       ratio applied to the PALEOS liquidus); the liquidus is the analytic
       PALEOS Belonoshko+2005 / Fei+2021 curve.
    2. ``PALEOS-2phase:<solid>`` (e.g. ``PALEOS-2phase:MgSiO3``): separate
       solid + liquid PALEOS tables. The solidus is derived exactly as in the
       unified layout, ``mushy_zone_factor * liquidus`` (default 0.8); the
       two-phase tables additionally supply the latent-heat entropy gap
       between the liquid-table entropy at the liquidus and the solid-table
       entropy at the derived solidus.

    For non-PALEOS EOS types (WolfBower2018, RTPress100TPa), returns None
    and the caller is expected to fall back on pre-existing SPIDER tables.
    A PALEOS mantle with a missing table raises instead.

    Parameters
    ----------
    config : Config
        Configuration object with struct.zalmoxis settings.
    outdir : str
        Output directory. Tables are written to ``outdir/data/spider_eos/``, or,
        when the ``PROTEUS_PS_CACHE_DIR`` environment variable is set, to a
        subdirectory of it named after the sanitised :func:`_ps_cache_key` string, which
        independent runs with the same key share.

    Returns
    -------
    dict or None
        Keys ``'eos_dir'``, ``'solidus_path'``, ``'liquidus_path'`` with
        absolute paths. Returns None if the mantle EOS is not PALEOS.

    Raises
    ------
    ZalmoxisMissingEOSFilesError
        When a table of a PALEOS mantle or its MgSiO3 2-phase pair is missing.
    """
    from zalmoxis.eos_export import generate_spider_eos_tables, generate_spider_phase_boundaries
    from zalmoxis.melting_curves import (
        derive_solidus_from_liquidus,
        get_solidus_liquidus_functions,
    )

    mantle_eos = config.interior_struct.zalmoxis.mantle_eos

    # Use FWL_DATA paths (not ZALMOXIS_ROOT) for EOS file lookup
    mat_dicts = load_zalmoxis_material_dictionaries()
    key, eos_entry = energetics_entry(mantle_eos, mat_dicts)

    # A resumed run stays on the tables it started with; the key only feeds the warning.
    if config.params.resume:
        dropped = []
        resumed = _resumed_ps_tables(
            outdir,
            lambda: _ps_resume_key(config, key, eos_entry, mat_dicts),
            _ps_p_max(config),
            dropped,
        )
        if resumed is not None:
            return resumed

    if not eos_entry or key not in PALEOS_REGISTRY_KEYS:
        log.info(
            'Mantle EOS %s has no PALEOS table set; using pre-existing SPIDER tables.',
            mantle_eos,
        )
        return None
    if paleos_companion_keys(mantle_eos):
        check_zalmoxis_eos_files({'mantle': mantle_eos}, mat_dicts, paleos_companions=True)
    try:
        inputs = _ps_table_inputs(config, key, eos_entry, mat_dicts)
    except _NoPSTables as exc:
        log.log(exc.level, 'No PALEOS P-S tables: %s; using pre-existing SPIDER tables.', exc)
        return None
    eos_file, solid_eos, liquid_eos, is_twophase, P_max, cache_key = inputs
    if solid_eos and liquid_eos:
        log.info('Using PALEOS-2phase tables for entropy-IC table generation')
    nP = config.interior_struct.zalmoxis.lookup_nP
    nS = config.interior_struct.zalmoxis.lookup_nS
    # Tables dropped for a mass change were reported by _resumed_ps_tables.
    if config.params.resume and not dropped:
        log.warning(
            'Resumed run has no kept P-S entropy tables in %s or at its shared-cache '
            'pointer; it continues on the tables of the current key %s, built now if absent',
            os.path.join(outdir, 'data', 'spider_eos'),
            cache_key,
        )

    mzf = config.interior_struct.zalmoxis.mushy_zone_factor
    # Phase boundaries: PALEOS-liquidus is the analytic Belonoshko+2005 /
    # Fei+2021 Simon-Glatzel curve. The derived solidus is
    # T_solidus = T_liquidus * mushy_zone_factor for both layouts. A two-phase
    # table adds the latent-heat gap between liquid_table.s(P, T_liq) and
    # solid_table.s(P, T_sol) with T_sol = mushy_zone_factor * T_liq.
    _, liquidus_func = get_solidus_liquidus_functions(
        solidus_id='Stixrude14-solidus',  # unused, but API requires it
        liquidus_id='PALEOS-liquidus',
    )
    solidus_func = derive_solidus_from_liquidus(liquidus_func, mzf)
    if is_twophase:
        # This solidus_func also reaches Zalmoxis's own 2-phase structure
        # solve via load_zalmoxis_solidus_liquidus_functions, so mzf moves
        # nabla_ad there too, separately from the density blend below.
        log.info(
            'PALEOS-2phase phase boundaries: solidus = liquidus * %.2f '
            '(mushy_zone_factor); latent heat from 2-phase tables',
            mzf,
        )
    else:
        log.info(
            'PALEOS unified phase boundaries: solidus = liquidus * %.2f (mushy_zone_factor)',
            mzf,
        )

    # Table location: output/<run>/data/spider_eos, or with PROTEUS_PS_CACHE_DIR a
    # shared directory keyed by cache_key (fields in _ps_cache_key), so runs with
    # the same key reuse one slow full-resolution PALEOS P-S table.
    _ps_cache_root = os.environ.get('PROTEUS_PS_CACHE_DIR')
    if _ps_cache_root:
        _safe_key = cache_key.replace('.', 'p').replace('=', '-').replace('+', '')
        spider_eos_dir = os.path.join(_ps_cache_root, _safe_key)
        os.makedirs(spider_eos_dir, exist_ok=True)
        # The shared-cache tables live outside the run directory, so a resumed
        # run cannot find them via the per-run output/<run>/data/spider_eos
        # path. Leave a pointer so resume can follow the tables to the cache.
        _write_ps_cache_pointer(outdir, spider_eos_dir)
    else:
        spider_eos_dir = os.path.join(outdir, 'data', 'spider_eos')

    # Cache check: skip regeneration if tables exist and pressure range unchanged.
    # The pressure range depends on planet mass, which doesn't change during evolution.
    cache_marker = os.path.join(spider_eos_dir, '.cache_info.txt')
    if os.path.isfile(cache_marker):
        with open(cache_marker) as f:
            existing_key = f.read().strip()
        if existing_key == cache_key:
            # Tables are up to date. File names must match the writer in
            # zalmoxis.eos_export.generate_spider_phase_boundaries, which
            # emits solidus_P-S.dat / liquidus_P-S.dat.
            solidus_path = os.path.join(spider_eos_dir, 'solidus_P-S.dat')
            liquidus_path = os.path.join(spider_eos_dir, 'liquidus_P-S.dat')
            if os.path.isfile(solidus_path) and os.path.isfile(liquidus_path):
                log.info(
                    'Reusing cached PALEOS-derived P-S entropy tables (P_max=%.2e, %dx%d)',
                    P_max,
                    nP,
                    nS,
                )
                return {
                    'eos_dir': spider_eos_dir,
                    'solidus_path': solidus_path,
                    'liquidus_path': liquidus_path,
                }
        else:
            log.info(
                'Regenerating P-S entropy tables in %s: cache key %s does not match %s',
                spider_eos_dir,
                existing_key,
                cache_key,
            )

    # Choose where to generate. For a shared PROTEUS_PS_CACHE_DIR the tables are
    # written into a private staging directory on the same filesystem and then
    # published into spider_eos_dir with per-file atomic renames, so two cluster
    # runs that miss the cache marker at the same moment cannot interleave
    # partial writes into the shared table directory. For a per-run directory
    # there is no sharing, so tables are generated in place as before.
    if _ps_cache_root:
        gen_dir = tempfile.mkdtemp(prefix='.gen-', dir=os.path.dirname(spider_eos_dir))
    else:
        gen_dir = spider_eos_dir

    try:
        # Generate phase boundaries
        log.info(
            'Generating PALEOS-derived P-S phase boundaries (%d P points)...',
            nP,
        )
        generate_spider_phase_boundaries(
            solidus_func=solidus_func,
            liquidus_func=liquidus_func,
            eos_file=eos_file,
            P_range=(1e5, P_max),
            n_P=nP,
            output_dir=gen_dir,
            solid_eos_file=solid_eos,
            liquid_eos_file=liquid_eos,
        )

        # Generate full EOS tables
        log.info(
            'Generating PALEOS-derived P-S EOS tables (%d x %d)...',
            nP,
            nS,
        )
        generate_spider_eos_tables(
            eos_file=eos_file,
            solidus_func=solidus_func,
            liquidus_func=liquidus_func,
            P_range=(1e5, P_max),
            n_P=nP,
            n_S=nS,
            output_dir=gen_dir,
            solid_eos_file=solid_eos,
            liquid_eos_file=liquid_eos,
        )

        # Publish staged tables into the shared cache with atomic renames.
        if gen_dir != spider_eos_dir:
            _publish_ps_tables(gen_dir, spider_eos_dir)
    finally:
        if gen_dir != spider_eos_dir:
            shutil.rmtree(gen_dir, ignore_errors=True)

    # Write the cache marker last, atomically, so a concurrent reader only
    # trusts the directory once every table file is already in place.
    try:
        _atomic_write_text(cache_marker, cache_key)
    except OSError:
        pass

    # File names match the writer in zalmoxis.eos_export, which emits
    # solidus_P-S.dat / liquidus_P-S.dat; use the published locations.
    return {
        'eos_dir': spider_eos_dir,
        'solidus_path': os.path.join(spider_eos_dir, 'solidus_P-S.dat'),
        'liquidus_path': os.path.join(spider_eos_dir, 'liquidus_P-S.dat'),
    }

compute_structure_mass_desync(radii, density, mass_enclosed)

Relative divergence between the density-profile mass integral and the structure ODE accumulator total.

The Zalmoxis structure ODE accumulates the enclosed mass with an RK45 integrator (mass_enclosed[-1]). A direct trapezoid of the shell mass 4 pi r^2 rho over the converged (radii, density) profile is an independent estimate of the same total. The two agree only when the density Picard iteration and the structure ODE are fully co-converged; their relative divergence is the mass self-consistency diagnostic tracked for issue #68.

Parameters:

Name Type Description Default
radii array_like

Radial node positions from the converged structure solve [m].

required
density array_like

Density at each radial node [kg m-3].

required
mass_enclosed array_like

Cumulative enclosed mass from the structure ODE; the last element is the accumulator total [kg].

required

Returns:

Type Description
float

|trapezoid - accumulator| / accumulator, or 0.0 when the accumulator total is non-finite or non-positive (degenerate or empty profile), which keeps the metric defined for a failed structure solve.

Source code in src/proteus/interior_struct/zalmoxis.py
3063
3064
3065
3066
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
def compute_structure_mass_desync(radii, density, mass_enclosed) -> float:
    """Relative divergence between the density-profile mass integral and the
    structure ODE accumulator total.

    The Zalmoxis structure ODE accumulates the enclosed mass with an RK45
    integrator (``mass_enclosed[-1]``). A direct trapezoid of the shell mass
    ``4 pi r^2 rho`` over the converged ``(radii, density)`` profile is an
    independent estimate of the same total. The two agree only when the
    density Picard iteration and the structure ODE are fully co-converged;
    their relative divergence is the mass self-consistency diagnostic tracked
    for issue #68.

    Parameters
    ----------
    radii : array_like
        Radial node positions from the converged structure solve [m].
    density : array_like
        Density at each radial node [kg m-3].
    mass_enclosed : array_like
        Cumulative enclosed mass from the structure ODE; the last element is
        the accumulator total [kg].

    Returns
    -------
    float
        ``|trapezoid - accumulator| / accumulator``, or 0.0 when the
        accumulator total is non-finite or non-positive (degenerate or empty
        profile), which keeps the metric defined for a failed structure solve.
    """
    accumulator_total = float(mass_enclosed[-1])
    if not np.isfinite(accumulator_total) or accumulator_total <= 0.0:
        return 0.0
    r = np.asarray(radii, dtype=float)
    rho = np.asarray(density, dtype=float)
    shell_mass_trapezoid = float(np.trapezoid(4.0 * np.pi * r**2 * rho, r))
    return abs(shell_mass_trapezoid - accumulator_total) / accumulator_total

zalmoxis_solver(config, outdir, hf_row, num_spider_nodes=0, temperature_function=None, temperature_mode_override=None, temperature_arrays=None)

Run the Zalmoxis solver to compute the interior structure of a planet.

Parameters:

Name Type Description Default
config Config

Configuration object.

required
outdir str

Output directory where results will be saved.

required
hf_row dict

Dictionary containing volatile masses and other parameters.

required
num_spider_nodes int

Number of SPIDER basic nodes. If > 0, writes a SPIDER mesh file and returns its path as the second element of the return tuple.

0
temperature_function callable or None

External temperature function f(r, P) -> T in (m, Pa, K). When provided, bypasses Zalmoxis's internal temperature mode dispatch. Used to pass SPIDER/Aragog T(r) profiles in memory.

None
temperature_arrays tuple[ndarray, ndarray] or None

Explicit r-indexed (r_arr, T_arr) for the Zalmoxis JAX path. Consumed only when use_jax=True, the configured EOS pair can take the Zalmoxis JAX dispatch (a unified or 2-phase PALEOS mantle plus a unified PALEOS core; see :func:_zalmoxis_jax_structure_viable), and the solve is either dry (no VolatileProfile in play) or wet with a profile inside the Zalmoxis JAX wet envelope (see :func:_volatile_profile_jax_viable). In that case the external callable is withheld so the inner Picard converges on Zalmoxis' internal linear-T profile while the JAX RHS integrates against the arrays. For any other configuration the solve runs on the numpy path, which consumes temperature_function, and the callable is therefore passed through. See Zalmoxis' solve_structure_via_jax docstring for why both kwargs can be passed together.

None
temperature_mode_override str or None

Local override for config.planet.temperature_mode. Lets callers force a different structure-solve mode without mutating the shared Config object (see AGENTS.md, "Physics and coupling contract"). When None, the Config value is used. Currently used by determine_interior_radius_with_zalmoxis to force adiabatic for SPIDER coupling with a T-dependent mantle EOS.

None

Returns:

Name Type Description
cmb_radius float

Core-mantle boundary radius [m].

spider_mesh_file str or None

Path to the SPIDER mesh file, or None if num_spider_nodes == 0.

Source code in src/proteus/interior_struct/zalmoxis.py
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
3249
3250
3251
3252
3253
3254
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
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
def zalmoxis_solver(
    config: Config,
    outdir: str,
    hf_row: dict,
    num_spider_nodes: int = 0,
    temperature_function=None,
    temperature_mode_override: str | None = None,
    temperature_arrays=None,
):
    """Run the Zalmoxis solver to compute the interior structure of a planet.

    Parameters
    ----------
    config : Config
        Configuration object.
    outdir : str
        Output directory where results will be saved.
    hf_row : dict
        Dictionary containing volatile masses and other parameters.
    num_spider_nodes : int
        Number of SPIDER basic nodes. If > 0, writes a SPIDER mesh file
        and returns its path as the second element of the return tuple.
    temperature_function : callable or None, optional
        External temperature function ``f(r, P) -> T`` in (m, Pa, K).
        When provided, bypasses Zalmoxis's internal temperature mode
        dispatch. Used to pass SPIDER/Aragog T(r) profiles in memory.
    temperature_arrays : tuple[ndarray, ndarray] or None, optional
        Explicit r-indexed ``(r_arr, T_arr)`` for the Zalmoxis JAX path.
        Consumed only when ``use_jax=True``, the configured EOS pair
        can take the Zalmoxis JAX dispatch (a unified or 2-phase PALEOS
        mantle plus a unified PALEOS core; see
        :func:`_zalmoxis_jax_structure_viable`), and the solve is either
        dry (no ``VolatileProfile`` in play) or wet with a profile
        inside the Zalmoxis JAX wet envelope (see
        :func:`_volatile_profile_jax_viable`). In that case the
        external callable is withheld so the inner Picard converges on
        Zalmoxis' internal linear-T profile while the JAX RHS integrates
        against the arrays. For any other configuration the solve
        runs on the numpy path, which consumes ``temperature_function``,
        and the callable is therefore passed through. See Zalmoxis'
        ``solve_structure_via_jax`` docstring for why both kwargs can be
        passed together.
    temperature_mode_override : str or None, optional
        Local override for ``config.planet.temperature_mode``. Lets callers
        force a different structure-solve mode without mutating the shared
        Config object (see AGENTS.md, "Physics and coupling contract"). When None,
        the Config value is used. Currently used by
        ``determine_interior_radius_with_zalmoxis`` to force ``adiabatic``
        for SPIDER coupling with a T-dependent mantle EOS.

    Returns
    -------
    cmb_radius : float
        Core-mantle boundary radius [m].
    spider_mesh_file : str or None
        Path to the SPIDER mesh file, or None if ``num_spider_nodes == 0``.
    """

    # Load the Zalmoxis configuration parameters. Flag an external temperature
    # source so 'liquidus_super' skips re-solving the super-liquidus CMB anchor
    # on this call: an evolved T(r) (or the IC adiabat callable) drives the
    # structure here, so the anchor is discarded and reusing the last solved
    # value avoids the scan-and-bisection on every re-solve.
    external_temperature_source = (
        temperature_function is not None or temperature_arrays is not None
    )
    config_params = load_zalmoxis_configuration(
        config,
        hf_row,
        temperature_mode_override=temperature_mode_override,
        external_temperature_source=external_temperature_source,
    )

    # Build volatile profile from dissolved volatile masses (if available).
    # This enables phi(r)-weighted volatile blending inside the Zalmoxis ODE.
    # Skipped when dry_mantle=True: the structure solver then uses only
    # the canonical mantle EOS tables.
    mantle_eos = config.interior_struct.zalmoxis.mantle_eos
    if config.interior_struct.zalmoxis.dry_mantle:
        volatile_profile = None
        log.debug(
            'Structure solver: dry_mantle=True, skipping VolatileProfile '
            '(mantle EOS uses %s tables only).',
            mantle_eos,
        )
    else:
        volatile_profile = build_volatile_profile(hf_row, mantle_eos)

    # Configure global miscibility if enabled. The config gate rejects
    # global_miscibility at load time until the Zalmoxis pin supports
    # per-shell volatile profiles, so this branch is exercised only via
    # test doubles; it stays in place for when the gate lifts.
    if config.interior_struct.zalmoxis.global_miscibility and volatile_profile is not None:
        volatile_profile.global_miscibility = True
        # Initialize x_interior from current dissolved masses
        M_mantle = float(hf_row.get('M_mantle', 0.0))
        if M_mantle > 0:
            H2_kg_liquid = float(hf_row.get('H2_kg_liquid', 0.0))
            if H2_kg_liquid > 0:
                volatile_profile.x_interior['Chabrier:H'] = H2_kg_liquid / (
                    M_mantle + H2_kg_liquid
                )
            H2O_kg_liquid = float(hf_row.get('H2O_kg_liquid', 0.0))
            if H2O_kg_liquid > 0:
                volatile_profile.x_interior['PALEOS:H2O'] = H2O_kg_liquid / (
                    M_mantle + H2O_kg_liquid
                )

    # Extend mantle EOS string with volatile components so the LayerMixture
    # includes them (VolatileProfile overrides fractions at each radius).
    # Rebuild mushy_zone_factors afterward so a dissolved component (e.g.
    # PALEOS:H2O, Chabrier:H) gets the real mzf instead of the 1.0 default
    # from the dry EOS string load_zalmoxis_configuration saw.
    if volatile_profile is not None:
        config_params['layer_eos_config']['mantle'] = extend_mantle_eos_with_volatiles(
            config_params['layer_eos_config']['mantle'], volatile_profile
        )
        config_params['mushy_zone_factors'] = _build_mushy_zone_factors(
            config_params['layer_eos_config'],
            config.interior_struct.zalmoxis.mushy_zone_factor,
        )

    # Get the output location for Zalmoxis output and create the file if it does not exist
    output_zalmoxis = get_zalmoxis_output_filepath(outdir)
    open(output_zalmoxis, 'a').close()

    # JAX-path wall_timeout: Zalmoxis' default is 300 s, which is a
    # sanity cap. The bench (``bench_performance.py``) and the JAX
    # parity fixture override it to 3600 s because the first JAX call
    # on a cold JIT can incur compilation time on top of the solve.
    # Mirror that here when the caller opted into JAX, so a cold first
    # call does not fall into the best-solution branch and trip the
    # downstream array-write path.
    if config_params.get('use_jax') and 'wall_timeout' not in config_params:
        config_params['wall_timeout'] = 3600.0

    # Disable JAX for calls without temperature data across all outer solvers;
    # internal temperature mode converges differently. Keep Anderson as configured.
    if temperature_function is None and temperature_arrays is None:
        if config_params.get('use_jax'):
            log.debug(
                'Disabling use_jax for call without temperature profile; keeping use_anderson.'
            )
            config_params['use_jax'] = False

    # Run structure solve: use miscibility wrapper when enabled
    mat_dicts = load_zalmoxis_material_dictionaries()
    check_zalmoxis_eos_files(config_params['layer_eos_config'], mat_dicts)
    melt_funcs = load_zalmoxis_solidus_liquidus_functions(mantle_eos, config)
    input_data_dir = os.path.join(outdir, 'data')

    # Temperature-source dispatch for this call. temperature_arrays can be
    # consumed only by the Zalmoxis JAX inner path, which requires a
    # JAX-capable EOS layout (a unified or 2-phase PALEOS mantle plus a
    # unified PALEOS core) and, on wet solves, a VolatileProfile inside
    # the Zalmoxis JAX wet envelope (exactly one paleos_unified volatile
    # blended into the mantle; see _volatile_profile_jax_viable). Only in
    # that case is the external callable withheld: the JAX RHS integrates
    # against the arrays while the numpy Picard helper converges quickly
    # on Zalmoxis' internal linear-T profile (passing the callable there
    # lands Picard near PALEOS phase-boundary clamps and costs roughly
    # two orders of magnitude more wall time at the same JAX arrays). For
    # every other EOS configuration, and for wet solves whose profile
    # falls outside the envelope, the JAX dispatch declines and the numpy
    # ODE runs; that path consumes only the callable, so it must pass
    # through for the solve to follow the evolved T(r) instead of
    # rebuilding the internal temperature_mode profile from the hot
    # initial anchor.
    _use_jax_active = bool(config_params.get('use_jax'))
    _jax_viable = _zalmoxis_jax_structure_viable(
        mat_dicts, config.interior_struct.zalmoxis.core_eos, mantle_eos
    )
    # Surface a JAX->numpy fallback once from the PROTEUS side (see helper).
    if _use_jax_active and not _jax_viable:
        _log_jax_nonviable_once(config.interior_struct.zalmoxis.core_eos, mantle_eos)
    _wet_jax_viable = volatile_profile is None or _volatile_profile_jax_viable(
        volatile_profile, mat_dicts, config_params['layer_eos_config']['mantle']
    )
    if _use_jax_active and _jax_viable and volatile_profile is not None and not _wet_jax_viable:
        log.debug(
            'VolatileProfile falls outside the Zalmoxis JAX wet envelope; '
            'the structure solve stays on the numpy path with the callable.'
        )
    _drop_callable = (
        _use_jax_active and temperature_arrays is not None and _jax_viable and _wet_jax_viable
    )
    _tf_effective = None if _drop_callable else temperature_function
    if _drop_callable:
        log.debug(
            'Structure-solve T source: temperature_arrays via the Zalmoxis '
            'JAX path; external callable withheld for this call.'
        )
    elif temperature_function is not None:
        log.debug(
            'Structure-solve T source: external temperature_function '
            '(consumed by the numpy path).'
        )
    else:
        log.debug(
            'Structure-solve T source: internal %r mode dispatch.',
            config_params.get('temperature_mode'),
        )

    if config.interior_struct.zalmoxis.global_miscibility:
        from zalmoxis.solver import solve_miscible_interior

        # Build H2 mass targets from current volatile inventories
        h2_mass_targets = {}
        H2_kg_total = float(hf_row.get('H2_kg_total', 0.0))
        H2_kg_atm = float(hf_row.get('H2_kg_atm', 0.0))
        H2_kg_dissolved = H2_kg_total - H2_kg_atm
        if H2_kg_dissolved > 0:
            h2_mass_targets['Chabrier:H'] = H2_kg_dissolved

        H2O_kg_liquid = float(hf_row.get('H2O_kg_liquid', 0.0))
        if H2O_kg_liquid > 0:
            h2_mass_targets['PALEOS:H2O'] = H2O_kg_liquid

        model_results = solve_miscible_interior(
            config_params,
            material_dictionaries=mat_dicts,
            melting_curves_functions=melt_funcs,
            input_dir=input_data_dir,
            volatile_profile=volatile_profile,
            temperature_function=_tf_effective,
            temperature_arrays=temperature_arrays,
            h2_mass_targets=h2_mass_targets,
            max_iterations=config.interior_struct.zalmoxis.miscibility_max_iter,
            mass_tolerance=config.interior_struct.zalmoxis.miscibility_tol,
        )

        # Write solvus info to hf_row
        if model_results.get('solvus_radius') is not None:
            hf_row['R_solvus'] = model_results['solvus_radius']
            hf_row['T_solvus'] = model_results['solvus_temperature']
            hf_row['P_solvus'] = model_results['solvus_pressure']
        hf_row['X_H2_int'] = model_results.get('x_interior_converged', {}).get(
            'Chabrier:H', 0.0
        )

        log.info(
            'Global miscibility: solvus R=%.2e m, T=%.0f K, P=%.2e Pa, '
            'X_H2_int=%.4f, converged=%s (%d iters)',
            hf_row.get('R_solvus', 0.0),
            hf_row.get('T_solvus', 0.0),
            hf_row.get('P_solvus', 0.0),
            hf_row.get('X_H2_int', 0.0),
            model_results.get('miscibility_converged', False),
            model_results.get('miscibility_iterations', 0),
        )
    else:
        # _tf_effective carries the temperature-source decision hoisted
        # above: the callable is withheld only when the JAX inner path
        # will actually consume temperature_arrays (JAX-viable EOS
        # layout and, on wet solves, an in-envelope VolatileProfile);
        # on any other configuration the numpy path runs and the
        # callable passes through. Warm-starts
        # stay disabled on the JAX path: they drive Anderson into
        # oscillation and do not help otherwise, because the inner
        # Picard plateau at diff=0.1 is set by the lever-rule EOS kink,
        # not by initial density quality, so warm-start cannot collapse
        # the bail count.
        # Reuse the cached density profile as a Picard seed only when it
        # belongs to this same planet; otherwise start cold. Seeding never
        # changes the converged result, only the iteration count. The seed
        # and the central-pressure hint follow the temperature-source
        # dispatch: they are withheld only on the JAX-arrays path (where
        # warm-starts drive Anderson into oscillation) and applied on the
        # numpy path, where they cut the Newton iteration count for
        # repeated re-solves of the same planet.
        _seed_match = not _drop_callable and _density_cache.get('key') == _structure_cache_key(
            config
        )
        _seed_density = _density_cache['density'] if _seed_match else None
        _seed_radii = _density_cache['radii'] if _seed_match else None
        model_results = main(
            config_params,
            material_dictionaries=mat_dicts,
            melting_curves_functions=melt_funcs,
            input_dir=input_data_dir,
            volatile_profile=volatile_profile,
            temperature_function=_tf_effective,
            temperature_arrays=temperature_arrays,
            p_center_hint=None if _drop_callable else hf_row.get('P_center'),
            initial_density=_seed_density,
            initial_radii=_seed_radii,
        )

    # Extract results from the model
    radii = model_results['radii']
    density = model_results['density']
    gravity = model_results['gravity']
    pressure = model_results['pressure']
    temperature = model_results['temperature']
    mass_enclosed = model_results['mass_enclosed']
    cmb_mass = model_results['cmb_mass']
    core_mantle_mass = model_results['core_mantle_mass']
    converged = model_results['converged']
    converged_pressure = model_results['converged_pressure']
    converged_density = model_results['converged_density']
    converged_mass = model_results['converged_mass']

    # Adaptive retry: if the primary call did not converge, retry once with
    # relaxed tolerances. Retry fires on any non-converged result, including
    # the case where pressure, density, and mass flags are all False (e.g. a
    # timeout while the outer mass loop is still drifting), giving a clean
    # second attempt from fresh initial conditions; the wall_timeout cap
    # still bounds worst-case wall.
    #
    # If the primary's best_mass_error already exceeds 5 % the retry is
    # skipped entirely: at the structural-Picard plateau (7-10 %) looser
    # tolerance does not rescue a structurally-unsupported configuration.
    # Retry remains useful for transient flickers near the tolerance edge.
    primary_best_mass_error = model_results.get('best_mass_error')
    skip_retry_high_error = (
        primary_best_mass_error is not None and primary_best_mass_error > 0.05
    )
    if not converged and skip_retry_high_error:
        log.warning(
            'Zalmoxis primary call did not converge '
            '(pressure=%s, density=%s, mass=%s) AND best_mass_error=%.2e '
            '> 0.05; skipping retry (looser tolerance cannot rescue a '
            'structural-Picard plateau).',
            converged_pressure,
            converged_density,
            converged_mass,
            primary_best_mass_error,
        )
    if not converged and not skip_retry_high_error:
        retry_tol = config_params.get('tolerance_outer', 3e-3) * 3
        retry_iter = int(config_params.get('max_iterations_outer', 100) * 2)
        log.warning(
            'Zalmoxis primary call did not converge '
            '(pressure=%s, density=%s, mass=%s); retrying with relaxed '
            'tolerance (tol_outer=%.1e, max_iter=%d)',
            converged_pressure,
            converged_density,
            converged_mass,
            retry_tol,
            retry_iter,
        )
        config_params_retry = dict(config_params)
        config_params_retry['tolerance_outer'] = retry_tol
        config_params_retry['max_iterations_outer'] = retry_iter
        # Cap retry wall_timeout at 600 s. The JAX-path primary uses
        # 3600 s, which is appropriate for a successful first solve, but
        # the retry is a second-chance attempt under relaxed tolerances;
        # if it has not converged within 10 min of fresh outer iters it
        # is unlikely to succeed at any wall.
        config_params_retry['wall_timeout'] = 600.0

        # The retry copies use_jax unchanged, so the hoisted
        # temperature-source gate (_tf_effective) applies as-is.
        model_results = main(
            config_params_retry,
            material_dictionaries=mat_dicts,
            melting_curves_functions=melt_funcs,
            input_dir=input_data_dir,
            volatile_profile=volatile_profile,
            temperature_function=_tf_effective,
            temperature_arrays=temperature_arrays,
        )

        radii = model_results['radii']
        density = model_results['density']
        gravity = model_results['gravity']
        pressure = model_results['pressure']
        temperature = model_results['temperature']
        mass_enclosed = model_results['mass_enclosed']
        cmb_mass = model_results['cmb_mass']
        core_mantle_mass = model_results['core_mantle_mass']
        converged = model_results['converged']
        converged_pressure = model_results['converged_pressure']
        converged_density = model_results['converged_density']
        converged_mass = model_results['converged_mass']

        if converged:
            log.info('Zalmoxis converged on retry with relaxed tolerances')

    # Check convergence before proceeding. Non-converged solutions
    # (e.g. when EOS table range is exceeded) produce garbage values
    # that would corrupt the simulation state.
    if not converged:
        diag = (
            f'Zalmoxis did not converge: '
            f'pressure={converged_pressure}, density={converged_density}, '
            f'mass={converged_mass}. '
            f'Final M={mass_enclosed[-1]:.2e} kg, R={radii[-1]:.2e} m. '
            f'EOS: core={config.interior_struct.zalmoxis.core_eos}, '
            f'mantle={config.interior_struct.zalmoxis.mantle_eos}.'
        )
        log.error(diag)
        # Dump the exact arguments and the final model_results for offline
        # standalone replay. The pickle lands in <outdir>/data/, gitignored
        # via PROTEUS' default .gitignore. Numbered so multiple failures
        # within one run don't overwrite each other.
        try:
            import pickle
            import time as _ftime

            dump_dir = os.path.join(outdir, 'data')
            os.makedirs(dump_dir, exist_ok=True)
            stamp = int(_ftime.time())
            dump_path = os.path.join(dump_dir, f'zalmoxis_failure_{stamp}.pkl')
            r_arr_d, T_arr_d = (None, None)
            if temperature_arrays is not None:
                r_arr_d = np.asarray(temperature_arrays[0]).copy()
                T_arr_d = np.asarray(temperature_arrays[1]).copy()
            with open(dump_path, 'wb') as _fh:
                pickle.dump(
                    {
                        'config_params': dict(config_params),
                        'temperature_arrays': (r_arr_d, T_arr_d),
                        'hf_row_subset': {
                            k: hf_row[k]
                            for k in (
                                'P_center',
                                'M_int',
                                'R_int',
                                'T_magma',
                                'Phi_global',
                                'T_surf',
                            )
                            if k in hf_row
                        },
                        'model_results_keys': sorted(model_results.keys()),
                        'final_M': float(mass_enclosed[-1]),
                        'final_R': float(radii[-1]),
                        'best_mass_error': model_results.get('best_mass_error'),
                        'flags': {
                            'pressure': bool(converged_pressure),
                            'density': bool(converged_density),
                            'mass': bool(converged_mass),
                        },
                    },
                    _fh,
                    protocol=pickle.HIGHEST_PROTOCOL,
                )
            log.warning('Failure args dumped to %s', dump_path)
        except Exception as _dump_exc:
            log.warning('Failed to dump Zalmoxis failure args: %s', _dump_exc)
        raise RuntimeError(diag)

    # Extract the index of the core-mantle boundary mass in the mass array
    cmb_index = np.argmax(mass_enclosed >= cmb_mass)

    # Extract the planet radius and core-mantle boundary radius
    planet_radius = radii[-1]
    cmb_radius = radii[cmb_index]

    # Recompute density and temperature against the accurate T(r) when the
    # solve took the JAX+temperature_arrays path (_drop_callable). On that
    # path `temperature_function` is withheld so the numpy Picard converges
    # quickly using Zalmoxis' internal linear-T fallback. The JAX integrator
    # still uses `temperature_arrays` (Aragog's true T(r)) and produces
    # correct P(r), M(r), g(r), but `model_results` returns `density =
    # EOS(P, T_linear_fallback)` and `temperature = T_linear_fallback`
    # because those come from the Picard helper. Aragog later reads
    # `zalmoxis_output.dat` for mesh construction (`eos_method=2`), so a
    # stale density column would feed the wrong cell masses into its energy
    # evolution (~10% T-driven density error at the CMB in the
    # PALEOS-2phase melt regime). Recompute both columns here from
    # (P, T_aragog) using numpy EOS before any downstream consumer reads
    # them. When the callable was honored on the numpy path instead, the
    # solver's own columns already reflect the evolved T(r) and no rebuild
    # runs. Wet solves rebuild the mantle through the same per-shell blend
    # the numpy solver's density update evaluates (calculate_mixed_density
    # on the extended mantle mixture with the VolatileProfile at the local
    # melt fraction), so the written column keeps the dissolved-volatile
    # contribution instead of collapsing to the bare dry mantle EOS.
    if _drop_callable:
        from zalmoxis.eos.dispatch import calculate_density as _calc_rho

        # Wet path: the extended mantle mixture (primary silicate plus
        # profile-managed volatiles), parsed from the same EOS string the
        # solver parses, blended per shell by the profile.
        _mantle_mixture = None
        if volatile_profile is not None:
            from zalmoxis.mixing import calculate_mixed_density as _calc_rho_mixed
            from zalmoxis.mixing import parse_layer_components as _parse_mixture

            _mantle_mixture = _parse_mixture(config_params['layer_eos_config']['mantle'])

        _r_ref, _T_ref = temperature_arrays
        _T_ref_cmb = float(_T_ref[0])
        _core_eos = config.interior_struct.zalmoxis.core_eos
        _mantle_eos = config.interior_struct.zalmoxis.mantle_eos
        _mzf = config.interior_struct.zalmoxis.mushy_zone_factor
        _sol_f, _liq_f = (
            melt_funcs
            if isinstance(melt_funcs, tuple) and len(melt_funcs) == 2
            else (None, None)
        )
        _interp_cache: dict = {}
        _rho_fixed = np.zeros(len(radii))
        _T_fixed = np.zeros(len(radii))
        for _i in range(len(radii)):
            _r = float(radii[_i])
            _P = float(pressure[_i])
            # r-indexed T: below r_ref[0] (= first Aragog staggered node
            # near CMB), clamp to T_cmb; else interp along the Aragog grid.
            if _r <= float(_r_ref[0]):
                _T = _T_ref_cmb
            else:
                _T = float(np.interp(_r, _r_ref, _T_ref))
            _T_fixed[_i] = _T
            if _mantle_mixture is not None and _i >= cmb_index:
                # Wet mantle node: same evaluation as the numpy solver's
                # density update. calculate_mixed_density computes the
                # local melt fraction from the melting curves at this
                # node's (P, T) (lever rule in compute_melt_fraction) and
                # takes the per-component fractions from
                # volatile_profile.apply_to_mixture. The condensed and
                # binodal sigmoid parameters stay at the zalmoxis.mixing
                # defaults, the same values the solver resolves when
                # config_params carries no overrides (PROTEUS sets none).
                _rho = _calc_rho_mixed(
                    _P,
                    _T,
                    _mantle_mixture,
                    mat_dicts,
                    _sol_f,
                    _liq_f,
                    _interp_cache,
                    mushy_zone_factors=config_params.get('mushy_zone_factors'),
                    volatile_profile=volatile_profile,
                )
                if _rho is not None and not np.isfinite(_rho):
                    _rho = None
            else:
                _eos_here = _core_eos if _i < cmb_index else _mantle_eos
                _rho = _calc_rho(
                    _P,
                    mat_dicts,
                    _eos_here,
                    _T,
                    _sol_f,
                    _liq_f,
                    interpolation_functions=_interp_cache,
                    mushy_zone_factor=_mzf,
                )
            _rho_fixed[_i] = float(_rho) if _rho is not None else float(density[_i])
        density = _rho_fixed
        temperature = _T_fixed
        log.debug(
            'Rebuilt density/temperature against T_aragog (JAX path). '
            'density: CMB=%.1f kg/m^3, surface=%.1f kg/m^3. '
            'T: CMB=%.1f K, surface=%.1f K.',
            float(density[cmb_index]),
            float(density[-1]),
            float(temperature[cmb_index]),
            float(temperature[-1]),
        )

    # Calculate the average density of the planet using the calculated mass and radius
    average_density = mass_enclosed[-1] / (4 / 3 * np.pi * radii[-1] ** 3)

    # Mass self-consistency diagnostic (issue #68): record how far the density
    # profile's trapezoid mass integral diverges from the structure ODE
    # accumulator total, so the helpfile carries the desync as a quantified
    # per-run metric rather than only the pass/fail output-schema guard.
    hf_row['struct_mass_desync_frac'] = compute_structure_mass_desync(
        radii, density, mass_enclosed
    )
    log.debug(
        'Structure mass self-consistency desync: %.2e',
        hf_row['struct_mass_desync_frac'],
    )

    # Cache density for next call's Picard seeding. Applied on the numpy path
    # regardless of use_anderson, and withheld on the JAX-arrays path where
    # warm-starts drive Anderson into oscillation.
    _density_cache['density'] = density.copy()
    _density_cache['radii'] = np.asarray(radii).copy()
    _density_cache['key'] = _structure_cache_key(config)

    # Final results of the Zalmoxis interior model. One summary line at INFO so
    # a long coupled run stays readable across hundreds of re-solves; the
    # per-field breakdown drops to debug for when a single solve is inspected.
    log.info(
        'Zalmoxis interior solved: R=%.3f R_earth, dry M=%.3f M_earth, '
        'core R_frac=%.4f, converged=%s (P=%s, rho=%s, M=%s)',
        planet_radius / R_earth,
        mass_enclosed[-1] / M_earth,
        cmb_radius / planet_radius,
        converged,
        converged_pressure,
        converged_density,
        converged_mass,
    )
    log.debug(
        f'Interior (dry calculated mass) mass: {mass_enclosed[-1]} kg or approximately {mass_enclosed[-1] / M_earth:.2f} M_earth'
    )
    log.debug(
        f'Interior radius: {planet_radius:.2e} m or {planet_radius / R_earth:.2f} R_earth'
    )
    log.debug(f'Core radius: {cmb_radius:.2e} or {cmb_radius / R_earth:.2f} R_earth')
    log.debug(f'Core-mantle boundary mass: {mass_enclosed[cmb_index]:.2e} kg')
    log.debug(f'Mantle density at the core-mantle boundary: {density[cmb_index]:.2e} kg/m^3')
    log.debug(f'Core density at the core-mantle boundary: {density[cmb_index - 1]:.2e} kg/m^3')
    log.debug(f'Pressure at the core-mantle boundary: {pressure[cmb_index]:.2e} Pa')
    log.debug(f'Pressure at the center: {pressure[0]:.2e} Pa')
    log.debug(f'Average density: {average_density:.2e} kg/m^3')
    log.debug(
        f'Core-mantle boundary mass fraction: {mass_enclosed[cmb_index] / mass_enclosed[-1]:.3f}'
    )
    log.debug(f'Core radius fraction: {cmb_radius / planet_radius:.4f}')
    log.debug(
        f'Inner mantle radius fraction: {radii[np.argmax(mass_enclosed >= core_mantle_mass)] / planet_radius:.4f}'
    )
    log.debug(
        f'Overall Convergence Status: {converged} with Pressure: {converged_pressure}, Density: {converged_density}, Mass: {converged_mass}'
    )

    # Self-consistent initial thermal state (White+Li 2025, Boujibar+2020).
    # Honor temperature_mode_override here as well: the accretion thermal
    # state only runs when the user actually wants accretion mode, not
    # when SPIDER has forced a local adiabatic override.
    _effective_temp_mode = temperature_mode_override or config.planet.temperature_mode
    if _effective_temp_mode == 'accretion':
        from zalmoxis.energetics import initial_thermal_state

        cmf = config.interior_struct.core_frac
        mantle_eos = config.interior_struct.zalmoxis.mantle_eos

        # Build PALEOS-derived nabla_ad and C_p when PALEOS EOS is configured.
        # This uses the actual EOS tables for the adiabatic gradient and heat
        # capacities instead of the constant defaults (Gruneisen adiabat,
        # Dulong-Petit C_Fe=450, C_sil=1250 J/kg/K from White+Li 2025).
        nabla_ad_func = None
        cp_iron_func = None
        cp_silicate_func = None
        C_iron = 450.0
        C_silicate = 1250.0

        if 'PALEOS' in mantle_eos:
            try:
                import math

                from scipy.interpolate import LinearNDInterpolator
                from zalmoxis.eos.interpolation import load_paleos_unified_table

                # Get EOS file paths from the material dictionaries
                mat_dicts = load_zalmoxis_material_dictionaries()
                mantle_mat = mat_dicts.get(mantle_eos, {})
                core_mat = mat_dicts.get(config.interior_struct.zalmoxis.core_eos, {})

                # Build nabla_ad(P, T) from PALEOS MgSiO3 unified table
                mantle_file = mantle_mat.get('eos_file', '')
                if mantle_file and os.path.isfile(mantle_file):
                    _cache = load_paleos_unified_table(mantle_file)

                    def _paleos_nabla_ad(P_Pa, T_K, _c=_cache):
                        if P_Pa <= 0 or T_K <= 0:
                            return 0.3
                        lp = max(_c['logp_min'], min(math.log10(P_Pa), _c['logp_max']))
                        lt = max(_c['logt_min'], min(math.log10(T_K), _c['logt_max']))
                        try:
                            v = float(_c['nabla_ad_interp']([[lp, lt]])[0])
                            if np.isfinite(v) and v > 0:
                                return v
                        except Exception:
                            pass
                        return 0.3

                    nabla_ad_func = _paleos_nabla_ad
                    log.info('Using PALEOS nabla_ad(P,T) for initial thermal state adiabat')

                # Build C_p(P, T) interpolators from PALEOS tables for
                # mass-weighted integration over the radial structure
                def _build_cp_func(eos_file, fallback_cp):
                    """Build a C_p(P, T) interpolator from a PALEOS table."""
                    if not eos_file or not os.path.isfile(eos_file):
                        return None
                    _data = np.genfromtxt(eos_file, usecols=range(9), comments='#')
                    _P, _T, _cp = _data[:, 0], _data[:, 1], _data[:, 5]
                    _valid = (_P > 0) & np.isfinite(_cp) & (_cp > 0) & (_cp < 5000)
                    if np.sum(_valid) < 10:
                        return None
                    _lp = np.log10(_P[_valid])
                    _lt = np.log10(_T[_valid])
                    _interp = LinearNDInterpolator(list(zip(_lp, _lt)), _cp[_valid])

                    def _cp_func(P_Pa, T_K, _i=_interp, _fb=fallback_cp):
                        if P_Pa <= 0 or T_K <= 0:
                            return _fb
                        v = float(_i(math.log10(P_Pa), math.log10(T_K)))
                        if np.isfinite(v) and 0 < v < 5000:
                            return v
                        return _fb

                    return _cp_func

                core_file = core_mat.get('eos_file', '')
                cp_iron_func = _build_cp_func(core_file, C_iron)
                cp_silicate_func = _build_cp_func(mantle_file, C_silicate)

                if cp_iron_func is not None:
                    log.info('Using PALEOS C_p(P,T) for iron (mass-weighted integration)')
                if cp_silicate_func is not None:
                    log.info('Using PALEOS C_p(P,T) for silicate (mass-weighted integration)')

            except Exception as e:
                log.warning(
                    'Could not build PALEOS thermal properties: %s. Using constants.', e
                )

        thermal = initial_thermal_state(
            model_results,
            core_mass_fraction=cmf,
            T_radiative_eq=hf_row.get('T_eqm', 255.0),
            f_accretion=config.planet.f_accretion,
            f_differentiation=config.planet.f_differentiation,
            C_iron=C_iron,
            C_silicate=C_silicate,
            nabla_ad_func=nabla_ad_func,
            cp_iron_func=cp_iron_func,
            cp_silicate_func=cp_silicate_func,
        )
        hf_row['T_surf_accr'] = thermal['T_surf_accr']
        # Key consumed by Aragog setup_solver and _set_entropy_ic
        hf_row['T_surface_initial'] = thermal['T_surf_accr']
        hf_row['U_grav_diff'] = thermal['U_differentiated']
        hf_row['U_grav_undiff'] = thermal['U_undifferentiated']
        hf_row['DeltaT_accretion'] = thermal['Delta_T_accretion']
        hf_row['DeltaT_differentiation'] = thermal['Delta_T_differentiation']
        hf_row['DeltaT_adiabat'] = thermal['Delta_T_adiabat']
        hf_row['core_state_initial'] = thermal['core_state']

        # Store the adiabatic T(r) profile for interior solver initialization.
        # SPIDER/Aragog use this to set the initial temperature/entropy profile.
        hf_row['_initial_T_profile'] = thermal['T_profile']
        hf_row['_initial_T_radii'] = thermal['radii']
        hf_row['_initial_T_pressure'] = thermal['pressure']

        log.info(
            'Initial thermal state (White+Li 2025): T_CMB=%.0f K, '
            'T_surf_accr=%.0f K, DeltaT_G=%.0f K, DeltaT_D=%.0f K, '
            'DeltaT_ad=%.0f K, core=%s',
            thermal['T_cmb'],
            thermal['T_surf_accr'],
            thermal['Delta_T_accretion'],
            thermal['Delta_T_differentiation'],
            thermal['Delta_T_adiabat'],
            thermal['core_state'],
        )

    # Update the surface radius, interior radius, and mass in the hf_row
    hf_row['R_int'] = planet_radius
    hf_row['R_core'] = cmb_radius
    hf_row['M_int'] = mass_enclosed[-1]
    hf_row['M_core'] = mass_enclosed[cmb_index]
    hf_row['gravity'] = gravity[-1]

    if config.interior_energetics.module == 'boundary':
        # Boundary backend reads its initial potential and surface
        # temperatures off the freshly solved structure rather than off
        # the [interior_energetics.boundary] config block. Take the
        # uppermost-mantle node for T_magma and the radial surface
        # node for T_surf.
        hf_row['T_magma'] = temperature[-2]
        hf_row['T_surf'] = temperature[-1]
    hf_row['P_center'] = model_results.get('p_center')
    hf_row['P_cmb'] = float(pressure[cmb_index])
    # Expose the dry mass target Zalmoxis converged toward, so the
    # wrapper can enforce a mass-anchor contract
    # |M_int / M_int_target - 1| < _MASS_ANCHOR_TOL post-acceptance.
    # Zalmoxis' internal solver_tol_outer (default 3e-3) is a numerical
    # tolerance, not a coupling contract: it leaves room for ~0.3 % drift
    # between hf_row['M_int'] and the conserved planet mass. The wrapper
    # check tightens this to 1e-3 to satisfy the <0.1 % conservation
    # target for the 1-10 M_Earth coupling.
    hf_row['M_int_target'] = float(config_params.get('planet_mass', 0.0))

    # Self-consistent core density from Zalmoxis structure
    if cmb_radius > 0:
        hf_row['core_density'] = mass_enclosed[cmb_index] / (4.0 / 3.0 * np.pi * cmb_radius**3)
    else:
        hf_row['core_density'] = 0.0

    # Core heat capacity: when 'self', use Dulong-Petit for iron (~450 J/kg/K).
    # When numeric, use the config value directly.
    cfg_heatcap = config.interior_struct.core_heatcap
    hf_row['core_heatcap'] = 450.0 if cfg_heatcap == 'self' else float(cfg_heatcap)

    log.debug(f'Saving Zalmoxis output to {output_zalmoxis}')

    # Select mantle arrays (to match the mesh needed for Aragog)
    mantle_radii = radii[cmb_index:]
    mantle_pressure = pressure[cmb_index:]
    mantle_density = density[cmb_index:]
    mantle_gravity = gravity[cmb_index:]
    mantle_temperature = temperature[cmb_index:]

    # Scale mantle temperature to match Aragog temperature profile format
    mantle_temperature_scaled = scale_temperature_profile_for_aragog(
        config, mantle_radii, mantle_temperature
    )

    # Write temperature profile to a separate file for Aragog to read
    np.savetxt(
        os.path.join(outdir, 'data', 'zalmoxis_output_temp.txt'), mantle_temperature_scaled
    )

    # Scalar-g control knob: when
    # ``interior_energetics.aragog.scalar_gravity_override`` is True,
    # collapse the radial gravity array into a uniform scalar (the
    # surface value from hf_row['gravity']) for the files Aragog and
    # SPIDER both read. Aragog's per-node path at solver.reset() then
    # interpolates to that constant everywhere, giving a constant-gravity
    # interior structure.
    scalar_g_override = config.interior_energetics.aragog.scalar_gravity_override
    if scalar_g_override:
        g_scalar = float(hf_row.get('gravity', 9.81))
        mantle_gravity_out = np.full_like(mantle_gravity, g_scalar)
        log.info(
            'scalar_gravity_override=True: collapsing zalmoxis_output.dat + '
            'spider_mesh.dat gravity column to uniform %.4f m/s^2',
            g_scalar,
        )
    else:
        mantle_gravity_out = mantle_gravity

    # Backup the existing zalmoxis_output.dat before overwriting, so a
    # schema-violation raise can restore the last-good file. Without this,
    # the wrapper's fall-back path reverts hf_row but leaves the
    # just-written (failing-schema) file on disk, and the next Aragog
    # setup_or_update_solver crashes on EOS-vs-mesh inconsistency. The
    # .prev copy lives alongside the primary file.
    import shutil as _shutil

    _output_prev = output_zalmoxis + '.prev'
    if os.path.isfile(output_zalmoxis):
        try:
            _shutil.copy2(output_zalmoxis, _output_prev)
        except Exception as _exc:
            log.warning(
                'Could not backup %s before new write: %s',
                output_zalmoxis,
                _exc,
            )

    # Save final grids to the output file for the mantle for Aragog
    with open(output_zalmoxis, 'w') as f:
        for i in range(len(mantle_radii)):
            f.write(
                f'{mantle_radii[i]:.17e} {mantle_pressure[i]:.17e} {mantle_density[i]:.17e} {mantle_gravity_out[i]:.17e} {mantle_temperature[i]:.17e}\n'
            )

    # Schema check at the Zalmoxis -> Aragog file-handover boundary. On
    # violation: restore the .prev backup (so Aragog reads consistent
    # state on the next iteration via the wrapper's fall-back) and raise
    # RuntimeError.
    # Pass the structure's accurate mantle mass (accumulator total minus the
    # exact core-mass target) so the schema check does not re-integrate the
    # coarse output nodes with a grid trapezoid, which diverges from the RK45
    # accumulator by ~10% at high planet mass and false-rejects valid runs.
    mantle_mass_accumulator = float(mass_enclosed[-1]) - float(cmb_mass)
    try:
        validate_zalmoxis_output_schema(
            output_zalmoxis, hf_row, mantle_mass_ref=mantle_mass_accumulator
        )
    except RuntimeError:
        if os.path.isfile(_output_prev):
            try:
                _shutil.copy2(_output_prev, output_zalmoxis)
                log.warning(
                    'Schema violation: restored %s from %s before re-raise',
                    output_zalmoxis,
                    _output_prev,
                )
            except Exception as _restore_exc:
                log.warning(
                    'Schema violation: could not restore %s from %s: %s',
                    output_zalmoxis,
                    _output_prev,
                    _restore_exc,
                )
        raise

    # Determine SPIDER domain: [R_cmb, R_solvus] when global_miscibility is
    # enabled, otherwise [R_cmb, R_surface] (standard).
    spider_radii = mantle_radii
    spider_pressure = mantle_pressure
    spider_density = mantle_density
    spider_gravity = mantle_gravity

    R_solvus = solvus_radius(config, hf_row.get('R_solvus'), planet_radius, R_inner=cmb_radius)
    if R_solvus is not None:
        # Truncate arrays at the solvus: SPIDER only evolves the
        # miscible interior below the binodal surface
        solvus_mask = mantle_radii <= R_solvus * 1.001  # small tolerance
        if np.any(solvus_mask):
            spider_radii = mantle_radii[solvus_mask]
            spider_pressure = mantle_pressure[solvus_mask]
            spider_density = mantle_density[solvus_mask]
            spider_gravity = mantle_gravity[solvus_mask]
            log.info(
                'SPIDER domain truncated at solvus: R_solvus=%.3e m '
                '(%.2f R_earth), %d of %d shells',
                R_solvus,
                R_solvus / R_earth,
                len(spider_radii),
                len(mantle_radii),
            )

    # Write SPIDER mesh file if requested. Re-uses the possibly-collapsed
    # gravity array so the SPIDER path gets the same scalar-g override
    # behaviour when the flag is on.
    spider_mesh_file = None
    if num_spider_nodes > 0:
        if scalar_g_override:
            spider_gravity_out = np.full_like(
                spider_gravity, float(hf_row.get('gravity', 9.81))
            )
        else:
            spider_gravity_out = spider_gravity
        spider_mesh_file = write_spider_mesh_file(
            outdir,
            spider_radii,
            spider_pressure,
            spider_density,
            spider_gravity_out,
            num_spider_nodes,
        )

    return cmb_radius, spider_mesh_file