"""A module containing generic component functionality.
This module contains the abstract base class for all components in the
synthesizer. It defines the basic structure of a component and the methods
that all components should have.
StellarComponents and BlackHoleComponents are children of this class and
contain the specific functionality for stellar and black hole components
respectively.
"""
from abc import ABC, abstractmethod
from unyt import arcsecond, kpc, pc
from synthesizer import exceptions
from synthesizer.cosmology import (
get_angular_diameter_distance,
get_luminosity_distance,
)
from synthesizer.emission_models.utils import check_removed_overrides
from synthesizer.emissions import plot_observed_spectra, plot_spectra
from synthesizer.emissions.utils import alias_to_line_id
from synthesizer.imaging.data_cube_generators import (
_combine_spectral_cubes,
_prepare_component_data_cube_labels,
)
from synthesizer.imaging.image_generators import (
_combine_image_collections,
_prepare_component_image_labels,
)
from synthesizer.imaging.postprocess import (
_postprocess_existing_data_cubes,
_postprocess_existing_images,
_postprocess_existing_line_maps,
)
from synthesizer.synth_warnings import deprecated
from synthesizer.units import unit_is_compatible
from synthesizer.utils.ascii_table import TableFormatter
[docs]
class Component(ABC):
"""The parent class for all components in the synthesizer.
This class contains the basic structure of a component and the methods
that all components should have.
Attributes:
component_type (str):
The type of component, either "Stars" or "BlackHole".
spectra (dict):
A dictionary to hold the stellar spectra.
lines (dict):
A dictionary to hold the stellar emission lines.
photo_lnu (dict):
A dictionary to hold the stellar photometry in luminosity units.
photo_fnu (dict):
A dictionary to hold the stellar photometry in flux units.
images_lnu (dict):
A dictionary to hold the images in luminosity units.
images_fnu (dict):
A dictionary to hold the images in flux units
fesc (float):
The escape fraction of the component.
model_param_cache (dict):
A cache for parameters calculated by emission models.
"""
def __init__(
self,
component_type,
fesc,
**kwargs,
):
"""Initialise the Component.
Args:
component_type (str):
The type of component, either "Stars" or "BlackHole".
fesc (float):
The escape fraction of the component.
**kwargs (dict):
Any additional keyword arguments to attach to the Component.
"""
# Attach the component type and name to the object
self.component_type = component_type
# Define the spectra dictionary to hold the stellar spectra
self.spectra = {}
# Define the line dictionary to hold the stellar emission lines
self.lines = {}
# Define the photometry dictionaries to hold the stellar photometry
self.photo_lnu = {}
self.photo_fnu = {}
# Define the dictionaries to hold the images (we carry 3 different
# dictionaries for both lnu and fnu images to draw a distinction
# between images with and without a PSF and/or noise)
self.images_lnu = {}
self.images_fnu = {}
self.images_psf_lnu = {}
self.images_psf_fnu = {}
self.images_noise_lnu = {}
self.images_noise_fnu = {}
# Define the dictionaries to hold the emission line maps (same
# structure as the photometric images above, but keyed by line id
# rather than filter code)
self.line_maps_lnu = {}
self.line_maps_fnu = {}
self.line_maps_psf_lnu = {}
self.line_maps_psf_fnu = {}
self.line_maps_noise_lnu = {}
self.line_maps_noise_fnu = {}
# Define the dictionaries to hold instrument specific spectroscopy
# (rest frame in the lnu dictionaries, observer frame in the fnu)
self.spectroscopy_lnu = {}
self.spectroscopy_fnu = {}
self.particle_spectroscopy_lnu = {}
self.particle_spectroscopy_fnu = {}
self.data_cubes_lnu = {}
self.data_cubes_fnu = {}
# Attach a default escape fraction
self.fesc = fesc if fesc is not None else 0.0
# Set any of the extra attribute provided as kwargs and, if this
# instance also inherits from Particles, record the names so that
# methods like spatially_resample can discover them later.
for key, val in kwargs.items():
setattr(self, key, val)
if hasattr(self, "_register_custom_attrs"):
self._register_custom_attrs(**kwargs)
# A container for any grid weights we already computed
self._grid_weights = {"cic": {}, "ngp": {}}
# A container for caching parameters calculated by emission models
self.model_param_cache = {}
[docs]
@abstractmethod
def get_mask(
self,
attr,
thresh,
op,
mask=None,
attr_override_obj=None,
):
"""Return a mask based on the attribute and threshold.
Will derive a mask of the form attr op thresh, e.g. age > 10 Myr.
Overloading functions should use
synthesizer.emission_models.utils.get_param instead of getattr to
allow for attribute overrides, e.g.:
from synthesizer.emission_models.utils import get_param
attr_values = get_param(
attr,
override_obj,
None,
self
)
# then use attr_values to derive the mask
Args:
attr (str):
The attribute to derive the mask from.
thresh (float):
The threshold value.
op (str):
The operation to apply. Can be '<', '>', '<=', '>=', "==",
or "!=".
mask (np.ndarray):
Optionally, a mask to combine with the new mask.
attr_override_obj (object):
An alternative object to check from the attribute. This
is specifically used when an EmissionModel may have a
fixed parameter override, but can be used more generally.
Returns:
mask (np.ndarray):
The mask array.
"""
pass
[docs]
@abstractmethod
def get_weighted_attr(self, attr, weights, **kwargs):
"""Return the weighted attribute."""
pass
@property
def is_parametric(self):
"""Return whether the component is parametric.
Returns:
bool
Whether the component is parametric.
"""
# Import here to avoid circular imports
from synthesizer.parametric import BlackHole as ParametricBlackHole
from synthesizer.parametric import Stars as ParametricStars
return isinstance(self, (ParametricStars, ParametricBlackHole))
@property
def is_particle(self):
"""Return whether the component is particle based.
Returns:
bool
Whether the component is particle based.
"""
return not self.is_parametric
[docs]
def get_luminosity_distance(self, cosmo):
"""Get the luminosity distance of the component.
This requires the redshift to be set on the component.
This will use the astropy cosmology module to calculate the
luminosity distance. If the redshift is 0, the distance will be set to
10 pc to avoid any issues with 0s.
Args:
cosmo (astropy.cosmology):
The cosmology to use for the calculation.
Returns:
unyt_quantity:
The luminosity distance of the component in kpc.
"""
# If we don't have a redshift then we can't calculate the
# luminosity distance
if not hasattr(self, "redshift"):
raise exceptions.InconsistentArguments(
"The component does not have a redshift set."
)
# Check redshift is set
if self.redshift is None:
raise exceptions.InconsistentArguments(
"The component must have a redshift set to calculate the "
"luminosity distance."
)
# At redshift > 0 we can calculate the luminosity distance explicitly
if self.redshift > 0:
return get_luminosity_distance(cosmo, self.redshift).to("kpc")
# At redshift 0 just place the component at 10 pc to
# avoid any issues with 0s
return (10 * pc).to(kpc)
[docs]
def get_angular_diameter_distance(self, cosmo):
"""Get the angular diameter distance of the component.
This requires the redshift to be set on the component.
This will use the astropy cosmology module to calculate the
angular diameter distance. If the redshift is 0, the distance will be
set to 10 pc to avoid any issues with 0s.
Args:
cosmo (astropy.cosmology):
The cosmology to use for the calculation.
Returns:
unyt_quantity:
The angular diameter distance of the component in kpc.
"""
# If we don't have a redshift then we can't calculate the
# angular diameter distance
if not hasattr(self, "redshift"):
raise exceptions.InconsistentArguments(
"The component does not have a redshift set."
)
# Check redshift is set
if self.redshift is None:
raise exceptions.InconsistentArguments(
"The component must have a redshift set to calculate the "
"angular diameter distance."
)
# At redshift > 0 we can calculate the angular diameter distance
# explicitly
if self.redshift > 0:
return get_angular_diameter_distance(
cosmo,
self.redshift,
).to("kpc")
# At redshift 0 just place the component at 10 pc to
# avoid any issues with 0s
return (10 * pc).to(kpc)
[docs]
def get_photo_lnu(
self,
filters,
verbose=True,
nthreads=1,
limit_to=None,
out_dtype=None,
):
"""Calculate luminosity photometry using a FilterCollection object.
Args:
filters (filters.FilterCollection):
A FilterCollection object.
verbose (bool):
Are we talking?
nthreads (int):
The number of threads to use for the integration. If -1, all
threads will be used.
limit_to (str/list, optional):
If None, then photometry is calculated for all spectra in the
galaxy. If a string or list of strings is provided, then
photometry is only calculated for the specified spectra.
out_dtype (np.dtype):
Requested floating-point dtype for the returned photometry.
Returns:
photo_lnu (dict):
A dictionary of rest frame broadband luminosities.
"""
# Get the labels
labels = self.spectra.keys() if limit_to is None else limit_to
# Loop over spectra in the component
for label in labels:
# Create the photometry collection and store it in the object
self.photo_lnu[label] = self.spectra[label].get_photo_lnu(
filters,
verbose,
nthreads=nthreads,
out_dtype=out_dtype,
)
return self.photo_lnu
[docs]
def get_photo_fnu(
self,
filters,
verbose=True,
nthreads=1,
limit_to=None,
out_dtype=None,
):
"""Calculate flux photometry using a FilterCollection object.
Args:
filters (FilterCollection):
A FilterCollection object.
verbose (bool):
Are we talking?
nthreads (int):
The number of threads to use for the integration. If -1, all
threads will be used.
limit_to (str/list, optional):
If None, then photometry is calculated for all spectra in the
galaxy. If a string or list of strings is provided, then
photometry is only calculated for the specified spectra.
out_dtype (np.dtype):
Requested floating-point dtype for the returned photometry.
Returns:
dict:
A dictionary of fluxes in each filter in filters.
"""
# Get the labels
labels = self.spectra.keys() if limit_to is None else limit_to
# Loop over spectra in the component
for label in labels:
# Create the photometry collection and store it in the object
self.photo_fnu[label] = self.spectra[label].get_photo_fnu(
filters,
verbose,
nthreads=nthreads,
out_dtype=out_dtype,
)
return self.photo_fnu
[docs]
def get_spectra(
self,
emission_model,
dust_curves=None,
tau_v=None,
fesc=None,
mask=None,
vel_shift=None,
verbose=True,
nthreads=1,
grid_assignment_method="cic",
out_dtype=None,
covering_fraction=None,
**kwargs,
):
"""Generate stellar spectra as described by the emission model.
Args:
emission_model (EmissionModel):
The emission model to use.
dust_curves (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
tau_v (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
fesc (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
mask (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
vel_shift (bool):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
verbose (bool):
Are we talking?
nthreads (int):
The number of threads to use for the tree search. If -1, all
available threads will be used.
grid_assignment_method (str):
The method to use for assigning particles to the grid. Options
are "cic" (cloud-in-cell) or "ngp" (nearest grid point)."
out_dtype (np.dtype):
Requested floating-point dtype for extracted spectra arrays.
covering_fraction (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
**kwargs (dict):
Any additional keyword arguments to pass to
EmissionModel._get_spectra, which raises an error for any it
doesn't accept.
Returns:
dict
A dictionary of spectra which can be attached to the
appropriate spectra attribute of the component
(spectra/particle_spectra)
"""
# Passing overrides here is no longer supported, the model itself
# should be modified instead
check_removed_overrides(
dust_curves=dust_curves,
tau_v=tau_v,
fesc=fesc,
covering_fraction=covering_fraction,
mask=mask,
vel_shift=vel_shift,
)
# Get the spectra
spectra, particle_spectra = emission_model._get_spectra(
emitters={"stellar": self}
if self.component_type == "Stars"
else {"blackhole": self},
verbose=verbose,
nthreads=nthreads,
grid_assignment_method=grid_assignment_method,
out_dtype=out_dtype,
**kwargs,
)
# Update the spectra dictionary
self.spectra.update(spectra)
# Update the particle_spectra dictionary if it exists
if hasattr(self, "particle_spectra"):
self.particle_spectra.update(particle_spectra)
# Return the spectra the user wants
if emission_model.per_particle:
return self.particle_spectra[emission_model.label]
return self.spectra[emission_model.label]
[docs]
def get_lines(
self,
line_ids,
emission_model,
dust_curves=None,
tau_v=None,
fesc=None,
mask=None,
verbose=True,
out_dtype=None,
covering_fraction=None,
**kwargs,
):
"""Generate stellar lines as described by the emission model.
Args:
line_ids (list):
A list of line_ids. Doublets can be specified as a nested list
or using a comma (e.g. 'OIII4363,OIII4959').
emission_model (EmissionModel):
The emission model to use.
dust_curves (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
tau_v (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
fesc (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
mask (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
verbose (bool):
Are we talking?
out_dtype (np.dtype):
Requested floating-point dtype for extracted line arrays.
covering_fraction (dict):
No longer supported, passing it raises an error.
Modify the EmissionModel (or the emitter) instead.
kwargs (dict):
Any additional keyword arguments to pass to
EmissionModel._get_lines, which raises an error for any it
doesn't accept.
Returns:
LineCollection
A LineCollection object containing the lines defined by the
root model.
"""
# Passing overrides here is no longer supported, the model itself
# should be modified instead
check_removed_overrides(
dust_curves=dust_curves,
tau_v=tau_v,
fesc=fesc,
covering_fraction=covering_fraction,
mask=mask,
)
# Get the lines
lines, particle_lines = emission_model._get_lines(
line_ids=line_ids,
emitters={"stellar": self}
if self.component_type == "Stars"
else {"blackhole": self},
verbose=verbose,
out_dtype=out_dtype,
**kwargs,
)
# Update the lines dictionary
self.lines.update(lines)
# Update the particle_lines dictionary if it exists
if hasattr(self, "particle_lines"):
self.particle_lines.update(particle_lines)
# Return the lines the user wants
if emission_model.per_particle:
return self.particle_lines[emission_model.label]
return self.lines[emission_model.label]
def _generate_images(
self,
*labels,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
phot_type="lnu",
postprocess=True,
):
"""Make an ImageCollection from component luminosities or fluxes.
For Parametric components, images can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, images can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
Which images are produced is defined by the labels passed. If any
of the necessary photometry is missing for generating a particular
image, an exception will be raised.
Note that black holes will never be smoothed and only produce a
histogram due to the point source nature of black holes.
All images that are created will be stored on the emitter (Stars or
BlackHole/s) under the images_lnu attribute (for phot_type='lnu')
or images_fnu attribute (for phot_type='fnu').
Args:
*labels (str):
The labels of the emission models to make images for. These
must be present in the photometry dicts of the component. For
particle components, these labels must be present in the
particle photometry dicts.
fov (unyt_quantity of float):
The width of the image in image coordinates.
instrument (Instrument):
The instrument to use for the image.
img_type (str):
The type of image to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed images.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
phot_type (str):
The type of photometry to use, either 'lnu' for luminosity
units or 'fnu' for flux units.
postprocess (bool):
If True, automatically apply the instrument-defined imaging
post-processing after raw image generation.
Returns:
ImageCollection/dict
Either a single ImageCollection if only one label is passed,
otherwise a dict of ImageCollections keyed by label.
"""
# Convert labels tuple to a list and validate they are strings
labels = list(labels)
for label in labels:
if not isinstance(label, str):
raise exceptions.InconsistentArguments(
f"All labels must be strings, got {type(label).__name__}. "
"If passing an EmissionModel, use model.label instead."
)
# Are we doing a parametric image?
is_param = hasattr(self, "morphology")
# Ensure we aren't trying to make a histogram for a parametric
# component
if is_param and img_type == "hist":
raise exceptions.InconsistentArguments(
f"Parametric {self.component_type} can only produce "
"smoothed images."
)
# Ensure we have a cosmology if we need it
if unit_is_compatible(instrument.resolution, arcsecond):
if cosmo is None:
raise exceptions.InconsistentArguments(
"Cosmology must be provided when using an angular "
"resolution and FOV."
)
# Also ensure we have a redshift
if self.redshift is None:
raise exceptions.MissingAttribute(
"Redshift must be set when using an angular "
"resolution and FOV."
)
# Find which images must be generated and which can simply
# be combined
combine_labels, generate_labels = _prepare_component_image_labels(
labels,
self.model_param_cache,
remove_missing=True,
)
# Define dictionary to hold the images we are generating
out_images = {}
# Get the appropriate photometry
if is_param and phot_type == "lnu":
photometry_dict = self.photo_lnu
elif is_param and phot_type == "fnu":
photometry_dict = self.photo_fnu
elif phot_type == "lnu":
photometry_dict = self.particle_photo_lnu
elif phot_type == "fnu":
photometry_dict = self.particle_photo_fnu
else:
raise exceptions.InconsistentArguments(
f"Photometry type {phot_type} not recognised. Must be "
"'lnu' or 'fnu'."
)
# Get the images
for label in generate_labels:
# If label isn't in the photometry dict raise an exception
if label not in photometry_dict:
available_keys = list(photometry_dict.keys())
raise exceptions.MissingPhotometryType(
f"Photometry for model {label} not found on the "
f"{self.component_type} component. "
f"Instrument: {instrument.label}. "
f"Available photometry keys: {available_keys}"
)
out_images[label] = instrument.generate_images(
photometry=photometry_dict[label],
fov=fov,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
emitter=self,
cosmo=cosmo,
)
# OK, loop over the combination labels and make those images
for label in combine_labels:
out_images.update(
{
label: _combine_image_collections(
images=out_images,
label=label,
model_cache=self.model_param_cache,
)
}
)
# Get the instrument name
instrument_name = instrument.label
# Attach the images properly depending on whether we have a
# generic instrument or not
if instrument_name is not None:
if phot_type == "lnu":
self.images_lnu.setdefault(instrument_name, {})
self.images_lnu[instrument_name].update(out_images)
else:
self.images_fnu.setdefault(instrument_name, {})
self.images_fnu[instrument_name].update(out_images)
else:
if phot_type == "lnu":
self.images_lnu.update(out_images)
else:
self.images_fnu.update(out_images)
# If we generated nothing there's nothing to return
if len(out_images) == 0:
return out_images
# Stop after raw generation when the caller needs unprocessed images
# for a higher-level combination step.
if not postprocess:
if len(labels) == 1:
return out_images[labels[0]]
return out_images
# Apply any instrument-defined PSF and noise processing in the
# canonical order before returning the observable to the caller.
out_images = _postprocess_existing_images(
self,
instrument=instrument,
phot_type=phot_type,
limit_to=labels,
)
# Return either the single image or the dict of images
if len(labels) == 1:
return out_images[labels[0]]
return out_images
[docs]
def get_images_luminosity(
self,
*labels,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
):
"""Make an ImageCollection from component luminosities.
For Parametric components, images can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, images can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
Which images are produced is defined by the labels passed. If any
of the necessary photometry is missing for generating a particular
image, an exception will be raised.
Note that black holes will never be smoothed and only produce a
histogram due to the point source nature of black holes.
All images that are created will be stored on the emitter (Stars or
BlackHole/s) under the images_lnu attribute.
Args:
*labels (str):
The labels of the emission models to make images for. These
must be present in the photometry dicts of the component. For
particle components, these labels must be present in the
particle photometry dicts.
fov (unyt_quantity of float):
The width of the image in image coordinates.
instrument (Instrument):
The instrument to use for the image.
img_type (str):
The type of image to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed images.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
Returns:
ImageCollection/dict
Either a single ImageCollection if only one label is passed,
otherwise a dict of ImageCollections keyed by label.
"""
return self._generate_images(
*labels,
fov=fov,
instrument=instrument,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
cosmo=cosmo,
phot_type="lnu",
)
[docs]
def get_images_flux(
self,
*labels,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
):
"""Make an ImageCollection from component fluxes.
For Parametric components, images can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, images can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
Which images are produced is defined by the labels passed. If any
of the necessary photometry is missing for generating a particular
image, an exception will be raised.
Note that black holes will never be smoothed and only produce a
histogram due to the point source nature of black holes.
All images that are created will be stored on the emitter (Stars or
BlackHole/s) under the images_fnu attribute.
Args:
*labels (str):
The labels of the emission models to make images for. These
must be present in the photometry dicts of the component. For
particle components, these labels must be present in the
particle photometry dicts.
fov (unyt_quantity of float):
The width of the image in image coordinates.
instrument (Instrument):
The instrument to use for the image.
img_type (str):
The type of image to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed images.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
Returns:
ImageCollection/dict
Either a single ImageCollection if only one label is passed,
otherwise a dict of ImageCollections keyed by label.
"""
return self._generate_images(
*labels,
fov=fov,
instrument=instrument,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
cosmo=cosmo,
phot_type="fnu",
)
def _generate_line_maps(
self,
*labels,
line_ids,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
phot_type="lnu",
postprocess=True,
):
"""Make an ImageCollection of emission line maps per line id.
For Parametric components, maps can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, maps can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
Which maps are produced is defined by the labels passed. If any
of the necessary lines are missing for generating a particular
map, an exception will be raised.
All maps that are created will be stored on the emitter (Stars or
BlackHole/s) under the line_maps_lnu attribute (for
phot_type='lnu') or line_maps_fnu attribute (for phot_type='fnu').
Args:
*labels (str):
The labels of the emission models to make line maps for.
These must be present in the lines dicts of the component.
For particle components, these labels must be present in the
particle lines dict.
line_ids (list):
The line ids to make maps for. Each requested label must
have all of these lines available.
Blended lines (e.g. doublets) can be given as a comma separated
string (e.g. "O 3 4958.91A, O 3 5006.84A") or a nested list of
line ids; these produce a single map of the summed lines keyed
by the ", " joined id.
fov (unyt_quantity of float):
The width of the map in image coordinates.
instrument (Instrument):
The instrument to use for the map (typically a
LineImager).
img_type (str):
The type of map to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed maps.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
phot_type (str):
The type of line quantity to use for the maps, either
'lnu' for luminosity maps, or 'fnu' for flux.
postprocess (bool):
If True, automatically apply the instrument-defined mapping
post-processing after raw map generation.
Returns:
dict
A dict of dicts of the form
{label: {line_id: ImageCollection}}, one ImageCollection per
requested label, each containing one line map (Image) per
line id.
"""
labels = list(labels)
for label in labels:
if not isinstance(label, str):
raise exceptions.InconsistentArguments(
f"All labels must be strings, got {type(label).__name__}. "
"If passing an EmissionModel, use model.label instead."
)
if isinstance(line_ids, str):
line_ids = [line_ids]
# Canonicalise aliases so requested ids match the instrument's ids
line_ids = [str(alias_to_line_id(lid)) for lid in line_ids]
unsupported = [
lid for lid in line_ids if lid not in instrument.line_ids
]
if len(unsupported) > 0:
raise exceptions.InconsistentArguments(
f"Lines {unsupported} are not mapped by instrument "
f"{instrument.label}. Available lines: {instrument.line_ids}"
)
# Are we doing a parametric map?
is_param = hasattr(self, "morphology")
if is_param and img_type == "hist":
raise exceptions.InconsistentArguments(
f"Parametric {self.component_type} can only produce "
"smoothed maps."
)
if unit_is_compatible(instrument.resolution, arcsecond):
if cosmo is None:
raise exceptions.InconsistentArguments(
"Cosmology must be provided when using an angular "
"resolution and FOV."
)
if self.redshift is None:
raise exceptions.MissingAttribute(
"Redshift must be set when using an angular "
"resolution and FOV."
)
quantity = "luminosity" if phot_type == "lnu" else "flux"
if phot_type not in ("lnu", "fnu"):
raise exceptions.InconsistentArguments(
f"Photometry type {phot_type} not recognised. Must be "
"'lnu' or 'fnu'."
)
# Find which maps must be generated and which can simply
# be combined
combine_labels, generate_labels = _prepare_component_image_labels(
labels,
self.model_param_cache,
remove_missing=True,
)
out_maps = {}
# Get the appropriate lines dict
if is_param:
lines_dict = self.lines
else:
lines_dict = self.particle_lines
for label in generate_labels:
if label not in lines_dict:
raise exceptions.MissingLines(
f"Lines for model {label} not found on the "
f"{self.component_type} component. "
f"Available line sets: {list(lines_dict.keys())}"
)
lines = lines_dict[label]
missing_lines = [lid for lid in line_ids if lid not in lines]
if len(missing_lines) > 0:
raise exceptions.MissingLines(
f"Lines {missing_lines} not found in the lines saved "
f"for model {label}."
)
if quantity == "flux" and lines.flux is None:
raise exceptions.MissingAttribute(
f"Lines for model {label} have no flux. Did you forget "
"to call get_observed_lines?"
)
out_maps[label] = instrument.generate_maps(
lines=lines[line_ids],
fov=fov,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
emitter=self,
cosmo=cosmo,
quantity=quantity,
)
for label in combine_labels:
out_maps.update(
{
label: _combine_image_collections(
images=out_maps,
label=label,
model_cache=self.model_param_cache,
)
}
)
instrument_name = instrument.label
if instrument_name is not None:
if phot_type == "lnu":
self.line_maps_lnu.setdefault(instrument_name, {})
self.line_maps_lnu[instrument_name].update(out_maps)
else:
self.line_maps_fnu.setdefault(instrument_name, {})
self.line_maps_fnu[instrument_name].update(out_maps)
else:
if phot_type == "lnu":
self.line_maps_lnu.update(out_maps)
else:
self.line_maps_fnu.update(out_maps)
if len(out_maps) == 0:
return out_maps
if not postprocess:
if len(labels) == 1:
return out_maps[labels[0]]
return out_maps
out_maps = _postprocess_existing_line_maps(
self,
instrument=instrument,
phot_type=phot_type,
limit_to=labels,
)
if len(labels) == 1:
return out_maps[labels[0]]
return out_maps
[docs]
def get_line_maps_luminosity(
self,
*labels,
line_ids,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
):
"""Make an ImageCollection of emission line maps from luminosities.
For Parametric components, maps can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, maps can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
All maps that are created will be stored on the emitter (Stars or
BlackHole/s) under the line_maps_lnu attribute.
Args:
*labels (str):
The labels of the emission models to make line maps for.
These must be present in the lines dicts of the component.
line_ids (list):
The line ids to make maps for.
Blended lines (e.g. doublets) can be given as a comma separated
string (e.g. "O 3 4958.91A, O 3 5006.84A") or a nested list of
line ids; these produce a single map of the summed lines keyed
by the ", " joined id.
fov (unyt_quantity of float):
The width of the map in image coordinates.
instrument (Instrument):
The instrument to use for the map (typically a
LineImager).
img_type (str):
The type of map to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed maps.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
Returns:
dict
A dict of the form {label: ImageCollection}, each containing
one line map (Image) per requested line id.
"""
return self._generate_line_maps(
*labels,
line_ids=line_ids,
fov=fov,
instrument=instrument,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
cosmo=cosmo,
phot_type="lnu",
)
[docs]
def get_line_maps_flux(
self,
*labels,
line_ids,
fov,
instrument,
img_type="smoothed",
kernel=None,
kernel_threshold=1,
nthreads=1,
cosmo=None,
):
"""Make an ImageCollection of emission line maps from fluxes.
For Parametric components, maps can only be smoothed. An
exception will be raised if a histogram is requested.
For Particle components, maps can either be a simple
histogram ("hist") or an image with particles smoothed over
their SPH kernel.
All maps that are created will be stored on the emitter (Stars or
BlackHole/s) under the line_maps_fnu attribute.
Args:
*labels (str):
The labels of the emission models to make line maps for.
These must be present in the lines dicts of the component.
line_ids (list):
The line ids to make maps for.
Blended lines (e.g. doublets) can be given as a comma separated
string (e.g. "O 3 4958.91A, O 3 5006.84A") or a nested list of
line ids; these produce a single map of the summed lines keyed
by the ", " joined id.
fov (unyt_quantity of float):
The width of the map in image coordinates.
instrument (Instrument):
The instrument to use for the map (typically a
LineImager).
img_type (str):
The type of map to be made, either "hist" -> a histogram, or
"smoothed" -> particles smoothed over a kernel for a particle
galaxy. Otherwise, only smoothed is applicable.
kernel (np.ndarray of float):
The values from one of the kernels from the kernel_functions
module. Only used for smoothed maps.
kernel_threshold (float):
The kernel's impact parameter threshold (by default 1).
nthreads (int):
The number of threads to use in the tree search. Default is 1.
cosmo (astropy.cosmology):
The cosmology to use for the calculation of the luminosity
distance. Only needed for internal conversions from cartesian
to angular coordinates when an angular resolution is used.
Returns:
dict
A dict of the form {label: ImageCollection}, each containing
one line map (Image) per requested line id.
"""
return self._generate_line_maps(
*labels,
line_ids=line_ids,
fov=fov,
instrument=instrument,
img_type=img_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
nthreads=nthreads,
cosmo=cosmo,
phot_type="fnu",
)
[docs]
@deprecated(
"is deprecated and will be removed in version 1.3.0. "
"Use component.get_images_luminosity(...) instead."
)
def apply_psf_to_images_lnu(
self,
instrument,
limit_to=None,
):
"""Apply instrument PSFs to this component's luminosity images.
This method now acts as an orchestration wrapper around the
instrument-owned PSF application path. It fetches the relevant image
collections, passes them into the instrument, and stores the returned
PSF-processed images on the component.
Args:
instrument (Instrument):
The instrument with the PSF to apply.
limit_to (str/list):
If not None, defines a specific model (or list of models) to
limit the image generation to. Otherwise, all models with saved
spectra will have images generated.
Returns:
dict The images with the PSF applied.
"""
# Ensure limit_to is a list
limit_to = [limit_to] if isinstance(limit_to, str) else limit_to
# Sanity check that we have a PSF
if instrument.psfs is None:
raise exceptions.InconsistentArguments(
f"Instrument ({instrument.label}) does not have PSFs."
)
# Ensure we have images for this instrument
if instrument.label not in self.images_lnu:
raise exceptions.InconsistentArguments(
"No images found in images_lnu for instrument"
f" {instrument.label}."
)
# Create an entry for the instrument in the PSF images
# dictionary if it doesn't exist
if instrument.label not in self.images_psf_lnu:
self.images_psf_lnu[instrument.label] = {}
# Loop over the images in the component
for key in self.images_lnu[instrument.label]:
# Are we limiting to a specific model?
if limit_to is not None and key not in limit_to:
continue
# Unpack the image collection to be post-processed
imgs = self.images_lnu[instrument.label][key]
# Delegate the actual PSF application to the instrument so the
# component layer only handles routing and output storage
self.images_psf_lnu[instrument.label][key] = instrument.apply_psfs(
imgs,
)
return self.images_psf_lnu[instrument.label]
[docs]
@deprecated(
"is deprecated and will be removed in version 1.3.0. "
"Use component.get_images_flux(...) instead."
)
def apply_psf_to_images_fnu(
self,
instrument,
limit_to=None,
):
"""Apply instrument PSFs to this component's flux images.
This method now acts as an orchestration wrapper around the
instrument-owned PSF application path. It fetches the relevant image
collections, passes them into the instrument, and stores the returned
PSF-processed images on the component.
Args:
instrument (Instrument):
The instrument with the PSF to apply.
limit_to (str/list):
If not None, defines a specific model (or list of models) to
limit the image generation to. Otherwise, all models with saved
spectra will have images generated.
Returns:
dict The images with the PSF applied.
"""
# Ensure limit_to is a list
limit_to = [limit_to] if isinstance(limit_to, str) else limit_to
# Sanity check that we have a PSF
if instrument.psfs is None:
raise exceptions.InconsistentArguments(
f"Instrument ({instrument.label}) does not have PSFs."
)
# Ensure we have images for this instrument
if instrument.label not in self.images_fnu:
raise exceptions.InconsistentArguments(
"No images found in images_fnu for instrument"
f" {instrument.label}."
)
# Create an entry for the instrument in the PSF images
# dictionary if it doesn't exist
if instrument.label not in self.images_psf_fnu:
self.images_psf_fnu[instrument.label] = {}
# Loop over the images in the component
for key in self.images_fnu[instrument.label]:
# Are we limiting to a specific model?
if limit_to is not None and key not in limit_to:
continue
# Unpack the image collection to be post-processed
imgs = self.images_fnu[instrument.label][key]
# Delegate the actual PSF application to the instrument so the
# component layer only handles routing and output storage
self.images_psf_fnu[instrument.label][key] = instrument.apply_psfs(
imgs,
)
return self.images_psf_fnu[instrument.label]
[docs]
@deprecated(
"is deprecated and will be removed in version 1.3.0. "
"Use component.get_images_luminosity(...) instead."
)
def apply_noise_to_images_lnu(
self,
instrument,
limit_to=None,
apply_to_psf=True,
):
"""Apply instrument noise to this component's images.
This method now acts as an orchestration wrapper around the
instrument-owned imaging-noise path. It fetches the relevant image
collections, passes them into the instrument, and stores the returned
noisy images on the component.
Args:
instrument (Instrument):
The instrument with the noise to apply.
limit_to (str/list):
If not None, defines a specific model (or list of models) to
limit the image generation to. Otherwise, all models with saved
spectra will have images generated.
apply_to_psf (bool):
If True, apply the noise to the PSF images.
Otherwise, apply to the non-PSF images.
Returns:
dict The images with the noise applied.
"""
# Ensure limit_to is a list
limit_to = [limit_to] if isinstance(limit_to, str) else limit_to
# Get the images we are applying the noise to
if apply_to_psf and instrument.label in self.images_psf_lnu:
images = self.images_psf_lnu[instrument.label]
elif instrument.label in self.images_lnu:
images = self.images_lnu[instrument.label]
else:
if apply_to_psf:
raise exceptions.InconsistentArguments(
"No images found in images_psf_lnu for instrument"
f" {instrument.label}."
)
raise exceptions.InconsistentArguments(
"No images found in images_lnu for instrument"
f" {instrument.label}."
)
# Create an entry for the instrument in the noise images
# dictionary if it doesn't exist
if instrument.label not in self.images_noise_lnu:
self.images_noise_lnu[instrument.label] = {}
# Loop over the images in the component
for key in images:
# Are we limiting to a specific model?
if limit_to is not None and key not in limit_to:
continue
# Unpack the image collection to be post-processed
imgs = images[key]
# Delegate the actual noise application to the instrument so the
# component layer only handles routing and output storage
self.images_noise_lnu[instrument.label][key] = (
instrument.apply_noises(
imgs,
aperture_radius=instrument.depth_app_radius,
)
)
return self.images_noise_lnu[instrument.label]
[docs]
@deprecated(
"is deprecated and will be removed in version 1.3.0. "
"Use component.get_images_flux(...) instead."
)
def apply_noise_to_images_fnu(
self,
instrument,
limit_to=None,
apply_to_psf=True,
):
"""Apply instrument noise to this component's images.
This method now acts as an orchestration wrapper around the
instrument-owned imaging-noise path. It fetches the relevant image
collections, passes them into the instrument, and stores the returned
noisy images on the component.
Args:
instrument (Instrument):
The instrument with the noise to apply.
limit_to (str/list):
If not None, defines a specific model (or list of models) to
limit the image generation to. Otherwise, all models with saved
spectra will have images generated.
apply_to_psf (bool):
If True, apply the noise to the PSF images.
Otherwise, apply to the non-PSF images.
Returns:
dict The images with the noise applied.
"""
# Ensure limit_to is a list
limit_to = [limit_to] if isinstance(limit_to, str) else limit_to
# Get the images we are applying the noise to
if apply_to_psf and instrument.label in self.images_psf_fnu:
images = self.images_psf_fnu[instrument.label]
elif instrument.label in self.images_fnu:
images = self.images_fnu[instrument.label]
else:
if apply_to_psf:
raise exceptions.InconsistentArguments(
"No images found in images_psf_fnu for instrument"
f" {instrument.label}."
)
raise exceptions.InconsistentArguments(
"No images found in images_fnu for instrument"
f" {instrument.label}."
)
# Create an entry for the instrument in the noise images
# dictionary if it doesn't exist
if instrument.label not in self.images_noise_fnu:
self.images_noise_fnu[instrument.label] = {}
# Loop over the images in the component
for key in images:
# Are we limiting to a specific model?
if limit_to is not None and key not in limit_to:
continue
# Unpack the image collection to be post-processed
imgs = images[key]
# Delegate the actual noise application to the instrument so the
# component layer only handles routing and output storage
self.images_noise_fnu[instrument.label][key] = (
instrument.apply_noises(
imgs,
aperture_radius=instrument.depth_app_radius,
)
)
return self.images_noise_fnu[instrument.label]
@property
@deprecated(
"is deprecated and will be removed in version 1.4.0. "
"It is an alias for spectroscopy_fnu (observer frame); use that, or "
"spectroscopy_lnu for the rest frame, instead."
)
def spectroscopy(self):
"""Return the observer frame spectroscopy (deprecated alias).
Returns:
dict
The spectroscopy_fnu dictionary.
"""
return self.spectroscopy_fnu
@property
@deprecated(
"is deprecated and will be removed in version 1.4.0. "
"It is an alias for particle_spectroscopy_fnu (observer frame); use "
"that, or particle_spectroscopy_lnu for the rest frame, instead."
)
def particle_spectroscopy(self):
"""Return the observer frame particle spectroscopy (deprecated alias).
Returns:
dict
The particle_spectroscopy_fnu dictionary.
"""
return self.particle_spectroscopy_fnu
[docs]
def get_spectroscopy_lnu(
self,
instrument,
limit_to=None,
out_dtype=None,
):
"""Get rest frame spectroscopy for the component from an instrument.
The instrument wavelengths are interpreted as rest frame wavelengths
(see SpectroscopicInstrument.apply_lam_array_lnu). The results are
stored in spectroscopy_lnu (and particle_spectroscopy_lnu for any
particle spectra).
Args:
instrument (Instrument):
The instrument to use for the spectroscopy.
limit_to (str/list, optional):
If None, then spectroscopy is calculated for all spectra in
the component. If a string or list of strings is provided,
then spectroscopy is only calculated for the specified
spectra.
out_dtype (np.dtype, optional):
Requested floating-point dtype for the resulting spectra.
If None the spectroscopy inherits the source spectra dtype.
Returns:
dict
The rest frame spectroscopy for the component.
"""
return self._get_spectroscopy(
instrument,
"lnu",
limit_to=limit_to,
out_dtype=out_dtype,
)
[docs]
def get_spectroscopy_fnu(
self,
instrument,
limit_to=None,
out_dtype=None,
):
"""Get observer frame spectroscopy for the component.
The instrument wavelengths are interpreted as observer frame
wavelengths (see SpectroscopicInstrument.apply_lam_array_fnu), so the
spectra must already have their fluxes computed. The results are
stored in spectroscopy_fnu (and particle_spectroscopy_fnu for any
particle spectra).
Args:
instrument (Instrument):
The instrument to use for the spectroscopy.
limit_to (str/list, optional):
If None, then spectroscopy is calculated for all spectra in
the component. If a string or list of strings is provided,
then spectroscopy is only calculated for the specified
spectra.
out_dtype (np.dtype, optional):
Requested floating-point dtype for the resulting spectra.
If None the spectroscopy inherits the source spectra dtype.
Returns:
dict
The observer frame spectroscopy for the component.
"""
return self._get_spectroscopy(
instrument,
"fnu",
limit_to=limit_to,
out_dtype=out_dtype,
)
[docs]
@deprecated(
"is deprecated and will be removed in version 1.4.0. "
"It is an alias for get_spectroscopy_fnu(...) (observer frame); use "
"that, or get_spectroscopy_lnu(...) for the rest frame, instead."
)
def get_spectroscopy(
self,
instrument,
limit_to=None,
out_dtype=None,
):
"""Get spectroscopy for the component based on a specific instrument.
Deprecated alias for get_spectroscopy_fnu, which treats the
instrument wavelengths as observer frame wavelengths.
Args:
instrument (Instrument):
The instrument to use for the spectroscopy.
limit_to (str/list, optional):
If None, then spectroscopy is calculated for all spectra in
the component. If a string or list of strings is provided,
then spectroscopy is only calculated for the specified
spectra.
out_dtype (np.dtype, optional):
Requested floating-point dtype for the resulting spectra.
If None the spectroscopy inherits the source spectra dtype.
Returns:
dict
The observer frame spectroscopy for the component.
"""
return self.get_spectroscopy_fnu(
instrument,
limit_to=limit_to,
out_dtype=out_dtype,
)
def _get_spectroscopy(
self,
instrument,
quantity,
limit_to=None,
out_dtype=None,
):
"""Get spectroscopy for the component based on a specific instrument.
This method now acts as an orchestration wrapper around the
instrument-owned spectroscopy path. It fetches the relevant SEDs,
passes them into the instrument, and stores the returned spectroscopy
on the component.
Args:
instrument (Instrument):
The instrument to use for the spectroscopy.
quantity (str):
Either "lnu" (the instrument wavelengths are rest frame) or
"fnu" (the instrument wavelengths are observer frame). This
picks the instrument method and the dictionaries the results
are stored in.
limit_to (str/list, optional):
If None, then spectroscopy is calculated for all spectra in
the component. If a string or list of strings is provided,
then spectroscopy is only calculated for the specified
spectra.
out_dtype (np.dtype, optional):
Requested floating-point dtype for the resulting spectra.
If None the spectroscopy inherits the source spectra dtype.
Returns:
dict
The spectroscopy for the component.
"""
# Get the instrument method and output dictionaries for this frame
apply_lam_array = getattr(instrument, f"apply_lam_array_{quantity}")
spectroscopy = getattr(self, f"spectroscopy_{quantity}")
# Create an entry for the instrument in the spectroscopy
# dictionary if it doesn't exist
if instrument.label not in spectroscopy:
spectroscopy[instrument.label] = {}
# Get the labels
labels = self.spectra.keys() if limit_to is None else limit_to
# Loop over the spectra in the component and apply the instrument
for label in labels:
# Skip labels that don't exist on this component
if label not in self.spectra:
continue
# Delegate the spectroscopy observation to the instrument so the
# component layer only handles routing and output storage
spectrum = apply_lam_array(self.spectra[label])
if instrument.can_do_noisy_spectroscopy:
spectrum = instrument.apply_noise(spectrum)
if out_dtype is not None:
spectrum.cast(out_dtype)
spectroscopy[instrument.label][label] = spectrum
# If we have particle spectra then do the same for them
if (
hasattr(self, "particle_spectra")
and len(self.particle_spectra) > 0
):
particle_spectroscopy = getattr(
self, f"particle_spectroscopy_{quantity}"
)
if instrument.label not in particle_spectroscopy:
particle_spectroscopy[instrument.label] = {}
# Get the labels for particle spectra
particle_labels = (
self.particle_spectra.keys() if limit_to is None else limit_to
)
# Loop over the spectra in the component and apply the instrument
for label in particle_labels:
# Skip labels that don't exist on this component
if label not in self.particle_spectra:
continue
# Delegate the particle-spectrum observation to the instrument
# so the component layer only handles routing and output
# storage
spectrum = apply_lam_array(self.particle_spectra[label])
if instrument.can_do_noisy_spectroscopy:
spectrum = instrument.apply_noise(spectrum)
if out_dtype is not None:
spectrum.cast(out_dtype)
particle_spectroscopy[instrument.label][label] = spectrum
# Return the spectroscopy for the component
return spectroscopy[instrument.label]
[docs]
def get_data_cube(
self,
label,
fov,
instrument,
cube_type="smoothed",
kernel=None,
kernel_threshold=1,
quantity="lnu",
nthreads=1,
cosmo=None,
):
"""Get a data cube for one saved spectrum on this component.
This is the public component-level cube API. It delegates the
low-level cube construction to the IFU, stores the generated cube on
the component, and returns it.
Args:
label (str): Saved spectrum label to turn into a data cube.
fov (unyt_quantity): Width of the requested data cube.
instrument (IntegratedFieldUnit): Instrument defining the
wavelength sampling and spatial resolution.
cube_type (str): Either ``"smoothed"`` or ``"hist"``.
kernel (array-like, optional): Kernel used for smoothed particle
cubes.
kernel_threshold (float): Kernel impact-parameter threshold.
quantity (str): Spectral quantity to store in the cube.
nthreads (int): Number of threads to use for particle cube
generation.
cosmo (astropy.cosmology, optional): Cosmology used for mixed-unit
conversions.
Returns:
SpectralCube: Generated spectral data cube.
"""
# Reuse the shared component implementation so the public single-label
# API stays aligned with the multi-label/internal generation path.
return self._generate_data_cubes(
label,
fov=fov,
instrument=instrument,
cube_type=cube_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
quantity=quantity,
nthreads=nthreads,
cosmo=cosmo,
)
def _generate_data_cubes(
self,
*labels,
fov,
instrument,
cube_type="smoothed",
kernel=None,
kernel_threshold=1,
quantity="lnu",
nthreads=1,
cosmo=None,
postprocess=True,
):
"""Make SpectralCube objects for one component.
Args:
*labels (str):
The labels of the emission models to make data cubes for.
fov (unyt_quantity):
Width of the requested data cube.
instrument (IntegratedFieldUnit):
Instrument defining the wavelength sampling and spatial
resolution.
cube_type (str):
Either ``"smoothed"`` or ``"hist"``.
kernel (array-like, optional):
Kernel used for smoothed particle cubes.
kernel_threshold (float):
Kernel impact-parameter threshold.
quantity (str):
Spectral quantity to store in the cube.
nthreads (int):
Number of threads to use for particle cube generation.
cosmo (astropy.cosmology, optional):
Cosmology used for mixed-unit conversions.
postprocess (bool):
If True, automatically apply any instrument-defined IFU
post-processing after raw cube generation.
Returns:
SpectralCube/dict:
Either a single SpectralCube if only one label is passed,
otherwise a dict of SpectralCubes keyed by label.
"""
# Convert labels tuple to a list and validate they are strings.
labels = list(labels)
for label in labels:
if not isinstance(label, str):
raise exceptions.InconsistentArguments(
f"All labels must be strings, got {type(label).__name__}. "
"If passing an EmissionModel, use model.label instead."
)
# Split the request into labels that correspond to concrete saved
# spectra on this component and labels that represent combinations of
# those spectra. This mirrors the image-generation routing logic, but
# stays local to a single component.
model_cache = getattr(self, "model_param_cache", {})
combine_labels, generate_labels = _prepare_component_data_cube_labels(
labels,
model_cache,
remove_missing=False,
)
# Container for cubes generated or combined in this call.
out_cubes = {}
# Collect every spectrum store that can legitimately seed a raw cube.
# Particle components may expose both integrated and per-particle
# spectra, while parametric components usually only expose the former.
available_spectra = set(self.spectra)
if hasattr(self, "particle_spectra"):
available_spectra.update(self.particle_spectra)
# Ask the IFU for raw cubes only for labels that already exist as saved
# spectra. Any higher-level combination labels are handled afterwards
# from the cubes accumulated in ``out_cubes``.
for label in generate_labels:
if label not in available_spectra:
raise exceptions.InconsistentArguments(
f"No saved spectrum with label '{label}' was found on the "
f"{self.component_type} component."
)
out_cubes[label] = instrument.generate_data_cube(
component=self,
fov=fov,
sed=label,
cube_type=cube_type,
kernel=kernel,
kernel_threshold=kernel_threshold,
quantity=quantity,
nthreads=nthreads,
cosmo=cosmo,
)
# Resolve any component-owned combination labels from the raw cube set
# just generated above. Keeping this separate from raw generation makes
# it possible for the galaxy layer to reuse the same two-step pattern.
for label in combine_labels:
out_cubes[label] = _combine_spectral_cubes(
cubes=out_cubes,
label=label,
model_cache=model_cache,
)
# Cache raw cubes before any IFU observation recipe is applied. The
# galaxy-level orchestration path relies on these raw component cubes
# when it needs to assemble galaxy-owned combination cubes.
if quantity in {"lnu", "llam", "luminosity"}:
self.data_cubes_lnu.setdefault(instrument.label, {})
self.data_cubes_lnu[instrument.label].update(out_cubes)
elif quantity in {"fnu", "flam", "flux"}:
self.data_cubes_fnu.setdefault(instrument.label, {})
self.data_cubes_fnu[instrument.label].update(out_cubes)
# When called from the galaxy layer we stop here, returning raw cubes
# so the parent object can combine them before any PSF/noise step is
# applied. Standalone component calls continue on to post-processing.
if postprocess:
out_cubes = _postprocess_existing_data_cubes(
self,
instrument=instrument,
quantity=quantity,
limit_to=labels,
)
# If no cubes survived generation or post-processing, return the empty
# mapping directly.
if len(out_cubes) == 0:
return out_cubes
# Mirror the image-generation API: a single requested label unwraps to
# a bare SpectralCube, while multi-label requests return the full map.
if len(labels) == 1:
return out_cubes[labels[0]]
return out_cubes
[docs]
def plot_spectra(
self,
spectra_to_plot=None,
show=False,
ylimits=(),
xlimits=(),
figsize=(3.5, 5),
**kwargs,
):
"""Plot the spectra of the component.
Can either plot specific spectra (specified via spectra_to_plot) or
all spectra on the child object.
Args:
spectra_to_plot (string/list, string):
The specific spectra to plot.
- If None all spectra are plotted.
- If a list of strings each specifc spectra is plotted.
- If a single string then only that spectra is plotted.
show (bool):
Flag for whether to show the plot or just return the
figure and axes.
ylimits (tuple):
The limits to apply to the y axis. If not provided the limits
will be calculated with the lower limit set to 1000 (100) times
less than the peak of the spectrum for rest_frame (observed)
spectra.
xlimits (tuple):
The limits to apply to the x axis. If not provided the optimal
limits are found based on the ylimits.
figsize (tuple):
Tuple with size 2 defining the figure size.
kwargs (dict):
Arguments to the `sed.plot_spectra` method called from this
wrapper.
Returns:
fig (matplotlib.pyplot.figure)
The matplotlib figure object for the plot.
ax (matplotlib.axes)
The matplotlib axes object containing the plotted data.
"""
# Handling whether we are plotting all spectra, specific spectra, or
# a single spectra
if spectra_to_plot is None:
spectra = self.spectra
elif isinstance(spectra_to_plot, (list, tuple)):
spectra = {key: self.spectra[key] for key in spectra_to_plot}
else:
spectra = self.spectra[spectra_to_plot]
return plot_spectra(
spectra,
show=show,
ylimits=ylimits,
xlimits=xlimits,
figsize=figsize,
draw_legend=isinstance(spectra, dict),
**kwargs,
)
[docs]
def plot_spectroscopy(
self,
instrument_label,
spectra_to_plot=None,
show=False,
ylimits=(),
xlimits=(),
figsize=(3.5, 5),
fig=None,
ax=None,
**kwargs,
):
"""Plot the instrument's rest frame spectroscopy of the component.
This will plot the rest frame spectroscopy (spectroscopy_lnu) for the
component using the instrument's wavelength array. The spectra are
plotted in the order they are stored in the spectroscopy dictionary.
Can either plot specific spectroscopy (specified via spectra_to_plot)
or all spectroscopy on the component.
Args:
instrument_label (str):
The label of the instrument to use for the spectroscopy.
spectra_to_plot (string/list, string):
The specific spectroscopy to plot.
- If None all spectra are plotted.
- If a list of strings each specifc spectra is plotted.
- If a single string then only that spectra is plotted.
show (bool):
Flag for whether to show the plot or just return the
figure and axes.
ylimits (tuple):
The limits to apply to the y axis. If not provided the limits
will be calculated with the lower limit set to 1000 (100) times
less than the peak of the spectrum for rest_frame (observed)
spectra.
xlimits (tuple):
The limits to apply to the x axis. If not provided the optimal
limits are found based on the ylimits.
figsize (tuple):
Tuple with size 2 defining the figure size.
fig (matplotlib.pyplot.figure):
The matplotlib figure object for the plot.
ax (matplotlib.axes):
The matplotlib axes object containing the plotted data.
**kwargs (dict):
Arguments to the `sed.plot_spectra` method called from this
wrapper.
Returns:
fig (matplotlib.pyplot.figure)
The matplotlib figure object for the plot.
ax (matplotlib.axes)
The matplotlib axes object containing the plotted data.
"""
return self._plot_spectroscopy(
instrument_label,
"lnu",
spectra_to_plot=spectra_to_plot,
show=show,
ylimits=ylimits,
xlimits=xlimits,
figsize=figsize,
fig=fig,
ax=ax,
**kwargs,
)
[docs]
def plot_observed_spectroscopy(
self,
instrument_label,
spectra_to_plot=None,
show=False,
ylimits=(),
xlimits=(),
figsize=(3.5, 5),
fig=None,
ax=None,
**kwargs,
):
"""Plot the instrument's observer frame spectroscopy of the component.
This will plot the observer frame spectroscopy (spectroscopy_fnu) for
the component using the instrument's wavelength array. The spectra
are plotted in the order they are stored in the spectroscopy
dictionary.
Can either plot specific spectroscopy (specified via spectra_to_plot)
or all spectroscopy on the component.
Args:
instrument_label (str):
The label of the instrument to use for the spectroscopy.
spectra_to_plot (string/list, string):
The specific spectroscopy to plot.
- If None all spectra are plotted.
- If a list of strings each specifc spectra is plotted.
- If a single string then only that spectra is plotted.
show (bool):
Flag for whether to show the plot or just return the
figure and axes.
ylimits (tuple):
The limits to apply to the y axis. If not provided the limits
will be calculated with the lower limit set to 100 times less
than the peak of the spectrum.
xlimits (tuple):
The limits to apply to the x axis. If not provided the optimal
limits are found based on the ylimits.
figsize (tuple):
Tuple with size 2 defining the figure size.
fig (matplotlib.pyplot.figure):
The matplotlib figure object for the plot.
ax (matplotlib.axes):
The matplotlib axes object containing the plotted data.
**kwargs (dict):
Arguments to the `sed.plot_observed_spectra` method called
from this wrapper.
Returns:
fig (matplotlib.pyplot.figure)
The matplotlib figure object for the plot.
ax (matplotlib.axes)
The matplotlib axes object containing the plotted data.
"""
return self._plot_spectroscopy(
instrument_label,
"fnu",
spectra_to_plot=spectra_to_plot,
show=show,
ylimits=ylimits,
xlimits=xlimits,
figsize=figsize,
fig=fig,
ax=ax,
**kwargs,
)
def _plot_spectroscopy(
self,
instrument_label,
quantity,
spectra_to_plot=None,
**kwargs,
):
"""Plot the instrument's spectroscopy of the component in one frame.
Args:
instrument_label (str):
The label of the instrument to use for the spectroscopy.
quantity (str):
The frame to plot, either "lnu" (rest frame,
spectroscopy_lnu) or "fnu" (observer frame,
spectroscopy_fnu).
spectra_to_plot (string/list, string):
The specific spectroscopy to plot.
- If None all spectra are plotted.
- If a list of strings each specifc spectra is plotted.
- If a single string then only that spectra is plotted.
**kwargs (dict):
Arguments to the `sed.plot_spectra` (rest frame) or
`sed.plot_observed_spectra` (observer frame) method.
Returns:
fig (matplotlib.pyplot.figure)
The matplotlib figure object for the plot.
ax (matplotlib.axes)
The matplotlib axes object containing the plotted data.
"""
# Get the spectroscopy for this frame and instrument
spectroscopy = getattr(self, f"spectroscopy_{quantity}")[
instrument_label
]
# Handling whether we are plotting all spectra, specific spectra, or
# a single spectra
if spectra_to_plot is None:
spectra = spectroscopy
elif isinstance(spectra_to_plot, (list, tuple)):
spectra = {key: spectroscopy[key] for key in spectra_to_plot}
else:
spectra = spectroscopy[spectra_to_plot]
# Include the instrument label in the spectra key (i.e. plot lables)
if isinstance(spectra, dict):
spectra = {
f"{instrument_label}: {key}": spectroscopy[key]
for key in spectra
}
# Observer frame spectra are plotted against observed wavelengths,
# which needs the redshift
if quantity == "fnu":
return plot_observed_spectra(
spectra,
self.redshift,
draw_legend=isinstance(spectra, dict),
**kwargs,
)
return plot_spectra(
spectra,
draw_legend=isinstance(spectra, dict),
**kwargs,
)
[docs]
def clear_all_spectra(self):
"""Clear all spectra from the component."""
self.spectra = {}
if hasattr(self, "particle_spectra"):
self.particle_spectra = {}
[docs]
def clear_all_spectroscopy(self):
"""Clear all spectroscopy from the component."""
self.spectroscopy_lnu = {}
self.spectroscopy_fnu = {}
if hasattr(self, "particle_spectroscopy_lnu"):
self.particle_spectroscopy_lnu = {}
self.particle_spectroscopy_fnu = {}
[docs]
def clear_all_lines(self):
"""Clear all lines from the component."""
self.lines = {}
if hasattr(self, "particle_lines"):
self.particle_lines = {}
[docs]
def clear_all_photometry(self):
"""Clear all photometry from the component."""
self.photo_lnu = {}
self.photo_fnu = {}
if hasattr(self, "particle_photo_lnu"):
self.particle_photo_lnu = {}
if hasattr(self, "particle_photo_fnu"):
self.particle_photo_fnu = {}
[docs]
def clear_all_emissions(self):
"""Clear all emissions from the component.
This clears all spectra, lines, and photometry.
"""
self.clear_all_spectra()
self.clear_all_lines()
self.clear_all_photometry()
self.clear_all_spectroscopy()
[docs]
def clear_weights(self):
"""Clear all cached grid weights from the component.
This clears all grid weights calculated using different
methods from this component, and resets the `_grid_weights`
dictionary.
"""
if hasattr(self, "_grid_weights"):
self._grid_weights = {"cic": {}, "ngp": {}}
[docs]
def print_used_parameters(self, *models):
"""Print the parameters used by emission models in a formatted table.
This method displays all parameters that have been cached during
emission model calculations, organized by model label. Each model's
parameters are shown with their computed values.
The output is formatted using TableFormatter to match the style
of other print methods in synthesizer.
Args:
*models (str):
Optional model labels to print. If provided, only the
specified models will be printed. If not provided, all
cached models will be printed.
"""
# Check if cache is empty
if not self.model_param_cache:
print(
f"No cached model parameters found for {self.component_type}."
)
return
# Determine which models to print
if len(models) > 0:
# Filter to only the requested models
models_to_print = {
label: params
for label, params in self.model_param_cache.items()
if label in models
}
# Warn about any requested models that don't exist
missing = set(models) - set(self.model_param_cache.keys())
if len(missing) > 0:
print(
f"The following models were not found in "
f"the cache: {', '.join(missing)}"
)
else:
# Print all models
models_to_print = self.model_param_cache
# Check if we have any models to print after filtering
if not models_to_print:
print("No matching models found in cache.")
return
# Loop over each model in the cache
for model_label, params in models_to_print.items():
# Create a simple object to hold the parameters for this model
class ModelParams:
def __init__(self, params_dict):
for key, value in params_dict.items():
setattr(self, key, value)
# Create the object and format it
param_obj = ModelParams(params)
formatter = TableFormatter(param_obj)
# Print the table for this model
print("\n" + formatter.get_table(f"Model: {model_label}"))