Skip to content

proteus.outgas.lid_seal

The melt inventory held under a closed crust, and its leak to the atmosphere down to the dissolved equilibrium.

For how this part works, see Volatiles held under a closed crust.

lid_seal

Volatiles held in the melt under a closed crust, and their leak to the atmosphere.

With outgas.lid_seal.enabled, each step after the initialisation stage tests whether a crust seals the mantle melt from the atmosphere: the crust is at least delta_close thick and the top mesh cell holds less melt than phi_close. The thickness is the Aragog sub-grid lid lid_delta while that lid is active (lid_weight > 0), and otherwise the depth of the top run of solid cells of the mesh. When the seal closes, after the chemistry solve of that step, the dissolved inventory moves from {x}_kg_liquid to {x}_kg_sealed and the magma temperature of that solve is kept as seal_Tmagma_close. While sealed, the chemistry is frozen, escape draws on the atmosphere alone, and each sealed species leaks to the atmosphere down to its dissolved equilibrium,

dM_i/dt = -(1/tau + k_i) max(M_i - M_eq,i, 0),    k_i = chi_d Mdot_c / R_i,
M_eq,i = X_eq,i(p) R_i,    R_i = M_melt,

with tau = tau_leak, Mdot_c = crust_rate and chi_d the degassing efficiency of Schaefer & Sasselov (2015, ApJ 801:40, Eq. 14), whose plate spreading term rho_m F_melt D_melt S is replaced by the crust production rate. The volcanic part is their chi_d Mdot_c X_melt,i with X_melt,i = M_i / R_i, limited here to the excess over the solubility, X_melt,i - X_eq,i, which their Eq. 14 does not have. X_eq,i is the CALLIOPE solubility law of the species at its partial pressure in the atmosphere, at the temperature and IW offset of the closing solve; a species without a law has M_eq = 0. With front trapping R_i also counts the crystals formed since closure at (1 - F_tl) D_i + F_tl, with the trapped melt fraction F_tl of the step that froze them, as trapping buries them. Gas does not dissolve back through the crust, so a species below its floor stays as it is. Each step takes the exponential step of the law with M_eq at the end state, since the leak raises the partial pressure that sets it; the step is exact for a constant M_eq and first order where it moves. The seal opens once the top cell holds phi_open or more melt, the crust is thinner than delta_open, or a giant impact remelts the mantle; the sealed mass then returns to the melt and the chemistry solve of the same step takes it.

The leaked gas enters the atmosphere as the species it was sealed as, with no chemistry solve: each species keeps the molar mass of its sealed moles, and the partial pressures follow from the masses as in CALLIOPE (P_surf = M_atm g / A with A = 4 pi R_int**2, partial pressures by mole fraction).

add_crystals(hf_row, hf_all)

Add the crystals of a held step under front trapping, as the open scheme buries them.

A step that freezes dM = trap_dM_RM [kg] at the trapped melt fraction F_tl = trap_F_tl adds (1 - F_tl) dM to the crystals seal_xtal_kg and F_tl dM to their trapped melt seal_tl_kg. A remelt returns the youngest crystals first: the burial ledger of the rows of hf_all from seal_t_close on is replayed to the melt fraction of the step. Raises ValueError if trap_dM_RM is not finite, trap_F_tl is not in [0, 1], or a remelt finds no row since seal_t_close.

Source code in src/proteus/outgas/lid_seal.py
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
def add_crystals(hf_row: dict, hf_all) -> None:
    """Add the crystals of a held step under front trapping, as the open scheme buries them.

    A step that freezes ``dM = trap_dM_RM`` [kg] at the trapped melt fraction
    ``F_tl = trap_F_tl`` adds ``(1 - F_tl) dM`` to the crystals ``seal_xtal_kg`` and
    ``F_tl dM`` to their trapped melt ``seal_tl_kg``. A remelt returns the youngest
    crystals first: the burial ledger of the rows of ``hf_all`` from ``seal_t_close``
    on is replayed to the melt fraction of the step. Raises ``ValueError`` if
    ``trap_dM_RM`` is not finite, ``trap_F_tl`` is not in [0, 1], or a remelt finds
    no row since ``seal_t_close``.
    """
    dm, f_tl = (float(hf_row.get(k, np.nan)) for k in ('trap_dM_RM', 'trap_F_tl'))
    if not (np.isfinite(dm) and 0.0 <= f_tl <= 1.0):
        raise ValueError(
            f'Lid seal: trap_dM_RM = {dm} kg or trap_F_tl = {f_tl} is not readable'
        )
    if dm > 0.0:
        hf_row['seal_xtal_kg'] += (1.0 - f_tl) * dm
        hf_row['seal_tl_kg'] += f_tl * dm
    elif dm < 0.0:
        t_close = float(hf_row.get('seal_t_close', np.nan))
        since = hf_all[hf_all['Time'] >= t_close]
        if since.empty:
            raise ValueError(f'Lid seal: no row since seal_t_close = {t_close} yr')
        held = since[list(CRYSTAL_COLUMNS)].to_numpy(dtype=float)
        phi = np.append(since['Phi_global'].to_numpy(dtype=float), float(hf_row['Phi_global']))
        layers = build_ledger(phi, np.vstack([held, held[-1:]]))
        hf_row['seal_xtal_kg'], hf_row['seal_tl_kg'] = map(float, ledger_total(layers, 2))

