tardis.transport.montecarlo.packet_source package

Submodules

Module contents

Packet source subpackage for TARDIS Monte Carlo transport.

This subpackage contains classes for generating packets with different physical properties and distributions for Monte Carlo radiative transfer simulations.

class tardis.transport.montecarlo.packet_source.BasePacketSource(base_seed: int | None = None, legacy_mode_enabled: bool = False, legacy_second_seed: int | None = None)[source]

Bases: ABC

Abstract base packet source.

This abstract base class defines the interface for packet sources used in TARDIS Monte Carlo radiative transfer. Packet sources are responsible for creating radiation packets with specific properties.

Parameters:
base_seedint, optional

Base seed for random number generator. Default is None.

legacy_mode_enabledbool, optional

Whether to enable legacy mode for compatibility. Default is False.

legacy_second_seedint, optional

Secondary seed for global numpy rng (Deprecated: Legacy reasons only). Default is None.

Attributes:
MAX_SEED_VALint

Maximum seed value allowed by numpy (2**32 - 1).

base_seedint or None

Base seed for random number generator.

legacy_mode_enabledbool

Whether legacy mode is enabled.

rngnumpy.random.Generator

Random number generator instance.

MAX_SEED_VAL: int = 4294967295
calculate_radfield_luminosity() Quantity[source]

Calculate inner luminosity from blackbody radiation.

Uses the Stefan-Boltzmann law to calculate the luminosity from the inner boundary radius and temperature.

Returns:
astropy.units.Quantity

Inner luminosity in erg/s.

