NebulaPy.src package
Submodules
NebulaPy.src.Chianti module
- class NebulaPy.src.Chianti.chianti(temperature, ne, chianti_ion=None, pion_ion=None, pion_elements=None, continuum=False, verbose=False)[source]
Bases:
object- get_allLineTransitions()[source]
Retrieve all spectral lines associated with a specified ion :return: wave-length array
- get_allLines()[source]
Retrieve all spectral lines associated with a specified ion :return: wave-length array
- get_bremsstrahlung_coefficients(wavelength)[source]
Calculates the free-free emission (bremsstrahlung) rate for a single ion.
Returns
- numpy.ndarray
2D array with shape (n_temperature, n_wavelength), where each row contains the bremsstrahlung emission spectrum for one temperature.
- get_chianti_symbol(species, make=False)[source]
Converts a PION species symbol to a corresponding CHIANTI species symbol.
This function takes a species symbol used in PION (a computational tool) and converts it into the format required by CHIANTI, a database for atomic data. The function can generate either the elemental symbol or the ionized symbol depending on the ‘make’ parameter.
- Parameters:
species – str, the PION species symbol, which can represent both neutral and ionized states.
make – bool, if True, returns the elemental symbol (e.g., ‘h’ for hydrogen). if False, returns the CHIANTI ion symbol (e.g., ‘h_2’ for H+).
- Returns:
str, the corresponding CHIANTI symbol for the species.
- get_elements_attributes()[source]
Generates and appends species attributes for each element in the chianti_element_list to a dictionary called species_attributes.
This function first retrieves abundance data from the chdata.Abundance dictionary using the specified abundancoe name (‘unity’). It then initializes an instance of the specTrails class to handle species-related data, setting its abundance and temperature properties.
The function calls the ionGate method on the species object to process the elements in chianti_element_list, generating species data based on the specified parameters.
The species data is then looped over, and for each element key in the sorted species.Todo dictionary: - The key is converted using util.convertName and stored in species_attributes. - The relevant data is stored in the species_attributes dictionary under
each element’s key.
Unnecessary entries like ‘filename’ and ‘experimental’ are removed from the dictionary before final storage.
- Returns:
None
- get_freebound_coefficients(wavelength, verner=True)[source]
Calculates the free-bound (radiative recombination) continuum emissivity of an ion.
- get_line_emissivity(allLines=True)[source]
Retrieve the emissivity values for all spectral lines associated with a specified ion.
- Returns:
Dict Emiss. Emiss has several quantities, namely, ion,
# wvl(angstrom), emissivity (ergs s^-1 str^-1), pretty1, pretty2.
- get_line_emissivity_for_list(line_list)[source]
Retrieves the emissivity values for a given list of spectral lines.
Parameters:
- line_listlist
A list of spectral line identifiers for which emissivity values need to be retrieved.
Returns:
- line_emissivitydict
A dictionary where keys are formatted line identifiers (e.g., “Fe XIV 530.3”) and values are the corresponding emissivity values.
NebulaPy.src.Constants module
A set of physical constants, and constants strings.
NebulaPy.src.Cooling module
- class NebulaPy.src.Cooling.cooling(pion_ion, verbose=True)[source]
Bases:
object- generate_cooling_rate_map(temperature, ne)[source]
Generates a cooling rate map for a given temperature and electron density array.
This method computes the cooling rate at each point in the input arrays for temperature and electron density by using the pre-defined interpolation function self.cooling_rate. It ensures that the input arrays for temperature and electron density are of the same shape and then generates a corresponding map of cooling rates for each combination of temperature and electron density.
- Args:
temperature (array-like): A 2D or nD array of temperature values. ne (array-like): A 2D or nD array of electron density values corresponding to the temperature array.
- Returns:
np.ndarray: A 2D or nD array of cooling rates corresponding to each temperature and electron density value.
- Raises:
ValueError: If the shapes of the temperature and electron density arrays do not match.
- get_chianti_symbol(species, make=False)[source]
Converts a PION species symbol to a corresponding CHIANTI species symbol.
This function takes a species symbol used in PION (a computational tool) and converts it into the format required by CHIANTI, a database for atomic data. The function can generate either the elemental symbol or the ionized symbol depending on the ‘make’ parameter.
- Parameters:
species – str, the PION species symbol, which can represent both neutral and ionized states.
make – bool, if True, returns the elemental symbol (e.g., ‘h’ for hydrogen). if False, returns the CHIANTI ion symbol (e.g., ‘h_2’ for H+).
- Returns:
str, the corresponding CHIANTI symbol for the species.
- setup_cooling_table()[source]
Sets up the cooling table for the ion by loading the cooling data and preparing the interpolation function for cooling rates based on electron density and temperature.
The cooling rates are interpolated from a pre-existing table of temperature and electron density values, and stored in the self.cooling_rate function for use in further calculations.
This method processes the cooling data file by removing the temperature data and performing an interpolation to get a smooth cooling rate function.
NebulaPy.src.EmissionMeasure module
NebulaPy.src.LineEmission module
- class NebulaPy.src.LineEmission.line_emission(ion, verbose=True)[source]
Bases:
object- get_species_dominant_lines(temperature, ne, species_density, cell_volume, grid_mask, Nlines: int | None = None)[source]
Computes the most luminous emission lines for a given species in a 1D or 2D dataset.
This method calculates the line luminosity for a given ionized species across multiple grid levels. It retrieves the brightest emission lines by computing the line emissivity for each cell and summing the contributions across the grid.
Parameters
- temperaturelist (1D or 2D array-like)
Temperature values of the grid cells.
- nelist (1D or 2D array-like)
Electron density values corresponding to each grid cell.
- species_densitylist (1D or 2D array-like)
Density of the given ionized species in each grid cell.
- cell_volumelist (1D or 2D array-like)
Volume of each grid cell.
- grid_masklist (1D or 2D array-like)
Mask specifying active grid cells.
- Nlinesint
The number of most luminous emission lines to retrieve.
Returns
- dict
A dictionary containing: - ‘spectroscopic’ : str, the spectroscopic name of the species. - ‘lines’ : list, the N most luminous emission line wavelengths. - ‘luminosity’ : list, the luminosity values of the brightest lines.
Notes
A small electron density tolerance (electron_tolerance = 1.E-08) is set to avoid division by zero.
The method loops over each grid level and computes line luminosities.
The most luminous lines are selected using np.argsort().
- line_luminosity_1D(lines, temperature, ne, species_density, shell_volume)[source]
Parameters
lines temperature ne ns dV
Returns
- line_luminosity_2D(lines, temperature, ne, species_density, cell_volume, grid_mask, progress_bar=True)[source]
Compute the total line luminosity for a given ion in a cylindrical coordinate system.
Parameters: - lines: List of emission lines for which luminosity is calculated. - temperature: 3D array (NGlevel x rows x columns) containing temperature values at different grid levels. - ne: 3D array (NGlevel x rows x columns) containing electron density values at different grid levels. - species_density: 3D array containing the density of the species (ion) at different grid points. - cell_volume: 3D array containing the volume of each cell in the grid. - grid_mask: 3D array (boolean or numeric) acting as a mask to include/exclude specific grid cells.
Returns: - Dictionary mapping emission lines to their computed luminosity values.
The function follows these steps: 1. Ensures that electron densities are nonzero to avoid division errors. 2. Iterates over grid levels and rows to compute line emissivity using Chianti. 3. Computes and accumulates total line luminosity across the cylindrical grid.
- recombination_line_luminosity_2D(lines, temperature, ne, species_density, cell_volume, grid_mask, progress_bar=True)[source]
Compute the total line luminosity for a given ion in a cylindrical coordinate system.
Parameters: - lines: List of emission lines for which luminosity is calculated. - temperature: 3D array (NGlevel x rows x columns) containing temperature values at different grid levels. - ne: 3D array (NGlevel x rows x columns) containing electron density values at different grid levels. - species_density: 3D array containing the density of the species (ion) at different grid points. - cell_volume: 3D array containing the volume of each cell in the grid. - grid_mask: 3D array (boolean or numeric) acting as a mask to include/exclude specific grid cells.
Returns: - Dictionary mapping emission lines to their computed luminosity values.
The function follows these steps: 1. Ensures that electron densities are nonzero to avoid division errors. 2. Iterates over grid levels and rows to compute line emissivity using Chianti. 3. Computes and accumulates total line luminosity across the cylindrical grid.
NebulaPy.src.MultiProc module
- NebulaPy.src.MultiProc.do_freebound_Q(inQ, outQ)[source]
Multiprocessing helper for ChiantiPy.core.continuum.freeBound
Parameters
- inQ~multiprocessing.Queue
Ion free-bound emission jobs queued up by multiprocessing module
- outQ~multiprocessing.Queue
Finished free-bound emission jobs
- NebulaPy.src.MultiProc.do_freefree_Q(inQ, outQ)[source]
Multiprocessing helper for ChiantiPy.core.continuum.freeFree
Parameters
- inQ~multiprocessing.Queue
Ion free-free emission jobs queued up by multiprocessing module
- outQ~multiprocessing.Queue
Finished free-free emission jobs
- NebulaPy.src.MultiProc.do_line_emission_Q(inQ, outQ)[source]
Processes line emission calculations for a given set of inputs and puts the results into an output queue.
- Args:
- input_arg (queue): A queue containing input data, where each item is a list or tuple with the following:
ion (str): The ion species to be analyzed.
temperature (float): The temperature at which the ion is found.
ne (float): The electron density.
wavelength (float or list): The wavelength(s) at which to calculate the line emission.
abundance (float): The abundance of the ion species.
ion_fraction (float): The fraction of the ion present in the species.
em (float): The emission measure.
filter_name (str): The name of the filter to apply (optional).
filter_factor (float): A factor to apply with the filter (optional).
allLines (bool): A flag to include all lines in the spectrum.
- out_arg (queue): A queue for storing the results. Each result is a dictionary with:
‘intensity’ (array): The calculated line spectrum intensity for the given inputs.
- Workflow:
Continuously retrieves input data from the input queue until it encounters a ‘STOP’ signal.
For each set of inputs, initializes a Chianti ion object and calculates the line spectrum using the provided parameters.
Places the resulting spectrum intensity into the output queue.
Stops processing when the ‘STOP’ signal is received.
NebulaPy.src.PION module
- class NebulaPy.src.PION.pion(silo_set, verbose)[source]
Bases:
objectThis class is not an alternative to Pypion; rather, it is a bundle of methods useful for creating synthetic emission maps from the Silo file.
- get_chemical_tracer_list()[source]
Retrieve the list of chemical tracer strings for each tracer in the chemistry container dictionary, processed element by element. Each sublist starts with the mass fraction of the element followed by the tracers.
- Returns:
list of lists: Each sublist contains the mass fraction followed by the values of the tracers for a specific element.
- get_chemical_tracers(silo_instant)[source]
Retrieves the chemical tracer values for the given time instant from the simulation silo data. Parameters: ———- silo_instant : silo file(s)
Returns:
- tracer_valueslist of lists
A 2D list containing the tracer values for each ion in the tracers array.
- get_grid_volumes_2D()[source]
Computes the volume of grid cells in a cylindrical coordinate system.
This function assumes a static grid with multiple refinement levels. The volume of each cylindrical shell segment is calculated using the difference in squared radii multiplied by the cell height.
- Returns:
list[np.ndarray]: A list of 2D arrays containing cell volumes in the selected unit (‘cm’ or ‘pc’).
- get_ion_number_density(ion, silo_instant, verbose=True)[source]
Calculates the number density of a given ion across different nested grid levels.
This method is currently implemented for a cylindrical 2D coordinate system. A 1D spherically symmetric case will require separate handling (TODO).
Parameters: ion (str): The identifier for the ion (e.g., ‘H+’, ‘O++’). silo_instant: The current simulation time or instant for which the calculation is performed.
Returns: list: A list of arrays containing the ion number density for each nested grid level.
- get_ion_tracer(ion)[source]
Retrieves the tracer for a specific ion from the chemistry container.
Parameters: ion (str): The key corresponding to the specific ion (e.g., ‘H+’, ‘He++’).
Returns: tracer: The value associated with the provided ion key in the chemistry container.
Raises: KeyError: If the specified ion key does not exist in the chemistry container.
- get_ion_values(ion, silo_instant, verbose=True)[source]
This methods will return the ion mass fraction value set
Parameters
ion name silo_instant
Returns
ion mass fraction
- get_ne(silo_instant, verbose=True)[source]
Return electron number density for a specific silo file.
- get_parameter(parameter, silo_instant)[source]
Method will return the parameter value for a spherical nested grid
Parameters
parameter physical silo_instant
Returns
physical parameter value for a spherical nested grid
- ion_batch_check(ion=None, ion_list=None, top_ion_check=False, terminate=False)[source]
This method checks if the given ion(s) are valid according to the chemistry model and optional top-level ion conditions. It allows for checking a single ion or a list of ions, and can either raise an exception or print warnings when ions are invalid.
Parameters: ion (str): The ion to check (e.g., ‘O+2’, ‘H+1’). If provided, only this single ion will be checked. ion_list (list): A list of ions to check (e.g., [‘O+2’, ‘H+1’]). If provided, each ion in the list will be checked. top_ion_check (bool): If True, checks if the ion is a top-level ion using the top_ion_check method. Defaults to False. terminate (bool): If True and the ion is not found, an exception will be raised. If False, a warning is logged instead. Defaults to False.
Returns: list: A list of valid ions that passed the check.
- load_chemistry()[source]
This method extracts information related to the chemistry and chemical tracers, transforming the chemical tracer names to a format that PyPion can directly read from the Silo file. This method can be included in the next version of PyPion.
Parameters
instant_silo_set : The instance for which chemical data is to be extracted
Returns
Generates and stores the following in self.chemistry_container: - ‘dynamics’: Dynamics data retrieved from the Silo file - ‘chemistry’: Chemistry flag indicating if chemistry data is available - ‘E_update’: Energy update information (if chemistry flag is true) - ‘chemistry_code’: The code indicating the type of chemistry (if chemistry flag is true) - ‘microphysics’: List of microphysics processes (if chemistry flag is true) - ‘Ntracers’: Number of chemical tracers - ‘mpv10_elements’: List of elements identified for MPv10 chemistry code - ‘mpv10_tracers’: List of tracers corresponding to each element for MPv10 chemistry code
NebulaPy.src.PyNeb module
- class NebulaPy.src.PyNeb.pyneb(temperature, ne, pion_ion=None, verbose=False)[source]
Bases:
object- get_allLines()[source]
Retrieve all available H I recombination line wavelengths from PyNeb.
This method calculates the emissivities for a dummy electron temperature and density to access all transitions available in PyNeb’s recombination data. It then extracts the wavelengths for transitions up to a maximum principal quantum number (n_max = 40) and filters out invalid entries (wavelength = 0).
Steps: 1. Use a dummy temperature (1e4 K) and electron density (1e3 cm^-3)
to generate emissivities for all H I transitions.
Loop over all transitions, splitting the labels into upper and lower levels.
Skip transitions above the maximum level (n_max = 40).
Retrieve the wavelength for each valid transition using PyNeb.
Filter out any zero wavelengths.
Return a sorted list of all valid wavelengths.
- Returns:
list of float: Sorted wavelengths of all available H I recombination lines.
- get_pyneb_symbol(species)[source]
Parse a species string (e.g., ‘H1’, ‘He2+’, ‘o3’) into PyNeb convention.
- Args:
species (str): Input atomic/ionic species.
- Returns:
- tuple: (Element, Spectral Level, Ionization Level)
Element: str, e.g. ‘O’
Spectral Level: int, PyNeb stage (e.g. 3 for ‘O3’)
Ionization Level: int, electrons removed (Spectral Level - 1)
- get_recomb_line_emissivity_for_list(line_list)[source]
Retrieve recombination line emissivities for a given list of spectral lines.
Parameters
- line_listlist of float
Wavelengths of the spectral lines for which emissivities are requested.
Returns
- dict
Dictionary where keys are “SpectroscopicName Wavelength” strings and values are the corresponding emissivity values (erg s^-1 sr^-1).
NebulaPy.src.SED module
- class NebulaPy.src.SED.sed(energy_bins, plot=None, pion=None, verbose=False)[source]
Bases:
object- PotsdamWolfRayet(metallicity, composition, mdot)[source]
- Parameters:
metallicity
composition
mdot
- Returns:
- bundle_up_atlas_models(metallicity)[source]
TODO: no completed 1.get the model and return it 2.if the parameter are wrong return some advice
- Parameters:
metallicity
gravity
- Returns:
- bundle_up_potsdam_models(metallicity, composition, mdot)[source]
- Parameters:
metallicity
composition
mdot
- Returns:
- plotter(plot_path, binned_flux_set, min_plot_energy, max_plot_energy)[source]
- Parameters:
PlotDir
- Returns:
None
NebulaPy.src.Spectrum module
- NebulaPy.src.Spectrum.compute_row_spectrum(workerQ, doneQ, spectrum_obj, timeout)[source]
Worker function to compute spectra for each grid row.
- class NebulaPy.src.Spectrum.spectrum(min_wavelength=None, max_wavelength=None, min_photon_energy=None, max_photon_energy=None, doBremsstrahlung=False, doFreebound=False, doLine=False, doTwophoton=False, elements=None, filtername=None, filterfactor=None, allLines=True, userGrid=False, MPNcores=4, gridSize=1000, verbose=True)[source]
Bases:
object
NebulaPy.src.Utils module
- NebulaPy.src.Utils.batch_silos(dir, filebase, start_time=None, finish_time=None, time_unit=None, out_frequency=None)[source]
Organizes silo files into groups based on their corresponding time instants. This function scans a specified directory for silo files with a given base name, and if the simulation involves multiple grid levels, it groups the files by time instant. For each time instant, it creates a sublist containing silo files from different grid levels.
The function allows running from a particular start time to a finish time, enabling users to process specific intervals of simulation data. Additionally, one can restart the processing by adjusting the start time, making it flexible for iterative analysis or simulations.
- Parameters:
dir – Directory path where the silo files are located.
filebase – Base name of the silo files to search for.
start_time – The start time for processing, in the given time_unit.
finish_time – The finish time for processing, in the given time_unit.
time_unit – The time unit for start_time and finish_time (‘sec’, ‘yr’, or ‘kyr’).
- Returns:
A list of lists, where each sublist contains silo files for a specific time instant, with each file in the sublist representing a different grid level.
- Raises:
RuntimeError if no silo files are found or if expected files for certain levels are missing.
- NebulaPy.src.Utils.getPionSymbol(chianti_symbol)[source]
Convert a CHIANTI ion symbol to the corresponding PION symbol. Examples ——– h_1 -> H h_2 -> H1+ he_1 -> He he_2 -> He1+ he_3 -> He2+ fe_26 -> Fe25+
- NebulaPy.src.Utils.get_element_symbol(ion)[source]
Extracts the element symbol from an ion identifier by filtering out non-alphabetic characters.
Parameters: ion (str): The ion identifier, which may include both alphabetic and non-alphabetic characters
(e.g., ‘He1+’, ‘O2+’, ‘C5+’).
Returns: str: The element symbol extracted from the ion identifier (e.g., ‘He’ from ‘He1+’, ‘O’ from ‘O2+’).
- NebulaPy.src.Utils.get_spectroscopic_symbol(ion)[source]
Convert an ion string like ‘H1+’ or ‘Fe26+’ into its spectroscopic notation.
Spectroscopic notation uses Roman numerals to indicate the ionisation state: - ‘I’ = neutral atom - ‘II’ = singly ionised (one electron removed) - ‘III’ = doubly ionised (two electrons removed) - and so on.
For example: - ‘H1+’ -> ‘H II’ - ‘He2+’ -> ‘He III’ - ‘Fe26+’ -> ‘Fe XXVII’
Parameters:
- ionstr
Ion string in the form ‘ElementZ+’ where Z is the charge state (e.g., ‘26+’ for Fe26+).
Returns:
- str
Spectroscopic notation: ‘Element RomanNumeral’
Raises:
- ValueError:
If the ionisation level exceeds the supported range.
- NebulaPy.src.Utils.nebula_computing_comment(comment)[source]
Custom computing status display function. :param comment: Optional status message.
- NebulaPy.src.Utils.nebula_done_comment(comment)[source]
Custom completion status display function. :param comment: Optional status message.
- NebulaPy.src.Utils.nebula_exit_with_error(errorMessage)[source]
Custom exit function display error before exiting. :param message: Optional exit message.
- NebulaPy.src.Utils.nebula_info(infoMessage)[source]
Custom info display function. :param message: Optional info message.
- NebulaPy.src.Utils.nebula_version()[source]
return NebulaPy version :param message: Optional exit message.
- NebulaPy.src.Utils.nebula_warning(warnMessage)[source]
Custom warning function. :param message: Optional warn message.
- NebulaPy.src.Utils.progress_bar(step, Nstep, prefix='', suffix='', condition=False, completion_msg='')[source]
Displays a progress bar in the terminal.
Args: - step (int): Current step (0-indexed). Represents the current progress point. - Nstep (int): Total number of steps. Defines the total length of the process. - prefix (str): Optional prefix text for the progress bar. Allows user to add custom text at the start. - suffix (str): Optional suffix text for the progress bar. Allows user to add custom text at the end. - condition (bool): A flag to indicate whether the completion message should be shown once the progress reaches 100%. If True, the completion_msg is displayed at the end. - completion_msg (str): Message to display upon completion. This message appears when the progress reaches 100%.
Module contents
src - contains the main classes for NebulaPy.