assert_sealed_row(hf_row)

Invariants of a sealed row: no melt inventory; sealed masses and crystals finite, >= 0.

Source code in src/proteus/outgas/lid_seal.py
589
590
591
592
593
594
595
596
597
598
def assert_sealed_row(hf_row: dict) -> None:
    """Invariants of a sealed row: no melt inventory; sealed masses and crystals finite, >= 0."""
    for k in CRYSTAL_COLUMNS:
        mass = float(hf_row.get(k, 0.0))
        _check(np.isfinite(mass) and mass >= 0.0, f'{k} = {mass} kg')
    for name in (*SEALED_SPECIES, *SEALED_ELEMENTS):
        sealed = float(hf_row.get(f'{name}_kg_sealed', 0.0))
        _check(np.isfinite(sealed) and sealed >= 0.0, f'{name}_kg_sealed = {sealed} kg')
        liquid = float(hf_row.get(f'{name}_kg_liquid', 0.0))
        _check(liquid == 0.0, f'{name}_kg_liquid = {liquid} kg while sealed')

clear_seal(hf_row)

Empty the sealed reservoir and zero every seal column, as a desiccation does.

Source code in src/proteus/outgas/lid_seal.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def clear_seal(hf_row: dict) -> None:
    """Empty the sealed reservoir and zero every seal column, as a desiccation does."""
    for n in (*SEALED_SPECIES, *SEALED_ELEMENTS):
        hf_row[f'{n}_kg_sealed'] = 0.0
    for n in SEALED_SPECIES:
        hf_row[f'{n}_mol_sealed'] = 0.0
    reset_step_columns(hf_row)
    for k in (
        'seal_active',
        'seal_path',
        'seal_delta',
        'seal_phi_top',
        'seal_xtal_kg',
        'seal_tl_kg',
    ):
        hf_row[k] = 0.0

close_seal(hf_row)

Move the dissolved inventory into the sealed reservoir; return the species kg moved.

Every column is checked before any mass moves, so a refused row is left as it was.

Source code in src/proteus/outgas/lid_seal.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def close_seal(hf_row: dict) -> float:
    """Move the dissolved inventory into the sealed reservoir; return the species kg moved.

    Every column is checked before any mass moves, so a refused row is left as it was.
    """
    names = (*SEALED_SPECIES, *SEALED_ELEMENTS)
    kg = {n: _checked(hf_row.get(f'{n}_kg_liquid', 0.0), f'{n}_kg_liquid') for n in names}
    mol = {
        n: _checked(hf_row.get(f'{n}_mol_liquid', 0.0), f'{n}_mol_liquid')
        for n in SEALED_SPECIES
    }
    for n in names:
        hf_row[f'{n}_kg_sealed'] = float(hf_row.get(f'{n}_kg_sealed', 0.0)) + kg[n]
        hf_row[f'{n}_kg_liquid'] = 0.0
    for n in SEALED_SPECIES:
        hf_row[f'{n}_mol_sealed'] = float(hf_row.get(f'{n}_mol_sealed', 0.0)) + mol[n]
        hf_row[f'{n}_mol_liquid'] = 0.0
    return sum(kg[n] for n in SEALED_SPECIES)

closure_state(config, hf_row, interior_o, path=0)

Crust thickness [m], top-cell melt fraction [1] and the path that gives them.

Path 2 is the Aragog sub-grid lid hf_row['lid_delta'], read while the lid is active (lid_weight > 0); path 1 is the mesh crust of :func:crust_thickness. An open seal (path = 0) reads the lid when it is active and the mesh crust below phi_solid otherwise. A closed seal keeps the path that closed it: a lid-closed seal reads its lid while it is active, and every other closed seal reads the mesh crust below phi_open. The mesh crust is 0 or whole cells, so that threshold is the band on the mesh.

Raises:

Type Description
KeyError

With an active sub-grid lid and no lid_delta in the row.

ValueError

If lid_weight, the thickness or the melt fraction is not finite.

