Skip to content

Zalmoxis.solver

solver

Core solver loop for the Zalmoxis interior structure model.

Contains the main() function that implements the three nested iterative procedures: mass-radius convergence (outer), Picard density iteration (middle), and Brent root-finding on central pressure with RK45 ODE integration (inner).

Numerical solver parameters (tolerances, iteration limits, step sizes) are set internally via _default_solver_params() with mass-adaptive scaling. Callers do not need to provide them. If a first solve attempt fails to converge, main() automatically retries with tighter settings.

main(config_params, material_dictionaries, melting_curves_functions, input_dir, layer_mixtures=None, volatile_profile=None, temperature_function=None, temperature_arrays=None, p_center_hint=None, initial_density=None, initial_radii=None)

Run the exoplanet internal structure model with automatic retry.

Calls _solve() with mass-adaptive default parameters. If the first attempt does not converge, automatically retries once with tighter tolerances and doubled iteration limits.

Parameters:

Name Type Description Default
config_params dict

Configuration parameters for the model. Numerical solver parameters (tolerances, iteration limits, step sizes) are optional; sensible mass-adaptive defaults are used when absent.

required
material_dictionaries dict

EOS registry dict keyed by EOS identifier string.

required
melting_curves_functions tuple or None

(solidus_func, liquidus_func) for EOS needing external melting curves.

required
input_dir str

Directory containing input files.

required
layer_mixtures dict or None

Per-layer LayerMixture objects. If None, parsed from config_params['layer_eos_config']. PROTEUS/CALLIOPE can provide pre-built mixtures with runtime-updated fractions.

None
volatile_profile VolatileProfile or None

Volatile profile for binodal-aware structure. Passed through to _solve() but not used directly by the retry logic.

None
temperature_function callable or None

External temperature function with signature f(r, P) -> T where r is radius in m, P is pressure in Pa, and T is temperature in K. When provided, bypasses the internal temperature mode dispatch (isothermal/linear/prescribed/adiabatic). Used by PROTEUS to pass SPIDER/Aragog T(r) profiles directly in memory.

None
temperature_arrays tuple[ndarray, ndarray] or None

Explicit r-indexed T profile (r_arr, T_arr). Only consumed by the JAX path (config_params['use_jax']=True). Preferred over temperature_function when the caller's T is naturally r-indexed (e.g. SPIDER/Aragog-coupled runs): the P-indexed tabulation inside jax_eos.wrapper collapses to a constant for P-ignoring callables and breaks convergence. See tools/benchmarks/bench_coupled_tempfunc.py.

None
initial_density ndarray or None

Density profile from a previous solve, used to seed the Picard iteration. Must be paired with initial_radii. Interpolated onto the current radial grid. Dramatically accelerates convergence when the structure changes incrementally between coupling steps.

None
initial_radii ndarray or None

Radial grid corresponding to initial_density.

None

Returns:

Type Description
dict

Model results including radii, density, gravity, pressure, temperature, mass enclosed, convergence status, and timing.