abstractmethod create_packet_energies(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet energies.

Parameters:
no_of_packetsint

Number of packets to create.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
array-like

Packet energy values.

abstractmethod create_packet_mus(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet direction cosines.

Parameters:
no_of_packetsint

Number of packets to create.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
array-like

Packet direction cosine values.

abstractmethod create_packet_nus(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet frequencies.

Parameters:
no_of_packetsint

Number of packets to create.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
array-like

Packet frequency values.

create_packet_radii(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet radii.

This method should be implemented by subclasses that create packets with specific radii. Either this method or create_packet_velocities should be implemented.

Parameters:
no_of_packetsint

Number of packets to create.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
array-like

Packet radii values.

Raises:
NotImplementedError

If the method is not implemented by the subclass.

create_packet_velocities(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet velocities.

This method should be implemented by subclasses that create packets with specific velocities. Either this method or create_packet_radii should be implemented.

Parameters:
no_of_packetsint

Number of packets to create.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
array-like

Packet velocity values.

Raises:
NotImplementedError

If the method is not implemented by the subclass.

create_packets(no_of_packets: int, seed_offset: int = 0, *args: Any, **kwargs: Any) PacketCollection[source]

Generate packet properties as arrays.

Parameters:
no_of_packetsint

Number of packets to create.

seed_offsetint, optional

Offset added to the base seed for randomness across iterations. Default is 0.

*args

Additional positional arguments passed to packet creation methods.

**kwargs

Additional keyword arguments passed to packet creation methods.

Returns:
PacketCollection

Collection containing packet radii, frequencies, directions, energies, seeds, and radiation field luminosity.

class tardis.transport.montecarlo.packet_source.BlackBodySimpleSource(*args: Any, **kwargs: Any)[source]

Bases: BasePacketSource, HDFWriterMixin

Simple packet source that generates blackbody packets for Monte Carlo simulations.

This class creates packets with properties derived from blackbody radiation, including appropriate frequency distribution, uniform radii, and cosine-weighted direction distribution.

Parameters:
radiusastropy.units.Quantity, optional

Initial packet radius. Default is None.

temperatureastropy.units.Quantity, optional

Blackbody temperature. Default is None.

**kwargs

Additional keyword arguments passed to the parent class.

Attributes:
radiusastropy.units.Quantity

Initial packet radius.

temperatureastropy.units.Quantity

Blackbody temperature.

Initialize BlackBodySimpleSource.

Parameters:
radiusastropy.units.Quantity, optional

Initial packet radius. Default is None.

temperatureastropy.units.Quantity, optional

Absolute temperature. Default is None.

**kwargsAny

Additional keyword arguments passed to parent class.

create_packet_energies(no_of_packets: int) Quantity[source]

Create packet energies with uniform distribution.

Uniformly distribute energy in arbitrary units where the ensemble of packets has total energy of 1 erg.

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
astropy.units.Quantity

Array of packet energies in erg.

create_packet_mus(no_of_packets: int) ndarray[source]

Create zero-limb-darkening packet direction cosines.

Direction cosines are distributed according to \(\mu=\sqrt{z}\), where \(z \in [0, 1]\) is uniformly distributed.

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
numpy.ndarray

Array of direction cosines for packets.

create_packet_nus(no_of_packets: int, l_samples: int = 1000) Quantity[source]

Create packet \(\nu\) distributed using the algorithm described in Bjorkman & Wood 2001 (page 4) which references Carter & Cashwell 1975: First, generate a uniform random number, \(\xi_0 \in [0, 1]\) and determine the minimum value of \(l, l_{\rm min}\), that satisfies the condition .. math:

\sum_{i=1}^{l} i^{-4} \ge {{\pi^4}\over{90}} m_0 \;.

Next obtain four additional uniform random numbers (in the range 0 to 1) \(\xi_1, \xi_2, \xi_3, {\rm and } \xi_4\). Finally, the packet frequency is given by .. math:

x = -\ln{(\xi_1\xi_2\xi_3\xi_4)}/l_{\rm min}\;.

where \(x=h\nu/kT\)

Parameters:
no_of_packetsint
l_samplesint

number of l_samples needed in the algorithm

Returns:
array of frequencies

numpy.ndarray

create_packet_radii(no_of_packets: int) Quantity[source]

Create packet radii.

All packets are created at the same radius (inner boundary).

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
astropy.units.Quantity

Array of packet radii in CGS units.

create_packets(no_of_packets: int, *args: Any, **kwargs: Any) PacketCollection[source]

Create packet collection.

Parameters:
no_of_packetsint

Number of packets to create.

*argsAny

Additional positional arguments.

**kwargsAny

Additional keyword arguments.

Returns:
PacketCollection

Collection of packets.

Raises:
ValueError

If radius or temperature is not set.

classmethod from_simulation_state(simulation_state, *args: Any, **kwargs: Any) BlackBodySimpleSource[source]

Create BlackBodySimpleSource from simulation state.

Parameters:
simulation_stateSimulationState

The simulation state object containing inner radius and temperature.

*args

Additional positional arguments.

**kwargs

Additional keyword arguments.

Returns:
BlackBodySimpleSource

New instance initialized with simulation state parameters.

hdf_name = 'black_body_simple_source'
hdf_properties = ['radius', 'temperature', 'base_seed']
set_temperature_from_luminosity(luminosity: Quantity) None[source]

Set blackbody packet source temperature from luminosity.

Uses the Stefan-Boltzmann law to derive temperature from the given luminosity and the source radius.

Parameters:
luminosityastropy.units.Quantity

Total luminosity to match.

class tardis.transport.montecarlo.packet_source.BlackBodySimpleSourceRelativistic(*args: Any, **kwargs: Any)[source]

Bases: BlackBodySimpleSource, HDFWriterMixin

Relativistic blackbody packet source for Monte Carlo simulations.

This class generates blackbody packets with relativistic corrections for sources that are moving with respect to the lab frame. It accounts for the motion of the inner boundary where packets are created.

Parameters:
time_explosionastropy.units.Quantity

Time elapsed since explosion.

radiusastropy.units.Quantity

Initial packet radius.

temperatureastropy.units.Quantity

Absolute temperature.

base_seedint, optional

Base seed for random number generator.

legacy_secondary_seedint, optional

Secondary seed for global numpy rng (Deprecated: Legacy reasons only).

Attributes:
time_explosionastropy.units.Quantity

Time elapsed since explosion.

betafloat

Velocity of the inner boundary as a fraction of speed of light.

Initialize BlackBodySimpleSourceRelativistic.

Parameters:
time_explosionastropy.units.Quantity, optional

Time elapsed since explosion. Default is None.

**kwargsAny

Additional keyword arguments passed to parent class.

create_packet_energies(no_of_packets: int) Quantity[source]

Create relativistic packet energies with uniform distribution.

Uniformly distribute energy in arbitrary units where the ensemble of packets has total energy corrected for relativistic effects. Applies corrections for the static inner boundary to comoving frame transformation and time dilation.

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
astropy.units.Quantity

Array of packet energies in erg with relativistic corrections.

create_packet_mus(no_of_packets: int) ndarray[source]

Create relativistic packet direction cosines.

Direction cosines are distributed according to the relativistic transformation \(\mu^\prime=2 \frac{\mu^\prime + \beta}{2 \beta + 1}\). The distribution accounts for the fact that the inner boundary on which the packets are initialized is not comoving with the material.

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
numpy.ndarray

Array of relativistically corrected direction cosines for packets.

create_packets(no_of_packets: int, *args: Any, **kwargs: Any) PacketCollection[source]

Generate relativistic black-body packet properties as arrays.

Calculates the velocity (beta) of the inner boundary and applies relativistic corrections to packet creation.

Parameters:
no_of_packetsint

Number of packets to create.

*argsAny

Additional positional arguments.

**kwargsAny

Additional keyword arguments.

Returns:
PacketCollection

Collection of packets with relativistic corrections applied.

Raises:
ValueError

If radius or time_explosion is not set.

classmethod from_simulation_state(simulation_state, *args: Any, **kwargs: Any) BlackBodySimpleSourceRelativistic[source]

Create BlackBodySimpleSourceRelativistic from simulation state.

Parameters:
simulation_stateSimulationState

The simulation state object containing explosion time, inner radius, and temperature.

*argsAny

Additional positional arguments.

**kwargsAny

Additional keyword arguments.

Returns:
BlackBodySimpleSourceRelativistic

New instance initialized with simulation state parameters.

hdf_properties = ['time_explosion', 'radius', 'temperature', 'base_seed']
class tardis.transport.montecarlo.packet_source.BlackBodyWeightedSource(*args: Any, **kwargs: Any)[source]

Bases: BlackBodySimpleSource

Weighted blackbody packet source for Monte Carlo simulations.

This class generates blackbody packets with energies weighted according to their contribution to the Planck distribution, rather than uniform energy distribution.

Parameters:
radiusastropy.units.Quantity, optional

Initial packet radius. Default is None.

temperatureastropy.units.Quantity, optional

Absolute temperature. Default is None.

base_seedint, optional

Base seed for random number generator. Default is None.

legacy_secondary_seedint, optional

Secondary seed for global numpy rng (Deprecated: Legacy reasons only). Default is None.

**kwargsAny

Additional keyword arguments passed to parent class.

Attributes:
nusastropy.units.Quantity

Cached packet frequencies for energy weighting.

Initialize BlackBodyWeightedSource.

Parameters:
**kwargs

Additional keyword arguments passed to parent class.

create_packet_energies(no_of_packets)[source]

Create packet energies weighted by Planck distribution.

Set energy weight for each packet from the relative contribution to the Planck distribution, rather than uniform distribution.

Parameters:
no_of_packetsint

Number of packets to create.

Returns:
astropy.units.Quantity

Array of weighted packet energies in erg.

create_packet_nus(no_of_packets, l_samples=1000)[source]

Create packet frequencies distributed uniformly over blackbody bounds.

Creates frequencies uniformly distributed over the range of frequencies that would be generated by the base BlackBodySimpleSource distribution.

Parameters:
no_of_packetsint

Number of packets to create.

l_samplesint, optional

Number of l_samples needed for sampling from BlackBodySimpleSource. Default is 1000.

Returns:
astropy.units.Quantity

Array of packet frequencies.

hdf_name = 'black_body_weighted_source'
hdf_properties = ['radius', 'temperature', 'base_seed']
class tardis.transport.montecarlo.packet_source.GammaRayPacketSource(cumulative_decays_df: DataFrame, isotope_decay_df: DataFrame, positronium_fraction: float, inner_velocities: ndarray, outer_velocities: ndarray, times: ndarray, effective_times: ndarray, **kwargs)[source]

Bases: BasePacketSource

Initialize gamma ray packet source.

Initializes a gamma ray packet source for creating gamma ray packets from radioactive decay data, including support for positronium formation.

Parameters:
cumulative_decays_dfpd.DataFrame

DataFrame containing cumulative decay data with columns including radiation type, decay energies, and multi-level indices for isotope, shell_number, and time_index.

isotope_decay_dfpd.DataFrame

DataFrame containing isotope decay data with decay constants and other isotope-specific parameters.

positronium_fractionfloat

Fraction of positrons that form positronium (0.0 to 1.0). Used for modeling three-photon decay vs two-photon annihilation.

inner_velocitiesnp.ndarray

Array of inner shell velocities [cm/s] for each spatial shell.

outer_velocitiesnp.ndarray

Array of outer shell velocities [cm/s] for each spatial shell.

timesnp.ndarray

Array of time steps [s] used in the simulation.

effective_timesnp.ndarray

Array of effective time steps [s] accounting for simulation specifics.

**kwargs

Additional keyword arguments passed to the parent BasePacketSource class.

Notes

This packet source generates gamma ray packets from radioactive decay events, with proper handling of: - Spatial distribution within shells - Time-dependent decay processes - Positronium formation and decay modes - Doppler effects from moving material

create_packet_directions(no_of_packets: int, seed: int | None) ndarray[source]

Create random isotropic directions for packets.

Generates an array of random unit vectors representing isotropic directions for gamma ray packets.

Parameters:
no_of_packetsint

Number of packets to generate directions for.

seedint or None

Random seed for reproducible direction generation. If None, uses current random state.

Returns:
np.ndarray

Array of shape (3, no_of_packets) containing unit direction vectors. Each column represents a 3D unit vector [x, y, z].

Notes

Directions are sampled uniformly on the unit sphere to ensure isotropic distribution in 3D space.

create_packet_energies(no_of_packets: int, energy: float) ndarray[source]

Create uniform packet energies for gamma ray packets.

Generates an array of identical packet energies for a specified number of packets.

Parameters:
no_of_packetsint

Number of packets to create energies for.

energyfloat

Energy value [erg] to assign to each packet.

Returns:
np.ndarray

Array of packet energies [erg] with length no_of_packets, where each element equals the input energy value.

Notes

This method creates uniform energy packets, where each packet carries the same energy regardless of the specific gamma ray line that created it. The total energy is conserved through the packet weighting system.

create_packet_mus(no_of_packets: int, *args: Any, **kwargs: Any)[source]

Create packet directional cosines.

Creates packet directional cosines by calling the parent class method. This method is inherited from BasePacketSource.

Parameters:
no_of_packetsint

Number of packets for which to create directional cosines.

*args

Variable length argument list passed to parent method.

**kwargs

Arbitrary keyword arguments passed to parent method.

Returns:
The return value from the parent class create_packet_mus method.
create_packet_nus(packets: DataFrame, positronium_fraction: float, number_of_packets: int) ndarray[source]

Create packet frequency-energies accounting for positronium formation.

Generates an array of packet frequency-energies (E = h * nu) considering positronium formation and its decay modes for positron annihilation lines.

Parameters:
packetspd.DataFrame

DataFrame containing packet information with ‘radiation_energy_keV’ column.

positronium_fractionfloat

Fraction of positrons that form positronium (0.0 to 1.0). Default is 0.0 for no positronium formation.

number_of_packetsint

Number of packets to generate frequency-energies for.

Returns:
np.ndarray

Array of sampled frequency-energies [keV] with length number_of_packets.

Notes

For positron annihilation lines (511 keV), this method: - Determines if positronium forms based on positronium_fraction - For ortho-positronium: samples from 3-photon decay spectrum - For para-positronium: uses the 511 keV line energy - For direct annihilation: uses the original 511 keV energy

The para/ortho ratio is set by PARA_TO_ORTHO_RATIO constant (0.25).

create_packet_times_uniform_energy(no_of_packets: ndarray, isotopes: Series, decay_time: ndarray) ndarray[source]

Sample decay times from isotope mean lifetimes using rejection sampling.

Generates decay times by sampling from exponential distributions based on isotope mean lifetimes, constrained to specific time intervals.

Parameters:
no_of_packetsnp.ndarray

Array indices for the packets (used for iteration).

isotopespd.Series

Series containing parent isotope names for each packet.

decay_timenp.ndarray

Array of time step indices indicating the time interval for each packet’s decay.

Returns:
np.ndarray

Array of decay times [s] sampled from exponential distributions constrained to the appropriate time intervals.

Notes

This method uses rejection sampling to ensure decay times fall within the correct time bins. For each packet: 1. Determines the time interval [t_min, t_max] from decay_time index 2. Samples from exponential distribution: t = -tau * ln(random) 3. Rejects and resamples if t is outside the interval

Requires self.taus attribute containing isotope mean lifetimes.

create_packet_times_uniform_time(no_of_packets: int, start: float, end: float) ndarray[source]

Sample packet decay times uniformly within a time interval.

Generates decay times uniformly distributed between start and end times. This approach requires non-uniform packet energies to maintain energy conservation.

Parameters:
no_of_packetsint

Number of packets to generate decay times for.

startfloat

Start time [s] of the sampling interval.

endfloat

End time [s] of the sampling interval.

Returns:
np.ndarray

Array of decay times [s] with length no_of_packets, uniformly distributed between start and end.

Notes

This method samples decay times uniformly in time, which means the packet energies must be weighted according to the decay rate at each time to properly represent the physical decay process.

create_packet_velocities(sampled_packets_df: DataFrame) ndarray[source]

Initialize random radial velocities for packets within shells.

Generates random initial velocities for packets distributed within spherical shells using a uniform distribution in volume.

Parameters:
sampled_packets_dfpd.DataFrame

DataFrame where each row represents a packet, containing ‘inner_velocity’ and ‘outer_velocity’ columns for shell boundaries.

Returns:
np.ndarray

Array of initial velocities [cm/s] with length equal to the number of packets in sampled_packets_df.

Notes

Uses the cube root method to ensure uniform distribution in volume: r^3 = z * r_inner^3 + (1-z) * r_outer^3, where z is uniform random [0,1].

create_packets(cumulative_decays_df: DataFrame, number_of_packets: int, legacy_energy_per_packet: float | None = None) GXPacketCollection[source]

Initialize a collection of gamma ray packets for simulation.

Creates a collection of gamma ray packets from radioactive decay data, including proper spatial distribution, directional sampling, energy assignment, and Doppler corrections.

Parameters:
cumulative_decays_dfpd.DataFrame

DataFrame containing cumulative decay data with columns including ‘radiation’, ‘decay_energy_erg’, and multi-level index with ‘isotope’, ‘shell_number’, and ‘time_index’.

number_of_packetsint

Total number of gamma ray packets to create for the simulation.

legacy_energy_per_packetfloat, optional

Legacy energy per packet [erg] for backwards compatibility. If None, energy per packet is calculated from total gamma ray energy divided by number of packets. Default is None.

Returns:
GXPacketCollection

Collection of gamma ray packets with initialized properties: - locations: 3D positions in the simulation domain - directions: isotropic unit direction vectors - energies: rest frame and comoving frame energies - frequencies: rest frame and comoving frame frequencies - metadata: shell numbers, decay times, source isotopes

Notes

The packet creation process includes:

  1. Energy calculation: Total gamma ray energy is divided equally among packets (uniform energy approach)

  2. Spatial sampling: Packets are distributed within shells based on decay energy weighting

  3. Temporal placement: Packets are positioned at decay times with appropriate radial expansion

  4. Spectral sampling: Frequencies include positronium formation effects for 511 keV annihilation lines

  5. Doppler corrections: Applied for relativistic motion between rest and comoving frames

The method ensures energy conservation while providing proper statistical sampling of the decay process.