Source code in src/proteus/outgas/lid_seal.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def closure_state(
    config: Config, hf_row: dict, interior_o, path: int = 0
) -> tuple[float, float, int]:
    """Crust thickness [m], top-cell melt fraction [1] and the path that gives them.

    Path 2 is the Aragog sub-grid lid ``hf_row['lid_delta']``, read while the lid is
    active (``lid_weight > 0``); path 1 is the mesh crust of :func:`crust_thickness`.
    An open seal (``path = 0``) reads the lid when it is active and the mesh crust
    below ``phi_solid`` otherwise. A closed seal keeps the path that closed it: a
    lid-closed seal reads its lid while it is active, and every other closed seal
    reads the mesh crust below ``phi_open``. The mesh crust is 0 or whole cells, so
    that threshold is the band on the mesh.

    Raises
    ------
    KeyError
        With an active sub-grid lid and no ``lid_delta`` in the row.
    ValueError
        If ``lid_weight``, the thickness or the melt fraction is not finite.
    """
    seal = config.outgas.lid_seal
    phi_top = float(np.asarray(interior_o.phi, dtype=float)[-1])
    weight = float(hf_row.get('lid_weight', 0.0))
    if not np.isfinite(weight):
        raise ValueError(f'Lid seal: lid_weight = {weight} is not finite')
    lid = weight > 0.0
    if lid and path in (PATH_OPEN, PATH_LID):
        if 'lid_delta' not in hf_row:
            raise KeyError('The lid seal needs lid_delta [m] while the sub-grid lid is active')
        delta, used = float(hf_row['lid_delta']), PATH_LID
    else:
        phi_crust = seal.phi_solid if path == PATH_OPEN else seal.phi_open_value
        delta, used = crust_thickness(interior_o.phi, interior_o.radius, phi_crust), PATH_MESH
    if not (np.isfinite(delta) and np.isfinite(phi_top)):
        raise ValueError(
            f'Lid seal: crust thickness {delta} m or top-cell melt fraction {phi_top} '
            'is not finite'
        )
    return delta, phi_top, used

crust_thickness(phi, radius, phi_solid)

Depth of the top run of solid mesh cells [m].

Parameters:

Name Type Description Default
phi ndarray

Melt fraction of the mesh cells [1], core to surface.

required
radius ndarray

Radii of the cell faces [m], core to surface, one more than phi.

required
phi_solid float

Melt fraction below which a cell counts as crust [1].

required

Returns:

Type Description
float

Surface radius minus the radius of the lower face of the lowest cell in the top contiguous run of cells with phi < phi_solid; 0 when the top cell is not solid.

Source code in src/proteus/outgas/lid_seal.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def crust_thickness(phi: np.ndarray, radius: np.ndarray, phi_solid: float) -> float:
    """Depth of the top run of solid mesh cells [m].

    Parameters
    ----------
    phi : numpy.ndarray
        Melt fraction of the mesh cells [1], core to surface.
    radius : numpy.ndarray
        Radii of the cell faces [m], core to surface, one more than ``phi``.
    phi_solid : float
        Melt fraction below which a cell counts as crust [1].

    Returns
    -------
    float
        Surface radius minus the radius of the lower face of the lowest cell in
        the top contiguous run of cells with ``phi < phi_solid``; 0 when the top
        cell is not solid.
    """
    phi = np.asarray(phi, dtype=float)
    radius = np.asarray(radius, dtype=float)
    if radius.size != phi.size + 1 or phi.size == 0:
        raise ValueError(
            f'crust_thickness needs one more face than cells: {radius.size} faces, '
            f'{phi.size} cells'
        )
    if not np.all(np.diff(radius) > 0.0):
        raise ValueError('crust_thickness needs face radii that increase from core to surface')
    liquid = np.flatnonzero(~(phi < phi_solid))
    base = liquid[-1] + 1 if liquid.size else 0
    return float(radius[-1] - radius[base])

equilibrium_fractions(config, bar, p_tot, temp, fo2_shift)

Dissolved mass fraction X_eq,i [1] of each species of soluble_gases.

The laws and arguments of the CALLIOPE solve: H2O (Sossi et al. 2023), CO2 (Dixon et al. 1995) at temp [K], CO (Armstrong et al. 2015) and CH4 (Ardia et al. 2013) at the total pressure p_tot [bar], N2 (Dasgupta et al. 2022) and S2 (Gaillard et al. 2022) at temp and the IW offset fo2_shift [log10], and the noble gases by Henry's law (Jambon et al. 1986), each at its partial pressure in bar [bar]. CO, CH4 and the noble gases dissolve only where outgas.calliope.include_* is set, and every fraction is 0 with outgas.calliope.solubility off. Below S2_CUTOFF, where the CALLIOPE S2 law returns 0, the S2 fraction follows the same square-root law in its partial pressure, so the floor stays continuous.