Source code in src/zalmoxis/solver.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
def main(
    config_params,
    material_dictionaries,
    melting_curves_functions,
    input_dir,
    layer_mixtures=None,
    volatile_profile=None,
    temperature_function=None,
    temperature_arrays=None,
    p_center_hint=None,
    initial_density=None,
    initial_radii=None,
):
    """Run the exoplanet internal structure model with automatic retry.

    Calls `_solve()` with mass-adaptive default parameters. If the first
    attempt does not converge, automatically retries once with tighter
    tolerances and doubled iteration limits.

    Parameters
    ----------
    config_params : dict
        Configuration parameters for the model. Numerical solver
        parameters (tolerances, iteration limits, step sizes) are
        optional; sensible mass-adaptive defaults are used when absent.
    material_dictionaries : dict
        EOS registry dict keyed by EOS identifier string.
    melting_curves_functions : tuple or None
        (solidus_func, liquidus_func) for EOS needing external melting curves.
    input_dir : str
        Directory containing input files.
    layer_mixtures : dict or None, optional
        Per-layer LayerMixture objects. If None, parsed from
        ``config_params['layer_eos_config']``. PROTEUS/CALLIOPE can provide
        pre-built mixtures with runtime-updated fractions.
    volatile_profile : VolatileProfile or None, optional
        Volatile profile for binodal-aware structure. Passed through to
        ``_solve()`` but not used directly by the retry logic.
    temperature_function : callable or None, optional
        External temperature function with signature ``f(r, P) -> T``
        where ``r`` is radius in m, ``P`` is pressure in Pa, and ``T``
        is temperature in K. When provided, bypasses the internal
        temperature mode dispatch (isothermal/linear/prescribed/adiabatic).
        Used by PROTEUS to pass SPIDER/Aragog T(r) profiles directly
        in memory.
    temperature_arrays : tuple[ndarray, ndarray] or None, optional
        Explicit r-indexed T profile ``(r_arr, T_arr)``. Only consumed
        by the JAX path (``config_params['use_jax']=True``). Preferred
        over ``temperature_function`` when the caller's T is naturally
        r-indexed (e.g. SPIDER/Aragog-coupled runs): the P-indexed
        tabulation inside ``jax_eos.wrapper`` collapses to a constant
        for P-ignoring callables and breaks convergence. See
        ``tools/benchmarks/bench_coupled_tempfunc.py``.
    initial_density : numpy.ndarray or None, optional
        Density profile from a previous solve, used to seed the Picard
        iteration. Must be paired with ``initial_radii``. Interpolated
        onto the current radial grid. Dramatically accelerates convergence
        when the structure changes incrementally between coupling steps.
    initial_radii : numpy.ndarray or None, optional
        Radial grid corresponding to ``initial_density``.

    Returns
    -------
    dict
        Model results including radii, density, gravity, pressure, temperature,
        mass enclosed, convergence status, and timing.
    """
    # Validate outer-solver choice. Default is 'picard' (the damped
    # fixed-point loop inside `_solve()`); 'newton' dispatches to
    # `_solve_newton_outer()`.
    outer_solver_explicit = 'outer_solver' in config_params
    outer_solver = config_params.get('outer_solver', 'picard')
    if outer_solver not in _VALID_OUTER_SOLVERS:
        raise ValueError(
            f'outer_solver must be one of {_VALID_OUTER_SOLVERS!r}, got {outer_solver!r}.'
        )

    # Advisory: when outer_solver is implicitly picard AND the profile
    # is hot fully-molten (T_surf > 3000 K) or super-Earth scale
    # (planet_mass > 2 M_E), log a one-line INFO suggesting Newton.
    # Damped Picard has a basin attractor on hot fully-molten and
    # super-Earth-scale profiles where the outer R-search oscillates
    # without converging; Newton + brentq is robust across 1-10 M_E.
    # The default stays at picard so that opting into Newton (which
    # requires tighter integrator tolerances) is an explicit user choice.
    if not outer_solver_explicit:
        _planet_mass = float(config_params.get('planet_mass') or 0.0)
        _surface_temperature = float(config_params.get('surface_temperature') or 0.0)
        _is_hot = _surface_temperature > 3000.0
        _is_massive = _planet_mass > 2.0 * earth_mass
        if _is_hot or _is_massive:
            _trigger = []
            if _is_massive:
                _trigger.append(f'planet_mass={_planet_mass / earth_mass:.2f} M_E > 2 M_E')
            if _is_hot:
                _trigger.append(f'surface_temperature={_surface_temperature:.0f} K > 3000 K')
            logger.info(
                "Zalmoxis using outer_solver='picard' (default). "
                "For this regime (%s), 'newton' is recommended: damped "
                'Picard has a known basin attractor on hot fully-molten '
                "and super-Earth profiles. Set outer_solver='newton' "
                'in your config to opt in. This advisory does not '
                'change behaviour.',
                ', '.join(_trigger),
            )
    if outer_solver == 'newton':
        return _solve_newton_outer(
            config_params,
            material_dictionaries,
            melting_curves_functions,
            input_dir,
            layer_mixtures=layer_mixtures,
            volatile_profile=volatile_profile,
            temperature_function=temperature_function,
            temperature_arrays=temperature_arrays,
            p_center_hint=p_center_hint,
            initial_density=initial_density,
            initial_radii=initial_radii,
        )

    result = _solve(
        config_params,
        material_dictionaries,
        melting_curves_functions,
        input_dir,
        layer_mixtures=layer_mixtures,
        volatile_profile=volatile_profile,
        temperature_function=temperature_function,
        temperature_arrays=temperature_arrays,
        p_center_hint=p_center_hint,
        initial_density=initial_density,
        initial_radii=initial_radii,
    )

    # Skip retry when the first attempt is "good enough": density and
    # pressure converged, mass error within `_RETRY_SKIP_MASS_ERR`. On
    # hot fully-molten T(r) profiles (early CHILI coupled iters) the
    # retry path doubles every iteration cap and wall_timeout, takes
    # 600+ s, and routinely lands at the SAME or SLIGHTLY-WORSE mass
    # error as the first attempt. The outer mass-radius loop will
    # converge across PROTEUS iters anyway; one resolve ending at 5-7%
    # mass error is fine when the next resolve corrects it.
    _RETRY_SKIP_MASS_ERR = 0.07
    _first_mass_err = result.get('best_mass_error')
    _retry_skipped = (
        not result['converged']
        and result.get('converged_density', False)
        and result.get('converged_pressure', False)
        and _first_mass_err is not None
        and _first_mass_err < _RETRY_SKIP_MASS_ERR
    )
    if (
        _retry_skipped
    ):  # pragma: no cover - retry-skip diagnostic; reached only on borderline first-attempt
        logger.info(
            'Skipping retry: density and pressure converged, mass error '
            '%.4f%% < %.2f%% threshold. Accepting first-attempt solution.',
            _first_mass_err * 100,
            _RETRY_SKIP_MASS_ERR * 100,
        )
        result['converged'] = True
        result['converged_mass'] = True

    if not result['converged']:
        # Build tightened params for retry
        planet_mass = config_params['planet_mass']
        defaults = _default_solver_params(planet_mass)
        # Merge: explicit caller values override defaults
        effective = dict(defaults)
        for key in defaults:
            if key in config_params:
                effective[key] = config_params[key]
        tightened = _tighten_solver_params(effective)

        logger.warning(
            'Structure solve did not converge (mass=%s, density=%s, pressure=%s). '
            'Retrying with tighter parameters.',
            result.get('converged_mass', False),
            result.get('converged_density', False),
            result.get('converged_pressure', False),
        )

        # Seed retry with the first attempt's results
        retry_params = copy.copy(config_params)
        retry_params.update(tightened)
        retry_density = None
        retry_radii = None
        if 'radii' in result and result['radii'] is not None and len(result['radii']) > 0:
            r_last = result['radii'][-1]
            mass_in_earth = max(planet_mass, 0.01 * earth_mass) / earth_mass
            r_seager = earth_radius * mass_in_earth**0.282
            if np.isfinite(r_last) and r_last > 0 and 0.2 * r_seager < r_last < 5.0 * r_seager:
                retry_params['_initial_radius_guess'] = r_last
            # Use first attempt's density as seed for retry
            if result.get('density') is not None and np.any(result['density'] > 0):
                retry_density = result['density']
                retry_radii = result['radii']

        result = _solve(
            retry_params,
            material_dictionaries,
            melting_curves_functions,
            input_dir,
            layer_mixtures=layer_mixtures,
            volatile_profile=volatile_profile,
            temperature_function=temperature_function,
            temperature_arrays=temperature_arrays,
            p_center_hint=p_center_hint,
            initial_density=retry_density,
            initial_radii=retry_radii,
        )

        if not result['converged']:  # pragma: no cover - retry also failed; defensive
            logger.warning(
                'Structure solve did not converge after retry. '
                'Returning best result with converged=False.'
            )

    return result