From 892d3861b03db0e924dc3655b625c9d78b1e6aad Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 11:11:02 -0500 Subject: [PATCH 01/12] initial branch commit --- benchmarks/partial_absorbing_chain.py | 71 +++ docs/io/configuration/components/plasma.rst | 31 ++ docs/physics_walkthrough/montecarlo/index.rst | 3 +- .../montecarlo/partial_absorbing_chain.rst | 75 +++ tardis/io/configuration/schemas/plasma.yml | 16 + tardis/opacities/continuum/continuum_state.py | 2 + .../continuum/continuum_state_numba.py | 7 +- .../macro_atom/absorbing_markov_chain.py | 443 +++++++++++++----- .../opacities/macro_atom/macroatom_solver.py | 40 +- .../opacities/macro_atom/macroatom_state.py | 33 +- .../tests/test_absorbing_markov_chain.py | 8 +- .../tests/test_partial_absorbing_chain.py | 211 +++++++++ tardis/transport/montecarlo/macro_atom.py | 155 +++--- .../tests/test_partial_macro_atom.py | 124 +++++ .../tests/test_partial_chain_workflow.py | 96 ++++ tardis/workflows/type_iip_workflow.py | 4 + 16 files changed, 1134 insertions(+), 185 deletions(-) create mode 100644 benchmarks/partial_absorbing_chain.py create mode 100644 docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst create mode 100644 tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py create mode 100644 tardis/transport/montecarlo/tests/test_partial_macro_atom.py create mode 100644 tardis/workflows/tests/test_partial_chain_workflow.py diff --git a/benchmarks/partial_absorbing_chain.py b/benchmarks/partial_absorbing_chain.py new file mode 100644 index 00000000000..4c82776490f --- /dev/null +++ b/benchmarks/partial_absorbing_chain.py @@ -0,0 +1,71 @@ +"""Remote ASV setup/solve and retained-memory comparison on a fixed network.""" + +import numpy as np +import pandas as pd + +from tardis.opacities.macro_atom.absorbing_markov_chain import ( + create_absorbing_probs, +) + + +class BenchmarkPartialAbsorbingChain: + """Keep physics and cells fixed while changing the reduction boundary.""" + + params = ["full", "H", "He", "H+He", "explicit"] + param_names = ["selection"] + + def setup(self, selection: str) -> None: + """Build H/He/Fe levels plus shared i/k pools in eight cells.""" + states = [ + (atomic_number, 0, level) + for atomic_number in (1, 2, 26) + for level in range(30) + ] + states += [("i", -99, -99), ("k", -99, -99)] + sources = np.repeat(np.arange(len(states)), 3) + self.metadata = pd.DataFrame( + { + "source": [states[source] for source in sources], + "source_level_idx": sources, + "destination_level_idx": np.column_stack( + ( + (np.arange(len(states)) + 1) % len(states), + np.full(len(states), 90), + np.full(len(states), -1), + ) + ).ravel(), + "transition_type": np.tile([1, 2, -1], len(states)), + } + ) + self.probabilities = pd.DataFrame( + np.tile([0.4, 0.2, 0.4], len(states))[:, None] * np.ones((1, 8)) + ) + self.mode = ( + selection if selection in ("full", "explicit") else "partial" + ) + self.elements = ( + () if self.mode != "partial" else tuple(selection.split("+")) + ) + self.result = create_absorbing_probs( + self.probabilities, + self.metadata, + mode=self.mode, + elements=self.elements, + ) + + def time_create_absorbing_probs(self, selection: str) -> None: + """Measure full mapping construction, diagnostics, and per-cell LU solve.""" + create_absorbing_probs( + self.probabilities, + self.metadata, + mode=self.mode, + elements=self.elements, + ) + + def track_selected_states(self, selection: str) -> int: + """Report selected real/pool state count for interpreting solve cost.""" + return len(self.result.reduced_to_macro_level_idx) + + def track_dense_matrix_bytes(self, selection: str) -> int: + """Report retained matrix memory summed over the same eight cells.""" + return self.result.matrix.nbytes diff --git a/docs/io/configuration/components/plasma.rst b/docs/io/configuration/components/plasma.rst index 774439a8127..e8a26120d29 100644 --- a/docs/io/configuration/components/plasma.rst +++ b/docs/io/configuration/components/plasma.rst @@ -64,3 +64,34 @@ The NLTE configuration currently allows setting ``coronal_approximation``, which This is useful for debugging with :term:`chianti` for example. Furthermore, one can enable 'classical_nebular' to set all :math:`\beta_\textrm{Sobolev}` to 1. Both options are used for checking with other codes and should not be enabled in normal operations. + +Type IIP macro-atom reduction +-------------------------------- + +The ``plasma.continuum_interaction.markov_chain`` section controls how Type IIP +transport samples internal macro-atom transitions. Existing configurations use +``mode: full``, which reduces the whole chain. ``mode: explicit`` samples every +original transition and provides a reference for comparisons. Both modes require +an empty ``elements`` list. + +Use ``mode: partial`` with one or more element symbols to reduce internal jumps +between selected atomic states: + +.. code-block:: yaml + + plasma: + continuum_interaction: + species: [H I] + markov_chain: + mode: partial + elements: [H] + +For a multi-element selection, use ``elements: [H, He, Fe]`` when those elements +are present in the assembled network. Duplicate symbols are harmless. A symbol +selects all represented ions and levels of that element. This list is independent +of continuum ``species`` and ``nlte.species``: selecting an element does not +enable additional continuum processes or change its equilibrium treatment. + +The synthetic thermal and ionization pools remain explicit in partial mode. +See :doc:`../../../physics_walkthrough/montecarlo/partial_absorbing_chain` for the +probability contract and scientific verification. diff --git a/docs/physics_walkthrough/montecarlo/index.rst b/docs/physics_walkthrough/montecarlo/index.rst index f23def90068..f3e48548e8c 100644 --- a/docs/physics_walkthrough/montecarlo/index.rst +++ b/docs/physics_walkthrough/montecarlo/index.rst @@ -24,4 +24,5 @@ can also be found in various papers by L. Lucy and in the main TARDIS publicatio initialization propagation lineinteraction - estimators \ No newline at end of file + estimators + partial_absorbing_chain diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst new file mode 100644 index 00000000000..bc060ac55ad --- /dev/null +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -0,0 +1,75 @@ +Element-selected absorbing chains +================================= + +Type IIP transport can skip internal macro-atom jumps while preserving the +probabilities of eventual emission and cooling. In partial mode, let S contain +all represented real atomic levels of the requested elements. Only internal +edges with both endpoints in S are eliminated. The shared ionization (i) and +thermal (k) pools stay outside S, even when every atomic element is selected. + +For each cell, Q contains the eliminated transition probabilities, L contains +the original probabilities with just those edges removed, and r is the sum of +each selected state's remaining outgoing channels. The first-exit matrix B and +conditional channel probabilities C satisfy + +.. math:: + + (I-Q)B = \operatorname{diag}(r), \qquad + C_{j,c} = L_{j,c}/r_j, \qquad + (I-Q)^{-1} L = BC. + +Rows of B are activation states; columns identify exit-source states. This +matrix need not be symmetric. A draw from B selects the global source of the +next retained channel, followed by an independent draw from C. A retained +internal transition continues the interaction; only a negative transition code +ends it. Each return to S starts a fresh, independent pair of draws. Outside S, +transport samples the original channel probabilities directly. + +Emission-only states and global level zero are included. Explicit int64 forward +and inverse maps preserve global identities, including gaps in the level +indices. A zero residual row stays zero and cannot supply an exit. Metadata +and numerical probabilities are rebuilt consistently on every opacity solve; +continuum activation indices and estimator dimensions keep their original +ordering and shell count. + +Sparse LU solves are checked for finite, nonnegative, normalized probabilities +and a scale-aware equation residual. A reachable closed class without a physical +exit raises a diagnostic containing the cell and states. Channels are never +removed by a numerical probability threshold. The sampler allows a CDF endpoint +deficit of at most 1e-10 due to floating-point summation; larger deficits or +activations without outgoing probability raise an error. + +Exact small-network tests compare eventual channel distributions with an +independent dense solve of the unreduced network. Compiled sampling tests check +the analytic 50 percent / 25 percent / 25 percent re-entry example with binomial +uncertainty bounds. Full mode preserves the existing default and its two-draw +sampling behavior. The different modes preserve distributions, rather than +individual random packet histories. + +A smaller matrix does not guarantee faster transport: explicit cycling through +unselected states and shared pools can dominate. Compare setup and solve cost, +selected-state count, dense matrix bytes, explicit steps, and total transport +cost with the existing ASV remote benchmarking workflow on the same network and +packet count. No hardware-independent speedup is implied. + +Signed-channel limitation +------------------------- + +Some accepted plasma states produce negative stimulated-recombination-corrected +photoionization coefficients (for example, the existing 1500 K outer-shell +cutoff scenario). Full mode preserves the legacy aggregate elimination of these +signed internal coefficients and their legacy signed matrix. That legacy +case does not carry the probability nonnegativity guarantee of the new modes. +Partial and explicit modes reject negative original probabilities with a cell +and transition diagnostic: a signed channel cannot be sampled as an explicit +probability. Select full mode for those states. The reduction does not clip +coefficients or change the underlying plasma/opacity physics. + +Exceptionally near-trapping partial chains can lose tiny exits through +floating-point cancellation. Their diagonals use actual exits and off-diagonal +jumps; if float64 LU violates probability conservation, a Decimal +elimination with at least 80 digits (40 guard digits beyond the smallest +positive exit) retries the conservation-form system. This preserves tiny physical +channels without inventing probabilities or removing transitions. Full mode +retains the original numerical calculation for regression compatibility, +including its cancellation limits for exceptionally near-trapping chains. diff --git a/tardis/io/configuration/schemas/plasma.yml b/tardis/io/configuration/schemas/plasma.yml index cdc39423421..c54c7aec556 100644 --- a/tardis/io/configuration/schemas/plasma.yml +++ b/tardis/io/configuration/schemas/plasma.yml @@ -80,6 +80,22 @@ properties: default: {} additionalProperties: false properties: + markov_chain: + type: object + default: {} + additionalProperties: false + properties: + mode: + type: string + enum: [full, partial, explicit] + default: full + description: Macro-atom internal-transition reduction for Type IIP transport. + elements: + type: array + items: + type: string + default: [] + description: Element symbols reduced in partial mode; empty in other modes. nthreads: type: integer minimum: 1 diff --git a/tardis/opacities/continuum/continuum_state.py b/tardis/opacities/continuum/continuum_state.py index 517f37719e4..1e562beaea7 100644 --- a/tardis/opacities/continuum/continuum_state.py +++ b/tardis/opacities/continuum/continuum_state.py @@ -269,6 +269,8 @@ def to_numba( photo_ion_activation_idx, np.int64(macro_atom_state.k_packet_idx), macro_atom_state.absorbing_probability_matrix, + macro_atom_state.macro_level_to_reduced_idx, + macro_atom_state.reduced_to_macro_level_idx, ) @property diff --git a/tardis/opacities/continuum/continuum_state_numba.py b/tardis/opacities/continuum/continuum_state_numba.py index 45c6915dc6e..e71c8c7ae6f 100644 --- a/tardis/opacities/continuum/continuum_state_numba.py +++ b/tardis/opacities/continuum/continuum_state_numba.py @@ -21,6 +21,8 @@ class ContinuumOpacityStateNumba: photo_ion_activation_idx: nb.int64[:] k_packet_idx: nb.int64 absorbing_markov_probabilities: nb.float64[:, :, :] + macro_level_to_reduced_idx: nb.int64[:] + reduced_to_macro_level_idx: nb.int64[:] def __init__( self, @@ -37,6 +39,8 @@ def __init__( photo_ion_activation_idx: npt.NDArray[np.int64], k_packet_idx: int, absorbing_markov_probabilities: npt.NDArray[np.float64], + macro_level_to_reduced_idx: npt.NDArray[np.int64], + reduced_to_macro_level_idx: npt.NDArray[np.int64], ) -> None: self.bf_threshold_list_nu = bf_threshold_list_nu self.p_fb_deactivation = p_fb_deactivation @@ -51,4 +55,5 @@ def __init__( self.photo_ion_activation_idx = photo_ion_activation_idx self.k_packet_idx = k_packet_idx self.absorbing_markov_probabilities = absorbing_markov_probabilities - + self.macro_level_to_reduced_idx = macro_level_to_reduced_idx + self.reduced_to_macro_level_idx = reduced_to_macro_level_idx diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 42fc1bb6030..2926593fa1f 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -1,134 +1,367 @@ -"""Calculate absorption probabilities using absorbing Markov chain theory. - -This module implements the mathematical framework of absorbing Markov chains -to compute probabilities of photon absorption in each cell and the expected -number of steps before absorption from each source state. - -References ----------- - Absorbing Markov chain theory: https://en.wikipedia.org/wiki/Absorbing_Markov_chain -""" +"""First-exit probabilities for full and element-selected macro-atom chains.""" +from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor +from decimal import Decimal, localcontext +from typing import NamedTuple import numpy as np +import numpy.typing as npt import pandas as pd -import scipy +from scipy import sparse +from scipy.sparse.linalg import splu + +from tardis.util.base import element_symbol2atomic_number + +# LU/CDF arithmetic tolerance, not a tolerance for discarding physical channels. +PROBABILITY_TOLERANCE = 1e-10 + + +class AbsorbingChainResult(NamedTuple): + """Carry first-exit probabilities and their global/compact index contract.""" + + matrix: npt.NDArray[np.float64] + residual_probabilities: pd.DataFrame + macro_level_to_reduced_idx: npt.NDArray[np.int64] + reduced_to_macro_level_idx: npt.NDArray[np.int64] def create_absorbing_probs( transition_probabilities: pd.DataFrame, metadata: pd.DataFrame, + *, + mode: str = "full", + elements: Sequence[str] = (), max_workers: int = 1, -) -> tuple[np.ndarray, pd.DataFrame]: - """Calculate absorbing Markov chain probabilities and deactivation data. - - Computes the absorption probability matrices for each cell and extracts - deactivation probabilities by solving the absorbing Markov chain system. - The fundamental matrix is computed to determine absorption probabilities - and expected number of steps to absorption from each state. - - WARNING: This is currently slower than it needs to be for many element sims. - You should be able to slice out and process a subset of the probabilities - based on some source state filtering. We have a draft PR open for this - but it has not been finished. +) -> AbsorbingChainResult: + """Eliminate internal transitions within the selected state set. Parameters ---------- - transition_probabilities : pd.DataFrame - DataFrame with transition probabilities between states for each cell. - Rows represent transitions, columns represent cells. - metadata : pd.DataFrame - Metadata about transitions including source_level_idx, - destination_level_idx, and transition_type. Values >= 0 for - transition_type indicate internal transitions transitions that are not accompanied - by reemission of the r-packet, and an end to the interaction handler chain. - Negative values indicate deactivation, or reemitting from an absorbing state. + transition_probabilities : pandas.DataFrame + Normalized original channel probabilities; columns are cells. + metadata : pandas.DataFrame + Transition source tuples, global source/destination indices, and types. + mode : {'full', 'partial', 'explicit'} + Full eliminates all internal jumps. Partial eliminates only jumps with + both endpoints in selected elements; synthetic i/k pools stay explicit. + Explicit retains every original transition. + elements : sequence of str + Element symbols, required only in partial mode. All represented ions + and levels of each selected element are included. + max_workers : int + Maximum number of cell-independent sparse LU workers. Returns ------- - tuple[np.ndarray, pd.DataFrame] - - absorbing_probability_matrix : np.ndarray - Array of shape (num_cells, num_states, num_states) containing - absorption probabilities from each state for each cell. - - deactivating_probs : pd.DataFrame - DataFrame of deactivation transition probabilities from - absorption states. + AbsorbingChainResult + Cell-by-activation-by-exit-source matrix, residual channel probabilities, + and explicit global-to-reduced and reduced-to-global int64 maps. + + Notes + ----- + The solve is ``(I-Q) B = diag(r)``, where r is the sum of actual remaining + channels. Zero residual rows stay zero. No rate threshold removes a channel. + The matrix selects the source of the first retained transition, which can + itself be internal. It is not necessarily a final emission state. """ - num_cells = transition_probabilities.shape[1] - - internal_mask = metadata.transition_type >= 0 - internal_jump_probs = transition_probabilities[internal_mask] - # This logic fails if any source blocks are dropped. Previous implementation was - # num_states = len(metadata.source.unique()). Not needed right now but will be - # needed if we want to do Markov chain reduction for only specific species. - num_states = int(metadata.source_level_idx.max()) + 1 - - absorbing_probability_matrix = np.zeros((num_cells, num_states, num_states)) - # Josh: The expected steps calculation is another linear algebra solve. We don't need - # it for the MC calculation, so I'm removing it, but leaving it commented in case it is - # useful for diagnostic purposes in the future. - # expected_steps_in_cells_from_states = np.zeros((num_cells, num_states)) - - rows = metadata[internal_mask].source_level_idx.to_numpy() - cols = metadata[internal_mask].destination_level_idx.to_numpy() - identity_matrix = scipy.sparse.identity(num_states, format="csc") - - def solve_cell(cell: int) -> tuple[int, np.ndarray]: - """Solve the absorbing Markov chain system for one cell. - - Parameters - ---------- - cell : int - Cell index in the transition probability table. - - Returns - ------- - tuple[int, np.ndarray] - Cell index and full state-by-state absorbing probability matrix. - """ - # In each cell, solve for absorbing markov chain probability - # Follows math https://en.wikipedia.org/wiki/Absorbing_Markov_chain - vals = internal_jump_probs.iloc[:, cell].to_numpy() - - internal_jump_matrix = scipy.sparse.coo_matrix( - (vals, (rows, cols)), shape=(num_states, num_states) + if mode not in ("full", "partial", "explicit"): + raise ValueError("markov_chain.mode must be full, partial, or explicit") + if (mode == "partial") != bool(elements): + raise ValueError( + "markov_chain.elements must be nonempty only in partial mode" ) + try: + atomic_numbers = sorted( + {element_symbol2atomic_number(symbol) for symbol in elements} + ) + except Exception as error: + raise ValueError( + f"Invalid markov_chain element symbol in {list(elements)}" + ) from error - identity_minus_Q = identity_matrix - internal_jump_matrix - csc_N = identity_minus_Q.tocsc() - - # expected_steps = np.asarray( - # scipy.sparse.linalg.spsolve(csc_N, np.ones(num_states)) - # ).flatten() - # expected_steps_in_cells_from_states[cell] = expected_steps + sources = metadata.source_level_idx.to_numpy(dtype=np.int64) + destinations = metadata.destination_level_idx.to_numpy(dtype=np.int64) + internal = metadata.transition_type.to_numpy() >= 0 + global_size = int(sources.max()) + 1 + source_states = np.unique(sources) + missing = np.setdiff1d(destinations[internal], source_states) + if len(missing): + raise ValueError( + f"Internal destination levels lack outgoing transition blocks: {missing}" + ) + if mode == "full": + selected = np.arange(global_size, dtype=np.int64) + elif mode == "partial": + selected_rows = metadata.source.map( + lambda level: level[0] in atomic_numbers + ).to_numpy() + represented = {level[0] for level in metadata.source} + absent = set(atomic_numbers) - represented + if absent: + raise ValueError( + f"markov_chain.elements absent from assembled macro-atom network: {sorted(absent)}" + ) + selected = np.unique(sources[selected_rows]) + else: + selected = np.empty(0, dtype=np.int64) + lookup = np.full(global_size, -1, dtype=np.int64) + lookup[selected] = np.arange(len(selected), dtype=np.int64) + # Negative deactivation destinations must never index the lookup. + eliminated = np.zeros(len(metadata), dtype=bool) + eliminated[internal] = (lookup[sources[internal]] >= 0) & ( + lookup[destinations[internal]] >= 0 + ) + residual = transition_probabilities.copy() + residual.iloc[eliminated, :] = 0.0 + rows = lookup[sources[eliminated]] + columns = lookup[destinations[eliminated]] + matrices = np.zeros( + (transition_probabilities.shape[1], len(selected), len(selected)) + ) - deactivation_row = np.asarray( - internal_jump_matrix.sum(axis=1) - ).flatten() - solved_matrix = np.asarray( - scipy.sparse.linalg.splu(csc_N, permc_spec="MMD_AT_PLUS_A").solve( - np.diag(1 - deactivation_row) + def solve_cell(cell: int) -> tuple[int, npt.NDArray[np.float64]]: + """Check the cell's physical exits and solve its selected first-exit law.""" + values = transition_probabilities.iloc[:, cell].to_numpy() + totals = np.bincount(sources, weights=values, minlength=global_size) + active = totals > 0 + if not np.all(np.isfinite(values)) or ( + mode != "full" and np.any(values < -PROBABILITY_TOLERANCE) + ): + raise ValueError( + f"cell {cell}: nonfinite or negative channel probabilities at transitions {metadata.index[~np.isfinite(values) | (values < -PROBABILITY_TOLERANCE)].tolist()}; partial/explicit sampling requires nonnegative original channels; use full mode for signed stimulated-recombination coefficients" + ) + if not np.allclose( + totals[active], 1, rtol=0, atol=PROBABILITY_TOLERANCE + ): + raise ValueError( + f"cell {cell}: original outgoing probabilities are not normalized" + ) + # Reverse reachability from positive physical deactivation channels detects + # closed communicating classes even in explicit mode, before MC can trap. + reachable = ( + np.bincount( + sources[~internal], + weights=values[~internal], + minlength=global_size, + ) + > 0 + ) + positive_internal = internal & (values > 0) + graph = sparse.csr_matrix( + ( + np.ones(positive_internal.sum()), + (destinations[positive_internal], sources[positive_internal]), + ), + shape=(global_size, global_size), + ) + pending = np.flatnonzero(reachable).tolist() + while pending: + destination = pending.pop() + for source in graph.indices[ + graph.indptr[destination] : graph.indptr[destination + 1] + ]: + if not reachable[source]: + reachable[source] = True + pending.append(source) + trapped = np.flatnonzero(active & ~reachable) + if len(trapped): + raise ValueError( + f"cell {cell}: closed or non-emitting communicating class reachable from states {trapped}" ) + if not len(selected): + return cell, matrices[cell] + q_matrix = sparse.coo_matrix( + (values[eliminated], (rows, columns)), + shape=(len(selected), len(selected)), ) - return cell, solved_matrix + exit_rates = np.bincount( + sources, + weights=residual.iloc[:, cell].to_numpy(), + minlength=global_size, + )[selected] + q_totals = np.asarray(q_matrix.sum(axis=1)).ravel() + if not np.allclose( + q_totals + exit_rates, + totals[selected], + rtol=0, + atol=PROBABILITY_TOLERANCE, + ): + raise ValueError( + f"cell {cell}: eliminated and residual channels do not partition the original rates" + ) + system = (sparse.eye(len(selected), format="csc") - q_matrix).tocsc() + rhs = exit_rates + if mode == "full": + # Retain master's numerical/RNG behavior for ordinary full solves, + # including its inert rows for levels without outgoing probability. + rhs = 1 - q_totals + # For near-trapping self-loops, form the diagonal from physical exits + # and off-diagonal jumps, avoiding catastrophic cancellation in 1-Qii. + near_trapping = q_matrix.diagonal() > 0.99 + if mode != "full" and np.any(near_trapping): + off_diagonal = q_matrix.copy() + off_diagonal.setdiag(0) + stable_diagonal = ( + np.asarray(off_diagonal.sum(axis=1)).ravel() + exit_rates + ) + diagonal = system.diagonal() + diagonal[near_trapping] = stable_diagonal[near_trapping] + system.setdiag(diagonal) + rhs = rhs.copy() + rhs[near_trapping] = exit_rates[near_trapping] + try: + solved = splu(system, permc_spec="MMD_AT_PLUS_A").solve( + np.diag(rhs) + ) + except RuntimeError as error: + if mode == "full": + raise ValueError( + f"cell {cell}: closed selected chain at states {selected}" + ) from error + solved = solve_near_trapping_chain( + q_matrix, exit_rates, active[selected] + ) + if mode != "full" and not np.allclose( + solved[active[selected]].sum(axis=1), + 1, + rtol=0, + atol=32 * np.finfo(np.float64).eps, + ): + solved = solve_near_trapping_chain( + q_matrix, exit_rates, active[selected] + ) + residual_norm = np.max(np.abs(system @ solved - np.diag(rhs))) + residual_scale = max( + 1.0, + sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), + ) + signed_legacy_chain = mode == "full" and np.any(values < 0) + if ( + not np.all(np.isfinite(solved)) + or ( + not signed_legacy_chain + and np.any(solved < -PROBABILITY_TOLERANCE) + ) + or residual_norm > PROBABILITY_TOLERANCE * residual_scale + or not np.allclose( + solved[active[selected]].sum(axis=1), + 1, + rtol=0, + atol=PROBABILITY_TOLERANCE, + ) + ): + raise ValueError( + f"cell {cell}: invalid absorbing solve for states {selected}; residual {residual_norm}" + ) + return cell, solved - if max_workers > 1 and num_cells > 1: + if max_workers > 1 and len(matrices) > 1: with ThreadPoolExecutor( - max_workers=min(max_workers, num_cells) + max_workers=min(max_workers, len(matrices)) ) as executor: - cell_solutions = executor.map(solve_cell, range(num_cells)) - for cell, solved_matrix in cell_solutions: - absorbing_probability_matrix[cell] = solved_matrix + for cell, solved in executor.map(solve_cell, range(len(matrices))): + matrices[cell] = solved else: - for cell in range(num_cells): - _, solved_matrix = solve_cell(cell) - absorbing_probability_matrix[cell] = solved_matrix + for cell in range(len(matrices)): + _, matrices[cell] = solve_cell(cell) + return AbsorbingChainResult(matrices, residual, lookup, selected) - deactivating_probs = transition_probabilities.copy() - deactivating_probs[internal_mask] *= 0 - return ( - absorbing_probability_matrix, - deactivating_probs, - ) +def solve_near_trapping_chain( + internal_matrix: sparse.spmatrix, + exit_rates: npt.NDArray[np.float64], + active: npt.NDArray[np.bool_], +) -> npt.NDArray[np.float64]: + """Resolve exceptional cancellation in a transient sparse LU solve. + + Parameters + ---------- + internal_matrix : scipy.sparse.spmatrix + Selected internal probabilities Q. + exit_rates : numpy.ndarray + Actual retained channel sums, without subtracting from one. + active : numpy.ndarray + States having original outgoing probability. + + Returns + ------- + numpy.ndarray + First-exit matrix evaluated with at least 80-digit elimination, then rounded + to float64. Precision also resolves the smallest positive exit with 40 + guard digits. Used only if LU violates probability normalization. + + Notes + ----- + The conservation-form diagonal is the sum of off-diagonal internal jumps + and actual exits. This preserves tiny exits in multi-state near-closed + cycles, where even a long residence time must give total exit probability + one. Inactive rows represent no physical activation and stay zero. + """ + size = len(exit_rates) + with localcontext() as context: + positive_exit_rates = exit_rates[exit_rates > 0] + context.prec = max( + 80, 40 - int(np.floor(np.log10(positive_exit_rates.min()))) + ) + zero = Decimal(0) + one = Decimal(1) + dense = internal_matrix.toarray() + system = [ + [ + -Decimal(float(dense[row, column])) if row != column else zero + for column in range(size) + ] + for row in range(size) + ] + rhs = [[zero for _ in range(size)] for _ in range(size)] + for row in range(size): + rate = Decimal(float(exit_rates[row])) + system[row][row] = ( + sum( + ( + -system[row][column] + for column in range(size) + if row != column + ), + rate, + ) + if active[row] + else one + ) + rhs[row][row] = rate + for pivot_idx in range(size): + pivot_row = max( + range(pivot_idx, size), + key=lambda row: abs(system[row][pivot_idx]), + ) + if not system[pivot_row][pivot_idx]: + raise ValueError( + "Closed selected chain in high-precision solve" + ) + system[pivot_idx], system[pivot_row] = ( + system[pivot_row], + system[pivot_idx], + ) + rhs[pivot_idx], rhs[pivot_row] = rhs[pivot_row], rhs[pivot_idx] + pivot = system[pivot_idx][pivot_idx] + for row in range(pivot_idx + 1, size): + factor = system[row][pivot_idx] / pivot + for column in range(pivot_idx + 1, size): + system[row][column] -= factor * system[pivot_idx][column] + for column in range(size): + rhs[row][column] -= factor * rhs[pivot_idx][column] + solved = [[zero for _ in range(size)] for _ in range(size)] + for row in range(size - 1, -1, -1): + for channel in range(size): + solved[row][channel] = ( + rhs[row][channel] + - sum( + ( + system[row][column] * solved[column][channel] + for column in range(row + 1, size) + ), + zero, + ) + ) / system[row][row] + return np.asarray(solved, dtype=np.float64) diff --git a/tardis/opacities/macro_atom/macroatom_solver.py b/tardis/opacities/macro_atom/macroatom_solver.py index a0f513f6cd9..a69a477a863 100644 --- a/tardis/opacities/macro_atom/macroatom_solver.py +++ b/tardis/opacities/macro_atom/macroatom_solver.py @@ -816,6 +816,8 @@ def __init__( selected_continuum_transitions: np.ndarray = np.array([]), line_interaction_type: str = "macroatom", nthreads: int = 1, + markov_chain_mode: str = "full", + markov_chain_elements: tuple[str, ...] = (), ) -> None: """ Initialize the ContinuumMacroAtomSolver. @@ -838,6 +840,10 @@ def __init__( nthreads Maximum number of worker threads for shell-independent opacity calculations. + markov_chain_mode : str + Full, element-selected partial, or explicit sampling. + markov_chain_elements : tuple of str + Element symbols selected independently of enabled continuum physics. """ super().__init__( lines=lines, @@ -870,6 +876,8 @@ def __init__( # ) self.ionization_energies = ionization_energies self.nthreads = nthreads + self.markov_chain_mode = markov_chain_mode + self.markov_chain_elements = tuple(markov_chain_elements) def solve( self, @@ -1019,6 +1027,8 @@ def solve( absorbing_probability_matrix, photo_ion_block_idx, k_packet_idx, + macro_level_to_reduced_idx=self.macro_level_to_reduced_idx, + reduced_to_macro_level_idx=self.reduced_to_macro_level_idx, ) def set_static_properties( @@ -1320,14 +1330,21 @@ def _solve_first_macroatom_iteration( ) # normalized_probabilities = probabilities_df # Useful for debugging - ( - absorbing_probability_matrix, - deactivating_probs, - ) = create_absorbing_probs( + chain_result = create_absorbing_probs( normalized_probabilities, macro_atom_transition_metadata, + mode=self.markov_chain_mode, + elements=self.markov_chain_elements, max_workers=self.nthreads, ) + absorbing_probability_matrix = chain_result.matrix + deactivating_probs = chain_result.residual_probabilities + self.macro_level_to_reduced_idx = ( + chain_result.macro_level_to_reduced_idx + ) + self.reduced_to_macro_level_idx = ( + chain_result.reduced_to_macro_level_idx + ) normalized_deactivating_probs = self.normalize_transition_probabilities( deactivating_probs, macro_atom_transition_metadata ) @@ -1648,14 +1665,21 @@ def _solve_next_macroatom_iteration( normalized_probabilities = self.normalize_transition_probabilities( probabilities_df, macro_atom_transition_metadata ) - ( - absorbing_probability_matrix, - deactivating_probs, - ) = create_absorbing_probs( + chain_result = create_absorbing_probs( normalized_probabilities, macro_atom_transition_metadata, + mode=self.markov_chain_mode, + elements=self.markov_chain_elements, max_workers=self.nthreads, ) + absorbing_probability_matrix = chain_result.matrix + deactivating_probs = chain_result.residual_probabilities + self.macro_level_to_reduced_idx = ( + chain_result.macro_level_to_reduced_idx + ) + self.reduced_to_macro_level_idx = ( + chain_result.reduced_to_macro_level_idx + ) normalized_deactivating_probs = self.normalize_transition_probabilities( deactivating_probs, macro_atom_transition_metadata ) diff --git a/tardis/opacities/macro_atom/macroatom_state.py b/tardis/opacities/macro_atom/macroatom_state.py index 9ef8d4683b8..d371b3566d4 100644 --- a/tardis/opacities/macro_atom/macroatom_state.py +++ b/tardis/opacities/macro_atom/macroatom_state.py @@ -1,6 +1,7 @@ from typing import Self import numpy as np +import numpy.typing as npt import pandas as pd from tardis.io.hdf_writer_mixin import HDFWriterMixin @@ -8,6 +9,8 @@ class LegacyMacroAtomState(HDFWriterMixin): + """Store legacy macro-atom transition arrays for transport and HDF output.""" + hdf_name = "macro_atom_state" hdf_properties = [ @@ -26,7 +29,7 @@ def __init__( destination_level_id: pd.Series, transition_line_id: pd.Series, macro_block_edge_index: pd.DataFrame | pd.Series, - line2macro_level_upper, + line2macro_level_upper: np.ndarray | pd.Series, ) -> None: """ Initialize a LegacyMacroAtomState object. @@ -54,7 +57,7 @@ def __init__( self.line2macro_level_upper = line2macro_level_upper @classmethod - def from_legacy_plasma(cls, plasma) -> Self: + def from_legacy_plasma(cls, plasma: object) -> Self: """ Generate a LegacyMacroAtomState object from a tardis BasePlasma. @@ -96,6 +99,8 @@ def from_legacy_plasma(cls, plasma) -> Self: class MacroAtomState: + """Carry original rates, residual channels, and reduced-state identities.""" + hdf_name = "macro_atom_state" hdf_properties = [ @@ -115,6 +120,8 @@ def __init__( absorbing_probability_matrix: np.ndarray | None = None, photo_ion_block_idx: int = -99, k_packet_idx: int = -99, + macro_level_to_reduced_idx: npt.NDArray[np.int64] | None = None, + reduced_to_macro_level_idx: npt.NDArray[np.int64] | None = None, ) -> None: """ Initialize a MacroAtomState object. @@ -135,6 +142,10 @@ def __init__( Ndarray describing a single jump from an interaction handler activation to a state to deactivate from. k_packet_idx: Int describing the index location of the k_packet block + macro_level_to_reduced_idx : numpy.ndarray, optional + Global-to-compact index map; -1 denotes an explicit state. + reduced_to_macro_level_idx : numpy.ndarray, optional + Inverse map from compact matrix indices to global macro levels. """ self.transition_probabilities = transition_probabilities self.transition_metadata = transition_metadata @@ -145,6 +156,22 @@ def __init__( self.absorbing_probability_matrix = absorbing_probability_matrix self.photo_ion_block_idx = photo_ion_block_idx self.k_packet_idx = k_packet_idx + if ( + macro_level_to_reduced_idx is None + and absorbing_probability_matrix is not None + ): + macro_level_to_reduced_idx = np.arange( + absorbing_probability_matrix.shape[1], dtype=np.int64 + ) + if ( + reduced_to_macro_level_idx is None + and absorbing_probability_matrix is not None + ): + reduced_to_macro_level_idx = np.arange( + absorbing_probability_matrix.shape[1], dtype=np.int64 + ) + self.macro_level_to_reduced_idx = macro_level_to_reduced_idx + self.reduced_to_macro_level_idx = reduced_to_macro_level_idx def to_legacy_format(self) -> LegacyMacroAtomState: """ @@ -179,7 +206,7 @@ def to_legacy_format(self) -> LegacyMacroAtomState: def sort_to_legacy( self, legacy_state: LegacyMacroAtomState, lines: pd.DataFrame - ): + ) -> Self: """ Sort the current MacroAtomState to match the legacy MacroAtomState order. diff --git a/tardis/opacities/macro_atom/tests/test_absorbing_markov_chain.py b/tardis/opacities/macro_atom/tests/test_absorbing_markov_chain.py index f46e31cce17..e8c6118138a 100644 --- a/tardis/opacities/macro_atom/tests/test_absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/tests/test_absorbing_markov_chain.py @@ -91,14 +91,12 @@ def test_create_absorbing_probs_matches_full_diagonal_solve() -> None: ) ) - actual_matrix, actual_deactivating_probs = create_absorbing_probs( - transition_probabilities, metadata - ) + result = create_absorbing_probs(transition_probabilities, metadata) expected_matrix, expected_deactivating_probs = ( _create_absorbing_probs_reference(transition_probabilities, metadata) ) - np.testing.assert_allclose(actual_matrix, expected_matrix, rtol=1e-14) + np.testing.assert_allclose(result.matrix, expected_matrix, rtol=1e-14) pd.testing.assert_frame_equal( - actual_deactivating_probs, expected_deactivating_probs + result.residual_probabilities, expected_deactivating_probs ) diff --git a/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py new file mode 100644 index 00000000000..b101a3bf291 --- /dev/null +++ b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py @@ -0,0 +1,211 @@ +"""Comprehensive verification of element-selected macro-atom probabilities.""" + +import numpy as np +import pandas as pd +import pytest + +from tardis.opacities.macro_atom.absorbing_markov_chain import ( + create_absorbing_probs, +) + + +@pytest.fixture +def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: + """H/He/Fe levels, terminal H, shared pools, and two different cells.""" + levels = { + 0: (1, 0, 0), + 2: (1, 1, 0), + 4: ("i", -99, -99), + 5: (2, 0, 0), + 6: ("k", -99, -99), + 9: (1, 1, 1), + 12: (26, 1, 0), + } + sources = [0, 0, 2, 2, 2, 4, 4, 5, 5, 6, 6, 6, 9, 12, 12] + destinations = [2, -1, 4, 9, -1, 0, -1, 6, -1, 0, 12, -1, -1, 6, -1] + metadata = pd.DataFrame( + { + "source_level_idx": sources, + "destination_level_idx": destinations, + "transition_type": [1 if idx >= 0 else -1 for idx in destinations], + "source": [levels[idx] for idx in sources], + "destination": [ + levels.get(idx, ("r", -99, -99)) for idx in destinations + ], + } + ) + probabilities = pd.DataFrame( + { + 10: [ + 0.0, + 1.0, + 0.3, + 0.2, + 0.5, + 0.5, + 0.5, + 0.3, + 0.7, + 0.1, + 0.1, + 0.8, + 1.0, + 0.25, + 0.75, + ], + 30: [ + 1.0, + 0.0, + 0.2, + 0.1, + 0.7, + 0.8, + 0.2, + 0.6, + 0.4, + 0.05, + 0.05, + 0.9, + 1.0, + 0.4, + 0.6, + ], + } + ) + return probabilities, metadata + + +@pytest.mark.parametrize( + "mode,elements", + [ + ("full", []), + ("partial", ["H"]), + ("partial", ["He"]), + ("partial", ["Fe", "He", "H", "H"]), + ("explicit", []), + ], +) +def test_final_emission_law( + pool_network: tuple[pd.DataFrame, pd.DataFrame], + mode: str, + elements: list[str], +) -> None: + """Selection preserves every eventual emission channel in a mixed network. + + Regime: two cells, multiple ions, gapped indices including zero, an + emission-only destination, zero residual/internal rows, and pool re-entry. + Verify the mask and maps directly, then compare final channel probabilities + with a dense solve of the original network. The reference never uses the + reduced matrix. A 2e-14 tolerance allows floating-point LU roundoff. + """ + probabilities, metadata = pool_network + result = create_absorbing_probs( + probabilities, metadata, mode=mode, elements=elements, max_workers=2 + ) + serial = create_absorbing_probs( + probabilities, metadata, mode=mode, elements=elements + ) + np.testing.assert_array_equal(result.matrix, serial.matrix) + + states = np.unique(metadata.source_level_idx) + global_size = int(states.max()) + 1 + atomic_numbers = {"H": 1, "He": 2, "Fe": 26} + selected_elements = {atomic_numbers[symbol] for symbol in elements} + selected = ( + np.arange(global_size) + if mode == "full" + else np.unique( + metadata.loc[ + metadata.source.map( + lambda level: level[0] in selected_elements + ), + "source_level_idx", + ] + ) + ) + lookup = np.full(global_size, -1, dtype=np.int64) + lookup[selected] = np.arange(len(selected)) + np.testing.assert_array_equal(result.reduced_to_macro_level_idx, selected) + np.testing.assert_array_equal(result.macro_level_to_reduced_idx, lookup) + eliminated = ( + (metadata.transition_type >= 0) + & metadata.source_level_idx.isin(selected) + & metadata.destination_level_idx.isin(selected) + ) + expected_residual = probabilities.copy() + expected_residual.loc[eliminated] = 0.0 + pd.testing.assert_frame_equal( + result.residual_probabilities, expected_residual + ) + + channel_count = int((metadata.transition_type < 0).sum()) + for cell in range(probabilities.shape[1]): + original = np.zeros((global_size, global_size)) + channels = np.zeros((global_size, channel_count)) + residual = np.zeros((global_size, global_size + channel_count)) + channel = 0 + for transition, row in metadata.iterrows(): + source = row.source_level_idx + destination = row.destination_level_idx + probability = probabilities.iloc[transition, cell] + retained_probability = result.residual_probabilities.iloc[ + transition, cell + ] + if row.transition_type >= 0: + original[source, destination] += probability + residual[source, destination] += retained_probability + else: + channels[source, channel] += probability + residual[source, global_size + channel] += retained_probability + channel += 1 + expected = np.linalg.solve( + np.eye(len(states)) - original[np.ix_(states, states)], + channels[states], + ) + totals = residual.sum(axis=1) + np.divide( + residual, totals[:, None], out=residual, where=totals[:, None] != 0 + ) + composed = residual.copy() + composed[selected] = result.matrix[cell] @ residual[selected] + actual = np.linalg.solve( + np.eye(len(states)) - composed[np.ix_(states, states)], + composed[states, global_size:], + ) + np.testing.assert_allclose(actual, expected, rtol=2e-14, atol=2e-14) + + +def test_asymmetric_near_trapping_cycle_preserves_tiny_exit_ratio() -> None: + """Tiny 1:3 exit rates give asymptotic 1/4:3/4 branching, without cancellation. + + Exact two-state formula retains each actual exit rate; 1e-14 absolute + tolerance covers final float64 rounding, not an error amplified by trapping. + """ + first_exit, second_exit = 1e-12, 3e-12 + metadata = pd.DataFrame( + { + "source_level_idx": [0, 0, 1, 1], + "destination_level_idx": [1, -1, 0, -1], + "transition_type": [1, -1, 1, -1], + "source": [(1, 0, 0)] * 2 + [(1, 1, 0)] * 2, + } + ) + result = create_absorbing_probs( + pd.DataFrame( + [1 - first_exit, first_exit, 1 - second_exit, second_exit] + ), + metadata, + mode="partial", + elements=["H"], + ) + denominator = first_exit + second_exit - first_exit * second_exit + expected = ( + np.array( + [ + [first_exit, (1 - first_exit) * second_exit], + [(1 - second_exit) * first_exit, second_exit], + ] + ) + / denominator + ) + np.testing.assert_allclose(result.matrix[0], expected, rtol=0, atol=1e-14) diff --git a/tardis/transport/montecarlo/macro_atom.py b/tardis/transport/montecarlo/macro_atom.py index cf644725c1a..455bdd5cde3 100644 --- a/tardis/transport/montecarlo/macro_atom.py +++ b/tardis/transport/montecarlo/macro_atom.py @@ -13,10 +13,12 @@ class MacroAtomError(ValueError): - pass + """Report invalid macro-atom probability or activation state.""" class MacroAtomTransitionType(IntEnum): + """Identify internal jumps and negative-code deactivation processes.""" + # Bound bound transition block INTERNAL_UP = 1 INTERNAL_DOWN = 0 @@ -53,8 +55,9 @@ def macro_atom_interaction( activation_level_id: int, current_shell_id: int, opacity_state: OpacityStateNumba, -): - """ +) -> tuple[int, int]: + """Sample original macro-atom transitions until a deactivation occurs. + Parameters ---------- activation_level_id @@ -64,6 +67,8 @@ def macro_atom_interaction( Returns ------- + tuple[int, int] + Emission channel identifier and negative transition type. """ current_transition_type = 0 while current_transition_type >= 0: @@ -110,14 +115,19 @@ def macro_atom_interaction_iip( current_shell_id: int, opacity_state: OpacityStateNumba, continuum_state: ContinuumOpacityStateNumba, -): - """ +) -> tuple[int, int]: + """Alternate independent reduced visits and explicit retained transitions. + Parameters ---------- - activation_level_idx - Activation level idx of the macro atom. - current_shell_id - opacity_state + activation_level_idx : int + Global activation level, including valid level zero and i/k pools. + current_shell_id : int + Active shell index. + opacity_state : OpacityStateNumba + Residual probabilities and original channel metadata. + continuum_state : ContinuumOpacityStateNumba + First-exit matrices and forward/inverse level maps. Returns ------- @@ -126,60 +136,81 @@ def macro_atom_interaction_iip( emission_process : int, Type of process emission defined by MacroAtomTransitionType in this file. """ - # Do a single jump to the absorbing state, which we deactivate from - absorbing_state_probability = 0.0 - probability_event = np.random.random() + while True: + if activation_level_idx < 0 or activation_level_idx >= len( + continuum_state.macro_level_to_reduced_idx + ): + raise MacroAtomError( + "MacroAtom activation lies outside the global level map" + ) + reduced_idx = continuum_state.macro_level_to_reduced_idx[ + activation_level_idx + ] + if reduced_idx >= 0: + probability_event = np.random.random() + cumulative_probability = 0.0 + selected_idx = -1 + last_positive_idx = -1 + for exit_idx, state_probability in enumerate( + continuum_state.absorbing_markov_probabilities[ + current_shell_id, reduced_idx + ] + ): + if state_probability > 0: + last_positive_idx = exit_idx + cumulative_probability += state_probability + if cumulative_probability > probability_event: + selected_idx = exit_idx + break + if selected_idx < 0: + if ( + last_positive_idx >= 0 + and abs(cumulative_probability - 1.0) <= 1e-10 + ): + selected_idx = last_positive_idx + else: + raise MacroAtomError( + "MacroAtom first-exit probabilities are not normalized or activation has no outgoing probability" + ) + activation_level_idx = continuum_state.reduced_to_macro_level_idx[ + selected_idx + ] - for to_state_index, state_probability in enumerate( - continuum_state.absorbing_markov_probabilities[ - current_shell_id, activation_level_idx + block_start_idx = opacity_state.macro_block_edge_index[ + activation_level_idx ] - ): - absorbing_state_probability += state_probability - - if absorbing_state_probability > probability_event: - absorbing_activation_level_idx = to_state_index - break - else: - raise MacroAtomError( - "MacroAtom failed to select an absorbing state. The absorbing Markov" - "chain probabilities matrix may not be normalized or may contain only zeros. \n" - f"Attempted to activate from {activation_level_idx}." - ) - - # Handle second prob call for emission process from that state - block_start_idx = opacity_state.macro_block_edge_index[ - absorbing_activation_level_idx - ] - block_end_idx = opacity_state.macro_block_edge_index[ - absorbing_activation_level_idx + 1 - ] - emission_transition_probability = 0.0 - probability_emission_event = np.random.random() - - for deactivation_channel_idx in range(block_start_idx, block_end_idx): - deactivation_probability = opacity_state.transition_probabilities[ - deactivation_channel_idx, current_shell_id + block_end_idx = opacity_state.macro_block_edge_index[ + activation_level_idx + 1 ] - emission_transition_probability += deactivation_probability - - if emission_transition_probability > probability_emission_event: - emission_process = opacity_state.transition_type[ - deactivation_channel_idx - ] - emission_line_id = opacity_state.transition_line_id[ - deactivation_channel_idx + probability_event = np.random.random() + cumulative_probability = 0.0 + selected_transition_idx = -1 + last_positive_idx = -1 + for transition_idx in range(block_start_idx, block_end_idx): + transition_probability = opacity_state.transition_probabilities[ + transition_idx, current_shell_id ] - break - - else: - raise MacroAtomError( - "MacroAtom ran out of the block. This should not happen as " - "the sum of probabilities is normalized to 1 and " - "the probability_event should be less than 1. \n" - f"block indices are {block_start_idx}, {block_end_idx}" - ) - return ( - emission_line_id, - emission_process, - ) + if transition_probability > 0: + last_positive_idx = transition_idx + cumulative_probability += transition_probability + if cumulative_probability > probability_event: + selected_transition_idx = transition_idx + break + if selected_transition_idx < 0: + if ( + last_positive_idx >= 0 + and abs(cumulative_probability - 1.0) <= 1e-10 + ): + selected_transition_idx = last_positive_idx + else: + raise MacroAtomError( + "MacroAtom residual block is not normalized or activation has no outgoing probability" + ) + transition_type = opacity_state.transition_type[selected_transition_idx] + if transition_type < 0: + return opacity_state.transition_line_id[ + selected_transition_idx + ], transition_type + activation_level_idx = opacity_state.destination_level_id[ + selected_transition_idx + ] diff --git a/tardis/transport/montecarlo/tests/test_partial_macro_atom.py b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py new file mode 100644 index 00000000000..7c6fc77fc86 --- /dev/null +++ b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py @@ -0,0 +1,124 @@ +"""Compiled-path verification of independent hybrid macro-atom visits.""" + +import numpy as np +import numpy.typing as npt +import pandas as pd +import pytest +from numba import njit + +from tardis.opacities.continuum.continuum_state_numba import ( + ContinuumOpacityStateNumba, +) +from tardis.opacities.macro_atom.absorbing_markov_chain import ( + create_absorbing_probs, +) +from tardis.opacities.opacity_state_numba import OpacityStateNumba +from tardis.transport.montecarlo.macro_atom import macro_atom_interaction_iip + + +@njit +def sample_emissions( + opacity: OpacityStateNumba, + continuum: ContinuumOpacityStateNumba, + activation: int, + count: int, + seed: int, +) -> npt.NDArray[np.int64]: + """Draw independent packets through the production compiled interaction.""" + np.random.seed(seed) + outcomes = np.zeros(3, dtype=np.int64) + for _ in range(count): + channel, _ = macro_atom_interaction_iip( + activation, 0, opacity, continuum + ) + outcomes[channel] += 1 + return outcomes + + +@pytest.fixture(params=["full", "partial", "explicit"]) +def two_visit_state(request: pytest.FixtureRequest) -> tuple: + """A selected H block exits through k/i and returns to a second H block.""" + metadata = pd.DataFrame( + { + "source_level_idx": [0, 0, 1, 2, 3, 3, 4, 5], + "destination_level_idx": [1, -1, 2, 5, 4, -1, -1, 3], + "transition_type": [1, -1, 11, 22, 1, -7, -21, 3], + "source": [(1, 0, 0)] * 2 + + [(1, 0, 1), ("k", -99, -99)] + + [(1, 1, 0)] * 2 + + [(1, 1, 1), ("i", -99, -99)], + } + ) + result = create_absorbing_probs( + pd.DataFrame([0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 1.0, 1.0]), + metadata, + mode=request.param, + elements=["H"] if request.param == "partial" else [], + ) + residual = result.residual_probabilities.to_numpy(copy=True) + totals = np.bincount(metadata.source_level_idx, weights=residual[:, 0]) + np.divide( + residual[:, 0], + totals[metadata.source_level_idx], + out=residual[:, 0], + where=totals[metadata.source_level_idx] != 0, + ) + opacity = OpacityStateNumba( + np.ones(1), + np.ones(1), + np.ones(1), + np.ones((1, 1)), + residual, + np.array([0], dtype=np.int64), + np.array([0, 2, 3, 4, 6, 7, 8], dtype=np.int64), + metadata.transition_type.to_numpy(dtype=np.int64, copy=True), + metadata.destination_level_idx.to_numpy(dtype=np.int64), + np.array([0, 0, 0, 0, 0, 1, 2, 0], dtype=np.int64), + ) + continuum = ContinuumOpacityStateNumba( + np.ones(1), + np.ones((1, 1)), + np.ones(1), + np.ones(1), + np.array([0, 1], dtype=np.int64), + np.ones((1, 1)), + np.ones(1), + np.ones(1), + np.ones(1), + np.ones((1, 1)), + np.array([5], dtype=np.int64), + 2, + result.matrix, + result.macro_level_to_reduced_idx, + result.reduced_to_macro_level_idx, + ) + return opacity, continuum + + +def test_compiled_reentry_emission_distribution(two_visit_state: tuple) -> None: + """Exact tree law is 1/2, 1/4, 1/4, requiring independent reduced visits. + + Tolerance is six binomial standard deviations per channel (60000 packets), + giving a conservative familywise stochastic bound across three modes. + Reusing the first reduced random number suppresses one channel entirely. + """ + opacity, continuum = two_visit_state + count = 60000 + expected = np.array([0.5, 0.25, 0.25]) + actual = sample_emissions(opacity, continuum, 0, count, 1741) / count + assert np.all( + np.abs(actual - expected) + <= 6 * np.sqrt(expected * (1 - expected) / count) + ), actual + # Both global pool indices must enter the same downstream emission law. + for activation in (2, 5): + pool_outcomes = ( + sample_emissions(opacity, continuum, activation, 20000, 972) / 20000 + ) + np.testing.assert_allclose( + pool_outcomes, + [0.0, 0.5, 0.5], + atol=6 * np.sqrt(0.25 / 20000), + rtol=0, + ) + assert macro_atom_interaction_iip.nopython_signatures diff --git a/tardis/workflows/tests/test_partial_chain_workflow.py b/tardis/workflows/tests/test_partial_chain_workflow.py new file mode 100644 index 00000000000..33fbabb85eb --- /dev/null +++ b/tardis/workflows/tests/test_partial_chain_workflow.py @@ -0,0 +1,96 @@ +"""Comprehensive two-iteration verification of Type IIP reduction modes.""" + +from pathlib import Path + +import numpy as np +import pytest + +from tardis.io.configuration.config_reader import Configuration +from tardis.plasma.equilibrium.thermal_balance import ( + ElectronThermalBalanceSolver, +) +from tardis.workflows.type_iip_workflow import TypeIIPWorkflow + + +@pytest.fixture +def partial_chain_config(tardis_regression_path: Path) -> Configuration: + """Use the existing mixed H/He network, without changing enabled physics.""" + config = Configuration.from_yaml( + "tardis/workflows/tests/data/iip_hydrogen_helium.yml" + ) + config.atom_data = ( + tardis_regression_path + / "atom_data/christians_atomdata_converted_04Dec25.h5" + ) + config.montecarlo.nthreads = 1 + return config + + +@pytest.mark.parametrize( + "mode,elements", + [ + ("full", []), + ("partial", ["H"]), + ("partial", ["He"]), + ("partial", ["H", "He"]), + ("explicit", []), + ], +) +def test_coupled_workflow_thermal_closure( + partial_chain_config: Configuration, mode: str, elements: list[str] +) -> None: + """Each mode closes the same thermal equations through two transport steps. + + Regime: 20000 packets, mixed H/He, one plasma update and final transport. + Independent verification: the accepted physical balance residual is tested + against the solver's predeclared closure criteria, rather than just finite + output. Cross-mode stochastic comparisons are separate validation evidence. + """ + config = partial_chain_config + config.montecarlo.no_of_packets = 20000 + config.montecarlo.last_no_of_packets = 20000 + config.plasma.continuum_interaction.markov_chain.mode = mode + config.plasma.continuum_interaction.markov_chain.elements = elements + workflow = TypeIIPWorkflow(config) + workflow.show_progress_bars = False + workflow.run() + ElectronThermalBalanceSolver.validate_evaluation( + workflow._thermal_balance_evaluation + ) + assert workflow.completed_iterations == 1 + solver = workflow.macro_atom_solver + metadata = solver.computed_metadata[0] + continuum = workflow.transport_state.continuum_state_numba + np.testing.assert_array_equal( + continuum.macro_level_to_reduced_idx, solver.macro_level_to_reduced_idx + ) + np.testing.assert_array_equal( + continuum.reduced_to_macro_level_idx, solver.reduced_to_macro_level_idx + ) + assert len(continuum.photo_ion_activation_idx) == len( + workflow.continuum_opacity_state.level2continuum_idx + ) + photo_ion_block = metadata.loc[ + metadata.source == ("i", -99, -99), "source_level_idx" + ].unique()[0] + assert np.all(continuum.photo_ion_activation_idx == photo_ion_block) + for name in ( + "photo_ion_estimator", + "photo_ion_estimator_statistics", + "stim_recomb_estimator", + "bf_heating_estimator", + "stim_recomb_cooling_estimator", + ): + estimator = getattr(workflow.transport_state.estimators_continuum, name) + assert estimator.shape == ( + len(workflow.continuum_opacity_state.level2continuum_idx), + workflow.simulation_state.geometry.no_of_shells_active, + ) + if mode == "partial": + pool_levels = metadata.loc[ + metadata.source.map(lambda level: level[0] in ("i", "k")), + "source_level_idx", + ] + assert not set(continuum.reduced_to_macro_level_idx).intersection( + pool_levels + ) diff --git a/tardis/workflows/type_iip_workflow.py b/tardis/workflows/type_iip_workflow.py index 5e8113bc670..931ec5c5851 100644 --- a/tardis/workflows/type_iip_workflow.py +++ b/tardis/workflows/type_iip_workflow.py @@ -236,6 +236,10 @@ def __init__( ), line_interaction_type=line_interaction_type, nthreads=continuum_interactions.nthreads, + markov_chain_mode=continuum_interactions.markov_chain.mode, + markov_chain_elements=tuple( + continuum_interactions.markov_chain.elements + ), ) self.transport_state = None From 7939fc28897aff5abf90ce25d0451f33e78cc420 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 13:37:55 -0500 Subject: [PATCH 02/12] fix negative values and add ionization and thermal pool support --- docs/io/configuration/components/plasma.rst | 10 +- .../montecarlo/partial_absorbing_chain.rst | 60 +++++-- tardis/io/configuration/schemas/plasma.yml | 8 + .../macro_atom/absorbing_markov_chain.py | 46 ++++-- .../opacities/macro_atom/macroatom_solver.py | 16 ++ .../tests/test_partial_absorbing_chain.py | 156 ++++++++++++++++-- .../tests/test_partial_macro_atom.py | 51 ++++-- tardis/workflows/tests/test_iip_workflow.py | 26 +++ .../tests/test_partial_chain_workflow.py | 55 ++++-- tardis/workflows/type_iip_workflow.py | 2 + 10 files changed, 355 insertions(+), 75 deletions(-) diff --git a/docs/io/configuration/components/plasma.rst b/docs/io/configuration/components/plasma.rst index e8a26120d29..f739493addd 100644 --- a/docs/io/configuration/components/plasma.rst +++ b/docs/io/configuration/components/plasma.rst @@ -85,6 +85,8 @@ between selected atomic states: markov_chain: mode: partial elements: [H] + include_thermal_pool: true + include_ionization_pool: false For a multi-element selection, use ``elements: [H, He, Fe]`` when those elements are present in the assembled network. Duplicate symbols are harmless. A symbol @@ -92,6 +94,12 @@ selects all represented ions and levels of that element. This list is independen of continuum ``species`` and ``nlte.species``: selecting an element does not enable additional continuum processes or change its equilibrium treatment. -The synthetic thermal and ionization pools remain explicit in partial mode. +Both pool options default to ``false``. Set ``include_thermal_pool: true`` to +include the shared thermal state, ``include_ionization_pool: true`` to include +the shared ionization state, or enable both. Internal transitions between any +selected states are then collapsed, including paths through the enabled pools. +Pool emission/cooling and jumps to unselected states remain explicit exit +channels. These options require ``mode: partial``; full mode already includes +both pools, and explicit mode reduces neither. See :doc:`../../../physics_walkthrough/montecarlo/partial_absorbing_chain` for the probability contract and scientific verification. diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst index bc060ac55ad..2e80a35eb29 100644 --- a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -4,8 +4,12 @@ Element-selected absorbing chains Type IIP transport can skip internal macro-atom jumps while preserving the probabilities of eventual emission and cooling. In partial mode, let S contain all represented real atomic levels of the requested elements. Only internal -edges with both endpoints in S are eliminated. The shared ionization (i) and -thermal (k) pools stay outside S, even when every atomic element is selected. +edges with both endpoints in S are eliminated. For example, this would be +jumping over internal transitions that happen in a specified element. +The shared ionization (i) and thermal (k) pools stay outside S by default. +The independent ``include_ionization_pool`` and ``include_thermal_pool`` options +add their respective pool states to S in partial mode. Either pool or both can +be included without selecting additional atomic elements. For each cell, Q contains the eliminated transition probabilities, L contains the original probabilities with just those edges removed, and r is the sum of @@ -18,13 +22,26 @@ conditional channel probabilities C satisfy C_{j,c} = L_{j,c}/r_j, \qquad (I-Q)^{-1} L = BC. -Rows of B are activation states; columns identify exit-source states. This -matrix need not be symmetric. A draw from B selects the global source of the +Rows of B are activation states; columns identify exit-source states. +A draw from B selects the global source of the next retained channel, followed by an independent draw from C. A retained internal transition continues the interaction; only a negative transition code ends it. Each return to S starts a fresh, independent pair of draws. Outside S, transport samples the original channel probabilities directly. +With k included, selected-atom to k to selected-atom paths are collapsed inside +the matrix. With i included, the analogous ionization/recombination paths are +collapsed. If both are included, internal transfers between the pools also enter +Q. A pool can be the exit-source state selected by B: emission and cooling from +it are retained channels, as are jumps to unselected atoms or an excluded pool. +Those exits are sampled explicitly. Direct activation at an included pool uses +its reduced row; activation at an excluded pool uses its original channels. + +Shared pools couple the selected elements into one reduction. The final emission +distribution is preserved, but the explicit history of visits to included pools +is removed. Diagnostics that count individual pool visits would require separate +accounting for the collapsed transitions. + Emission-only states and global level zero are included. Explicit int64 forward and inverse maps preserve global identities, including gaps in the level indices. A zero residual row stays zero and cannot supply an exit. Metadata @@ -32,8 +49,10 @@ and numerical probabilities are rebuilt consistently on every opacity solve; continuum activation indices and estimator dimensions keep their original ordering and shell count. -Sparse LU solves are checked for finite, nonnegative, normalized probabilities -and a scale-aware equation residual. A reachable closed class without a physical +Sparse LU solves are checked for finite, normalized rows and a scale-aware +equation residual. Nonnegativity checks apply to networks with nonnegative +original coefficients in every reduction mode. Signed networks retain the +legacy behavior described below. A reachable closed class without a physical exit raises a diagnostic containing the cell and states. Channels are never removed by a numerical probability threshold. The sampler allows a CDF endpoint deficit of at most 1e-10 due to floating-point summation; larger deficits or @@ -41,8 +60,10 @@ activations without outgoing probability raise an error. Exact small-network tests compare eventual channel distributions with an independent dense solve of the unreduced network. Compiled sampling tests check -the analytic 50 percent / 25 percent / 25 percent re-entry example with binomial -uncertainty bounds. Full mode preserves the existing default and its two-draw +an analytic 50 percent / 18.75 percent / 31.25 percent emission distribution with +direct thermal emission, pool activation, and re-entry through an unselected +element. Every pool-option combination is checked with binomial uncertainty +bounds. Full mode preserves the existing default and its two-draw sampling behavior. The different modes preserve distributions, rather than individual random packet histories. @@ -57,13 +78,22 @@ Signed-channel limitation Some accepted plasma states produce negative stimulated-recombination-corrected photoionization coefficients (for example, the existing 1500 K outer-shell -cutoff scenario). Full mode preserves the legacy aggregate elimination of these -signed internal coefficients and their legacy signed matrix. That legacy -case does not carry the probability nonnegativity guarantee of the new modes. -Partial and explicit modes reject negative original probabilities with a cell -and transition diagnostic: a signed channel cannot be sampled as an explicit -probability. Select full mode for those states. The reduction does not clip -coefficients or change the underlying plasma/opacity physics. +cutoff scenario). Full, partial, and explicit modes preserve signed coefficients +without clipping or sign-based rejection. Partial reduction applies the same +algebraic elimination to the selected block; negative retained channels or +negative reduced entries do not introduce additional termination checks. +Including the ionization or thermal pool remains optional for signed networks. + +For example, a direct selected-state coefficient of -0.1 can combine with a +two-step contribution of +0.3 to give an exit coefficient of +0.2. Other +selections can leave signed entries. The existing cumulative sampler is retained +in all modes for compatibility. Running a signed case successfully does not +establish a valid categorical sampling law or mode-invariant sampled spectra. +This limitation is shared by full and partial reduction; resolving it is a +separate physics change. General physical treatment requires consistently separating +stimulated recombination from absorption, including corresponding changes to +packet opacities and emission, rather than only removing a sign check. See +`Lucy (2002), section 4.1 `_. Exceptionally near-trapping partial chains can lose tiny exits through floating-point cancellation. Their diagonals use actual exits and off-diagonal diff --git a/tardis/io/configuration/schemas/plasma.yml b/tardis/io/configuration/schemas/plasma.yml index c54c7aec556..79201a5473d 100644 --- a/tardis/io/configuration/schemas/plasma.yml +++ b/tardis/io/configuration/schemas/plasma.yml @@ -96,6 +96,14 @@ properties: type: string default: [] description: Element symbols reduced in partial mode; empty in other modes. + include_thermal_pool: + type: boolean + default: false + description: Include the shared thermal k state in partial reduction. + include_ionization_pool: + type: boolean + default: false + description: Include the shared ionization i state in partial reduction. nthreads: type: integer minimum: 1 diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 2926593fa1f..9ea20b24824 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -32,6 +32,8 @@ def create_absorbing_probs( *, mode: str = "full", elements: Sequence[str] = (), + include_thermal_pool: bool = False, + include_ionization_pool: bool = False, max_workers: int = 1, ) -> AbsorbingChainResult: """Eliminate internal transitions within the selected state set. @@ -39,16 +41,21 @@ def create_absorbing_probs( Parameters ---------- transition_probabilities : pandas.DataFrame - Normalized original channel probabilities; columns are cells. + Normalized original channel coefficients; columns are cells. Signed + coefficients retain the legacy full-mode behavior in every mode. metadata : pandas.DataFrame Transition source tuples, global source/destination indices, and types. mode : {'full', 'partial', 'explicit'} Full eliminates all internal jumps. Partial eliminates only jumps with - both endpoints in selected elements; synthetic i/k pools stay explicit. + both endpoints selected, optionally including either shared pool. Explicit retains every original transition. elements : sequence of str Element symbols, required only in partial mode. All represented ions and levels of each selected element are included. + include_thermal_pool : bool, optional + Include the shared k state in partial reduction. Defaults to False. + include_ionization_pool : bool, optional + Include the shared i state in partial reduction. Defaults to False. max_workers : int Maximum number of cell-independent sparse LU workers. @@ -64,6 +71,9 @@ def create_absorbing_probs( channels. Zero residual rows stay zero. No rate threshold removes a channel. The matrix selects the source of the first retained transition, which can itself be internal. It is not necessarily a final emission state. + Signed coefficients and reduced entries are preserved without clipping or + sign-based rejection, matching legacy full mode. The usual probabilistic + interpretation applies to nonnegative kernels. """ if mode not in ("full", "partial", "explicit"): raise ValueError("markov_chain.mode must be full, partial, or explicit") @@ -71,6 +81,11 @@ def create_absorbing_probs( raise ValueError( "markov_chain.elements must be nonempty only in partial mode" ) + if mode != "partial" and (include_thermal_pool or include_ionization_pool): + raise ValueError( + "markov_chain pool selection requires mode='partial'; full mode " + "already includes both pools and explicit mode reduces neither" + ) try: atomic_numbers = sorted( {element_symbol2atomic_number(symbol) for symbol in elements} @@ -102,6 +117,14 @@ def create_absorbing_probs( raise ValueError( f"markov_chain.elements absent from assembled macro-atom network: {sorted(absent)}" ) + if include_thermal_pool: + selected_rows = ( + selected_rows | (metadata.source == ("k", -99, -99)).to_numpy() + ) + if include_ionization_pool: + selected_rows = ( + selected_rows | (metadata.source == ("i", -99, -99)).to_numpy() + ) selected = np.unique(sources[selected_rows]) else: selected = np.empty(0, dtype=np.int64) @@ -125,11 +148,9 @@ def solve_cell(cell: int) -> tuple[int, npt.NDArray[np.float64]]: values = transition_probabilities.iloc[:, cell].to_numpy() totals = np.bincount(sources, weights=values, minlength=global_size) active = totals > 0 - if not np.all(np.isfinite(values)) or ( - mode != "full" and np.any(values < -PROBABILITY_TOLERANCE) - ): + if not np.all(np.isfinite(values)): raise ValueError( - f"cell {cell}: nonfinite or negative channel probabilities at transitions {metadata.index[~np.isfinite(values) | (values < -PROBABILITY_TOLERANCE)].tolist()}; partial/explicit sampling requires nonnegative original channels; use full mode for signed stimulated-recombination coefficients" + f"cell {cell}: nonfinite channel coefficients at transitions {metadata.index[~np.isfinite(values)].tolist()}" ) if not np.allclose( totals[active], 1, rtol=0, atol=PROBABILITY_TOLERANCE @@ -236,13 +257,16 @@ def solve_cell(cell: int) -> tuple[int, npt.NDArray[np.float64]]: 1.0, sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), ) - signed_legacy_chain = mode == "full" and np.any(values < 0) + # Keep signed-coefficient compatibility independent of the reduction + # mask. A physical treatment of signed sampling laws is a shared issue. + signed_legacy_chain = np.any(values < 0) + negative_exits = solved < -PROBABILITY_TOLERANCE + if not signed_legacy_chain and np.any(negative_exits): + raise ValueError( + f"cell {cell}: negative first-exit probabilities for {negative_exits.sum()} global activation/exit-source pairs, first pairs {selected[np.argwhere(negative_exits)[:8]].tolist()} (minimum {solved.min()})" + ) if ( not np.all(np.isfinite(solved)) - or ( - not signed_legacy_chain - and np.any(solved < -PROBABILITY_TOLERANCE) - ) or residual_norm > PROBABILITY_TOLERANCE * residual_scale or not np.allclose( solved[active[selected]].sum(axis=1), diff --git a/tardis/opacities/macro_atom/macroatom_solver.py b/tardis/opacities/macro_atom/macroatom_solver.py index a69a477a863..bc45ba2cbd0 100644 --- a/tardis/opacities/macro_atom/macroatom_solver.py +++ b/tardis/opacities/macro_atom/macroatom_solver.py @@ -818,6 +818,8 @@ def __init__( nthreads: int = 1, markov_chain_mode: str = "full", markov_chain_elements: tuple[str, ...] = (), + markov_chain_include_thermal_pool: bool = False, + markov_chain_include_ionization_pool: bool = False, ) -> None: """ Initialize the ContinuumMacroAtomSolver. @@ -844,6 +846,10 @@ def __init__( Full, element-selected partial, or explicit sampling. markov_chain_elements : tuple of str Element symbols selected independently of enabled continuum physics. + markov_chain_include_thermal_pool : bool + Include the shared thermal state in partial reduction. + markov_chain_include_ionization_pool : bool + Include the shared ionization state in partial reduction. """ super().__init__( lines=lines, @@ -878,6 +884,12 @@ def __init__( self.nthreads = nthreads self.markov_chain_mode = markov_chain_mode self.markov_chain_elements = tuple(markov_chain_elements) + self.markov_chain_include_thermal_pool = ( + markov_chain_include_thermal_pool + ) + self.markov_chain_include_ionization_pool = ( + markov_chain_include_ionization_pool + ) def solve( self, @@ -1335,6 +1347,8 @@ def _solve_first_macroatom_iteration( macro_atom_transition_metadata, mode=self.markov_chain_mode, elements=self.markov_chain_elements, + include_thermal_pool=self.markov_chain_include_thermal_pool, + include_ionization_pool=self.markov_chain_include_ionization_pool, max_workers=self.nthreads, ) absorbing_probability_matrix = chain_result.matrix @@ -1670,6 +1684,8 @@ def _solve_next_macroatom_iteration( macro_atom_transition_metadata, mode=self.markov_chain_mode, elements=self.markov_chain_elements, + include_thermal_pool=self.markov_chain_include_thermal_pool, + include_ionization_pool=self.markov_chain_include_ionization_pool, max_workers=self.nthreads, ) absorbing_probability_matrix = chain_result.matrix diff --git a/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py index b101a3bf291..f8a9058da50 100644 --- a/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py +++ b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py @@ -21,8 +21,8 @@ def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: 9: (1, 1, 1), 12: (26, 1, 0), } - sources = [0, 0, 2, 2, 2, 4, 4, 5, 5, 6, 6, 6, 9, 12, 12] - destinations = [2, -1, 4, 9, -1, 0, -1, 6, -1, 0, 12, -1, -1, 6, -1] + sources = [0, 0, 2, 2, 2, 4, 4, 4, 5, 5, 6, 6, 6, 9, 12, 12] + destinations = [2, -1, 4, 9, -1, 0, 5, -1, 6, -1, 0, 12, -1, -1, 6, -1] metadata = pd.DataFrame( { "source_level_idx": sources, @@ -42,7 +42,8 @@ def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: 0.3, 0.2, 0.5, - 0.5, + 0.4, + 0.1, 0.5, 0.3, 0.7, @@ -59,7 +60,8 @@ def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: 0.2, 0.1, 0.7, - 0.8, + 0.7, + 0.1, 0.2, 0.6, 0.4, @@ -76,34 +78,52 @@ def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: @pytest.mark.parametrize( - "mode,elements", + "mode,elements,include_thermal_pool,include_ionization_pool", [ - ("full", []), - ("partial", ["H"]), - ("partial", ["He"]), - ("partial", ["Fe", "He", "H", "H"]), - ("explicit", []), + ("full", [], False, False), + ("partial", ["H"], False, False), + ("partial", ["H"], True, False), + ("partial", ["H"], False, True), + ("partial", ["H"], True, True), + ("partial", ["He"], False, False), + ("partial", ["Fe", "He", "H", "H"], True, True), + ("explicit", [], False, False), ], ) def test_final_emission_law( pool_network: tuple[pd.DataFrame, pd.DataFrame], mode: str, elements: list[str], + include_thermal_pool: bool, + include_ionization_pool: bool, ) -> None: """Selection preserves every eventual emission channel in a mixed network. Regime: two cells, multiple ions, gapped indices including zero, an emission-only destination, zero residual/internal rows, and pool re-entry. + Either shared pool can be reduced independently; exits from included pools + to unselected elements and every physical emission remain represented. Verify the mask and maps directly, then compare final channel probabilities with a dense solve of the original network. The reference never uses the reduced matrix. A 2e-14 tolerance allows floating-point LU roundoff. """ probabilities, metadata = pool_network result = create_absorbing_probs( - probabilities, metadata, mode=mode, elements=elements, max_workers=2 + probabilities, + metadata, + mode=mode, + elements=elements, + include_thermal_pool=include_thermal_pool, + include_ionization_pool=include_ionization_pool, + max_workers=2, ) serial = create_absorbing_probs( - probabilities, metadata, mode=mode, elements=elements + probabilities, + metadata, + mode=mode, + elements=elements, + include_thermal_pool=include_thermal_pool, + include_ionization_pool=include_ionization_pool, ) np.testing.assert_array_equal(result.matrix, serial.matrix) @@ -117,7 +137,11 @@ def test_final_emission_law( else np.unique( metadata.loc[ metadata.source.map( - lambda level: level[0] in selected_elements + lambda level: ( + level[0] in selected_elements + or (include_thermal_pool and level[0] == "k") + or (include_ionization_pool and level[0] == "i") + ) ), "source_level_idx", ] @@ -209,3 +233,109 @@ def test_asymmetric_near_trapping_cycle_preserves_tiny_exit_ratio() -> None: / denominator ) np.testing.assert_allclose(result.matrix[0], expected, rtol=0, atol=1e-14) + + +@pytest.mark.parametrize( + "mode,include_ionization_pool", + [ + ("partial", True), + ("partial", False), + ("full", False), + ("explicit", False), + ], +) +@pytest.mark.parametrize("indirect_rate", [0.6, 0.1]) +def test_signed_coefficients_preserve_algebraic_emission_law( + mode: str, + include_ionization_pool: bool, + indirect_rate: float, +) -> None: + """Preserve full-mode signed-coefficient compatibility in every mode. + + Claim: direct H0->i=-0.1 and indirect H0->H1->i=0.3 combine to + +0.2; the remaining first-exit masses are 0.5 at H0 and 0.3 at H1. + Regime: net signed internal coefficients, a shared ionization pool, and + explicit He re-entry. These are algebraic coefficients, not path weights. + Verification: exact geometric-series final emissions with a 2e-14 + float64 LU tolerance. Excluding i exposes a negative retained channel; + reducing the indirect path to 0.05 leaves a negative reduced exit mass. + Both are retained without rejection or clipping, like full mode. This + verifies algebraic compatibility, not a categorical sampling law. + """ + levels = [(1, 0, 0), (1, 0, 1), ("i", -99, -99), (2, 0, 0)] + sources = [0, 0, 0, 0, 1, 1, 2, 3, 3] + destinations = [2, 1, 3, -1, 2, -1, -1, 0, -1] + metadata = pd.DataFrame( + { + "source_level_idx": sources, + "destination_level_idx": destinations, + "transition_type": [1 if idx >= 0 else -1 for idx in destinations], + "source": [levels[idx] for idx in sources], + } + ) + probabilities = pd.DataFrame( + [-0.1, indirect_rate, 0.1, 1 - indirect_rate, 0.5, 0.5, 1, 0.25, 0.75] + ) + options = { + "mode": mode, + "elements": ["H"] if mode == "partial" else [], + "include_ionization_pool": include_ionization_pool, + } + result = create_absorbing_probs(probabilities, metadata, **options) + # Compose the algebraic kernels, then sum explicit He returns. Signed + # entries are not frequencies that the ordinary CDF sampler can reproduce. + retained = np.zeros((4, 8)) + emission = 4 + for transition, row in metadata.iterrows(): + destination = row.destination_level_idx + if destination < 0: + destination = emission + emission += 1 + retained[row.source_level_idx, destination] += ( + result.residual_probabilities.iloc[transition, 0] + ) + retained /= retained.sum(axis=1, keepdims=True) + selected = result.reduced_to_macro_level_idx + composed = retained.copy() + composed[selected] = result.matrix[0] @ retained[selected] + actual = np.linalg.solve(np.eye(4) - composed[:, :4], composed[:, 4:]) + first_emission = ( + np.array( + [ + 1 - indirect_rate, + indirect_rate / 2, + indirect_rate / 2 - 0.1, + 0.075, + ] + ) + / 0.975 + ) + expected = np.vstack( + [ + first_emission, + [0, 0.5, 0.5, 0], + [0, 0, 1, 0], + 0.25 * first_emission + [0, 0, 0, 0.75], + ] + ) + np.testing.assert_allclose(actual, expected, rtol=0, atol=2e-14) + if mode == "partial" and include_ionization_pool: + np.testing.assert_allclose( + result.matrix[0], + [ + [ + 1.1 - indirect_rate, + indirect_rate / 2, + indirect_rate / 2 - 0.1, + ], + [0, 0.5, 0.5], + [0, 0, 1], + ], + rtol=0, + atol=2e-14, + ) + else: + # In explicit mode, or partial mode with i outside the selection, the + # original -0.1 H0->i coefficient must survive unchanged. + if mode != "full": + assert result.residual_probabilities.iloc[0, 0] == -0.1 diff --git a/tardis/transport/montecarlo/tests/test_partial_macro_atom.py b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py index 7c6fc77fc86..3ceccd47ef4 100644 --- a/tardis/transport/montecarlo/tests/test_partial_macro_atom.py +++ b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py @@ -35,25 +35,37 @@ def sample_emissions( return outcomes -@pytest.fixture(params=["full", "partial", "explicit"]) +@pytest.fixture( + params=[ + ("full", False, False), + ("partial", False, False), + ("partial", True, False), + ("partial", False, True), + ("partial", True, True), + ("explicit", False, False), + ] +) def two_visit_state(request: pytest.FixtureRequest) -> tuple: - """A selected H block exits through k/i and returns to a second H block.""" + """H visits k/i, with thermal emission and re-entry through unselected He.""" + mode, include_thermal_pool, include_ionization_pool = request.param metadata = pd.DataFrame( { - "source_level_idx": [0, 0, 1, 2, 3, 3, 4, 5], - "destination_level_idx": [1, -1, 2, 5, 4, -1, -1, 3], - "transition_type": [1, -1, 11, 22, 1, -7, -21, 3], + "source_level_idx": [0, 0, 1, 2, 2, 3, 3, 4, 5, 6], + "destination_level_idx": [1, -1, 2, 5, -1, 4, -1, -1, 6, 3], + "transition_type": [1, -1, 11, 22, -21, 1, -7, -1, 3, 1], "source": [(1, 0, 0)] * 2 - + [(1, 0, 1), ("k", -99, -99)] + + [(1, 0, 1), ("k", -99, -99), ("k", -99, -99)] + [(1, 1, 0)] * 2 - + [(1, 1, 1), ("i", -99, -99)], + + [(1, 1, 1), ("i", -99, -99), (2, 0, 0)], } ) result = create_absorbing_probs( - pd.DataFrame([0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 1.0, 1.0]), + pd.DataFrame([0.5, 0.5, 1.0, 0.75, 0.25, 0.5, 0.5, 1.0, 1.0, 1.0]), metadata, - mode=request.param, - elements=["H"] if request.param == "partial" else [], + mode=mode, + elements=["H"] if mode == "partial" else [], + include_thermal_pool=include_thermal_pool, + include_ionization_pool=include_ionization_pool, ) residual = result.residual_probabilities.to_numpy(copy=True) totals = np.bincount(metadata.source_level_idx, weights=residual[:, 0]) @@ -70,10 +82,10 @@ def two_visit_state(request: pytest.FixtureRequest) -> tuple: np.ones((1, 1)), residual, np.array([0], dtype=np.int64), - np.array([0, 2, 3, 4, 6, 7, 8], dtype=np.int64), + np.array([0, 2, 3, 5, 7, 8, 9, 10], dtype=np.int64), metadata.transition_type.to_numpy(dtype=np.int64, copy=True), metadata.destination_level_idx.to_numpy(dtype=np.int64), - np.array([0, 0, 0, 0, 0, 1, 2, 0], dtype=np.int64), + np.array([0, 0, 0, 0, 2, 0, 1, 2, 0, 0], dtype=np.int64), ) continuum = ContinuumOpacityStateNumba( np.ones(1), @@ -96,28 +108,31 @@ def two_visit_state(request: pytest.FixtureRequest) -> tuple: def test_compiled_reentry_emission_distribution(two_visit_state: tuple) -> None: - """Exact tree law is 1/2, 1/4, 1/4, requiring independent reduced visits. + """Exact tree law is 1/2, 3/16, 5/16 with thermal emission and re-entry. Tolerance is six binomial standard deviations per channel (60000 packets), - giving a conservative familywise stochastic bound across three modes. + giving a conservative familywise stochastic bound across all modes and pool selections. Reusing the first reduced random number suppresses one channel entirely. """ opacity, continuum = two_visit_state count = 60000 - expected = np.array([0.5, 0.25, 0.25]) + expected = np.array([0.5, 0.1875, 0.3125]) actual = sample_emissions(opacity, continuum, 0, count, 1741) / count assert np.all( np.abs(actual - expected) <= 6 * np.sqrt(expected * (1 - expected) / count) ), actual - # Both global pool indices must enter the same downstream emission law. - for activation in (2, 5): + # A k activation can emit directly; i goes through He before re-entering H. + for activation, pool_expected in ( + (2, np.array([0.0, 0.375, 0.625])), + (5, np.array([0.0, 0.5, 0.5])), + ): pool_outcomes = ( sample_emissions(opacity, continuum, activation, 20000, 972) / 20000 ) np.testing.assert_allclose( pool_outcomes, - [0.0, 0.5, 0.5], + pool_expected, atol=6 * np.sqrt(0.25 / 20000), rtol=0, ) diff --git a/tardis/workflows/tests/test_iip_workflow.py b/tardis/workflows/tests/test_iip_workflow.py index 32dd866fff5..ac7f70c80b4 100644 --- a/tardis/workflows/tests/test_iip_workflow.py +++ b/tardis/workflows/tests/test_iip_workflow.py @@ -984,8 +984,22 @@ def test_solve_montecarlo( ) +@pytest.mark.parametrize( + "mode,include_thermal_pool,include_ionization_pool", + [ + ("full", False, False), + ("partial", False, False), + ("partial", True, False), + ("partial", False, True), + ("partial", True, True), + ("explicit", False, False), + ], +) def test_iip_outer_shell_population_cutoff_second_iteration_opacity( tardis_regression_path: Path, + mode: str, + include_thermal_pool: bool, + include_ionization_pool: bool, ) -> None: """Evaluate finite outer-shell opacity at the 1500 K thermal floor. @@ -994,6 +1008,8 @@ def test_iip_outer_shell_population_cutoff_second_iteration_opacity( Regime: Second opacity iteration in shells forced to the 1500 K floor. Verification: The expected opacity is evaluated directly from the bound-free population equation, independently of continuum-state assembly. + All reduction modes retain legacy signed-coefficient compatibility and + complete ten transport packets; completion is not probability validation. """ config = Configuration.from_yaml( "tardis/workflows/tests/data/iip_population_cutoff.yml" @@ -1003,6 +1019,16 @@ def test_iip_outer_shell_population_cutoff_second_iteration_opacity( / "atom_data" / "christians_atomdata_converted_04Dec25.h5" ) + config.plasma.continuum_interaction.markov_chain.mode = mode + config.plasma.continuum_interaction.markov_chain.elements = ( + ["H"] if mode == "partial" else [] + ) + config.plasma.continuum_interaction.markov_chain.include_thermal_pool = ( + include_thermal_pool + ) + config.plasma.continuum_interaction.markov_chain.include_ionization_pool = ( + include_ionization_pool + ) workflow = TypeIIPWorkflow(config) workflow.show_progress_bars = False diff --git a/tardis/workflows/tests/test_partial_chain_workflow.py b/tardis/workflows/tests/test_partial_chain_workflow.py index 33fbabb85eb..3e6fd3ff6b6 100644 --- a/tardis/workflows/tests/test_partial_chain_workflow.py +++ b/tardis/workflows/tests/test_partial_chain_workflow.py @@ -27,30 +27,43 @@ def partial_chain_config(tardis_regression_path: Path) -> Configuration: @pytest.mark.parametrize( - "mode,elements", + "mode,elements,include_thermal_pool,include_ionization_pool", [ - ("full", []), - ("partial", ["H"]), - ("partial", ["He"]), - ("partial", ["H", "He"]), - ("explicit", []), + ("full", [], False, False), + ("partial", ["H"], False, False), + ("partial", ["H"], True, False), + ("partial", ["H"], False, True), + ("partial", ["H"], True, True), + ("partial", ["He"], False, False), + ("partial", ["H", "He"], True, True), + ("explicit", [], False, False), ], ) def test_coupled_workflow_thermal_closure( - partial_chain_config: Configuration, mode: str, elements: list[str] + partial_chain_config: Configuration, + mode: str, + elements: list[str], + include_thermal_pool: bool, + include_ionization_pool: bool, ) -> None: """Each mode closes the same thermal equations through two transport steps. - Regime: 20000 packets, mixed H/He, one plasma update and final transport. + Regime: the fixture's 200000 packets, mixed H/He, one plasma update and + final transport. Retain the physical fixture's packet count because smaller + development samples can trigger the known nonlinear thermal-solver basin. Independent verification: the accepted physical balance residual is tested against the solver's predeclared closure criteria, rather than just finite output. Cross-mode stochastic comparisons are separate validation evidence. """ config = partial_chain_config - config.montecarlo.no_of_packets = 20000 - config.montecarlo.last_no_of_packets = 20000 config.plasma.continuum_interaction.markov_chain.mode = mode config.plasma.continuum_interaction.markov_chain.elements = elements + config.plasma.continuum_interaction.markov_chain.include_thermal_pool = ( + include_thermal_pool + ) + config.plasma.continuum_interaction.markov_chain.include_ionization_pool = ( + include_ionization_pool + ) workflow = TypeIIPWorkflow(config) workflow.show_progress_bars = False workflow.run() @@ -87,10 +100,18 @@ def test_coupled_workflow_thermal_closure( workflow.simulation_state.geometry.no_of_shells_active, ) if mode == "partial": - pool_levels = metadata.loc[ - metadata.source.map(lambda level: level[0] in ("i", "k")), - "source_level_idx", - ] - assert not set(continuum.reduced_to_macro_level_idx).intersection( - pool_levels - ) + selected = set(continuum.reduced_to_macro_level_idx) + for pool, included in ( + ("k", include_thermal_pool), + ("i", include_ionization_pool), + ): + pool_levels = set( + metadata.loc[ + metadata.source.map(lambda level: level[0] == pool), + "source_level_idx", + ] + ) + if included: + assert pool_levels <= selected + else: + assert pool_levels.isdisjoint(selected) diff --git a/tardis/workflows/type_iip_workflow.py b/tardis/workflows/type_iip_workflow.py index 931ec5c5851..6034fa367be 100644 --- a/tardis/workflows/type_iip_workflow.py +++ b/tardis/workflows/type_iip_workflow.py @@ -240,6 +240,8 @@ def __init__( markov_chain_elements=tuple( continuum_interactions.markov_chain.elements ), + markov_chain_include_thermal_pool=continuum_interactions.markov_chain.include_thermal_pool, + markov_chain_include_ionization_pool=continuum_interactions.markov_chain.include_ionization_pool, ) self.transport_state = None From c1cd27761c8ab4598f7f24d6abef401dbbb983dc Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 13:46:49 -0500 Subject: [PATCH 03/12] remove more negative guards --- .../montecarlo/partial_absorbing_chain.rst | 53 +++---------------- .../macro_atom/absorbing_markov_chain.py | 8 --- 2 files changed, 7 insertions(+), 54 deletions(-) diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst index 2e80a35eb29..230b3301172 100644 --- a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -39,8 +39,7 @@ its reduced row; activation at an excluded pool uses its original channels. Shared pools couple the selected elements into one reduction. The final emission distribution is preserved, but the explicit history of visits to included pools -is removed. Diagnostics that count individual pool visits would require separate -accounting for the collapsed transitions. +is removed. Emission-only states and global level zero are included. Explicit int64 forward and inverse maps preserve global identities, including gaps in the level @@ -50,11 +49,10 @@ continuum activation indices and estimator dimensions keep their original ordering and shell count. Sparse LU solves are checked for finite, normalized rows and a scale-aware -equation residual. Nonnegativity checks apply to networks with nonnegative -original coefficients in every reduction mode. Signed networks retain the -legacy behavior described below. A reachable closed class without a physical -exit raises a diagnostic containing the cell and states. Channels are never -removed by a numerical probability threshold. The sampler allows a CDF endpoint +equation residual. Input coefficients and reduced entries are not rejected +based on their sign in any reduction mode. A reachable closed class without a +physical exit raises a diagnostic containing the cell and states. Channels are +never removed by a numerical probability threshold. The sampler allows a CDF endpoint deficit of at most 1e-10 due to floating-point summation; larger deficits or activations without outgoing probability raise an error. @@ -64,42 +62,5 @@ an analytic 50 percent / 18.75 percent / 31.25 percent emission distribution wit direct thermal emission, pool activation, and re-entry through an unselected element. Every pool-option combination is checked with binomial uncertainty bounds. Full mode preserves the existing default and its two-draw -sampling behavior. The different modes preserve distributions, rather than -individual random packet histories. - -A smaller matrix does not guarantee faster transport: explicit cycling through -unselected states and shared pools can dominate. Compare setup and solve cost, -selected-state count, dense matrix bytes, explicit steps, and total transport -cost with the existing ASV remote benchmarking workflow on the same network and -packet count. No hardware-independent speedup is implied. - -Signed-channel limitation -------------------------- - -Some accepted plasma states produce negative stimulated-recombination-corrected -photoionization coefficients (for example, the existing 1500 K outer-shell -cutoff scenario). Full, partial, and explicit modes preserve signed coefficients -without clipping or sign-based rejection. Partial reduction applies the same -algebraic elimination to the selected block; negative retained channels or -negative reduced entries do not introduce additional termination checks. -Including the ionization or thermal pool remains optional for signed networks. - -For example, a direct selected-state coefficient of -0.1 can combine with a -two-step contribution of +0.3 to give an exit coefficient of +0.2. Other -selections can leave signed entries. The existing cumulative sampler is retained -in all modes for compatibility. Running a signed case successfully does not -establish a valid categorical sampling law or mode-invariant sampled spectra. -This limitation is shared by full and partial reduction; resolving it is a -separate physics change. General physical treatment requires consistently separating -stimulated recombination from absorption, including corresponding changes to -packet opacities and emission, rather than only removing a sign check. See -`Lucy (2002), section 4.1 `_. - -Exceptionally near-trapping partial chains can lose tiny exits through -floating-point cancellation. Their diagonals use actual exits and off-diagonal -jumps; if float64 LU violates probability conservation, a Decimal -elimination with at least 80 digits (40 guard digits beyond the smallest -positive exit) retries the conservation-form system. This preserves tiny physical -channels without inventing probabilities or removing transitions. Full mode -retains the original numerical calculation for regression compatibility, -including its cancellation limits for exceptionally near-trapping chains. +sampling behavior. For nonnegative kernels, the different modes preserve +distributions, rather than individual random packet histories. \ No newline at end of file diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 9ea20b24824..f3ebfe291ce 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -257,14 +257,6 @@ def solve_cell(cell: int) -> tuple[int, npt.NDArray[np.float64]]: 1.0, sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), ) - # Keep signed-coefficient compatibility independent of the reduction - # mask. A physical treatment of signed sampling laws is a shared issue. - signed_legacy_chain = np.any(values < 0) - negative_exits = solved < -PROBABILITY_TOLERANCE - if not signed_legacy_chain and np.any(negative_exits): - raise ValueError( - f"cell {cell}: negative first-exit probabilities for {negative_exits.sum()} global activation/exit-source pairs, first pairs {selected[np.argwhere(negative_exits)[:8]].tolist()} (minimum {solved.min()})" - ) if ( not np.all(np.isfinite(solved)) or residual_norm > PROBABILITY_TOLERANCE * residual_scale From 5b64e19a157841aa28153d76cc36ee82e49edf96 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 13:55:57 -0500 Subject: [PATCH 04/12] free up existing memory --- .../montecarlo/partial_absorbing_chain.rst | 5 ++++- .../macro_atom/absorbing_markov_chain.py | 20 +++++++++++++------ tardis/workflows/type_iip_workflow.py | 14 ++++++++++++- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst index 230b3301172..702c4a19bbc 100644 --- a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -48,6 +48,9 @@ and numerical probabilities are rebuilt consistently on every opacity solve; continuum activation indices and estimator dimensions keep their original ordering and shell count. +Before recalculating the matrix, the workflow releases the previous iteration's +matrix references from both the macro-atom state and the Numba transport state. + Sparse LU solves are checked for finite, normalized rows and a scale-aware equation residual. Input coefficients and reduced entries are not rejected based on their sign in any reduction mode. A reachable closed class without a @@ -63,4 +66,4 @@ direct thermal emission, pool activation, and re-entry through an unselected element. Every pool-option combination is checked with binomial uncertainty bounds. Full mode preserves the existing default and its two-draw sampling behavior. For nonnegative kernels, the different modes preserve -distributions, rather than individual random packet histories. \ No newline at end of file +distributions, rather than individual random packet histories. diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index f3ebfe291ce..2b101096fda 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -1,4 +1,13 @@ -"""First-exit probabilities for full and element-selected macro-atom chains.""" +"""Calculate absorption probabilities using absorbing Markov chain theory. + +This module implements the mathematical framework of absorbing Markov chains +to compute probabilities of photon absorption in each cell and the expected +number of steps before absorption from each source state. + +References +---------- + Absorbing Markov chain theory: https://en.wikipedia.org/wiki/Absorbing_Markov_chain +""" from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor @@ -68,12 +77,11 @@ def create_absorbing_probs( Notes ----- The solve is ``(I-Q) B = diag(r)``, where r is the sum of actual remaining - channels. Zero residual rows stay zero. No rate threshold removes a channel. + channels. Zero residual rows stay zero. The matrix selects the source of the first retained transition, which can - itself be internal. It is not necessarily a final emission state. - Signed coefficients and reduced entries are preserved without clipping or - sign-based rejection, matching legacy full mode. The usual probabilistic - interpretation applies to nonnegative kernels. + itself be internal. It is not necessarily a final emission state because + only requested physical blocks are blocks are processed out of the matrix, + and the not-requested blocks retain full internal transition probability tables. """ if mode not in ("full", "partial", "explicit"): raise ValueError("markov_chain.mode must be full, partial, or explicit") diff --git a/tardis/workflows/type_iip_workflow.py b/tardis/workflows/type_iip_workflow.py index 6034fa367be..8c68e96fca7 100644 --- a/tardis/workflows/type_iip_workflow.py +++ b/tardis/workflows/type_iip_workflow.py @@ -18,7 +18,9 @@ from tardis.opacities.macro_atom.macroatom_solver import ( ContinuumMacroAtomSolver, ) +from tardis.opacities.macro_atom.macroatom_state import MacroAtomState from tardis.opacities.opacity_solver import OpacitySolver +from tardis.opacities.opacity_state import OpacityState from tardis.opacities.tau_sobolev import ( SOBOLEV_COEFFICIENT, calculate_beta_sobolev, @@ -1127,7 +1129,7 @@ def get_ff_heating_norm_factor( norm_factor *= np.sqrt(t_electrons) return norm_factor - def solve_opacity(self): + def solve_opacity(self) -> dict[str, OpacityState | MacroAtomState]: """Solve the opacity state and any associated objects. Returns @@ -1145,6 +1147,16 @@ def solve_opacity(self): ) continuum_rates = self.continuum_macro_atom_state + # Release both owners of the previous matrix before rebuilding it. + if hasattr(self, "opacity_states"): + self.opacity_states[ + "macro_atom_state" + ].absorbing_probability_matrix = None + if self.transport_state is not None: + self.transport_state.continuum_state_numba.absorbing_markov_probabilities = np.empty( + (0, 0, 0), dtype=np.float64 + ) + macro_atom_state = self.macro_atom_solver.solve( self.plasma_solver.j_blues, opacity_state.beta_sobolev, From aa4eae037e6d93e29af821ec8763937bb78443e9 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 14:46:28 -0500 Subject: [PATCH 05/12] pop out nested solve cell function --- .../macro_atom/absorbing_markov_chain.py | 359 +++++++++++------- 1 file changed, 218 insertions(+), 141 deletions(-) diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 2b101096fda..777c218e31d 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -1,8 +1,10 @@ -"""Calculate absorption probabilities using absorbing Markov chain theory. +"""Calculate first-exit probabilities for reduced macro-atom chains. -This module implements the mathematical framework of absorbing Markov chains -to compute probabilities of photon absorption in each cell and the expected -number of steps before absorption from each source state. +This module eliminates selected internal transitions independently in each cell +and computes the source-state probabilities for the first retained transition. +It does not calculate expected step counts or visit counts, though the formalism +does allow for that. It would require an additional potentially expensive linear +algebra solve so it has been omitted. References ---------- @@ -12,6 +14,7 @@ from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from decimal import Decimal, localcontext +from functools import partial from typing import NamedTuple import numpy as np @@ -27,7 +30,11 @@ class AbsorbingChainResult(NamedTuple): - """Carry first-exit probabilities and their global/compact index contract.""" + """ + Carry processed reduced block exit probabilities and their global/compact index mapping. + + Necessary for the monte-carlo step to enter and exit the reduced block. + """ matrix: npt.NDArray[np.float64] residual_probabilities: pd.DataFrame @@ -45,18 +52,23 @@ def create_absorbing_probs( include_ionization_pool: bool = False, max_workers: int = 1, ) -> AbsorbingChainResult: - """Eliminate internal transitions within the selected state set. + """Calculate absorbing Markov chain probabilities and deactivation data. + + Computes the absorption probability matrices for each cell and extracts + deactivation probabilities by solving the absorbing Markov chain system + for the requested block. + Eliminates internal transition inside handled blocks. Parameters ---------- transition_probabilities : pandas.DataFrame - Normalized original channel coefficients; columns are cells. Signed - coefficients retain the legacy full-mode behavior in every mode. + Normalized original channel coefficients; columns are cells. metadata : pandas.DataFrame Transition source tuples, global source/destination indices, and types. mode : {'full', 'partial', 'explicit'} Full eliminates all internal jumps. Partial eliminates only jumps with - both endpoints selected, optionally including either shared pool. + both endpoints selected (e.g., internal transitions for a requested element), + optionally including either shared pool. Explicit retains every original transition. elements : sequence of str Element symbols, required only in partial mode. All represented ions @@ -78,16 +90,18 @@ def create_absorbing_probs( ----- The solve is ``(I-Q) B = diag(r)``, where r is the sum of actual remaining channels. Zero residual rows stay zero. + The matrix selects the source of the first retained transition, which can itself be internal. It is not necessarily a final emission state because only requested physical blocks are blocks are processed out of the matrix, and the not-requested blocks retain full internal transition probability tables. + This means you can move freely back and forth between the absorbing-processed block. """ if mode not in ("full", "partial", "explicit"): raise ValueError("markov_chain.mode must be full, partial, or explicit") if (mode == "partial") != bool(elements): raise ValueError( - "markov_chain.elements must be nonempty only in partial mode" + "markov_chain.elements must not be empty in partial mode. Specify which elements to process" ) if mode != "partial" and (include_thermal_pool or include_ionization_pool): raise ValueError( @@ -134,7 +148,7 @@ def create_absorbing_probs( selected_rows | (metadata.source == ("i", -99, -99)).to_numpy() ) selected = np.unique(sources[selected_rows]) - else: + else: # Explicit mode skips the calculation and reduction selected = np.empty(0, dtype=np.int64) lookup = np.full(global_size, -1, dtype=np.int64) lookup[selected] = np.arange(len(selected), dtype=np.int64) @@ -151,147 +165,210 @@ def create_absorbing_probs( (transition_probabilities.shape[1], len(selected), len(selected)) ) - def solve_cell(cell: int) -> tuple[int, npt.NDArray[np.float64]]: - """Check the cell's physical exits and solve its selected first-exit law.""" - values = transition_probabilities.iloc[:, cell].to_numpy() - totals = np.bincount(sources, weights=values, minlength=global_size) - active = totals > 0 - if not np.all(np.isfinite(values)): - raise ValueError( - f"cell {cell}: nonfinite channel coefficients at transitions {metadata.index[~np.isfinite(values)].tolist()}" - ) - if not np.allclose( - totals[active], 1, rtol=0, atol=PROBABILITY_TOLERANCE - ): - raise ValueError( - f"cell {cell}: original outgoing probabilities are not normalized" - ) - # Reverse reachability from positive physical deactivation channels detects - # closed communicating classes even in explicit mode, before MC can trap. - reachable = ( - np.bincount( - sources[~internal], - weights=values[~internal], - minlength=global_size, - ) - > 0 - ) - positive_internal = internal & (values > 0) - graph = sparse.csr_matrix( - ( - np.ones(positive_internal.sum()), - (destinations[positive_internal], sources[positive_internal]), - ), - shape=(global_size, global_size), - ) - pending = np.flatnonzero(reachable).tolist() - while pending: - destination = pending.pop() - for source in graph.indices[ - graph.indptr[destination] : graph.indptr[destination + 1] - ]: - if not reachable[source]: - reachable[source] = True - pending.append(source) - trapped = np.flatnonzero(active & ~reachable) - if len(trapped): - raise ValueError( - f"cell {cell}: closed or non-emitting communicating class reachable from states {trapped}" - ) - if not len(selected): - return cell, matrices[cell] - q_matrix = sparse.coo_matrix( - (values[eliminated], (rows, columns)), - shape=(len(selected), len(selected)), - ) - exit_rates = np.bincount( - sources, - weights=residual.iloc[:, cell].to_numpy(), - minlength=global_size, - )[selected] - q_totals = np.asarray(q_matrix.sum(axis=1)).ravel() - if not np.allclose( - q_totals + exit_rates, - totals[selected], - rtol=0, - atol=PROBABILITY_TOLERANCE, - ): - raise ValueError( - f"cell {cell}: eliminated and residual channels do not partition the original rates" - ) - system = (sparse.eye(len(selected), format="csc") - q_matrix).tocsc() - rhs = exit_rates - if mode == "full": - # Retain master's numerical/RNG behavior for ordinary full solves, - # including its inert rows for levels without outgoing probability. - rhs = 1 - q_totals - # For near-trapping self-loops, form the diagonal from physical exits - # and off-diagonal jumps, avoiding catastrophic cancellation in 1-Qii. - near_trapping = q_matrix.diagonal() > 0.99 - if mode != "full" and np.any(near_trapping): - off_diagonal = q_matrix.copy() - off_diagonal.setdiag(0) - stable_diagonal = ( - np.asarray(off_diagonal.sum(axis=1)).ravel() + exit_rates - ) - diagonal = system.diagonal() - diagonal[near_trapping] = stable_diagonal[near_trapping] - system.setdiag(diagonal) - rhs = rhs.copy() - rhs[near_trapping] = exit_rates[near_trapping] - try: - solved = splu(system, permc_spec="MMD_AT_PLUS_A").solve( - np.diag(rhs) - ) - except RuntimeError as error: - if mode == "full": - raise ValueError( - f"cell {cell}: closed selected chain at states {selected}" - ) from error - solved = solve_near_trapping_chain( - q_matrix, exit_rates, active[selected] - ) - if mode != "full" and not np.allclose( - solved[active[selected]].sum(axis=1), - 1, - rtol=0, - atol=32 * np.finfo(np.float64).eps, - ): - solved = solve_near_trapping_chain( - q_matrix, exit_rates, active[selected] - ) - residual_norm = np.max(np.abs(system @ solved - np.diag(rhs))) - residual_scale = max( - 1.0, - sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), - ) - if ( - not np.all(np.isfinite(solved)) - or residual_norm > PROBABILITY_TOLERANCE * residual_scale - or not np.allclose( - solved[active[selected]].sum(axis=1), - 1, - rtol=0, - atol=PROBABILITY_TOLERANCE, - ) - ): - raise ValueError( - f"cell {cell}: invalid absorbing solve for states {selected}; residual {residual_norm}" - ) - return cell, solved + cell_solver = partial( + solve_cell, + transition_probabilities=transition_probabilities, + transition_index=metadata.index, + sources=sources, + destinations=destinations, + internal=internal, + global_size=global_size, + selected=selected, + eliminated=eliminated, + residual=residual, + rows=rows, + columns=columns, + mode=mode, + ) if max_workers > 1 and len(matrices) > 1: with ThreadPoolExecutor( max_workers=min(max_workers, len(matrices)) ) as executor: - for cell, solved in executor.map(solve_cell, range(len(matrices))): + for cell, solved in executor.map(cell_solver, range(len(matrices))): matrices[cell] = solved else: for cell in range(len(matrices)): - _, matrices[cell] = solve_cell(cell) + _, matrices[cell] = cell_solver(cell) return AbsorbingChainResult(matrices, residual, lookup, selected) +def solve_cell( + cell: int, + *, + transition_probabilities: pd.DataFrame, + transition_index: pd.Index, + sources: npt.NDArray[np.int64], + destinations: npt.NDArray[np.int64], + internal: npt.NDArray[np.bool_], + global_size: int, + selected: npt.NDArray[np.int64], + eliminated: npt.NDArray[np.bool_], + residual: pd.DataFrame, + rows: npt.NDArray[np.int64], + columns: npt.NDArray[np.int64], + mode: str, +) -> tuple[int, npt.NDArray[np.float64]]: + """Check one cell's physical exits and solve its selected first-exit law. + + Parameters + ---------- + cell : int + Positional cell column to solve. + transition_probabilities : pandas.DataFrame + Normalized original channel coefficients for all cells. + transition_index : pandas.Index + Original transition labels for diagnostics. + sources, destinations : numpy.ndarray + Global source and destination indices for every original channel. + internal : numpy.ndarray + Mask identifying original internal transitions. + global_size : int + Number of global level indices, including gaps. + selected : numpy.ndarray + Global states in compact matrix order. + eliminated : numpy.ndarray + Mask of selected-to-selected internal channels to eliminate. + residual : pandas.DataFrame + Original channels with eliminated coefficients set to zero. + rows, columns : numpy.ndarray + Compact source and destination indices for eliminated channels. + mode : {'full', 'partial', 'explicit'} + Reduction mode, including legacy full-mode numerical behavior. + + Returns + ------- + tuple[int, numpy.ndarray] + Cell position and its first-exit matrix; explicit mode returns an + empty matrix after checking the original channels. + + Notes + ----- + Shared input tables and index arrays are read without modification so + cells can be solved independently in parallel. + """ + values = transition_probabilities.iloc[:, cell].to_numpy() + totals = np.bincount(sources, weights=values, minlength=global_size) + active = totals > 0 + if not np.all(np.isfinite(values)): + raise ValueError( + f"cell {cell}: nonfinite channel coefficients at transitions {transition_index[~np.isfinite(values)].tolist()}" + ) + if not np.allclose(totals[active], 1, rtol=0, atol=PROBABILITY_TOLERANCE): + raise ValueError( + f"cell {cell}: original outgoing probabilities are not normalized" + ) + # Reverse reachability from positive physical deactivation channels detects + # closed communicating classes even in explicit mode, before MC can trap. + reachable = ( + np.bincount( + sources[~internal], + weights=values[~internal], + minlength=global_size, + ) + > 0 + ) + positive_internal = internal & (values > 0) + graph = sparse.csr_matrix( + ( + np.ones(positive_internal.sum()), + (destinations[positive_internal], sources[positive_internal]), + ), + shape=(global_size, global_size), + ) + pending = np.flatnonzero(reachable).tolist() + while pending: + destination = pending.pop() + for source in graph.indices[ + graph.indptr[destination] : graph.indptr[destination + 1] + ]: + if not reachable[source]: + reachable[source] = True + pending.append(source) + trapped = np.flatnonzero(active & ~reachable) + if len(trapped): + raise ValueError( + f"cell {cell}: closed or non-emitting communicating class reachable from states {trapped}" + ) + if not len(selected): + return cell, np.zeros((0, 0), dtype=np.float64) + q_matrix = sparse.coo_matrix( + (values[eliminated], (rows, columns)), + shape=(len(selected), len(selected)), + ) + exit_rates = np.bincount( + sources, + weights=residual.iloc[:, cell].to_numpy(), + minlength=global_size, + )[selected] + q_totals = np.asarray(q_matrix.sum(axis=1)).ravel() + if not np.allclose( + q_totals + exit_rates, + totals[selected], + rtol=0, + atol=PROBABILITY_TOLERANCE, + ): + raise ValueError( + f"cell {cell}: eliminated and residual channels do not partition the original rates" + ) + system = (sparse.eye(len(selected), format="csc") - q_matrix).tocsc() + rhs = exit_rates + if mode == "full": + rhs = 1 - q_totals + # For near-trapping self-loops, form the diagonal from physical exits + # and off-diagonal jumps. + near_trapping = q_matrix.diagonal() > 0.99 + if mode != "full" and np.any(near_trapping): + off_diagonal = q_matrix.copy() + off_diagonal.setdiag(0) + stable_diagonal = ( + np.asarray(off_diagonal.sum(axis=1)).ravel() + exit_rates + ) + diagonal = system.diagonal() + diagonal[near_trapping] = stable_diagonal[near_trapping] + system.setdiag(diagonal) + rhs = rhs.copy() + rhs[near_trapping] = exit_rates[near_trapping] + try: + solved = splu(system, permc_spec="MMD_AT_PLUS_A").solve(np.diag(rhs)) + except RuntimeError as error: + if mode == "full": + raise ValueError( + f"cell {cell}: closed selected chain at states {selected}" + ) from error + solved = solve_near_trapping_chain( + q_matrix, exit_rates, active[selected] + ) + if mode != "full" and not np.allclose( + solved[active[selected]].sum(axis=1), + 1, + rtol=0, + atol=32 * np.finfo(np.float64).eps, + ): + solved = solve_near_trapping_chain( + q_matrix, exit_rates, active[selected] + ) + residual_norm = np.max(np.abs(system @ solved - np.diag(rhs))) + residual_scale = max( + 1.0, + sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), + ) + if ( + not np.all(np.isfinite(solved)) + or residual_norm > PROBABILITY_TOLERANCE * residual_scale + or not np.allclose( + solved[active[selected]].sum(axis=1), + 1, + rtol=0, + atol=PROBABILITY_TOLERANCE, + ) + ): + raise ValueError( + f"cell {cell}: invalid absorbing solve for states {selected}; residual {residual_norm}" + ) + return cell, solved + + def solve_near_trapping_chain( internal_matrix: sparse.spmatrix, exit_rates: npt.NDArray[np.float64], From 706bd50038cd81bf2583fc6b0ad837084fc995d4 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 15:15:02 -0500 Subject: [PATCH 06/12] address comments --- .../macro_atom/absorbing_markov_chain.py | 56 +++++++++++++++---- .../opacities/macro_atom/macroatom_state.py | 4 +- tardis/transport/montecarlo/macro_atom.py | 21 ++++++- .../tests/test_partial_macro_atom.py | 15 +++-- 4 files changed, 76 insertions(+), 20 deletions(-) diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 777c218e31d..6ba606012eb 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -316,7 +316,8 @@ def solve_cell( if mode == "full": rhs = 1 - q_totals # For near-trapping self-loops, form the diagonal from physical exits - # and off-diagonal jumps. + # and off-diagonal jumps. Helps prevent losing individually unlikely + # transitions that are amplified in blocks that are sampled many times. near_trapping = q_matrix.diagonal() > 0.99 if mode != "full" and np.any(near_trapping): off_diagonal = q_matrix.copy() @@ -374,30 +375,61 @@ def solve_near_trapping_chain( exit_rates: npt.NDArray[np.float64], active: npt.NDArray[np.bool_], ) -> npt.NDArray[np.float64]: - """Resolve exceptional cancellation in a transient sparse LU solve. + """Recover first-exit coefficients when tiny exits destabilize float64 LU. + + Nearly closed cycles can amplify small retained exit coefficients, so losing + those coefficients through cancellation can corrupt the final branching + ratios. Rebuild the system using the actual exits and solve it with dense + Decimal arithmetic, rather than subtracting nearly equal float64 values. + The partial-mode caller uses this fallback when sparse LU fails or its + active rows do not sum to one within 32 float64 machine epsilons. Full mode + keeps its existing sparse calculation. Parameters ---------- internal_matrix : scipy.sparse.spmatrix - Selected internal probabilities Q. + Square matrix Q of eliminated internal coefficients, in compact + selected-state order. For each active state, its row sum plus the + corresponding retained exit mass must equal one. exit_rates : numpy.ndarray - Actual retained channel sums, without subtracting from one. + Float64 vector r of retained channel sums for the selected states. + These are normalized coefficients, not dimensional rates. Supply the + actual channel sums rather than deriving them as one minus Q's row + sums. At least one entry must be positive. active : numpy.ndarray - States having original outgoing probability. + Boolean vector marking states with positive total outgoing mass in the + original network. Inactive states are assumed to have zero outgoing + coefficients and zero retained exit mass. Returns ------- numpy.ndarray - First-exit matrix evaluated with at least 80-digit elimination, then rounded - to float64. Precision also resolves the smallest positive exit with 40 - guard digits. Used only if LU violates probability normalization. + Float64 matrix B with the same shape as Q. Entry B[i, j] is the + first-exit coefficient for retaining a channel from selected state j + after activation at selected state i. Inactive rows are zero. The + result is converted to float64 only after high-precision elimination + and back substitution. + + Raises + ------ + ValueError + If elimination encounters a zero pivot and cannot solve the selected + system, as for a closed class with no exit. Notes ----- - The conservation-form diagonal is the sum of off-diagonal internal jumps - and actual exits. This preserves tiny exits in multi-state near-closed - cycles, where even a long residence time must give total exit probability - one. Inactive rows represent no physical activation and stay zero. + Solve ``A B = diag(r)`` with off-diagonal entries ``A[i, j] = -Q[i, j]`` + and active diagonals ``A[i, i] = r[i] + sum(Q[i, j] for j != i)``. + Row conservation makes this equivalent to ``I-Q`` for normalized active + states, while avoiding cancellation in ``1-Q[i, i]``. Inactive diagonals + are set to one. + + Gaussian elimination uses partial row pivoting. Decimal precision is + ``max(80, 40 - floor(log10(r_min)))``, where r_min is the smallest positive + exit coefficient. This increases arithmetic precision but cannot recover + information already lost from the supplied float64 coefficients. Dense + storage and high-precision arithmetic make this an exceptional fallback, + rather than the normal solver. """ size = len(exit_rates) with localcontext() as context: diff --git a/tardis/opacities/macro_atom/macroatom_state.py b/tardis/opacities/macro_atom/macroatom_state.py index d371b3566d4..dda8d2ee5cc 100644 --- a/tardis/opacities/macro_atom/macroatom_state.py +++ b/tardis/opacities/macro_atom/macroatom_state.py @@ -143,9 +143,11 @@ def __init__( k_packet_idx: Int describing the index location of the k_packet block macro_level_to_reduced_idx : numpy.ndarray, optional - Global-to-compact index map; -1 denotes an explicit state. + Full transition index to markov-chain reduced index. + Tells the MC RT step how to leave and enter the absorbing matrix. reduced_to_macro_level_idx : numpy.ndarray, optional Inverse map from compact matrix indices to global macro levels. + Tells the MC RT step how to leave and enter the absorbing matrix. """ self.transition_probabilities = transition_probabilities self.transition_metadata = transition_metadata diff --git a/tardis/transport/montecarlo/macro_atom.py b/tardis/transport/montecarlo/macro_atom.py index 455bdd5cde3..597c24f9023 100644 --- a/tardis/transport/montecarlo/macro_atom.py +++ b/tardis/transport/montecarlo/macro_atom.py @@ -146,11 +146,16 @@ def macro_atom_interaction_iip( reduced_idx = continuum_state.macro_level_to_reduced_idx[ activation_level_idx ] + if reduced_idx >= 0: + # This tells us we're in the reduced block and should take one step + # and see what state we leave the reduced block from. See absorbing_markov_chain.py probability_event = np.random.random() cumulative_probability = 0.0 selected_idx = -1 last_positive_idx = -1 + + # Step through the probability block for exit_idx, state_probability in enumerate( continuum_state.absorbing_markov_probabilities[ current_shell_id, reduced_idx @@ -160,8 +165,10 @@ def macro_atom_interaction_iip( last_positive_idx = exit_idx cumulative_probability += state_probability if cumulative_probability > probability_event: + # Found the deactivating state. Break out of the cumulative probability loop. selected_idx = exit_idx break + if selected_idx < 0: if ( last_positive_idx >= 0 @@ -170,12 +177,16 @@ def macro_atom_interaction_iip( selected_idx = last_positive_idx else: raise MacroAtomError( - "MacroAtom first-exit probabilities are not normalized or activation has no outgoing probability" + "MacroAtom first-exit probabilities are not normalized or activation has no outgoing probability " + f"(starting reduced state {reduced_idx}, global activation level {activation_level_idx}, cell {current_shell_id})" ) activation_level_idx = continuum_state.reduced_to_macro_level_idx[ selected_idx ] + # End of reduced block handling. + # You necessarily are now either going to deactivate OR are in a block with internal transitions. + # Below is largely the same behavior as the classic macro atom interaction. block_start_idx = opacity_state.macro_block_edge_index[ activation_level_idx ] @@ -186,6 +197,7 @@ def macro_atom_interaction_iip( cumulative_probability = 0.0 selected_transition_idx = -1 last_positive_idx = -1 + for transition_idx in range(block_start_idx, block_end_idx): transition_probability = opacity_state.transition_probabilities[ transition_idx, current_shell_id @@ -196,6 +208,7 @@ def macro_atom_interaction_iip( if cumulative_probability > probability_event: selected_transition_idx = transition_idx break + if selected_transition_idx < 0: if ( last_positive_idx >= 0 @@ -204,13 +217,17 @@ def macro_atom_interaction_iip( selected_transition_idx = last_positive_idx else: raise MacroAtomError( - "MacroAtom residual block is not normalized or activation has no outgoing probability" + "MacroAtom residual block is not normalized or activation has no outgoing probability " + f"(global activation level {activation_level_idx}, cell {current_shell_id}, transition rows {block_start_idx}:{block_end_idx})" ) transition_type = opacity_state.transition_type[selected_transition_idx] + if transition_type < 0: + # We've found a deactivating transition so we'll break out of the function and return that transition. return opacity_state.transition_line_id[ selected_transition_idx ], transition_type + # Otherwise, we've found an internal transition and need to go back to the top of the while loop. activation_level_idx = opacity_state.destination_level_id[ selected_transition_idx ] diff --git a/tardis/transport/montecarlo/tests/test_partial_macro_atom.py b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py index 3ceccd47ef4..1656f24bf76 100644 --- a/tardis/transport/montecarlo/tests/test_partial_macro_atom.py +++ b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py @@ -1,4 +1,7 @@ -"""Compiled-path verification of independent hybrid macro-atom visits.""" +""" +Test file primarily to test the partial absorbing markov chain implementation. +Checks hybrid blocks against the fully expliict macro atom. +""" import numpy as np import numpy.typing as npt @@ -108,11 +111,13 @@ def two_visit_state(request: pytest.FixtureRequest) -> tuple: def test_compiled_reentry_emission_distribution(two_visit_state: tuple) -> None: - """Exact tree law is 1/2, 3/16, 5/16 with thermal emission and re-entry. + """Check emission outcomes when packets leave and return to reduced states. - Tolerance is six binomial standard deviations per channel (60000 packets), - giving a conservative familywise stochastic bound across all modes and pool selections. - Reusing the first reduced random number suppresses one channel entirely. + Packets can emit from the thermal pool, or pass through the ionization + pool and helium before returning to hydrogen. Every reduction mode and + pool selection should give the same emission mix: 50%, 18.75%, and 31.25% + across the three channels. Also check packets starting in either pool. + Allow for the random variation expected from a finite sample of packets. """ opacity, continuum = two_visit_state count = 60000 From ea378d884a3231bd8615d2c9b49b315c8cd0e3bb Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 15:22:41 -0500 Subject: [PATCH 07/12] remove benchmark --- benchmarks/partial_absorbing_chain.py | 71 --------------------------- 1 file changed, 71 deletions(-) delete mode 100644 benchmarks/partial_absorbing_chain.py diff --git a/benchmarks/partial_absorbing_chain.py b/benchmarks/partial_absorbing_chain.py deleted file mode 100644 index 4c82776490f..00000000000 --- a/benchmarks/partial_absorbing_chain.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Remote ASV setup/solve and retained-memory comparison on a fixed network.""" - -import numpy as np -import pandas as pd - -from tardis.opacities.macro_atom.absorbing_markov_chain import ( - create_absorbing_probs, -) - - -class BenchmarkPartialAbsorbingChain: - """Keep physics and cells fixed while changing the reduction boundary.""" - - params = ["full", "H", "He", "H+He", "explicit"] - param_names = ["selection"] - - def setup(self, selection: str) -> None: - """Build H/He/Fe levels plus shared i/k pools in eight cells.""" - states = [ - (atomic_number, 0, level) - for atomic_number in (1, 2, 26) - for level in range(30) - ] - states += [("i", -99, -99), ("k", -99, -99)] - sources = np.repeat(np.arange(len(states)), 3) - self.metadata = pd.DataFrame( - { - "source": [states[source] for source in sources], - "source_level_idx": sources, - "destination_level_idx": np.column_stack( - ( - (np.arange(len(states)) + 1) % len(states), - np.full(len(states), 90), - np.full(len(states), -1), - ) - ).ravel(), - "transition_type": np.tile([1, 2, -1], len(states)), - } - ) - self.probabilities = pd.DataFrame( - np.tile([0.4, 0.2, 0.4], len(states))[:, None] * np.ones((1, 8)) - ) - self.mode = ( - selection if selection in ("full", "explicit") else "partial" - ) - self.elements = ( - () if self.mode != "partial" else tuple(selection.split("+")) - ) - self.result = create_absorbing_probs( - self.probabilities, - self.metadata, - mode=self.mode, - elements=self.elements, - ) - - def time_create_absorbing_probs(self, selection: str) -> None: - """Measure full mapping construction, diagnostics, and per-cell LU solve.""" - create_absorbing_probs( - self.probabilities, - self.metadata, - mode=self.mode, - elements=self.elements, - ) - - def track_selected_states(self, selection: str) -> int: - """Report selected real/pool state count for interpreting solve cost.""" - return len(self.result.reduced_to_macro_level_idx) - - def track_dense_matrix_bytes(self, selection: str) -> int: - """Report retained matrix memory summed over the same eight cells.""" - return self.result.matrix.nbytes From 26ec4cea1051472196055fe8393e259e19ec8ae4 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Mon, 2 Nov 2026 15:24:06 -0500 Subject: [PATCH 08/12] remove line from plasma.rst --- docs/io/configuration/components/plasma.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/io/configuration/components/plasma.rst b/docs/io/configuration/components/plasma.rst index f739493addd..da1ea7fae35 100644 --- a/docs/io/configuration/components/plasma.rst +++ b/docs/io/configuration/components/plasma.rst @@ -101,5 +101,4 @@ selected states are then collapsed, including paths through the enabled pools. Pool emission/cooling and jumps to unselected states remain explicit exit channels. These options require ``mode: partial``; full mode already includes both pools, and explicit mode reduces neither. -See :doc:`../../../physics_walkthrough/montecarlo/partial_absorbing_chain` for the -probability contract and scientific verification. +See :doc:`../../../physics_walkthrough/montecarlo/partial_absorbing_chain` for more. From 8cb904de87e1eb768f333ff35fd319d007404e0d Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Tue, 3 Nov 2026 10:08:11 -0500 Subject: [PATCH 09/12] remove trapping checks and handling --- .../montecarlo/partial_absorbing_chain.rst | 8 - .../macro_atom/absorbing_markov_chain.py | 271 +++++------------- .../tests/test_partial_absorbing_chain.py | 114 ++------ 3 files changed, 92 insertions(+), 301 deletions(-) diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst index 702c4a19bbc..b62b87a5dec 100644 --- a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -59,11 +59,3 @@ never removed by a numerical probability threshold. The sampler allows a CDF end deficit of at most 1e-10 due to floating-point summation; larger deficits or activations without outgoing probability raise an error. -Exact small-network tests compare eventual channel distributions with an -independent dense solve of the unreduced network. Compiled sampling tests check -an analytic 50 percent / 18.75 percent / 31.25 percent emission distribution with -direct thermal emission, pool activation, and re-entry through an unselected -element. Every pool-option combination is checked with binomial uncertainty -bounds. Full mode preserves the existing default and its two-draw -sampling behavior. For nonnegative kernels, the different modes preserve -distributions, rather than individual random packet histories. diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 6ba606012eb..140501b22fd 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -1,20 +1,19 @@ """Calculate first-exit probabilities for reduced macro-atom chains. -This module eliminates selected internal transitions independently in each cell -and computes the source-state probabilities for the first retained transition. -It does not calculate expected step counts or visit counts, though the formalism -does allow for that. It would require an additional potentially expensive linear -algebra solve so it has been omitted. +This module eliminates internal transitions for selected blocks independently in each cell +and computes the source-state probabilities for retained transitions. + +Effectively this compresses the macro atom evaluation by internal reducing probability chains +to equivalent single appropriate probability steps. References ---------- Absorbing Markov chain theory: https://en.wikipedia.org/wiki/Absorbing_Markov_chain """ +from collections import deque from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor -from decimal import Decimal, localcontext -from functools import partial from typing import NamedTuple import numpy as np @@ -25,7 +24,8 @@ from tardis.util.base import element_symbol2atomic_number -# LU/CDF arithmetic tolerance, not a tolerance for discarding physical channels. +# LU/CDF arithmetic tolerance. All probabilities at this stage are normalized so this a tolerance +# of 1e-10 is small enough that we should effectively never notice the error in a simulation. PROBABILITY_TOLERANCE = 1e-10 @@ -61,10 +61,15 @@ def create_absorbing_probs( Parameters ---------- - transition_probabilities : pandas.DataFrame - Normalized original channel coefficients; columns are cells. - metadata : pandas.DataFrame - Transition source tuples, global source/destination indices, and types. + transition_probabilities : pd.DataFrame + DataFrame with transition probabilities between states for each cell. + Rows represent transitions, columns represent cells. + metadata : pd.DataFrame + Metadata about transitions including source_level_idx, + destination_level_idx, and transition_type. Values >= 0 for + transition_type indicate internal transitions transitions that are not accompanied + by reemission of the r-packet, and an end to the interaction handler chain. + Negative values indicate deactivation, or reemitting from an absorbing state. mode : {'full', 'partial', 'explicit'} Full eliminates all internal jumps. Partial eliminates only jumps with both endpoints selected (e.g., internal transitions for a requested element), @@ -83,7 +88,7 @@ def create_absorbing_probs( Returns ------- AbsorbingChainResult - Cell-by-activation-by-exit-source matrix, residual channel probabilities, + Cell-by-activation-by-exit-source matrix, containing deactivation probabilities, and explicit global-to-reduced and reduced-to-global int64 maps. Notes @@ -130,10 +135,10 @@ def create_absorbing_probs( if mode == "full": selected = np.arange(global_size, dtype=np.int64) elif mode == "partial": - selected_rows = metadata.source.map( - lambda level: level[0] in atomic_numbers - ).to_numpy() - represented = {level[0] for level in metadata.source} + # Source tuples start with an atomic number or a shared-pool label. + source_identifiers = metadata.source.str[0] + selected_rows = source_identifiers.isin(atomic_numbers).to_numpy() + represented = set(source_identifiers) absent = set(atomic_numbers) - represented if absent: raise ValueError( @@ -165,37 +170,59 @@ def create_absorbing_probs( (transition_probabilities.shape[1], len(selected), len(selected)) ) - cell_solver = partial( - solve_cell, - transition_probabilities=transition_probabilities, - transition_index=metadata.index, - sources=sources, - destinations=destinations, - internal=internal, - global_size=global_size, - selected=selected, - eliminated=eliminated, - residual=residual, - rows=rows, - columns=columns, - mode=mode, - ) - if max_workers > 1 and len(matrices) > 1: with ThreadPoolExecutor( max_workers=min(max_workers, len(matrices)) ) as executor: - for cell, solved in executor.map(cell_solver, range(len(matrices))): - matrices[cell] = solved + futures = deque( + executor.submit( + solve_cell, + cell, + transition_probabilities, + metadata.index, + sources, + destinations, + internal, + global_size, + selected, + eliminated, + residual, + rows, + columns, + mode, + ) + for cell in range(len(matrices)) + ) + try: + # Release each future after copying its matrix into the result. + while futures: + cell, solved = futures.popleft().result() + matrices[cell] = solved + finally: + for future in futures: + future.cancel() else: for cell in range(len(matrices)): - _, matrices[cell] = cell_solver(cell) + _, matrices[cell] = solve_cell( + cell, + transition_probabilities, + metadata.index, + sources, + destinations, + internal, + global_size, + selected, + eliminated, + residual, + rows, + columns, + mode, + ) return AbsorbingChainResult(matrices, residual, lookup, selected) def solve_cell( cell: int, - *, transition_probabilities: pd.DataFrame, transition_index: pd.Index, sources: npt.NDArray[np.int64], @@ -258,8 +285,10 @@ def solve_cell( raise ValueError( f"cell {cell}: original outgoing probabilities are not normalized" ) - # Reverse reachability from positive physical deactivation channels detects - # closed communicating classes even in explicit mode, before MC can trap. + # Start with states that have a positive probability of deactivation. + # Follow internal jumps with positive probability backward to find all states + # that can reach deactivation. An active state left unmarked has no such exit + # path and could trap a packet forever. Check this even in explicit mode. reachable = ( np.bincount( sources[~internal], @@ -315,40 +344,12 @@ def solve_cell( rhs = exit_rates if mode == "full": rhs = 1 - q_totals - # For near-trapping self-loops, form the diagonal from physical exits - # and off-diagonal jumps. Helps prevent losing individually unlikely - # transitions that are amplified in blocks that are sampled many times. - near_trapping = q_matrix.diagonal() > 0.99 - if mode != "full" and np.any(near_trapping): - off_diagonal = q_matrix.copy() - off_diagonal.setdiag(0) - stable_diagonal = ( - np.asarray(off_diagonal.sum(axis=1)).ravel() + exit_rates - ) - diagonal = system.diagonal() - diagonal[near_trapping] = stable_diagonal[near_trapping] - system.setdiag(diagonal) - rhs = rhs.copy() - rhs[near_trapping] = exit_rates[near_trapping] try: solved = splu(system, permc_spec="MMD_AT_PLUS_A").solve(np.diag(rhs)) except RuntimeError as error: - if mode == "full": - raise ValueError( - f"cell {cell}: closed selected chain at states {selected}" - ) from error - solved = solve_near_trapping_chain( - q_matrix, exit_rates, active[selected] - ) - if mode != "full" and not np.allclose( - solved[active[selected]].sum(axis=1), - 1, - rtol=0, - atol=32 * np.finfo(np.float64).eps, - ): - solved = solve_near_trapping_chain( - q_matrix, exit_rates, active[selected] - ) + raise ValueError( + f"cell {cell}: closed selected chain at states {selected}" + ) from error residual_norm = np.max(np.abs(system @ solved - np.diag(rhs))) residual_scale = max( 1.0, @@ -368,133 +369,3 @@ def solve_cell( f"cell {cell}: invalid absorbing solve for states {selected}; residual {residual_norm}" ) return cell, solved - - -def solve_near_trapping_chain( - internal_matrix: sparse.spmatrix, - exit_rates: npt.NDArray[np.float64], - active: npt.NDArray[np.bool_], -) -> npt.NDArray[np.float64]: - """Recover first-exit coefficients when tiny exits destabilize float64 LU. - - Nearly closed cycles can amplify small retained exit coefficients, so losing - those coefficients through cancellation can corrupt the final branching - ratios. Rebuild the system using the actual exits and solve it with dense - Decimal arithmetic, rather than subtracting nearly equal float64 values. - The partial-mode caller uses this fallback when sparse LU fails or its - active rows do not sum to one within 32 float64 machine epsilons. Full mode - keeps its existing sparse calculation. - - Parameters - ---------- - internal_matrix : scipy.sparse.spmatrix - Square matrix Q of eliminated internal coefficients, in compact - selected-state order. For each active state, its row sum plus the - corresponding retained exit mass must equal one. - exit_rates : numpy.ndarray - Float64 vector r of retained channel sums for the selected states. - These are normalized coefficients, not dimensional rates. Supply the - actual channel sums rather than deriving them as one minus Q's row - sums. At least one entry must be positive. - active : numpy.ndarray - Boolean vector marking states with positive total outgoing mass in the - original network. Inactive states are assumed to have zero outgoing - coefficients and zero retained exit mass. - - Returns - ------- - numpy.ndarray - Float64 matrix B with the same shape as Q. Entry B[i, j] is the - first-exit coefficient for retaining a channel from selected state j - after activation at selected state i. Inactive rows are zero. The - result is converted to float64 only after high-precision elimination - and back substitution. - - Raises - ------ - ValueError - If elimination encounters a zero pivot and cannot solve the selected - system, as for a closed class with no exit. - - Notes - ----- - Solve ``A B = diag(r)`` with off-diagonal entries ``A[i, j] = -Q[i, j]`` - and active diagonals ``A[i, i] = r[i] + sum(Q[i, j] for j != i)``. - Row conservation makes this equivalent to ``I-Q`` for normalized active - states, while avoiding cancellation in ``1-Q[i, i]``. Inactive diagonals - are set to one. - - Gaussian elimination uses partial row pivoting. Decimal precision is - ``max(80, 40 - floor(log10(r_min)))``, where r_min is the smallest positive - exit coefficient. This increases arithmetic precision but cannot recover - information already lost from the supplied float64 coefficients. Dense - storage and high-precision arithmetic make this an exceptional fallback, - rather than the normal solver. - """ - size = len(exit_rates) - with localcontext() as context: - positive_exit_rates = exit_rates[exit_rates > 0] - context.prec = max( - 80, 40 - int(np.floor(np.log10(positive_exit_rates.min()))) - ) - zero = Decimal(0) - one = Decimal(1) - dense = internal_matrix.toarray() - system = [ - [ - -Decimal(float(dense[row, column])) if row != column else zero - for column in range(size) - ] - for row in range(size) - ] - rhs = [[zero for _ in range(size)] for _ in range(size)] - for row in range(size): - rate = Decimal(float(exit_rates[row])) - system[row][row] = ( - sum( - ( - -system[row][column] - for column in range(size) - if row != column - ), - rate, - ) - if active[row] - else one - ) - rhs[row][row] = rate - for pivot_idx in range(size): - pivot_row = max( - range(pivot_idx, size), - key=lambda row: abs(system[row][pivot_idx]), - ) - if not system[pivot_row][pivot_idx]: - raise ValueError( - "Closed selected chain in high-precision solve" - ) - system[pivot_idx], system[pivot_row] = ( - system[pivot_row], - system[pivot_idx], - ) - rhs[pivot_idx], rhs[pivot_row] = rhs[pivot_row], rhs[pivot_idx] - pivot = system[pivot_idx][pivot_idx] - for row in range(pivot_idx + 1, size): - factor = system[row][pivot_idx] / pivot - for column in range(pivot_idx + 1, size): - system[row][column] -= factor * system[pivot_idx][column] - for column in range(size): - rhs[row][column] -= factor * rhs[pivot_idx][column] - solved = [[zero for _ in range(size)] for _ in range(size)] - for row in range(size - 1, -1, -1): - for channel in range(size): - solved[row][channel] = ( - rhs[row][channel] - - sum( - ( - system[row][column] * solved[column][channel] - for column in range(row + 1, size) - ), - zero, - ) - ) / system[row][row] - return np.asarray(solved, dtype=np.float64) diff --git a/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py index f8a9058da50..eb4f1f87301 100644 --- a/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py +++ b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py @@ -34,46 +34,14 @@ def pool_network() -> tuple[pd.DataFrame, pd.DataFrame]: ], } ) - probabilities = pd.DataFrame( - { - 10: [ - 0.0, - 1.0, - 0.3, - 0.2, - 0.5, - 0.4, - 0.1, - 0.5, - 0.3, - 0.7, - 0.1, - 0.1, - 0.8, - 1.0, - 0.25, - 0.75, - ], - 30: [ - 1.0, - 0.0, - 0.2, - 0.1, - 0.7, - 0.7, - 0.1, - 0.2, - 0.6, - 0.4, - 0.05, - 0.05, - 0.9, - 1.0, - 0.4, - 0.6, - ], - } - ) + # fmt: off + probabilities = pd.DataFrame({ + 10: [0.0, 1.0, 0.3, 0.2, 0.5, 0.4, 0.1, 0.5, + 0.3, 0.7, 0.1, 0.1, 0.8, 1.0, 0.25, 0.75], + 30: [1.0, 0.0, 0.2, 0.1, 0.7, 0.7, 0.1, 0.2, + 0.6, 0.4, 0.05, 0.05, 0.9, 1.0, 0.4, 0.6], + }) + # fmt: on return probabilities, metadata @@ -130,23 +98,19 @@ def test_final_emission_law( states = np.unique(metadata.source_level_idx) global_size = int(states.max()) + 1 atomic_numbers = {"H": 1, "He": 2, "Fe": 26} - selected_elements = {atomic_numbers[symbol] for symbol in elements} - selected = ( - np.arange(global_size) - if mode == "full" - else np.unique( - metadata.loc[ - metadata.source.map( - lambda level: ( - level[0] in selected_elements - or (include_thermal_pool and level[0] == "k") - or (include_ionization_pool and level[0] == "i") - ) - ), - "source_level_idx", - ] - ) - ) + source_identifiers = metadata.source.str[0] + selected_identifiers: set[int | str] = { + atomic_numbers[symbol] for symbol in elements + } + if include_thermal_pool: + selected_identifiers.add("k") + if include_ionization_pool: + selected_identifiers.add("i") + if mode == "full": + selected = np.arange(global_size) + else: + selected_rows = source_identifiers.isin(selected_identifiers) + selected = np.unique(metadata.loc[selected_rows, "source_level_idx"]) lookup = np.full(global_size, -1, dtype=np.int64) lookup[selected] = np.arange(len(selected)) np.testing.assert_array_equal(result.reduced_to_macro_level_idx, selected) @@ -199,42 +163,6 @@ def test_final_emission_law( np.testing.assert_allclose(actual, expected, rtol=2e-14, atol=2e-14) -def test_asymmetric_near_trapping_cycle_preserves_tiny_exit_ratio() -> None: - """Tiny 1:3 exit rates give asymptotic 1/4:3/4 branching, without cancellation. - - Exact two-state formula retains each actual exit rate; 1e-14 absolute - tolerance covers final float64 rounding, not an error amplified by trapping. - """ - first_exit, second_exit = 1e-12, 3e-12 - metadata = pd.DataFrame( - { - "source_level_idx": [0, 0, 1, 1], - "destination_level_idx": [1, -1, 0, -1], - "transition_type": [1, -1, 1, -1], - "source": [(1, 0, 0)] * 2 + [(1, 1, 0)] * 2, - } - ) - result = create_absorbing_probs( - pd.DataFrame( - [1 - first_exit, first_exit, 1 - second_exit, second_exit] - ), - metadata, - mode="partial", - elements=["H"], - ) - denominator = first_exit + second_exit - first_exit * second_exit - expected = ( - np.array( - [ - [first_exit, (1 - first_exit) * second_exit], - [(1 - second_exit) * first_exit, second_exit], - ] - ) - / denominator - ) - np.testing.assert_allclose(result.matrix[0], expected, rtol=0, atol=1e-14) - - @pytest.mark.parametrize( "mode,include_ionization_pool", [ From 60c243e91b79f7241a2df2ac0f242111b5091857 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Tue, 3 Nov 2026 10:32:41 -0500 Subject: [PATCH 10/12] readability improvements --- .../montecarlo/partial_absorbing_chain.rst | 10 +- .../macro_atom/absorbing_markov_chain.py | 295 ++++++------------ 2 files changed, 108 insertions(+), 197 deletions(-) diff --git a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst index b62b87a5dec..6222374583e 100644 --- a/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -51,11 +51,11 @@ ordering and shell count. Before recalculating the matrix, the workflow releases the previous iteration's matrix references from both the macro-atom state and the Numba transport state. -Sparse LU solves are checked for finite, normalized rows and a scale-aware -equation residual. Input coefficients and reduced entries are not rejected -based on their sign in any reduction mode. A reachable closed class without a -physical exit raises a diagnostic containing the cell and states. Channels are -never removed by a numerical probability threshold. The sampler allows a CDF endpoint +The reduction uses an ordinary sparse LU solve without numerical acceptance +or reachability checks. Input coefficients and reduced entries are not rejected +based on their sign in any reduction mode. Sparse factorization failures +propagate from the solver. Channels are never removed by a numerical probability +threshold. The sampler allows a CDF endpoint deficit of at most 1e-10 due to floating-point summation; larger deficits or activations without outgoing probability raise an error. diff --git a/tardis/opacities/macro_atom/absorbing_markov_chain.py b/tardis/opacities/macro_atom/absorbing_markov_chain.py index 140501b22fd..476737c4f47 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -11,7 +11,6 @@ Absorbing Markov chain theory: https://en.wikipedia.org/wiki/Absorbing_Markov_chain """ -from collections import deque from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from typing import NamedTuple @@ -24,10 +23,6 @@ from tardis.util.base import element_symbol2atomic_number -# LU/CDF arithmetic tolerance. All probabilities at this stage are normalized so this a tolerance -# of 1e-10 is small enough that we should effectively never notice the error in a simulation. -PROBABILITY_TOLERANCE = 1e-10 - class AbsorbingChainResult(NamedTuple): """ @@ -45,7 +40,6 @@ class AbsorbingChainResult(NamedTuple): def create_absorbing_probs( transition_probabilities: pd.DataFrame, metadata: pd.DataFrame, - *, mode: str = "full", elements: Sequence[str] = (), include_thermal_pool: bool = False, @@ -170,202 +164,119 @@ def create_absorbing_probs( (transition_probabilities.shape[1], len(selected), len(selected)) ) - if max_workers > 1 and len(matrices) > 1: - with ThreadPoolExecutor( - max_workers=min(max_workers, len(matrices)) - ) as executor: - futures = deque( - executor.submit( - solve_cell, - cell, - transition_probabilities, - metadata.index, - sources, - destinations, - internal, - global_size, - selected, - eliminated, - residual, - rows, - columns, - mode, - ) - for cell in range(len(matrices)) - ) - try: - # Release each future after copying its matrix into the result. - while futures: - cell, solved = futures.popleft().result() + if mode == "explicit": + return AbsorbingChainResult(matrices, residual, lookup, selected) + + internal_matrices = ( + sparse.coo_matrix( + ( + transition_probabilities.iloc[:, cell].to_numpy()[eliminated], + (rows, columns), + ), + shape=(len(selected), len(selected)), + ) + for cell in range(len(matrices)) + ) + if mode == "full": + if max_workers > 1 and len(matrices) > 1: + with ThreadPoolExecutor( + max_workers=min(max_workers, len(matrices)) + ) as executor: + for cell, solved in enumerate( + executor.map( + solve_cell_full, + internal_matrices, + buffersize=max_workers, + ) + ): matrices[cell] = solved - finally: - for future in futures: - future.cancel() - else: - for cell in range(len(matrices)): - _, matrices[cell] = solve_cell( - cell, - transition_probabilities, - metadata.index, + else: + for cell, solved in enumerate( + map(solve_cell_full, internal_matrices) + ): + matrices[cell] = solved + elif mode == "partial": + exit_rates = ( + np.bincount( sources, - destinations, - internal, - global_size, - selected, - eliminated, - residual, - rows, - columns, - mode, - ) + weights=residual.iloc[:, cell].to_numpy(), + minlength=global_size, + )[selected] + for cell in range(len(matrices)) + ) + if max_workers > 1 and len(matrices) > 1: + with ThreadPoolExecutor( + max_workers=min(max_workers, len(matrices)) + ) as executor: + for cell, solved in enumerate( + executor.map( + solve_cell_partial, + internal_matrices, + exit_rates, + buffersize=max_workers, + ) + ): + matrices[cell] = solved + else: + for cell, solved in enumerate( + map( + solve_cell_partial, + internal_matrices, + exit_rates, + strict=True, + ) + ): + matrices[cell] = solved return AbsorbingChainResult(matrices, residual, lookup, selected) -def solve_cell( - cell: int, - transition_probabilities: pd.DataFrame, - transition_index: pd.Index, - sources: npt.NDArray[np.int64], - destinations: npt.NDArray[np.int64], - internal: npt.NDArray[np.bool_], - global_size: int, - selected: npt.NDArray[np.int64], - eliminated: npt.NDArray[np.bool_], - residual: pd.DataFrame, - rows: npt.NDArray[np.int64], - columns: npt.NDArray[np.int64], - mode: str, -) -> tuple[int, npt.NDArray[np.float64]]: - """Check one cell's physical exits and solve its selected first-exit law. +def solve_cell_full( + internal_matrix: sparse.spmatrix, +) -> npt.NDArray[np.float64]: + """Solve one cell's full reduction using the legacy exit calculation. Parameters ---------- - cell : int - Positional cell column to solve. - transition_probabilities : pandas.DataFrame - Normalized original channel coefficients for all cells. - transition_index : pandas.Index - Original transition labels for diagnostics. - sources, destinations : numpy.ndarray - Global source and destination indices for every original channel. - internal : numpy.ndarray - Mask identifying original internal transitions. - global_size : int - Number of global level indices, including gaps. - selected : numpy.ndarray - Global states in compact matrix order. - eliminated : numpy.ndarray - Mask of selected-to-selected internal channels to eliminate. - residual : pandas.DataFrame - Original channels with eliminated coefficients set to zero. - rows, columns : numpy.ndarray - Compact source and destination indices for eliminated channels. - mode : {'full', 'partial', 'explicit'} - Reduction mode, including legacy full-mode numerical behavior. + internal_matrix : scipy.sparse.spmatrix + Square matrix Q of this cell's internal transition coefficients, + including all global states. Supply COO format to preserve the legacy + row-summation order. Returns ------- - tuple[int, numpy.ndarray] - Cell position and its first-exit matrix; explicit mode returns an - empty matrix after checking the original channels. + numpy.ndarray + Activation-by-exit-source matrix for this cell. Exit coefficients are + calculated as one minus each row sum of Q. + """ + exit_rates = 1 - np.asarray(internal_matrix.sum(axis=1)).ravel() + system = ( + sparse.eye(internal_matrix.shape[0], format="csc") - internal_matrix + ).tocsc() + return splu(system, permc_spec="MMD_AT_PLUS_A").solve(np.diag(exit_rates)) - Notes - ----- - Shared input tables and index arrays are read without modification so - cells can be solved independently in parallel. + +def solve_cell_partial( + internal_matrix: sparse.spmatrix, + exit_rates: npt.NDArray[np.float64], +) -> npt.NDArray[np.float64]: + """Solve one cell's partial reduction from a specified subset of probabilities. + + Parameters + ---------- + internal_matrix : scipy.sparse.spmatrix + Square matrix Q of this cell's eliminated internal coefficients, + in compact selected-state order. + exit_rates : numpy.ndarray + One-dimensional sums of this cell's retained channel coefficients, + in the same selected-state order. + + Returns + ------- + numpy.ndarray + Activation-by-exit-source matrix B satisfying + ``(I-Q) B = diag(exit_rates)`` for this cell. """ - values = transition_probabilities.iloc[:, cell].to_numpy() - totals = np.bincount(sources, weights=values, minlength=global_size) - active = totals > 0 - if not np.all(np.isfinite(values)): - raise ValueError( - f"cell {cell}: nonfinite channel coefficients at transitions {transition_index[~np.isfinite(values)].tolist()}" - ) - if not np.allclose(totals[active], 1, rtol=0, atol=PROBABILITY_TOLERANCE): - raise ValueError( - f"cell {cell}: original outgoing probabilities are not normalized" - ) - # Start with states that have a positive probability of deactivation. - # Follow internal jumps with positive probability backward to find all states - # that can reach deactivation. An active state left unmarked has no such exit - # path and could trap a packet forever. Check this even in explicit mode. - reachable = ( - np.bincount( - sources[~internal], - weights=values[~internal], - minlength=global_size, - ) - > 0 - ) - positive_internal = internal & (values > 0) - graph = sparse.csr_matrix( - ( - np.ones(positive_internal.sum()), - (destinations[positive_internal], sources[positive_internal]), - ), - shape=(global_size, global_size), - ) - pending = np.flatnonzero(reachable).tolist() - while pending: - destination = pending.pop() - for source in graph.indices[ - graph.indptr[destination] : graph.indptr[destination + 1] - ]: - if not reachable[source]: - reachable[source] = True - pending.append(source) - trapped = np.flatnonzero(active & ~reachable) - if len(trapped): - raise ValueError( - f"cell {cell}: closed or non-emitting communicating class reachable from states {trapped}" - ) - if not len(selected): - return cell, np.zeros((0, 0), dtype=np.float64) - q_matrix = sparse.coo_matrix( - (values[eliminated], (rows, columns)), - shape=(len(selected), len(selected)), - ) - exit_rates = np.bincount( - sources, - weights=residual.iloc[:, cell].to_numpy(), - minlength=global_size, - )[selected] - q_totals = np.asarray(q_matrix.sum(axis=1)).ravel() - if not np.allclose( - q_totals + exit_rates, - totals[selected], - rtol=0, - atol=PROBABILITY_TOLERANCE, - ): - raise ValueError( - f"cell {cell}: eliminated and residual channels do not partition the original rates" - ) - system = (sparse.eye(len(selected), format="csc") - q_matrix).tocsc() - rhs = exit_rates - if mode == "full": - rhs = 1 - q_totals - try: - solved = splu(system, permc_spec="MMD_AT_PLUS_A").solve(np.diag(rhs)) - except RuntimeError as error: - raise ValueError( - f"cell {cell}: closed selected chain at states {selected}" - ) from error - residual_norm = np.max(np.abs(system @ solved - np.diag(rhs))) - residual_scale = max( - 1.0, - sparse.linalg.norm(system, np.inf) * np.linalg.norm(solved, np.inf), - ) - if ( - not np.all(np.isfinite(solved)) - or residual_norm > PROBABILITY_TOLERANCE * residual_scale - or not np.allclose( - solved[active[selected]].sum(axis=1), - 1, - rtol=0, - atol=PROBABILITY_TOLERANCE, - ) - ): - raise ValueError( - f"cell {cell}: invalid absorbing solve for states {selected}; residual {residual_norm}" - ) - return cell, solved + system = ( + sparse.eye(internal_matrix.shape[0], format="csc") - internal_matrix + ).tocsc() + return splu(system, permc_spec="MMD_AT_PLUS_A").solve(np.diag(exit_rates)) From 4c207abb58362e873b481fde5a3dc16b1ec44657 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Tue, 3 Nov 2026 10:33:06 -0500 Subject: [PATCH 11/12] docs change --- tutorials.rst | 4 ++++ workflows.rst | 6 ++++++ 2 files changed, 10 insertions(+) create mode 100644 tutorials.rst create mode 100644 workflows.rst diff --git a/tutorials.rst b/tutorials.rst new file mode 100644 index 00000000000..23840c4890b --- /dev/null +++ b/tutorials.rst @@ -0,0 +1,4 @@ +Tutorials +********* + +The following pages contain the TARDIS tutorials: diff --git a/workflows.rst b/workflows.rst new file mode 100644 index 00000000000..2f0c13ce6aa --- /dev/null +++ b/workflows.rst @@ -0,0 +1,6 @@ +Workflows +********* + +The following pages contain the TARDIS workflows: + + These examples are intended to help users explore specific modules within TARDIS, with the goal of supporting their individual scientific objectives. From 17abae7a34011236476ec9fe7d04d7bbc34a5b59 Mon Sep 17 00:00:00 2001 From: Josh Shields Date: Tue, 3 Nov 2026 11:13:04 -0500 Subject: [PATCH 12/12] remove rst files --- tutorials.rst | 4 ---- workflows.rst | 6 ------ 2 files changed, 10 deletions(-) delete mode 100644 tutorials.rst delete mode 100644 workflows.rst diff --git a/tutorials.rst b/tutorials.rst deleted file mode 100644 index 23840c4890b..00000000000 --- a/tutorials.rst +++ /dev/null @@ -1,4 +0,0 @@ -Tutorials -********* - -The following pages contain the TARDIS tutorials: diff --git a/workflows.rst b/workflows.rst deleted file mode 100644 index 2f0c13ce6aa..00000000000 --- a/workflows.rst +++ /dev/null @@ -1,6 +0,0 @@ -Workflows -********* - -The following pages contain the TARDIS workflows: - - These examples are intended to help users explore specific modules within TARDIS, with the goal of supporting their individual scientific objectives.