Source code in src/proteus/outgas/lid_seal.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def equilibrium_fractions(
    config: Config, bar: dict, p_tot: float, temp: float, fo2_shift: float
) -> dict:
    """Dissolved mass fraction ``X_eq,i`` [1] of each species of ``soluble_gases``.

    The laws and arguments of the CALLIOPE solve: H2O (Sossi et al. 2023), CO2
    (Dixon et al. 1995) at ``temp`` [K], CO (Armstrong et al. 2015) and CH4
    (Ardia et al. 2013) at the total pressure ``p_tot`` [bar], N2 (Dasgupta et
    al. 2022) and S2 (Gaillard et al. 2022) at ``temp`` and the IW offset
    ``fo2_shift`` [log10], and the noble gases by Henry's law (Jambon et al.
    1986), each at its partial pressure in ``bar`` [bar]. CO, CH4 and the noble
    gases dissolve only where ``outgas.calliope.include_*`` is set, and every
    fraction is 0 with ``outgas.calliope.solubility`` off. Below
    ``S2_CUTOFF``, where the CALLIOPE S2 law returns 0, the S2 fraction follows
    the same square-root law in its partial pressure, so the floor stays continuous.
    """
    calliope = config.outgas.calliope
    x = dict.fromkeys(soluble_gases, 0.0)
    if not calliope.solubility:
        return x
    args = {'CO2': (temp,), 'CO': (p_tot,), 'CH4': (p_tot,), 'N2': (p_tot, temp, fo2_shift)}
    args['S2'] = (temp, fo2_shift)
    for s in soluble_gases:  # every law is 0 at p = 0, where the CO law warns
        p = bar[s]
        if calliope.is_included(s) and p > 0.0:
            q = max(p, S2_CUTOFF) if s == 'S2' else p
            x[s] = 1e-6 * float(_LAW[s](q, *args.get(s, ()))) * np.sqrt(p / q)
    return x

floor_leak(mass, frac, floor_of)

Leak [kg] of one sealed species over a step toward the floor of its end state.

Solves L = frac max(mass - floor_of(L), 0) with frac = 1 - exp(-lam dt), the exact step of dM/dt = -lam max(M - M_eq, 0) for a constant M_eq, with M_eq = floor_of(L) [kg] taken at the state after the leak L. The residual is <= 0 at L = 0 and >= 0 at L = frac mass, so the root is bracketed for any continuous floor. Raises ValueError on a floor that is negative or not finite.

Source code in src/proteus/outgas/lid_seal.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def floor_leak(mass: float, frac: float, floor_of) -> float:
    """Leak [kg] of one sealed species over a step toward the floor of its end state.

    Solves ``L = frac max(mass - floor_of(L), 0)`` with ``frac = 1 - exp(-lam dt)``,
    the exact step of ``dM/dt = -lam max(M - M_eq, 0)`` for a constant ``M_eq``,
    with ``M_eq = floor_of(L)`` [kg] taken at the state after the leak ``L``. The
    residual is <= 0 at ``L = 0`` and >= 0 at ``L = frac mass``, so the root is
    bracketed for any continuous floor. Raises ``ValueError`` on a floor that is
    negative or not finite.
    """
    floor = floor_of(0.0)
    if not (np.isfinite(floor) and floor >= 0.0):
        raise ValueError(
            f'Lid seal: dissolved equilibrium {floor} kg is negative or not finite'
        )
    if floor >= mass:
        return 0.0
    return brentq(
        lambda leak: leak - frac * max(mass - floor_of(leak), 0.0),
        0.0,
        frac * mass,
        xtol=1e-300,
        rtol=4.0 * np.finfo(float).eps,
        maxiter=200,
    )

leak_rates(config, hf_row, dt)

Relaxation rate and volcanic rate per sealed species [yr-1].

Parameters:

Name Type Description Default
config Config

Model configuration; reads outgas.lid_seal, outgas.trap_mode and outgas.D_const_*.

required
hf_row dict

Row with M_mantle [kg] and Phi_global [1].

required
dt float

Step length [yr].

required

Returns:

Name Type Description
rates dict

{species: (1 / tau, k_i)} [yr-1].

mdot float

Crust production rate applied over the step [kg yr-1].

capped bool

Whether crust_rate dt exceeded the melt mass and was cut to it.

Raises:

Type Description
ValueError

If M_mantle or Phi_global is not finite.

Source code in src/proteus/outgas/lid_seal.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def leak_rates(config: Config, hf_row: dict, dt: float) -> tuple[dict, float, bool]:
    """Relaxation rate and volcanic rate per sealed species [yr-1].

    Parameters
    ----------
    config : Config
        Model configuration; reads ``outgas.lid_seal``, ``outgas.trap_mode`` and
        ``outgas.D_const_*``.
    hf_row : dict
        Row with ``M_mantle`` [kg] and ``Phi_global`` [1].
    dt : float
        Step length [yr].

    Returns
    -------
    rates : dict
        ``{species: (1 / tau, k_i)}`` [yr-1].
    mdot : float
        Crust production rate applied over the step [kg yr-1].
    capped : bool
        Whether ``crust_rate dt`` exceeded the melt mass and was cut to it.

    Raises
    ------
    ValueError
        If ``M_mantle`` or ``Phi_global`` is not finite.
    """
    seal = config.outgas.lid_seal
    reservoir, phi, m_melt = reservoirs(config, hf_row)
    mdot = float(seal.crust_rate) if phi >= seal.phi_solid else 0.0
    capped = mdot * dt > m_melt
    if capped:
        mdot = m_melt / dt
    inv_tau = 1.0 / float(seal.tau_leak)
    rates = {}
    for s in SEALED_SPECIES:
        k = seal.chi_d * mdot / reservoir[s] if mdot > 0.0 else 0.0
        rates[s] = (inv_tau, k)
    return rates, mdot, capped

