Skip to content

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, adiabat_seed=None, core_temperature_arrays=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), r_arr increasing. Consumed only with config_params['use_jax']=True; it then gives T everywhere, in place of temperature_function and the temperature mode: in the JAX structure solves, their numpy fallback, the density update at the nodes and the output temperature. 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
adiabat_seed mapping or None

radii [m], pressure [Pa] and mass_enclosed [kg] of an earlier solve of the same planet, each of length num_layers. When the solve computes the adiabat of its temperature mode, it skips the Newton root and the blend ramp: the first pass reads the adiabat of the seed structure at blend 1 on a table labelled adiabat_table_blend -1.0, which no accept test takes, and the solve runs at min(tolerance_outer, newton_tol) with the Newton outer solver. A seed that fails the checks of _adiabat_seed is refused with a warning; a seeded solve that does not converge or raises StructureSolveError is repeated without the seed, and its time counts in total_time. A seeded result has no newton_* keys. Ignored with an external temperature.

None
core_temperature_arrays tuple[ndarray, ndarray] or None

Core temperature table (P_arr, T_arr): pressures [Pa], finite, positive and strictly increasing, and temperatures [K], finite, positive and not falling with P; 2 one-dimensional arrays of equal length >= 2 (else ValueError). Every core node and core ODE evaluation (enclosed mass below cmb_mass, outer and inner core) takes T(P) from the table, linear in P and extended with the end slopes outside it; the mantle keeps temperature_function, or temperature_arrays with use_jax, one of which must be given (else ValueError). A core without a T-dependent EOS ignores the table (one INFO line). The result then holds core_T_used (True when the table set the core T), core_T_nodes_outside (core nodes with P outside the table) and core_T_max_excess (their largest distance beyond the table as a fraction of P_arr[-1] - P_arr[0], 0.0 for none; a WARNING when above 0). Above 0.1 the result is not accepted (converged False, accepted_on None). An accepted result with a core node at T <= 0, or a node off its source by more than a relative 1e-9, raises StructureInvariantError. With a table, core_liquidus and temperature_mode = 'adiabatic_from_cmb' are accepted together.

None

Returns:

Type Description
dict

Model results including radii, density, gravity, pressure, temperature, mass enclosed, convergence status, and timing. accepted_on names the test that accepted the solve ('strict', 'mass_only', 'max_iter', 'timeout', 'oscillation', 'retry_skip', 'newton_tol' or 'brentq_best'; None when it was not accepted), and mass_error_at_accept is the relative mass error of the returned profile. 'timeout' replaces the other labels when the wall clock stopped the solve of the returned profile. In an adiabatic mode with a T-dependent EOS and no external temperature only the full adiabat on a table of a full-adiabat pass (adiabat_blend and adiabat_table_blend 1) is accepted, on its strict test only when the pass that built the table was itself within tolerance_outer in mass; the table is read by layer (the core part at core masses) and continued past its high-pressure end with the adiabat slope of its end interval, the core part also past its low-pressure end, while the mantle part holds its low-pressure end T; and adiabat_self_consistency gives the largest difference in K between the returned mantle T and the adiabat recomputed on the returned structure (None below blend 1), and adiabat_self_consistency_core the same at the core nodes, whose T comes from the T table of the pass before (None with temperature_mode = 'adiabatic_from_cmb', which integrates no core adiabat); a Newton root there seeds the Picard blend ramp at min(tolerance_outer, newton_tol), and the result keeps its newton_* keys and its time in total_time. In a ramp that main starts (after a Newton root or from adiabat_seed), a pass on a full-adiabat table more than 2 times the mass tolerance of the ramp off the mass takes the next radius from the secant of the mass through the last 2 such passes, within 2 % of its radius; the cube-root update takes over once a secant step does not shrink the mass error. adiabat_seeded is True when the returned solve started from the seed. A failed table band check sets converged to False and leaves accepted_on as it is. A converged result has integration_tolerances, the (rtol, atol) of the solve that returned, with rtol at least the RK45 floor of 100 eps, which the invariant check used; an unconverged result has none. padded (bool) is True when the pressure at the outer radius is 0: the integration stopped at P = 0 before the outer radius, and the nodes past the stop hold P = 0. main logs one warning when it returns a converged padded result. With core_liquidus, icb_converged is True when the returned pass meets the ICB tests; icb_superheat [K] is the superheat S of the outer-core liquid at the ICB on an adiabat (at the centre with no inner core, at the core mass with a full one; None on a given profile), and icb_adiabat [kg] the inner-core mass that the adiabat of the returned pass took (None without an adiabat).

