From 99f73a4c45f9a29b8eda6cf449adee0fbde7bc62 Mon Sep 17 00:00:00 2001 From: Andrew Fullard <20341051+andrewfullard@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:58:45 -0500 Subject: [PATCH 1/3] Close IIP level equations relative to their total rate The level solve accepted a population when every residual of the normalized rate equations was below an absolute 1e-10. That limit depends on the unit of time and on how fast each level is populated, and sits at the precision the root finder reaches, so accepted states could fail final closure at 1.0-2.3e-10. Each residual is now divided by the gross rate of its equation, the sum of the magnitudes of the rates into and out of the level, and closes at LEVEL_RESIDUAL_LIMIT = 1e-10 of it. A metamorphic test checks that the relative residual does not depend on the rate unit. The terminal level residual, re-evaluated at the charge-solved electron density, is removed. It was a diagnostic only, and rebuilt the bound-bound rates on every evaluation. Co-Authored-By: Claude Opus 5.5 --- tardis/plasma/equilibrium/evaluator.py | 195 ++++++++++++++---- .../equilibrium/tests/test_evaluator.py | 2 +- .../tests/test_level_populations.py | 109 +++++++++- tardis/plasma/equilibrium/thermal_balance.py | 6 +- tardis/workflows/tests/test_iip_workflow.py | 9 +- 5 files changed, 263 insertions(+), 58 deletions(-) diff --git a/tardis/plasma/equilibrium/evaluator.py b/tardis/plasma/equilibrium/evaluator.py index 47a0a3df99e..715e2d31d07 100644 --- a/tardis/plasma/equilibrium/evaluator.py +++ b/tardis/plasma/equilibrium/evaluator.py @@ -61,6 +61,10 @@ EstimatorsContinuum, ) +# Level equations close when every scaled residual is below this fraction of the +# total rate into and out of its level. +LEVEL_RESIDUAL_LIMIT = 1e-10 + @dataclass(frozen=True) class PlasmaEquilibriumEvaluation: @@ -85,6 +89,8 @@ class PlasmaEquilibriumEvaluation: level_to_continuum_saha_factor: pd.DataFrame lte_ion_population: pd.DataFrame lte_level_population: pd.DataFrame + relative_trial_level_residual: pd.DataFrame + relative_level_residual: pd.DataFrame def calculate_lte_populations( @@ -150,7 +156,12 @@ def calculate_nlte_level_population_residual( sobolev: SobolevInputs, level_density: npt.NDArray[np.float64] | None = None, bound_bound_rates: BoundBoundMatrixRates | None = None, -) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], float]: +) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + float, + npt.NDArray[np.float64], +]: """Calculate the reduced fixed-density NLTE level residual. The auxiliary continuum ratio is eliminated algebraically as @@ -186,9 +197,11 @@ def calculate_nlte_level_population_residual( Returns ------- - tuple[numpy.ndarray, numpy.ndarray, float] - Component level residual, candidate Sobolev escape probabilities, and - the reduced ionized-to-neutral ratio. + tuple[numpy.ndarray, numpy.ndarray, float, numpy.ndarray] + Component level residual, candidate Sobolev escape probabilities, the + reduced ionized-to-neutral ratio, and the total rate of each equation: + the sum of the magnitudes of its inflow and outflow terms, and 1 for + the normalization equation. """ level_fractions = np.asarray(level_fractions, dtype=np.float64) total_recombination_rates = level_rates.recombination.copy() @@ -239,13 +252,49 @@ def calculate_nlte_level_population_residual( beta_sobolev, ) level_rate_matrix += level_rates.ionization_loss_matrix + total_rate = np.abs(level_rate_matrix * level_fractions).sum( + axis=1 + ) + np.abs(total_recombination_rates * ionized_to_neutral_ratio) + total_rate[0] = 1.0 level_rate_matrix[0, :] = 1.0 level_residual = ( level_rate_matrix @ level_fractions + total_recombination_rates * ionized_to_neutral_ratio ) level_residual[0] -= 1.0 - return level_residual, beta_sobolev, ionized_to_neutral_ratio + return level_residual, beta_sobolev, ionized_to_neutral_ratio, total_rate + + +def calculate_relative_level_residual( + level_residual: npt.NDArray[np.float64], + total_rate: npt.NDArray[np.float64], +) -> npt.NDArray[np.float64]: + """Express level residuals relative to the total rate of each equation. + + An absolute residual depends on the unit of time and on how fast a level + is populated. Dividing by the sum of the magnitudes of the rates that + enter the equation measures how well the equation balances. + + Parameters + ---------- + level_residual : numpy.ndarray + Residual of each level equation. + total_rate : numpy.ndarray + Total rate of each equation from + ``calculate_nlte_level_population_residual``. + + Returns + ------- + numpy.ndarray + Relative residual; equations without any rate keep their absolute + residual. + """ + return np.divide( + level_residual, + total_rate, + out=np.array(level_residual, dtype=np.float64), + where=total_rate > 0.0, + ) @dataclass(frozen=True) @@ -271,6 +320,7 @@ class SolvedLevelState: normalized_population: pd.DataFrame trial_escape_probability: pd.DataFrame trial_level_residual: pd.DataFrame + relative_trial_level_residual: pd.DataFrame hydrogen_index: pd.MultiIndex bound_bound_rates: tuple[BoundBoundMatrixRates, ...] @@ -613,8 +663,16 @@ def _calculate_level_state( sobolev_inputs: SobolevInputs, level_density: npt.NDArray[np.float64] | None = None, bound_bound_rates: BoundBoundMatrixRates | None = None, - ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], float]: - """Evaluate one level residual at an explicit electron density.""" + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + float, + npt.NDArray[np.float64], + ]: + """Evaluate one level residual at an explicit electron density. + + Returns the outputs of ``calculate_nlte_level_population_residual``. + """ total_ionization_rates = continuum_rates.photoionization + ( continuum_rates.collisional_ionization * electron_density ) @@ -669,8 +727,15 @@ def _calculate_level_solution( float, npt.NDArray[np.float64], npt.NDArray[np.float64], + npt.NDArray[np.float64], ]: - """Solve one shell's normalized reduced level equations.""" + """Solve one shell's normalized reduced level equations. + + A solution is accepted once every level equation closes to + ``LEVEL_RESIDUAL_LIMIT`` of its total rate. Returns the fractions, + the ionized-to-neutral ratio, the escape probabilities, and the + absolute and relative level residuals. + """ if bound_bound_rates is None: shell_j_blues = self.j_blues.iloc[:, [shell_idx]].copy() shell_j_blues.columns = pd.RangeIndex(1) @@ -686,9 +751,14 @@ def _calculate_level_solution( sobolev_inputs.line_index, )[0] - def residual( + def calculate_trial_level_state( level_fractions: npt.NDArray[np.float64], - ) -> npt.NDArray[np.float64]: + ) -> tuple[ + npt.NDArray[np.float64], + npt.NDArray[np.float64], + float, + npt.NDArray[np.float64], + ]: return self._calculate_level_state( shell_idx, electron_density, @@ -698,7 +768,12 @@ def residual( population_geometry, sobolev_inputs, bound_bound_rates=bound_bound_rates, - )[0] + ) + + def residual( + level_fractions: npt.NDArray[np.float64], + ) -> npt.NDArray[np.float64]: + return calculate_trial_level_state(level_fractions)[0] def calculate_physical_level_residual( candidate: npt.NDArray[np.float64], @@ -709,10 +784,20 @@ def calculate_physical_level_residual( or candidate.sum() <= 0.0 ): return np.inf - candidate_residual = residual(candidate / candidate.sum()) + candidate_residual, _, _, total_rate = calculate_trial_level_state( + candidate / candidate.sum() + ) if not np.isfinite(candidate_residual).all(): return np.inf - return float(np.max(np.abs(candidate_residual))) + return float( + np.max( + np.abs( + calculate_relative_level_residual( + candidate_residual, total_rate + ) + ) + ) + ) # An empirical per-level floor lets a retry repopulate excited levels # depleted by the previous thermal state while retaining its shape. @@ -728,7 +813,7 @@ def calculate_physical_level_residual( if seed_idx == 0 or root_residual < best_residual: level_solution = root_solution best_residual = root_residual - if best_residual <= 1e-10: + if best_residual <= LEVEL_RESIDUAL_LIMIT: break # Log ratios preserve positive, normalized populations while @@ -736,7 +821,9 @@ def calculate_physical_level_residual( def calculate_log_ratio_residual( log_ratios: npt.NDArray[np.float64], ) -> npt.NDArray[np.float64]: - return residual(softmax(np.concatenate(([0.0], log_ratios))))[1:] + return residual(softmax(np.concatenate(([0.0], log_ratios))))[ + 1: + ] minimum_fraction = np.finfo(np.float64).eps initial_log_ratios = np.log( @@ -751,14 +838,12 @@ def calculate_log_ratio_residual( gtol=1e-14, max_nfev=3000, ) - log_fractions = softmax( - np.concatenate(([0.0], log_solution.x)) - ) + log_fractions = softmax(np.concatenate(([0.0], log_solution.x))) log_residual = calculate_physical_level_residual(log_fractions) if log_residual < best_residual: level_solution = log_fractions best_residual = log_residual - if best_residual <= 1e-10: + if best_residual <= LEVEL_RESIDUAL_LIMIT: break if not np.isfinite(level_solution).all(): raise ValueError( @@ -774,7 +859,7 @@ def calculate_log_ratio_residual( ) fractions = level_solution / level_solution.sum() - level_residual, beta_sobolev, ionized_to_neutral_ratio = ( + level_residual, beta_sobolev, ionized_to_neutral_ratio, total_rate = ( self._calculate_level_state( shell_idx, electron_density, @@ -805,6 +890,7 @@ def calculate_log_ratio_residual( ionized_to_neutral_ratio, beta_sobolev, level_residual, + calculate_relative_level_residual(level_residual, total_rate), ) def _hydrogen_index(self) -> pd.MultiIndex: @@ -833,6 +919,7 @@ def _solve_levels( ionized_to_neutral_ratios: list[float] = [] trial_escape_probabilities: list[npt.NDArray[np.float64]] = [] trial_residuals: list[npt.NDArray[np.float64]] = [] + relative_trial_residuals: list[npt.NDArray[np.float64]] = [] full_population = pd.DataFrame( np.column_stack( [ @@ -889,6 +976,7 @@ def _solve_levels( ionized_to_neutral_ratios.append(shell_result[1]) trial_escape_probabilities.append(shell_result[2]) trial_residuals.append(shell_result[3]) + relative_trial_residuals.append(shell_result[4]) hydrogen_index = self._hydrogen_index() columns = self.elemental_number_density.columns @@ -909,6 +997,11 @@ def _solve_levels( index=hydrogen_index, columns=columns, ), + pd.DataFrame( + np.asarray(relative_trial_residuals).T, + index=hydrogen_index, + columns=columns, + ), hydrogen_index, prepared_bound_bound_rates, ) @@ -1084,9 +1177,14 @@ def _calculate_final_residual( absolute_levels: pd.DataFrame, state: SolvedLevelState, thermal_state: IntermediateThermalState, - ) -> pd.DataFrame: - """Re-evaluate reduced equations at the terminal density.""" + ) -> tuple[pd.DataFrame, pd.DataFrame]: + """Re-evaluate reduced equations at the terminal density. + + Returns the absolute residuals and the residuals relative to the + total rate of each equation. + """ residuals = [] + relative_residuals = [] for shell_idx, ( continuum_rates, population_geometry, @@ -1099,25 +1197,36 @@ def _calculate_final_residual( strict=True, ) ): - residuals.append( - self._calculate_level_state( - shell_idx, - final_density.iloc[shell_idx], - electron_temperature[shell_idx], - state.fractions[shell_idx], - continuum_rates, - population_geometry, - sobolev_inputs, - absolute_levels.iloc[:, shell_idx].to_numpy(dtype=float), - state.bound_bound_rates[shell_idx], - )[0] + residual, _, _, total_rate = self._calculate_level_state( + shell_idx, + final_density.iloc[shell_idx], + electron_temperature[shell_idx], + state.fractions[shell_idx], + continuum_rates, + population_geometry, + sobolev_inputs, + absolute_levels.iloc[:, shell_idx].to_numpy(dtype=float), + state.bound_bound_rates[shell_idx], ) - return pd.DataFrame( + residuals.append(residual) + relative_residuals.append( + calculate_relative_level_residual(residual, total_rate) + ) + + residuals_df = pd.DataFrame( np.asarray(residuals).T, index=state.hydrogen_index, columns=self.elemental_number_density.columns, ) + relative_residuals_df = pd.DataFrame( + np.asarray(relative_residuals).T, + index=state.hydrogen_index, + columns=self.elemental_number_density.columns, + ) + + return residuals_df, relative_residuals_df + def _calculate_heating( self, final_electron_distribution: ThermalElectronEnergyDistribution, @@ -1294,12 +1403,14 @@ def evaluate( ion_population, thermal_state, ) - final_residual = self._calculate_final_residual( - final_density, - electron_temperature, - absolute_levels, - level_state, - thermal_state, + final_residual, relative_final_residual = ( + self._calculate_final_residual( + final_density, + electron_temperature, + absolute_levels, + level_state, + thermal_state, + ) ) return PlasmaEquilibriumEvaluation( @@ -1325,4 +1436,6 @@ def evaluate( thermal_state.level_to_continuum_saha_factor, lte_ion_population, lte_level_population, + level_state.relative_trial_level_residual, + relative_final_residual, ) diff --git a/tardis/plasma/equilibrium/tests/test_evaluator.py b/tardis/plasma/equilibrium/tests/test_evaluator.py index 8936f079e4a..da57443ff46 100644 --- a/tardis/plasma/equilibrium/tests/test_evaluator.py +++ b/tardis/plasma/equilibrium/tests/test_evaluator.py @@ -231,7 +231,7 @@ def test_evaluator_finds_same_unique_root_from_distinct_initial_guesses( err_msg="the equilibrium populations do not sum to one", ) npt.assert_allclose( - low_excitation_result.level_residual, + low_excitation_result.relative_level_residual, 0.0, rtol=0.0, atol=1e-10, diff --git a/tardis/plasma/equilibrium/tests/test_level_populations.py b/tardis/plasma/equilibrium/tests/test_level_populations.py index 3b0e69a8173..127de4799ab 100644 --- a/tardis/plasma/equilibrium/tests/test_level_populations.py +++ b/tardis/plasma/equilibrium/tests/test_level_populations.py @@ -175,22 +175,24 @@ def test_reduced_nlte_residual_recomputes_q_and_beta() -> None: line_index, ) - residual, beta_sobolev, q_ratio = calculate_nlte_level_population_residual( - level_fractions, - level_rates, - rate_matrix_solver, - j_blues, - electron_distribution, - (1, 0), - population, - sobolev, + residual, beta_sobolev, q_ratio, _ = ( + calculate_nlte_level_population_residual( + level_fractions, + level_rates, + rate_matrix_solver, + j_blues, + electron_distribution, + (1, 0), + population, + sobolev, + ) ) npt.assert_allclose(q_ratio, 0.25) npt.assert_allclose(residual, np.array([0.0, 0.5])) npt.assert_allclose(beta_sobolev, np.array([1.0])) - _, _, perturbed_q_ratio = calculate_nlte_level_population_residual( + _, _, perturbed_q_ratio, _ = calculate_nlte_level_population_residual( np.array([0.25, 0.75]), level_rates, rate_matrix_solver, @@ -203,6 +205,93 @@ def test_reduced_nlte_residual_recomputes_q_and_beta() -> None: npt.assert_allclose(perturbed_q_ratio, 0.125) +def test_relative_level_residual_does_not_depend_on_rate_unit() -> None: + """Judge level closure relative to the rates that flow through each level. + + Claim: Dividing each level equation by its total rate makes the residual + independent of the unit of time, while the absolute residual scales with + it. + Regime: Two-level atom with one radiative line and an open continuum, + away from equilibrium. + Verification: Metamorphic. Multiplying every rate by k = 1e6 multiplies + each rate equation by k and leaves the normalization row unchanged. The + rtol of 1e-12 covers floating-point rounding. + """ + rate_scale = 1.0e6 + level_index = pd.MultiIndex.from_tuples( + [(1, 0, 0), (1, 0, 1)], + names=["atomic_number", "ion_number", "level_number"], + ) + line_index = pd.MultiIndex.from_tuples( + [(1, 0, 0, 1)], + names=[ + "atomic_number", + "ion_number", + "level_number_lower", + "level_number_upper", + ], + ) + sobolev = SobolevInputs( + np.array([0]), + np.array([1]), + np.array([2.0]), + np.array([4.0]), + np.array([False]), + np.array([True]), + np.array([1.0e-20]), + np.array([0]), + line_index, + ) + + residuals = {} + for scale in (1.0, rate_scale): + rate_matrix_solver = RateMatrix( + RadiativeRatesSolver( + pd.DataFrame( + { + "A_ul": [2.0 * scale], + "B_ul": [0.0], + "B_lu": [1.0 * scale], + "nu": [1.0], + }, + index=line_index, + ) + ), + ZeroElectronRateSolver(), + pd.DataFrame( + {"energy": [0.0, 1.0], "g": [2.0, 4.0]}, index=level_index + ), + ) + residual, _, _, total_rate = calculate_nlte_level_population_residual( + np.array([0.3, 0.7]), + LevelEquationRates( + np.array([2.0, 0.0]) * scale, + np.array([0.0, 4.0]) * scale, + np.zeros((2, 2)), + ), + rate_matrix_solver, + pd.DataFrame([1.0], index=line_index), + ThermalElectronEnergyDistribution( + 0.0 * u.erg, + np.array([1.0e4]) * u.K, + np.array([1.0e9]) / u.cm**3, + ), + (1, 0), + ShellNumberDensity( + 1.0e10, np.array([1.0e10, 0.0]), np.array([0, 1]) + ), + sobolev, + ) + residuals[scale] = (residual, residual / total_rate) + + absolute, relative = residuals[1.0] + scaled_absolute, scaled_relative = residuals[rate_scale] + npt.assert_allclose( + scaled_absolute[1], rate_scale * absolute[1], rtol=1e-12 + ) + npt.assert_allclose(scaled_relative, relative, rtol=1e-12) + + def test_equilibrium_rate_matrices_converge_to_equilibrium_lte( nlte_atomic_dataset: AtomData, ) -> None: diff --git a/tardis/plasma/equilibrium/thermal_balance.py b/tardis/plasma/equilibrium/thermal_balance.py index 4be0adeedac..15a921af9c8 100644 --- a/tardis/plasma/equilibrium/thermal_balance.py +++ b/tardis/plasma/equilibrium/thermal_balance.py @@ -10,6 +10,7 @@ ThermalElectronEnergyDistribution, ) from tardis.plasma.equilibrium.evaluator import ( + LEVEL_RESIDUAL_LIMIT, PlasmaEquilibriumEvaluation, PlasmaEquilibriumEvaluator, ) @@ -24,8 +25,9 @@ logger = logging.getLogger(__name__) THERMAL_BALANCE_RESIDUAL_LIMITS = { - "trial_level_residual": 1e-10, - "level_residual": 1e-10, + # Level equations close relative to the total rate of each equation. + "relative_trial_level_residual": LEVEL_RESIDUAL_LIMIT, + "relative_level_residual": LEVEL_RESIDUAL_LIMIT, "charge_residual": 1e-10, # The charge projection independently solves for the electron density, so # the projected value can differ slightly from the outer trial value. diff --git a/tardis/workflows/tests/test_iip_workflow.py b/tardis/workflows/tests/test_iip_workflow.py index ac7f70c80b4..42399d9c1b7 100644 --- a/tardis/workflows/tests/test_iip_workflow.py +++ b/tardis/workflows/tests/test_iip_workflow.py @@ -487,14 +487,14 @@ def test_iip_level_solution_is_seed_independent_after_first_transport( err_msg="the IIP level equilibrium depends on its initial population", ) np.testing.assert_allclose( - initial_result.trial_level_residual[shell_idx], + initial_result.relative_trial_level_residual[shell_idx], 0.0, rtol=0.0, atol=1e-10, err_msg="the initial-seed IIP level equations do not close", ) np.testing.assert_allclose( - accepted_result.trial_level_residual[shell_idx], + accepted_result.relative_trial_level_residual[shell_idx], 0.0, rtol=0.0, atol=1e-10, @@ -752,7 +752,8 @@ def test_iip_hydrogen_helium_hydrogen_levels_follow_nlte_rate_equations( instead of following dilute-LTE excitation. Regime: Accepted final thermal-balance state of the hydrogen-helium model. Verification: The plasma H I level fractions must equal the solved NLTE - fractions, the level equations must close at the workflow's 1e-10 limit, + fractions, the level equations must close to the workflow's 1e-10 of + each equation's total rate, and at least one H I level must depart from its directly evaluated dilute-LTE fraction by more than 10 %. The 1e-12 relative tolerance allows only floating-point differences in the population rebuild. @@ -776,7 +777,7 @@ def test_iip_hydrogen_helium_hydrogen_levels_follow_nlte_rate_equations( check_names=False, ) np.testing.assert_allclose( - evaluation.level_residual, + evaluation.relative_level_residual, 0.0, rtol=0.0, atol=1e-10, From 4bea3892f30897657a158165e2ee096380fd6244 Mon Sep 17 00:00:00 2001 From: Andrew Fullard <20341051+andrewfullard@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:52:58 -0500 Subject: [PATCH 2/3] Fix assignment --- tardis/plasma/equilibrium/evaluator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tardis/plasma/equilibrium/evaluator.py b/tardis/plasma/equilibrium/evaluator.py index 715e2d31d07..694ddc114e4 100644 --- a/tardis/plasma/equilibrium/evaluator.py +++ b/tardis/plasma/equilibrium/evaluator.py @@ -696,7 +696,7 @@ def _calculate_level_state( np.array([electron_temperature]) * u.K, np.array([electron_density]) / u.cm**3, ) - residual, beta_sobolev, ionized_to_neutral_ratio = ( + residual, beta_sobolev, ionized_to_neutral_ratio, total_rate = ( calculate_nlte_level_population_residual( level_fractions, level_rates, @@ -710,7 +710,7 @@ def _calculate_level_state( bound_bound_rates, ) ) - return residual, beta_sobolev, ionized_to_neutral_ratio + return residual, beta_sobolev, ionized_to_neutral_ratio, total_rate def _calculate_level_solution( self, From d9e3e19d64ef2829ea42b03c92b246cdeb56acc5 Mon Sep 17 00:00:00 2001 From: Andrew Fullard <20341051+andrewfullard@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:59:59 -0500 Subject: [PATCH 3/3] Better test hopefully --- .../tests/test_level_populations.py | 74 ++++++++++++------- 1 file changed, 49 insertions(+), 25 deletions(-) diff --git a/tardis/plasma/equilibrium/tests/test_level_populations.py b/tardis/plasma/equilibrium/tests/test_level_populations.py index 127de4799ab..61ce3a4c569 100644 --- a/tardis/plasma/equilibrium/tests/test_level_populations.py +++ b/tardis/plasma/equilibrium/tests/test_level_populations.py @@ -11,6 +11,7 @@ ) from tardis.plasma.equilibrium.evaluator import ( calculate_nlte_level_population_residual, + calculate_relative_level_residual, ) from tardis.plasma.equilibrium.inputs import ( LevelEquationRates, @@ -243,7 +244,7 @@ def test_relative_level_residual_does_not_depend_on_rate_unit() -> None: line_index, ) - residuals = {} + relative_residuals = {} for scale in (1.0, rate_scale): rate_matrix_solver = RateMatrix( RadiativeRatesSolver( @@ -262,34 +263,57 @@ def test_relative_level_residual_does_not_depend_on_rate_unit() -> None: {"energy": [0.0, 1.0], "g": [2.0, 4.0]}, index=level_index ), ) - residual, _, _, total_rate = calculate_nlte_level_population_residual( - np.array([0.3, 0.7]), - LevelEquationRates( - np.array([2.0, 0.0]) * scale, - np.array([0.0, 4.0]) * scale, - np.zeros((2, 2)), - ), - rate_matrix_solver, - pd.DataFrame([1.0], index=line_index), - ThermalElectronEnergyDistribution( - 0.0 * u.erg, - np.array([1.0e4]) * u.K, - np.array([1.0e9]) / u.cm**3, - ), - (1, 0), - ShellNumberDensity( - 1.0e10, np.array([1.0e10, 0.0]), np.array([0, 1]) - ), - sobolev, + residual, _, ionized_to_neutral_ratio, total_rate = ( + calculate_nlte_level_population_residual( + np.array([0.3, 0.7]), + LevelEquationRates( + np.array([2.0, 3.0]) * scale, + np.array([0.0, 4.0]) * scale, + -np.diag(np.array([2.0, 3.0])) * scale, + ), + rate_matrix_solver, + pd.DataFrame([1.0], index=line_index), + ThermalElectronEnergyDistribution( + 0.0 * u.erg, + np.array([1.0e4]) * u.K, + np.array([1.0e9]) / u.cm**3, + ), + (1, 0), + ShellNumberDensity( + 1.0e10, np.array([1.0e10, 0.0]), np.array([0, 1]) + ), + sobolev, + ) + ) + + # q = (Gamma_0 b_0 + Gamma_1 b_1) / (alpha_0 + alpha_1), with + # Gamma = (2, 3), b = (0.3, 0.7), and alpha = (0, 4). + expected_ionized_to_neutral_ratio = (2.0 * 0.3 + 3.0 * 0.7) / 4.0 + # For level 1, R_0->1 = B_lu J = 1 and R_1->0 = A_ul = 2, so + # total rate = |R_0->1 b_0| + |(-R_1->0 - Gamma_1) b_1| + |alpha_1 q|. + expected_total_rate = np.array( + [ + 1.0, + ( + abs(1.0 * 0.3) + + abs((-2.0 - 3.0) * 0.7) + + abs(4.0 * expected_ionized_to_neutral_ratio) + ) + * scale, + ] + ) + npt.assert_allclose( + ionized_to_neutral_ratio, expected_ionized_to_neutral_ratio + ) + npt.assert_allclose(total_rate, expected_total_rate, rtol=1e-12) + relative_residuals[scale] = calculate_relative_level_residual( + residual, total_rate ) - residuals[scale] = (residual, residual / total_rate) - absolute, relative = residuals[1.0] - scaled_absolute, scaled_relative = residuals[rate_scale] + # Rescaling every rate changes its time unit, not the relative closure. npt.assert_allclose( - scaled_absolute[1], rate_scale * absolute[1], rtol=1e-12 + relative_residuals[rate_scale], relative_residuals[1.0], rtol=1e-12 ) - npt.assert_allclose(scaled_relative, relative, rtol=1e-12) def test_equilibrium_rate_matrices_converge_to_equilibrium_lte(