leak_step(config, hf_row, dt)

Advance the sealed reservoir by dt [yr] toward its dissolved equilibrium.

Each species follows dM/dt = -(1/tau + k_i) max(M - M_eq, 0) in the exponential step with M_eq taken at the end state (:func:floor_leak). The leaked mass splits into its relaxation and volcanic parts in the ratio (1/tau) : k_i. Each element of a species leaves in the same mass fraction of its sealed total as the species weights of that element give, so the element and species ledgers stay apart from the stoichiometry of the chemistry that filled them.

Source code in src/proteus/outgas/lid_seal.py
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
def leak_step(config: Config, hf_row: dict, dt: float) -> None:
    """Advance the sealed reservoir by ``dt`` [yr] toward its dissolved equilibrium.

    Each species follows ``dM/dt = -(1/tau + k_i) max(M - M_eq, 0)`` in the
    exponential step with ``M_eq`` taken at the end state (:func:`floor_leak`).
    The leaked mass splits into its relaxation and volcanic parts in the ratio
    ``(1/tau) : k_i``. Each element of a species leaves in the same mass fraction
    of its sealed total as the species weights of that element give, so the
    element and species ledgers stay apart from the stoichiometry of the
    chemistry that filled them.
    """
    rates, mdot, capped = leak_rates(config, hf_row, dt)
    before = {s: float(hf_row.get(f'{s}_kg_sealed', 0.0)) for s in SEALED_SPECIES}
    lam = {s: sum(rates[s]) for s in SEALED_SPECIES}
    frac = {
        s: -np.expm1(-dt * lam[s]) for s in SEALED_SPECIES if before[s] > 0.0 and lam[s] > 0.0
    }
    leak = _leaks(config, hf_row, before, frac) if frac else {}
    tau_part, volc_part = dict.fromkeys(SEALED_SPECIES, 0.0), dict.fromkeys(SEALED_SPECIES, 0.0)
    with np.errstate(over='ignore', invalid='ignore'):  # the check below stops an overflow
        for s, out in leak.items():
            if out > 0.0:
                tau_part[s], volc_part[s] = (
                    out * rates[s][0] / lam[s],
                    out * rates[s][1] / lam[s],
                )
    _check(
        all(np.isfinite(out + tau_part[s] + volc_part[s]) for s, out in leak.items()),
        'the leak is not finite; tau_leak is too short',
    )
    hf_row['seal_crust_rate'], hf_row['seal_volc_capped'] = mdot, float(capped)
    for s, out in leak.items():
        if out <= 0.0:
            continue
        mol = float(hf_row.get(f'{s}_mol_sealed', 0.0))
        moved = mol * (out / before[s])
        hf_row[f'{s}_kg_sealed'] = before[s] - out
        hf_row[f'{s}_mol_sealed'] = mol - moved
        hf_row[f'{s}_kg_atm'] = float(hf_row.get(f'{s}_kg_atm', 0.0)) + out
        hf_row[f'{s}_mol_atm'] = float(hf_row.get(f'{s}_mol_atm', 0.0)) + moved

    leak_kg = sum(tau_part[g] + volc_part[g] for g in noble_gases)
    for g in noble_gases:
        hf_row[f'{g}_kg_leak_tau'], hf_row[f'{g}_kg_leak_volc'] = tau_part[g], volc_part[g]
    for e, weights in _WEIGHTS.items():
        sealed_e = float(hf_row.get(f'{e}_kg_sealed', 0.0))
        held = sum(w * before[s] for s, w in weights.items())
        share = sealed_e / held if held > 0.0 else 0.0
        by_tau = share * sum(w * tau_part[s] for s, w in weights.items())
        by_volc = share * sum(w * volc_part[s] for s, w in weights.items())
        out = by_tau + by_volc
        hf_row[f'{e}_kg_leak_tau'], hf_row[f'{e}_kg_leak_volc'] = by_tau, by_volc
        hf_row[f'{e}_kg_sealed'] = max(sealed_e - out, 0.0)
        hf_row[f'{e}_kg_atm'] = float(hf_row.get(f'{e}_kg_atm', 0.0)) + out
        leak_kg += out
    _check(np.isfinite(leak_kg), f'the element leak of {leak_kg} kg is not finite')
    hf_row['seal_leak_kg_cum'] = float(hf_row.get('seal_leak_kg_cum', 0.0)) + leak_kg
    if leak_kg > 0.0:
        _refresh_atmosphere(hf_row)
    if frac and config.outgas.calliope.solubility:
        _check_floors(config, hf_row, before, leak, frac)