Raises:

Type Description
StructureSolveError

A structure solve gave a non-finite profile (a stop in the integration deep inside the planet), with either outer solver. Any trial central pressure counts, including a bracket end of the pressure search.

StructureInvariantError

An accepted result breaks a physical invariant of zalmoxis.invariants: the layer masses, the padding, positive and monotone profiles, gravity, the mass closure within accept_mass_limit, or the EOS density; or, in such an adiabatic mode, the accepted profile is not the full adiabat. It is not a RuntimeError, so a caller that keeps its structure after a failed solve does not catch it.

Source code in src/zalmoxis/solver.py
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
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,
    adiabat_seed=None,
    core_temperature_arrays=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)``, ``r_arr`` increasing.
        Consumed only with ``config_params['use_jax']=True``; it then gives T
        everywhere, in place of ``temperature_function`` and the temperature
        mode: in the JAX structure solves, their numpy fallback, the density
        update at the nodes and the output temperature. 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``.
    adiabat_seed : mapping or None, optional
        ``radii`` [m], ``pressure`` [Pa] and ``mass_enclosed`` [kg] of an earlier solve of
        the same planet, each of length ``num_layers``. When the solve computes the adiabat
        of its temperature mode, it skips the Newton root and the blend ramp: the first pass
        reads the adiabat of the seed structure at blend 1 on a table labelled
        ``adiabat_table_blend`` -1.0, which no accept test takes, and the solve runs at
        min(tolerance_outer, newton_tol) with the Newton outer solver. A seed that fails the
        checks of ``_adiabat_seed`` is refused with a warning; a seeded solve that does not
        converge or raises StructureSolveError is repeated without the seed, and its time
        counts in ``total_time``. A seeded result has no ``newton_*`` keys. Ignored with an
        external temperature.
    core_temperature_arrays : tuple[ndarray, ndarray] or None, optional
        Core temperature table ``(P_arr, T_arr)``: pressures [Pa], finite, positive and
        strictly increasing, and temperatures [K], finite, positive and not falling with P; 2
        one-dimensional arrays of equal length >= 2 (else ValueError). Every core node and core ODE evaluation
        (enclosed mass below ``cmb_mass``, outer and inner core) takes T(P) from the table,
        linear in P and extended with the end slopes outside it; the mantle keeps
        ``temperature_function``, or ``temperature_arrays`` with ``use_jax``, one of which must
        be given (else ValueError). A core without a T-dependent EOS ignores the table (one
        INFO line). The result then holds ``core_T_used`` (True when the table set the core
        T), ``core_T_nodes_outside`` (core nodes with P outside the table) and
        ``core_T_max_excess`` (their largest distance beyond the table as a fraction of
        ``P_arr[-1] - P_arr[0]``, 0.0 for none; a WARNING when above 0). Above 0.1 the result
        is not accepted (``converged`` False, ``accepted_on`` None). An accepted result with a
        core node at T <= 0, or a node off its source by more than a relative 1e-9, raises
        StructureInvariantError. With a table, ``core_liquidus`` and ``temperature_mode =
        'adiabatic_from_cmb'`` are accepted together.

    Returns
    -------
    dict
        Model results including radii, density, gravity, pressure, temperature,
        mass enclosed, convergence status, and timing. ``accepted_on`` names the
        test that accepted the solve ('strict', 'mass_only', 'max_iter', 'timeout',
        'oscillation', 'retry_skip', 'newton_tol' or 'brentq_best'; None when it
        was not accepted), and ``mass_error_at_accept`` is the relative mass error
        of the returned profile. 'timeout' replaces the other labels when the wall
        clock stopped the solve of the returned profile. In an adiabatic mode with a
        T-dependent EOS and no external temperature only the full adiabat on a table of a
        full-adiabat pass (``adiabat_blend`` and ``adiabat_table_blend`` 1) is accepted, on its
        strict test only when the pass that built the table was itself within
        ``tolerance_outer`` in mass; the table is read by layer (the core part at core masses)
        and continued past its high-pressure end with the adiabat slope of its end interval,
        the core part also past its low-pressure end, while the mantle part holds its
        low-pressure end T; and
        ``adiabat_self_consistency`` gives the largest difference in K between the returned
        mantle T and the adiabat recomputed on the returned structure (None below blend 1),
        and ``adiabat_self_consistency_core`` the same at the core nodes, whose T comes from
        the T table of the pass before (None with ``temperature_mode = 'adiabatic_from_cmb'``,
        which integrates no core adiabat);
        a Newton root there seeds the Picard blend ramp at min(tolerance_outer, newton_tol),
        and the result keeps its ``newton_*`` keys and its time in ``total_time``. In a ramp
        that main starts (after a Newton root or from ``adiabat_seed``), a pass on a
        full-adiabat table more than 2 times the mass tolerance of the ramp off the mass takes
        the next radius from the secant of the mass through the last 2 such passes, within 2 %
        of its radius; the cube-root update takes over once a secant step does not shrink the
        mass error.
        ``adiabat_seeded`` is True when the returned solve started from the seed. A failed
        table band check sets ``converged`` to False and leaves ``accepted_on`` as it is. A
        converged result has ``integration_tolerances``, the (rtol, atol) of the solve
        that returned, with rtol at least the RK45 floor of 100 eps, which the invariant
        check used; an unconverged result has none. ``padded`` (bool) is True when
        the pressure at the outer radius is 0: the integration stopped at P = 0 before
        the outer radius, and the nodes past the stop hold P = 0. ``main`` logs one
        warning when it returns a converged padded result. With ``core_liquidus``,
        ``icb_converged`` is True when the returned pass meets the ICB tests;
        ``icb_superheat`` [K] is the superheat S of the outer-core liquid at the ICB on an
        adiabat (at the centre with no inner core, at the core mass with a full one; None
        on a given profile), and ``icb_adiabat`` [kg] the inner-core mass that the adiabat of
        the returned pass took (None without an adiabat).

    Raises
    ------
    StructureSolveError
        A structure solve gave a non-finite profile (a stop in the integration
        deep inside the planet), with either outer solver. Any trial central
        pressure counts, including a bracket end of the pressure search.
    StructureInvariantError
        An accepted result breaks a physical invariant of ``zalmoxis.invariants``:
        the layer masses, the padding, positive and monotone profiles, gravity, the
        mass closure within ``accept_mass_limit``, or the EOS density; or, in such an
        adiabatic mode, the accepted profile is not the full adiabat. It is not a
        RuntimeError, so a caller that keeps its structure after a failed solve does
        not catch it.
    """
    _interpolation_cache.pop('_jax_fell_back', None)  # set by solve_structure's numpy fallback
    _band_debug_seen.clear()
    # 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),
            )
    band_limit(config_params)  # a bad limit fails before the solve, not after it
    table = mantle_T = None
    if core_temperature_arrays is not None:
        core_temperature_arrays = table = check_core_temperature_arrays(core_temperature_arrays)
        jax_arrays = config_params.get('use_jax', False) and temperature_arrays is not None
        mantle_T = (
            temperature_from_arrays(temperature_arrays) if jax_arrays else temperature_function
        )
        if mantle_T is None:
            raise ValueError(
                'core_temperature_arrays needs a mantle temperature: temperature_function, or '
                'temperature_arrays with use_jax'
            )
        mixes = layer_mixtures or parse_all_layer_mixtures(config_params['layer_eos_config'])
        if not any_component_is_tdep({k: v for k, v in mixes.items() if k in CORE_LAYERS}):
            logger.info('The core EOS reads no temperature; core_temperature_arrays is unused.')
            core_temperature_arrays = None
    # the layer and ICB checks also for callers that skip validate_config
    _check_two_layer_core(config_params['layer_eos_config'])
    _check_icb_rule(config_params, core_table=table is not None)
    bands = (config_params, material_dictionaries, melting_curves_functions, layer_mixtures)
    asked = _adiabat_asked(
        config_params, layer_mixtures, temperature_function, temperature_arrays
    )
    newton_keys, newton_time, seed_time, result = {}, 0.0, 0.0, None
    seed = (
        _adiabat_seed(adiabat_seed, config_params)
        if asked and adiabat_seed is not None
        else None
    )
    if seed is not None:  # the ramp starts at blend 1 on the adiabat of the seed structure
        seeded_params = {
            **config_params,
            '_initial_radius_guess': float(seed['radii'][-1]),
            '_secant_tail': True,
        }
        if outer_solver == 'newton':
            seeded_params['tolerance_outer'] = _ramp_tolerance(config_params)
        seed_start = time.time()
        try:
            result = _solve(
                seeded_params,
                material_dictionaries,
                melting_curves_functions,
                input_dir,
                layer_mixtures=layer_mixtures,
                volatile_profile=volatile_profile,
                temperature_function=temperature_function,
                temperature_arrays=temperature_arrays,
                core_temperature_arrays=core_temperature_arrays,
                p_center_hint=float(seed['pressure'][0])
                if p_center_hint is None
                else p_center_hint,
                initial_density=initial_density,
                initial_radii=initial_radii,
                adiabat_seed=seed,
            )
        except StructureSolveError as err:
            logger.info('The seeded solve raised (%s); solving without the seed.', err)
            seed_time = time.time() - seed_start
        else:
            if not result['converged']:
                logger.info('The seeded solve did not converge; solving without the seed.')
                seed_time, result = result['total_time'], None
    if result is None and outer_solver == 'newton':
        result = _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,
            core_temperature_arrays=core_temperature_arrays,
            p_center_hint=p_center_hint,
            initial_density=initial_density,
            initial_radii=initial_radii,
        )
        if not (asked and result['converged']):
            result = _report_table_bands(result, *bands)
            if seed_time:
                result['total_time'] += seed_time
            result = _check_core_table(
                result, table, core_temperature_arrays is not None, mantle_T
            )
            return _check_accepted(result, config_params, *bands, volatile_profile, asked)
        # the Newton root holds the linear first guess; the blend ramp from it makes the adiabat
        logger.info(
            'Newton root on the linear first guess; continuing with the adiabat blend ramp.'
        )
        newton_keys = {
            k: result[k] for k in ('newton_n_iter', 'newton_history', 'newton_used_brentq')
        }
        newton_time = result['total_time']
        config_params = {
            **config_params,
            '_initial_radius_guess': float(result['radii'][-1]),
            '_secant_tail': True,
            'tolerance_outer': _ramp_tolerance(config_params),
        }
        p_center_hint = float(result['pressure'][0])
        initial_density, initial_radii = result['density'], result['radii']
        result = None

    if result is None:
        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,
            core_temperature_arrays=core_temperature_arrays,
            p_center_hint=p_center_hint,
            initial_density=initial_density,
            initial_radii=initial_radii,
        )

    # Skip the retry when density and pressure converged and the mass error is within
    # `_RETRY_SKIP_MASS_ERR` (on hot molten T(r) the retry takes 600+ s for no better mass and the
    # caller's next re-solve corrects it); a ramp after a Newton root always retries.
    _RETRY_SKIP_MASS_ERR = 0.07
    _first_mass_err = result.get('mass_error_at_accept')
    run_params = config_params  # the parameters of the solve that returns
    _retry_skipped = (
        not result['converged']
        and result.get('icb_converged', True)
        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
        and not _short_of_adiabat(result, asked)
        and not newton_keys
    )
    if _retry_skipped:
        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
        result['accepted_on'] = (
            'timeout' if result.get('stopped_on_wall_clock') else 'retry_skip'
        )
        result['accept_mass_limit'] = _RETRY_SKIP_MASS_ERR

    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)
        if newton_keys:  # the hand-off already runs at the Newton mass tolerance
            tightened['tolerance_outer'] = config_params['tolerance_outer']

        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']

        run_params = retry_params
        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,
            core_temperature_arrays=core_temperature_arrays,
            p_center_hint=p_center_hint,
            initial_density=retry_density,
            initial_radii=retry_radii,
        )

        if not result['converged']:  # the retry also failed
            logger.warning(
                'Structure solve did not converge after retry. '
                'Returning best result with converged=False.'
            )

    result = _report_table_bands(result, *bands)
    if newton_keys or seed_time:
        result.update(newton_keys, total_time=result['total_time'] + newton_time + seed_time)
    result = _check_core_table(result, table, core_temperature_arrays is not None, mantle_T)
    return _check_accepted(result, run_params, *bands, volatile_profile, asked)