diff --git a/docs/io/configuration/components/plasma.rst b/docs/io/configuration/components/plasma.rst index 774439a8127..da1ea7fae35 100644 --- a/docs/io/configuration/components/plasma.rst +++ b/docs/io/configuration/components/plasma.rst @@ -64,3 +64,41 @@ 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] + 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 +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. + +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 more. 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..6222374583e --- /dev/null +++ b/docs/physics_walkthrough/montecarlo/partial_absorbing_chain.rst @@ -0,0 +1,61 @@ +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. 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 +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. +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. + +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. + +Before recalculating the matrix, the workflow releases the previous iteration's +matrix references from both the macro-atom state and the Numba transport state. + +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/io/configuration/schemas/plasma.yml b/tardis/io/configuration/schemas/plasma.yml index cdc39423421..79201a5473d 100644 --- a/tardis/io/configuration/schemas/plasma.yml +++ b/tardis/io/configuration/schemas/plasma.yml @@ -80,6 +80,30 @@ 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. + 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/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..476737c4f47 100644 --- a/tardis/opacities/macro_atom/absorbing_markov_chain.py +++ b/tardis/opacities/macro_atom/absorbing_markov_chain.py @@ -1,37 +1,57 @@ -"""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 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.abc import Sequence from concurrent.futures import ThreadPoolExecutor +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 + + +class AbsorbingChainResult(NamedTuple): + """ + 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 + 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] = (), + include_thermal_pool: bool = False, + include_ionization_pool: bool = False, max_workers: int = 1, -) -> tuple[np.ndarray, pd.DataFrame]: +) -> AbsorbingChainResult: """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. + deactivation probabilities by solving the absorbing Markov chain system + for the requested block. + Eliminates internal transition inside handled blocks. Parameters ---------- @@ -44,91 +64,219 @@ def create_absorbing_probs( 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), + 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. 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, containing deactivation 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. + + 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. """ - 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 not be empty in partial mode. Specify which elements to process" + ) + 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} ) + 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() + 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": + # 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( + 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: # 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) + # 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)) + ) - # expected_steps = np.asarray( - # scipy.sparse.linalg.spsolve(csc_N, np.ones(num_states)) - # ).flatten() - # expected_steps_in_cells_from_states[cell] = expected_steps + if mode == "explicit": + return AbsorbingChainResult(matrices, residual, lookup, 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) - ) + internal_matrices = ( + sparse.coo_matrix( + ( + transition_probabilities.iloc[:, cell].to_numpy()[eliminated], + (rows, columns), + ), + shape=(len(selected), len(selected)), ) - return cell, solved_matrix - - if max_workers > 1 and num_cells > 1: - with ThreadPoolExecutor( - max_workers=min(max_workers, num_cells) - ) as executor: - cell_solutions = executor.map(solve_cell, range(num_cells)) - for cell, solved_matrix in cell_solutions: - absorbing_probability_matrix[cell] = solved_matrix - else: - for cell in range(num_cells): - _, solved_matrix = solve_cell(cell) - absorbing_probability_matrix[cell] = solved_matrix - - deactivating_probs = transition_probabilities.copy() - deactivating_probs[internal_mask] *= 0 - - return ( - absorbing_probability_matrix, - deactivating_probs, + 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 + else: + for cell, solved in enumerate( + map(solve_cell_full, internal_matrices) + ): + matrices[cell] = solved + elif mode == "partial": + exit_rates = ( + np.bincount( + sources, + 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_full( + internal_matrix: sparse.spmatrix, +) -> npt.NDArray[np.float64]: + """Solve one cell's full reduction using the legacy exit calculation. + + Parameters + ---------- + 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 + ------- + 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)) + + +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. + """ + 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)) diff --git a/tardis/opacities/macro_atom/macroatom_solver.py b/tardis/opacities/macro_atom/macroatom_solver.py index a0f513f6cd9..bc45ba2cbd0 100644 --- a/tardis/opacities/macro_atom/macroatom_solver.py +++ b/tardis/opacities/macro_atom/macroatom_solver.py @@ -816,6 +816,10 @@ 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, ...] = (), + markov_chain_include_thermal_pool: bool = False, + markov_chain_include_ionization_pool: bool = False, ) -> None: """ Initialize the ContinuumMacroAtomSolver. @@ -838,6 +842,14 @@ 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. + 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, @@ -870,6 +882,14 @@ 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) + 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, @@ -1019,6 +1039,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 +1342,23 @@ 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, + 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 + 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 +1679,23 @@ 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, + 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 + 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..dda8d2ee5cc 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,12 @@ 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 + 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 @@ -145,6 +158,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 +208,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..eb4f1f87301 --- /dev/null +++ b/tardis/opacities/macro_atom/tests/test_partial_absorbing_chain.py @@ -0,0 +1,269 @@ +"""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, 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, + "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 + ], + } + ) + # 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 + + +@pytest.mark.parametrize( + "mode,elements,include_thermal_pool,include_ionization_pool", + [ + ("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, + 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, + include_thermal_pool=include_thermal_pool, + include_ionization_pool=include_ionization_pool, + ) + 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} + 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) + 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) + + +@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/macro_atom.py b/tardis/transport/montecarlo/macro_atom.py index cf644725c1a..597c24f9023 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,98 @@ 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 + ] - for to_state_index, state_probability in enumerate( - continuum_state.absorbing_markov_probabilities[ - current_shell_id, 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 + ] + ): + if state_probability > 0: + 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 + 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 " + 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 ] - ): - 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 + probability_event = np.random.random() + cumulative_probability = 0.0 + selected_transition_idx = -1 + last_positive_idx = -1 - 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 + 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 " + 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 new file mode 100644 index 00000000000..1656f24bf76 --- /dev/null +++ b/tardis/transport/montecarlo/tests/test_partial_macro_atom.py @@ -0,0 +1,144 @@ +""" +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 +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", 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: + """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, 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), ("k", -99, -99)] + + [(1, 1, 0)] * 2 + + [(1, 1, 1), ("i", -99, -99), (2, 0, 0)], + } + ) + result = create_absorbing_probs( + pd.DataFrame([0.5, 0.5, 1.0, 0.75, 0.25, 0.5, 0.5, 1.0, 1.0, 1.0]), + metadata, + 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]) + 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, 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, 2, 0, 1, 2, 0, 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: + """Check emission outcomes when packets leave and return to reduced states. + + 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 + 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 + # 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, + pool_expected, + atol=6 * np.sqrt(0.25 / 20000), + rtol=0, + ) + assert macro_atom_interaction_iip.nopython_signatures 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 new file mode 100644 index 00000000000..3e6fd3ff6b6 --- /dev/null +++ b/tardis/workflows/tests/test_partial_chain_workflow.py @@ -0,0 +1,117 @@ +"""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,include_thermal_pool,include_ionization_pool", + [ + ("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], + include_thermal_pool: bool, + include_ionization_pool: bool, +) -> None: + """Each mode closes the same thermal equations through two transport steps. + + 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.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() + 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": + 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 5e8113bc670..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, @@ -236,6 +238,12 @@ 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 + ), + 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 @@ -1121,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 @@ -1139,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,