open_seal(hf_row)

Return the sealed inventory to the melt; return the species kg moved.

Every column is checked before any mass moves, so a refused row is left as it was. The crystals since closure, seal_xtal_kg and seal_tl_kg, are zeroed.

Source code in src/proteus/outgas/lid_seal.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def open_seal(hf_row: dict) -> float:
    """Return the sealed inventory to the melt; return the species kg moved.

    Every column is checked before any mass moves, so a refused row is left as it was.
    The crystals since closure, ``seal_xtal_kg`` and ``seal_tl_kg``, are zeroed.
    """
    names = (*SEALED_SPECIES, *SEALED_ELEMENTS)
    kg = {n: _checked(hf_row.get(f'{n}_kg_sealed', 0.0), f'{n}_kg_sealed') for n in names}
    mol = {
        n: _checked(hf_row.get(f'{n}_mol_sealed', 0.0), f'{n}_mol_sealed')
        for n in SEALED_SPECIES
    }
    for n in names:
        hf_row[f'{n}_kg_liquid'] = float(hf_row.get(f'{n}_kg_liquid', 0.0)) + kg[n]
        hf_row[f'{n}_kg_sealed'] = 0.0
    for n in SEALED_SPECIES:
        hf_row[f'{n}_mol_liquid'] = float(hf_row.get(f'{n}_mol_liquid', 0.0)) + mol[n]
        hf_row[f'{n}_mol_sealed'] = 0.0
    hf_row['seal_xtal_kg'] = hf_row['seal_tl_kg'] = 0.0
    hf_row['seal_open_kg'] = sum(kg[n] for n in SEALED_SPECIES)
    return hf_row['seal_open_kg']

reservoirs(config, hf_row)

Reservoir R_i [kg] of each sealed species.

Without trapping R_i = M_melt, the reservoir of the open solve. With outgas.trap_mode = 'front' the solid formed after closure also holds the species, as the open front scheme buries it: R_i = M_melt + D_i M_xtal + M_tl with the crystals M_xtal = seal_xtal_kg and their trapped melt M_tl = seal_tl_kg (:func:add_crystals), so a step that froze dM at the trapped melt fraction F_tl adds [(1 - F_tl) D_i + F_tl] dM. The held mass takes one melt concentration over the whole reservoir. Returns the reservoirs, the global melt fraction clipped to [0, 1] and the melt mass [kg]. Raises ValueError if M_mantle or Phi_global is not finite, or under front trapping if a crystal column is not a finite mass >= 0.

Source code in src/proteus/outgas/lid_seal.py
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
def reservoirs(config: Config, hf_row: dict) -> tuple[dict, float, float]:
    """Reservoir ``R_i`` [kg] of each sealed species.

    Without trapping ``R_i = M_melt``, the reservoir of the open solve. With
    ``outgas.trap_mode = 'front'`` the solid formed after closure also holds the
    species, as the open front scheme buries it: ``R_i = M_melt + D_i M_xtal + M_tl``
    with the crystals ``M_xtal = seal_xtal_kg`` and their trapped melt
    ``M_tl = seal_tl_kg`` (:func:`add_crystals`), so a step that froze ``dM`` at the
    trapped melt fraction ``F_tl`` adds ``[(1 - F_tl) D_i + F_tl] dM``. The held mass
    takes one melt concentration over the whole reservoir. Returns the
    reservoirs, the global melt fraction clipped to [0, 1] and the melt mass [kg].
    Raises ``ValueError`` if ``M_mantle`` or ``Phi_global`` is not finite, or under
    front trapping if a crystal column is not a finite mass >= 0.
    """
    m_mantle, phi = float(hf_row['M_mantle']), float(hf_row['Phi_global'])
    for key, value in (('M_mantle', m_mantle), ('Phi_global', phi)):
        if not np.isfinite(value):
            raise ValueError(f'Lid seal: {key} = {value} is not finite')
    phi = min(max(phi, 0.0), 1.0)
    m_melt = phi * m_mantle
    if config.outgas.trap_mode != 'front':
        return dict.fromkeys(SEALED_SPECIES, m_melt), phi, m_melt
    xtal, tl = _crystal_masses(hf_row)
    d = {s: float(getattr(config.outgas, f'D_const_{s}', 0.0)) for s in SEALED_SPECIES}
    return {s: m_melt + d[s] * xtal + tl for s in SEALED_SPECIES}, phi, m_melt

reset_step_columns(hf_row)

Zero the per-step seal columns before a step writes them, and after a desiccation.

Source code in src/proteus/outgas/lid_seal.py
686
687
688
689
690
691
692
693
694
695
def reset_step_columns(hf_row: dict) -> None:
    """Zero the per-step seal columns before a step writes them, and after a desiccation."""
    hf_row['seal_open_kg'] = 0.0
    hf_row['seal_crust_rate'] = 0.0
    hf_row['seal_volc_capped'] = 0.0
    for e in LEAK_ELEMENTS:
        hf_row[f'{e}_kg_leak_tau'] = 0.0
        hf_row[f'{e}_kg_leak_volc'] = 0.0
    for s in soluble_gases:
        hf_row[f'{s}_kg_eq'] = 0.0

restore_seal_state(config, hf_row)

Whether a resumed run starts sealed, from seal_active of its last row.

With the seal off and nothing held, a stale flag and path in the row are zeroed.

Raises:

Type Description
ValueError

If the flag, the path or a sealed mass is not readable, if a sealed row has no closing temperature seal_Tmagma_close > 0 K or, under front trapping, no finite crystal masses seal_xtal_kg and seal_tl_kg

= 0 kg, or both at 0 below its closing melt fraction seal_phi_close or with a melt fraction that is not finite (a resume reads missing seal_ columns as 0 before this check, so a zero-filled seal_phi_close turns it off), or no closing time seal_t_close > 0 yr, if the row holds sealed mass under an open flag, or if it holds sealed mass with the seal off, since nothing could open it then.

Source code in src/proteus/outgas/lid_seal.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def restore_seal_state(config: Config, hf_row: dict) -> bool:
    """Whether a resumed run starts sealed, from ``seal_active`` of its last row.

    With the seal off and nothing held, a stale flag and path in the row are zeroed.

    Raises
    ------
    ValueError
        If the flag, the path or a sealed mass is not readable, if a sealed row
        has no closing temperature ``seal_Tmagma_close`` > 0 K or, under front
        trapping, no finite crystal masses ``seal_xtal_kg`` and ``seal_tl_kg``
        >= 0 kg, or both at 0 below its closing melt fraction ``seal_phi_close`` or
        with a melt fraction that is not finite (a resume reads missing ``seal_``
        columns as 0 before this check, so a zero-filled ``seal_phi_close`` turns
        it off), or no closing time ``seal_t_close`` > 0 yr, if the row holds
        sealed mass under an open flag, or if it holds sealed mass with the seal
        off, since nothing could open it then.
    """
    on = seal_enabled(config)
    names = (*SEALED_SPECIES, *SEALED_ELEMENTS)
    values = [('seal_active', float(hf_row.get('seal_active', 0.0)))]
    values += [('seal_path', float(hf_row.get('seal_path', PATH_OPEN)))]
    values += [(f'{n}_kg_sealed', float(hf_row.get(f'{n}_kg_sealed', 0.0))) for n in names]
    bad = [k for k, v in values if not (np.isfinite(v) and v >= 0.0)]
    if values[1][1] not in (PATH_OPEN, PATH_MESH, PATH_LID):
        bad.append('seal_path')
    if bad:
        raise ValueError(f'Resume: unreadable seal state in the last row: {", ".join(bad[:4])}')
    held = [k for k, v in values[2:] if v > 0.0]
    if held and not on:
        raise ValueError(
            f'Resume: the last row holds sealed mass ({", ".join(held[:4])}) but '
            'outgas.lid_seal.enabled = false; resume with the seal on.'
        )
    if held and values[0][1] < 0.5:
        raise ValueError(
            f'Resume: seal_active is 0 but the last row holds sealed mass ({held[0]})'
        )
    if not on:
        hf_row['seal_active'] = hf_row['seal_path'] = 0.0
    sealed = on and values[0][1] >= 0.5
    temp = float(hf_row.get('seal_Tmagma_close', np.nan))
    if sealed and not (np.isfinite(temp) and temp > 0.0):
        raise ValueError(f'Resume: a sealed last row needs seal_Tmagma_close > 0 K, not {temp}')
    if sealed and config.outgas.trap_mode == 'front':
        xtal, tl = _crystal_masses(hf_row)
        phi = float(hf_row.get('Phi_global', np.nan))
        phi_c = float(hf_row.get('seal_phi_close', np.nan))
        if xtal + tl == 0.0 and not (
            np.isfinite(phi + phi_c) and min(max(phi, 0.0), 1.0) >= phi_c
        ):
            raise ValueError(
                f'Resume: a sealed row with Phi_global = {phi} and seal_phi_close = {phi_c} '
                'holds no seal_xtal_kg or seal_tl_kg'
            )
        t_close = float(hf_row.get('seal_t_close', np.nan))
        if not (np.isfinite(t_close) and t_close > 0.0):
            raise ValueError(f'Resume: a sealed row needs seal_t_close > 0 yr, not {t_close}')
    return sealed

run_lid_seal_step(dirs, config, hf_row, interior_o, sealed, *, hf_all, first_iter, init_stage, dt)

Volatile exchange of one step with the lid seal on; return whether it is sealed.

An open seal runs the chemistry solve and then closes when the crust allows it (never in the initialisation stage or on an impact step). A sealed step opens first when the band is crossed or an impact remelts the mantle; otherwise escape is applied to the atmosphere as on a crystallized mantle and the sealed reservoir leaks over dt [yr]. Under front trapping a held step adds its crystals (:func:add_crystals), reading the completed rows hf_all on a remelt.

Source code in src/proteus/outgas/lid_seal.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def run_lid_seal_step(
    dirs: dict,
    config: Config,
    hf_row: dict,
    interior_o,
    sealed: bool,
    *,
    hf_all,
    first_iter: bool,
    init_stage: bool,
    dt: float,
) -> bool:
    """Volatile exchange of one step with the lid seal on; return whether it is sealed.

    An open seal runs the chemistry solve and then closes when the crust allows
    it (never in the initialisation stage or on an impact step). A sealed step
    opens first when the band is crossed or an impact remelts the mantle;
    otherwise escape is applied to the atmosphere as on a crystallized mantle and
    the sealed reservoir leaks over ``dt`` [yr]. Under front trapping a held step
    adds its crystals (:func:`add_crystals`), reading the completed rows ``hf_all``
    on a remelt.
    """
    from proteus.outgas.compaction import BRANCH_REMELT
    from proteus.outgas.wrapper import (
        check_ic_oxygen_budget,
        run_crystallized,
        run_outgassing_and_vapourisation,
    )

    seal = config.outgas.lid_seal
    reset_step_columns(hf_row)
    path = int(hf_row.get('seal_path', PATH_OPEN)) if sealed else PATH_OPEN
    if sealed and path == 0:  # a sealed row without its path reads the source it has now
        path = PATH_LID if float(hf_row.get('lid_weight', 0.0)) > 0.0 else PATH_MESH
    delta, phi_top, used = closure_state(config, hf_row, interior_o, path)
    hf_row['seal_delta'], hf_row['seal_phi_top'] = delta, phi_top
    impact = bool(getattr(interior_o, 'impact_reset', False))
    if sealed and (impact or phi_top >= seal.phi_open_value or delta < seal.delta_open_value):
        log.info(
            'Lid seal opens (crust %.3e m, top-cell melt fraction %.3f, impact %s); '
            '%.3e kg returns to the melt',
            delta,
            phi_top,
            impact,
            open_seal(hf_row),
        )
        sealed, used = False, PATH_OPEN
    phi = min(max(float(hf_row['Phi_global']), 0.0), 1.0)
    if sealed:
        if config.outgas.trap_mode == 'front':
            add_crystals(hf_row, hf_all)
        if float(hf_row.get('trap_branch', 0.0)) == BRANCH_REMELT:
            close_seal(hf_row)  # a release, also of element mass alone, is under the crust too
        run_crystallized(config, hf_row, dt)
        leak_step(config, hf_row, dt)
        assert_sealed_row(hf_row)
    else:
        run_outgassing_and_vapourisation(dirs, config, hf_row, first_iter)
        check_ic_oxygen_budget(config, hf_row)
        if (
            not (init_stage or impact)
            and delta >= seal.delta_close
            and phi_top < seal.phi_close
        ):
            moved = close_seal(hf_row)
            hf_row['seal_t_close'] = float(hf_row['Time'])
            hf_row['seal_Tmagma_close'] = max(float(hf_row['T_magma']), config.outgas.T_floor)
            hf_row['seal_phi_close'] = phi
            hf_row['seal_xtal_kg'] = hf_row['seal_tl_kg'] = 0.0
            log.info(
                'Lid seal closes (crust %.3e m, top-cell melt fraction %.3f); %.3e kg sealed',
                delta,
                phi_top,
                moved,
            )
            sealed = True
        else:
            used = PATH_OPEN
    hf_row['seal_active'], hf_row['seal_path'] = float(sealed), float(used)
    return sealed

seal_enabled(config)

Whether the run uses the lid seal; False for a config built without it.

Source code in src/proteus/outgas/lid_seal.py
105
106
107
108
def seal_enabled(config: Config) -> bool:
    """Whether the run uses the lid seal; ``False`` for a config built without it."""
    seal = getattr(config.outgas, 'lid_seal', None)
    return getattr(seal, 'enabled', False) is True

sealed_mass(hf_row, element)

Mass of one element [kg] held in the sealed reservoir, 0 when unreadable.

Source code in src/proteus/outgas/lid_seal.py
662
663
664
665
def sealed_mass(hf_row: dict, element: str) -> float:
    """Mass of one element [kg] held in the sealed reservoir, 0 when unreadable."""
    mass = float(hf_row.get(f'{element}_kg_sealed', 0.0))
    return mass if np.isfinite(mass) and mass > 0.0 else 0.0