"""The base module from which all other particle types inherit.
This generic particle class forms the base class containing all attributes and
methods common to all child particle types. It should rarely if ever be
directly instantiated.
"""
import copy
import inspect
import numpy as np
from numpy.random import multivariate_normal
from unyt import Mpc, Msun, km, pc, rad, s, unyt_array
from synthesizer import exceptions
from synthesizer.emission_models.utils import get_param
from synthesizer.particle.utils import calculate_smoothing_lengths, rotate
from synthesizer.synth_warnings import warn
from synthesizer.units import (
Quantity,
accepts,
convert_in_place,
deepcopy_with_shared_units,
get_quantity_unit,
)
from synthesizer.utils import TableFormatter
from synthesizer.utils.geometry import get_rotation_matrix
from synthesizer.utils.operation_timers import timed, timer
from synthesizer.utils.precision import resolve_out_dtype
[docs]
class Particles:
"""The base particle class.
All attributes of this class are optional keyword arguments in the child
classes. Here we demand they are passed as positional arguments to protect
against future changes.
Attributes:
coordinates (np.ndarray of float):
The 3D coordinates of each particle.
velocities (np.ndarray of float):
The 3D velocity of each stellar particle.
masses (np.ndarray of float):
The mass of each particle in Msun.
redshift (np.ndarray of float):
The redshift/s of the stellar particles.
softening_length (float):
The physical gravitational softening length.
nparticle : int
How many particles are there?
centre (array, float):
Centre of the particle distribution.
metallicity_floor (float):
The metallicity floor when using log properties (only matters for
baryons). This is used to avoid log(0) errors.
tau_v (float):
The V band optical depth.
radii (np.ndarray of float):
The radii of the particles.
_grid_weights (dict, np.ndarray of float):
Weights for each particle sorted onto a grid. This dictionary takes
the form of {<method>: {grid_name: weights}} where weights is an
array of the same shape as the grid containg the particles sorted
onto the grid.
"""
# Define class level Quantity attributes
coordinates = Quantity("spatial")
velocities = Quantity("velocity")
masses = Quantity("mass")
softening_lengths = Quantity("spatial")
centre = Quantity("spatial")
radii = Quantity("spatial")
# Share units rather than deep copying unyt's whole unit registry
__deepcopy__ = deepcopy_with_shared_units
@accepts(
coordinates=Mpc,
velocities=km / s,
masses=Msun.in_base("galactic"),
softening_length=Mpc,
centre=Mpc,
)
def __init__(
self,
coordinates,
velocities,
masses,
redshift,
softening_lengths,
nparticles,
centre,
metallicity_floor=1e-5,
tau_v=None,
name="Particles",
):
"""Initialise the Particles.
Args:
coordinates (np.ndarray of float):
The 3D positions of the particles.
velocities (np.ndarray of float):
The 3D velocities of the particles.
masses (np.ndarray of float):
The mass of each particle.
redshift (float):
The redshift/s of the particles.
softening_lengths (float):
The physical gravitational softening length.
nparticles (int):
How many particles are there?
centre (array, float):
Centre of the particle distribution.
metallicity_floor (float):
The metallicity floor when using log properties (only matters
for baryons). This is used to avoid log(0) errors.
tau_v (float):
The V band optical depth.
name (str):
The name of the particle type.
"""
# Set phase space coordinates
self.coordinates = coordinates
self.velocities = velocities
# Define the dictionary to hold particle spectra
self.particle_spectra = {}
# Define the dictionary to hold particle lines
self.particle_lines = {}
# Initialise the particle photometry dictionaries
self.particle_photo_lnu = {}
self.particle_photo_fnu = {}
# Set unit information
# Set the softening length
self.softening_lengths = softening_lengths
# Set the particle masses
self.masses = masses
# Set the redshift of the particles
self.redshift = redshift
# How many particles are there?
self.nparticles = nparticles
# Set the centre of the particle distribution
self.centre = centre
# Set the radius to None, this will be populated when needed and
# can then be subsequently accessed
self.radii = None
# Set the metallicity floor when using log properties (only matters for
# baryons)
self.metallicity_floor = metallicity_floor
# Set the V band optical depths
self.tau_v = tau_v
# Attach the name of the particle type
self.name = name
# Track names of any extra attributes set via **kwargs by subclasses.
# Populated by _register_custom_attrs; used by spatially_resample.
self._custom_attr_names = []
def _register_custom_attrs(self, **kwargs):
"""Record the names of extra attributes added via ``**kwargs``.
Each subclass constructor should call this with its own ``**kwargs``
after setting those attributes on *self* so that methods like
:meth:`spatially_resample` can later discover and handle them.
Args:
**kwargs:
The same keyword arguments that were passed to the subclass
constructor.
"""
for name in kwargs:
if name not in self._custom_attr_names:
self._custom_attr_names.append(name)
@property
def centered_coordinates(self):
"""Returns the coordinates centred on the geometric mean."""
if self.centre is None:
raise exceptions.InconsistentArguments(
"Can't centre coordinates without a centre."
)
return self.coordinates - self.centre
[docs]
def get_projected_angular_coordinates(
self,
cosmo=None,
los_dists=None,
):
"""Get the projected angular coordinates in radians.
This will return the angular coordinates of the particles in radians
projected along the line of sight axis (always the z-axis). The
coordinates along the line of sight axis will be set to 0.0, to
maintain the shape of coordinates array.
The coordinates will be centred on the centre of the particle
distribution before calculating the angular coordinates. If the centre
is not set then an error will be raised.
Note that a redshift is required if the los_dists aren't given to
convert the coordinates to angular coordinates. If this redshift
is 0.0 then the particles will be treated as if they are at 10 pc
(minimum distance) from the observer.
Args:
cosmo (astropy.cosmology):
The cosmology object from which to derive the luminosity
distance.
los_dists (unyt_quantity):
The line of sight distances to the particles. If None, this
will be calculated using the redshift and cosmology object.
Returns:
unyt_array: The projected angular coordinates of the particles
in radians.
"""
# Either cosmo or los_dists must be provided
if cosmo is None and los_dists is None:
raise exceptions.InconsistentArguments(
"Either cosmo or los_dists must be provided to get "
"projected angular coordinates."
)
# Get the centered coordinates
cent_coords = self.centered_coordinates
# If we don't have the LOS distances then we need to calculate them
if los_dists is None:
# Get the angular diameter distance
ang_diam_dist = self.get_angular_diameter_distance(cosmo)
# Combine the angular diameter distance with the line of sight
# distance (along the z-axis)
los_dists = ang_diam_dist + cent_coords[:, 2]
# If we are at redshift 0.0 then we need to shift things to
# put the closest particle at 10 pc
if self.redshift == 0.0:
z_min = np.min(cent_coords[:, 2])
los_dists += np.abs(z_min) + 10 * pc
else:
# Ok, we have been handed LOS distances, make sure they are the
# right shape
if los_dists.size != self.nparticles:
raise exceptions.InconsistentArguments(
"The LOS distances must be the same shape as the "
f"coordinates. Got {los_dists.size} but expected "
f"{self.nparticles}."
)
# Ensure the distances are in the right units
x = cent_coords[:, 0].ndview
y = cent_coords[:, 1].ndview
d = convert_in_place(los_dists, cent_coords.units).ndview
# Get the angular coordinates and store them in a (N, 3) array
coords = np.zeros((self.nparticles, 3), dtype=np.float64)
coords[:, 0] = np.arctan2(x, d)
coords[:, 1] = np.arctan2(y, d)
# Ensure the array is C-contiguous
coords = np.ascontiguousarray(coords)
return coords * rad
[docs]
def get_projected_angular_smoothing_lengths(
self,
cosmo=None,
los_dists=None,
):
"""Get the projected angular smoothing lengths in radians.
This will return the angular smoothing lengths of the particles in
radians projected along the line of sight axis (always the z-axis). The
coordinates along the line of sight axis will be set to 0.0, to
maintain the shape of coordinates array.
Note that a redshift is required if the los_dists aren't given to
convert the coordinates to angular coordinates. If this redshift
is 0.0 then the particles will be treated as if they are at 10 pc
(minimum distance) from the observer.
Args:
cosmo (astropy.cosmology):
The cosmology object from which to derive the luminosity
distance.
los_dists (unyt_quantity):
The line of sight distances to the particles. If None, this
will be calculated using the redshift and cosmology object.
Returns:
unyt_array: The projected angular smoothing lengths of the
particles in radians.
"""
# Either cosmo or los_dists must be provided
if cosmo is None and los_dists is None:
raise exceptions.InconsistentArguments(
"Either cosmo or los_dists must be provided to get "
"projected angular smoothing lengths."
)
# Get the centered coordinates
cent_coords = self.centered_coordinates
# If we don't have the LOS distances then we need to calculate them
if los_dists is None:
# Get the angular diameter distance
ang_diam_dist = self.get_angular_diameter_distance(cosmo)
# Combine the angular diameter distance with the line of sight
# distance
# (along the z-axis)
los_dists = ang_diam_dist + cent_coords[:, 2]
# If we are at redshift 0.0 then we need to shift things to
# put the closest particle at 10 pc
if self.redshift == 0.0:
z_min = np.min(cent_coords[:, 2])
los_dists += np.abs(z_min) + 10 * pc
else:
# Ok, we have been handed LOS distances, make sure they are the
# right shape
if los_dists.size != self.nparticles:
raise exceptions.InconsistentArguments(
"The LOS distances must be the same shape as the "
f"coordinates. Got {los_dists.size} but expected "
f"{self.nparticles}."
)
# Ensure the distances are in the right units
d = convert_in_place(
los_dists, get_quantity_unit(self, "smoothing_lengths")
).ndview
# Calculate and return the projected angular smoothing lengths
projected_smoothing_lengths = np.ascontiguousarray(
np.arctan2(self._smoothing_lengths, d)
)
return projected_smoothing_lengths * rad
[docs]
def split(self, max_npart):
"""Split a particle component into chunks.
Args:
max_npart (int):
The maximum number of particles permitted in each child
component.
Returns:
list:
A list of child particle components containing views of the
parent particle data.
"""
if max_npart is None:
return [self]
if max_npart <= 0:
raise exceptions.InconsistentArguments(
"max_npart must be a positive integer."
)
children = []
start = 0
nparticles = self.nparticles
# Introspect the child constructor so we can rebuild children from
# sliced constructor inputs rather than copying the parent object.
signature = inspect.signature(self.__class__.__init__)
constructor_params = {
name: param
for name, param in signature.parameters.items()
if name != "self"
}
while start < self.nparticles:
stop = min(start + max_npart, self.nparticles)
part_slice = slice(start, stop)
kwargs = {}
# First collect any attributes that map directly onto explicit
# constructor arguments, slicing particle-shaped arrays to views.
for name, param in constructor_params.items():
if param.kind == inspect.Parameter.VAR_KEYWORD:
continue
if not hasattr(self, name):
continue
value = getattr(self, name)
if hasattr(value, "shape") and value.shape != ():
if value.shape[0] == nparticles:
kwargs[name] = value[part_slice]
else:
kwargs[name] = value
else:
kwargs[name] = value
# Then pass through any extra keyword-style attributes that should
# survive the split, again slicing particle-shaped arrays to views
# and skipping transient pipeline outputs/caches.
for key, value in self.__dict__.items():
if (
key.startswith("_")
or key in kwargs
or key in constructor_params
or key
in {
"nparticles",
"nstars",
"nbh",
"component_type",
"log10ages",
"log10metallicities",
"spectra",
"lines",
"photo_lnu",
"photo_fnu",
"spectroscopy_lnu",
"spectroscopy_fnu",
"images_lnu",
"images_fnu",
"images_psf_lnu",
"images_psf_fnu",
"images_noise_lnu",
"images_noise_fnu",
"particle_spectra",
"particle_lines",
"particle_photo_lnu",
"particle_photo_fnu",
"particle_spectroscopy_lnu",
"particle_spectroscopy_fnu",
"data_cubes_lnu",
"data_cubes_fnu",
"model_param_cache",
"_grid_weights",
"sfh",
"sfzh",
}
):
continue
if hasattr(value, "shape") and value.shape != ():
if value.shape[0] == nparticles:
kwargs[key] = value[part_slice]
else:
kwargs[key] = value
else:
kwargs[key] = value
# Reconstruct the child from constructor inputs only, ensuring the
# split object starts with fresh output containers.
child = self.__class__(**kwargs)
children.append(child)
start = stop
return children
[docs]
def get_projected_angular_imaging_props(self, cosmo):
"""Get the projected angular imaging properties.
This is a convenience method to reduce repeated calculations when
getting angular coordinates and smoothing lengths since they both
require similar calculations. This method will return the
projected angular coordinates and projected angular smoothing
lengths of the particles in radians projected along the line of
sight axis (always the z-axis). The coordinates along the line of
sight axis will be set to 0.0, to maintain the shape of coordinates
array.
Arguments:
cosmo (astropy.cosmology):
The cosmology object from which to derive the luminosity
distance.
Returns:
tuple: A tuple containing the projected angular coordinates and
projected angular smoothing lengths of the particles in
radians.
"""
# Get the centered coordinates
cent_coords = self.centered_coordinates
# Get the angular diameter distance
ang_diam_dist = self.get_angular_diameter_distance(cosmo)
# Combine the angular diameter distance with the line of sight distance
# (along the z-axis)
los_dists = ang_diam_dist + cent_coords[:, 2]
# If we are at redshift 0.0 then we need to shift things to
# put the closest particle at 10 pc
if self.redshift == 0.0:
z_min = np.min(cent_coords[:, 2])
los_dists += np.abs(z_min) + 10 * pc
# Compute the projected angular properties
projected_angular_coords = self.get_projected_angular_coordinates(
los_dists=los_dists,
)
projected_angular_smls = self.get_projected_angular_smoothing_lengths(
los_dists=los_dists,
)
return (
projected_angular_coords,
projected_angular_smls,
)
[docs]
def get_particle_photo_lnu(
self,
filters,
verbose=True,
nthreads=1,
limit_to=None,
out_dtype=None,
):
"""Calculate luminosity 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:
photo_lnu (dict): A dictionary of rest frame broadband
luminosities.
"""
# Get the labels
labels = self.particle_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.particle_photo_lnu[label] = self.particle_spectra[
label
].get_photo_lnu(
filters, verbose, nthreads=nthreads, out_dtype=out_dtype
)
return self.particle_photo_lnu
[docs]
def get_particle_photo_fnu(
self,
filters,
verbose=True,
nthreads=1,
limit_to=None,
out_dtype=None,
):
"""Calculate flux photometry using a FilterCollection object.
Args:
filters (object):
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.particle_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.particle_photo_fnu[label] = self.particle_spectra[
label
].get_photo_fnu(
filters, verbose, nthreads=nthreads, out_dtype=out_dtype
)
return self.particle_photo_fnu
[docs]
@timed("Particles.get_mask")
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.
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.
"""
# Get the attribute
attr_str = attr
try:
attr = get_param(
attr_str, attr_override_obj, None, self, preserve_units=True
)
except exceptions.MissingAttribute as e:
raise exceptions.MissingMaskAttribute(
f"Masking attribute ({attr_str}) not found on particle object."
) from e
# Resolve a string threshold as an attribute alias on the emitter
if isinstance(thresh, str):
thresh_str = thresh
try:
thresh = get_param(
thresh_str,
attr_override_obj,
None,
self,
preserve_units=True,
)
except exceptions.MissingAttribute as e:
raise exceptions.MissingMaskAttribute(
f"Mask threshold alias ({thresh_str}) not found on "
"particle object."
) from e
# Strip dimensionless units since they are inconsequential
if hasattr(attr, "units") and attr.units.is_dimensionless:
attr = attr.ndview
if hasattr(thresh, "units") and thresh.units.is_dimensionless:
thresh = thresh.ndview
# Ensure the attribute is not None
if attr is None:
raise exceptions.MissingMaskAttribute(
f"Masking attribute ({attr_str}) not found on particle object."
)
# If only one value has units throw an error
if hasattr(attr, "units") and not hasattr(thresh, "units"):
raise exceptions.InconsistentArguments(
f"Masking attribute ({attr_str}) has units "
f"but threshold does not ({thresh})."
)
elif not hasattr(attr, "units") and hasattr(thresh, "units"):
raise exceptions.InconsistentArguments(
f"Masking attribute ({attr_str}) does not have units "
f"but threshold has ({thresh})."
)
# If we only have a scalar attribute we need to expand it to a
# nparticle array
if attr.size == 1:
if hasattr(attr, "units"):
attr = (
np.full(
self.nparticles,
attr.value,
dtype=np.float64,
)
* attr.units
)
else:
attr = np.full(self.nparticles, attr, dtype=np.float64)
# Apply the operator
if op == ">":
new_mask = attr > thresh
elif op == "<":
new_mask = attr < thresh
elif op == ">=":
new_mask = attr >= thresh
elif op == "<=":
new_mask = attr <= thresh
elif op == "==":
new_mask = attr == thresh
elif op == "!=":
new_mask = attr != thresh
else:
raise exceptions.InconsistentArguments(
"Masking operation must be '<', '>', '<=', '>=', '==', or "
f"'!=', not {op}"
)
# Combine with the existing mask
if mask is not None:
new_mask = np.logical_and(new_mask, mask)
return new_mask
[docs]
def integrate_particle_spectra(self):
"""Integrate any particle spectra to get integrated spectra.
This will take all spectra in self.particle_spectra and call the sum
method on them, populating self.spectra with the results.
"""
# Loop over the particle spectra
for key, sed in self.particle_spectra.items():
# Sum the spectra
self.spectra[key] = sed.sum()
[docs]
def spatially_resample(self, resample_factor, **kwargs):
"""Resample this particle distribution spatially.
Each particle is replaced by *resample_factor* new particles whose
positions are sampled from the SPH kernel centred on the original
position. Any extra attributes registered via ``**kwargs`` at
construction time (see :attr:`_custom_attr_names`) are automatically
included and duplicated by default.
Subclasses (Gas, Stars) override this with a concrete implementation
that harvests their own attributes and delegates to the class-level
resampling engine.
Args:
resample_factor (int):
Number of new particles per original particle (>= 2).
**kwargs:
Additional keyword arguments forwarded to the subclass
implementation (e.g. ``seed``, ``mask``, ``kernel``,
``proportional_attrs``, ``distributions``).
Returns:
A new particle object of the same type with the resampled
distribution.
Raises:
NotImplementedError: If the subclass has not overridden this
method.
"""
raise NotImplementedError(
f"{self.__class__.__name__} does not implement spatially_resample."
)
def __str__(self):
"""Return a string representation of the particle object.
Returns:
table (str):
A string representation of the particle object.
"""
# Intialise the table formatter
formatter = TableFormatter(self)
return formatter.get_table("Particles")
[docs]
def calculate_centre_of_mass(self):
"""Calculate the centre of mass of the collection of particles.
Uses the `masses` and `coordinates` attributes,
and assigns the centre of mass to the `centre` attribute
"""
total_mass = np.sum(self.masses)
com = np.array([0.0, 0.0, 0.0])
for i, coods in enumerate(self.coordinates):
com += coods * self.masses[i]
com /= total_mass
self.center = com
[docs]
def calculate_smoothing_lengths(self, source_coords=None, **kwargs):
"""Calculate smoothing lengths of particles and assign.
Calls utility function directly, see
`synthesizer.particle.utils.calculate_smoothing_lengths`
for a full list of accepted arguments.
Args:
source_coords (unyt_array, optional):
Coordinates to query against when calculating smoothing
lengths. If None, the particle coordinates are used.
**kwargs (dict):
Additional keyword arguments passed to
`calculate_smoothing_lengths`.
"""
self.smoothing_lengths = calculate_smoothing_lengths(
coordinates=self.coordinates,
source_coords=source_coords,
**kwargs,
)
[docs]
def get_radii(self):
"""Calculate the radii of the particles.
Returns:
radii (np.ndarray of float):
The radii of the particles.
"""
# Raise an error if the centre is not set
if self.centre is None:
raise exceptions.InconsistentArguments(
"Can't calculate radii without a centre."
)
# Calculate the radii
self.radii = np.linalg.norm(self.centered_coordinates, axis=1)
return self.radii
@accepts(aperture_radius=Mpc)
def _aperture_mask(self, aperture_radius):
"""Mask for particles within spherical aperture.
Args:
aperture_radius (float):
Radius of spherical aperture in kpc
"""
if self.centre is None:
raise ValueError(
"Centre of particles must be set to use aperture mask."
)
# Get the radii if not already set
if self.radii is None:
self.get_radii()
return self.radii < aperture_radius
def _get_radius(self, weights, frac):
"""Calculate the radius of a particle distribution.
Args:
weights (np.ndarray of float):
The weights to use to weight the particles.
frac (float):
The fraction of the total weight for the radius.
Returns:
radius (float):
The radius of the particle distribution.
"""
# If we have no particles then return 0 with a warning
if self.nparticles == 0:
warn(
f"Trying to calculate radius for {self.__class__.__name__}"
" with no particles. Returning 0."
)
return 0 * get_quantity_unit(self, "coordinates")
# Get the radii if not already set
if self.radii is None:
self.get_radii()
# Handle special cases
if frac == 0:
return 0 * get_quantity_unit(self, "radii")
elif frac == 1:
return np.max(self._radii) * get_quantity_unit(self, "radii")
elif self.nparticles == 1:
return (
self.radii[0].value
* frac
* get_quantity_unit(self, "coordinates")
)
elif np.sum(weights) == 0:
return 0 * get_quantity_unit(self, "coordinates")
# Strip units off the weights if they have them
if hasattr(weights, "units"):
weights = weights.value
# Sort the weights and radii by radius
sinds = np.argsort(self.radii)
weights = weights[sinds]
radii = self._radii[sinds]
# Get the total of the weights
total = np.sum(weights)
# Get the cumulative array for the weights
cum_weight = np.cumsum(weights)
# Interpolate to get an accurate radius
radius = np.interp(frac * total, cum_weight, radii)
return radius * get_quantity_unit(self, "radii")
[docs]
def get_attr_radius(self, weight_attr, frac=0.5):
"""Calculate the radius of a particle distribution.
By default this will return the "half attr radius."
Args:
weight_attr (str):
The attribute to use to weight the particles.
frac (float):
The fraction of the total attribute for the radius.
Returns:
radius (float):
The radius of the particle distribution.
"""
# Get the weight attribute
weights = getattr(self, weight_attr, None)
# Ensure we found the attribute
if weights is None:
raise exceptions.InconsistentArguments(
f"{weight_attr} not found in particle object."
)
return self._get_radius(weights, frac)
[docs]
def get_luminosity_radius(self, spectra_type, filter_code, frac=0.5):
"""Calculate the radius of a particle distribution based on luminoisty.
Args:
spectra_type (str):
The type of spectra to use to compute radius.
filter_code (str):
The filter code to compute the radius for.
frac (float):
The fraction of the total light for the radius.
Returns:
radius (float):
The radius of the particle distribution.
"""
# Check we have that spectra type, if so unpack it
if spectra_type not in self.particle_photo_lnu:
raise exceptions.InconsistentArguments(
f"{spectra_type} not found in particle photometry. "
"Call get_particle_photo_lnu first."
)
else:
phot_collection = self.particle_photo_lnu[spectra_type]
# Check we have the filter code
if filter_code not in phot_collection.filter_codes:
raise exceptions.InconsistentArguments(
f"{filter_code} not found in particle photometry. "
"Call get_particle_photo_lnu first."
)
else:
light = phot_collection[filter_code]
return self._get_radius(light, frac)
[docs]
def get_flux_radius(self, spectra_type, filter_code, frac=0.5):
"""Calculate the radius of a particle distribution based on flux.
Args:
spectra_type (str):
The type of spectra to use to compute radius.
filter_code (str):
The filter code to compute the radius for.
frac (float):
The fraction of the total light for the radius.
Returns:
radius (float):
The radius of the particle distribution.
"""
# Check we have that spectra type, if so unpack it
if spectra_type not in self.particle_photo_fnu:
raise exceptions.InconsistentArguments(
f"{spectra_type} not found in particle photometry. "
"Call get_particle_photo_fnu first."
)
else:
phot_collection = self.particle_photo_fnu[spectra_type]
# Check we have the filter code
if filter_code not in phot_collection.filter_codes:
raise exceptions.InconsistentArguments(
f"{filter_code} not found in particle photometry. "
"Call get_particle_photo_fnu first."
)
else:
light = phot_collection[filter_code]
return self._get_radius(light, frac)
[docs]
def get_half_mass_radius(self):
"""Calculate the half mass radius of the particle distribution.
Returns:
radius (float):
The half mass radius of the particle distribution.
"""
# Hanlde
return self.get_attr_radius("masses", 0.5)
[docs]
def get_half_luminosity_radius(self, spectra_type, filter_code):
"""Calculate the half luminosity radius of the particle distribution.
Args:
spectra_type (str):
The type of spectra to use to compute radius.
filter_code (str):
The filter code to compute the radius for.
Returns:
radius (float):
The half luminosity radius of the particle distribution.
"""
return self.get_luminosity_radius(spectra_type, filter_code, 0.5)
[docs]
def get_half_flux_radius(self, spectra_type, filter_code):
"""Calculate the half flux radius of the particle distribution.
Args:
spectra_type (str):
The type of spectra to use to compute radius.
filter_code (str):
The filter code to compute the radius for.
Returns:
radius (float):
The half flux radius of the particle distribution.
"""
return self.get_flux_radius(spectra_type, filter_code, 0.5)
def _prepare_los_args(
self,
other_parts,
attrs,
kernel,
mask,
threshold,
force_loop,
min_count,
nthreads,
out_dtype,
):
"""Prepare the arguments for line of sight column density computation.
Args:
other_parts (Particles):
The other particles to compute the column density with.
attrs (tuple, str):
The attributes to compute the column densities of.
kernel (Kernel):
A ``synthesizer.kernel_functions.Kernel`` instance. This is
used to provide both the projected LOS kernel table and the
truncated LOS lookup table needed by the C extension.
mask (bool):
A mask to be applied to the stars. Surface densities will only
be computed and returned for stars with True in the mask.
threshold (float):
The threshold above which the SPH kernel is 0. This is normally
at a value of the impact parameter of q = r / h = 1.
force_loop (bool):
Whether to force the use of a simple loop rather than the tree.
min_count (int):
The minimum number of particles allowed in a leaf cell when
using the tree. This can be used for tuning the tree
performance.
nthreads (int):
The number of threads to use for the calculation.
out_dtype (np.dtype):
The dtype for the output column densities.
"""
# Ensure we actually have the properties needed
if self.coordinates is None:
raise exceptions.InconsistentArguments(
f"{self.name} object is missing coordinates!"
)
if other_parts.coordinates is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing coordinates!"
)
if other_parts.smoothing_lengths is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing smoothing lengths!"
)
# Set up the kernel inputs to the C function.
if not hasattr(kernel, "get_kernel") or not hasattr(
kernel, "get_truncated_los_kernel"
):
raise exceptions.InconsistentArguments(
"LOS column densities require a Kernel instance so the "
"projected and truncated LOS kernel tables are available."
)
projected_kernel = kernel.get_kernel()
truncated_kernel = kernel.get_truncated_los_kernel()[0]
# Set up the inputs from this particle instance.
pos_i = self._coordinates[mask, :]
# Set up the kernel inputs to the C function.
kernel = projected_kernel
kdim = kernel.size
trunc_qdim = truncated_kernel.shape[0]
zdim = truncated_kernel.shape[1]
# Get particle counts.
npart_i = pos_i.shape[0]
npart_j = other_parts.nparticles
# Set up the inputs from the other particle instance.
pos_j = other_parts._coordinates
smls = other_parts._smoothing_lengths
# Pass existing arrays by reference; the extension reads them directly.
surf_den_vals = tuple(getattr(other_parts, attr) for attr in attrs)
return (
kernel,
truncated_kernel,
pos_i,
pos_j,
smls,
surf_den_vals,
npart_i,
npart_j,
kdim,
trunc_qdim,
zdim,
threshold,
force_loop,
min_count,
nthreads,
out_dtype,
tuple(attrs),
)
def _prepare_smoothed_los_args(
self,
other_parts,
attrs,
kernel,
mask,
threshold,
force_loop,
min_count,
nthreads,
out_dtype,
):
"""Prepare the arguments for smoothed LOS column density computation.
Args:
other_parts (Particles):
The other particles to compute the column density with.
attrs (tuple, str):
The attributes to compute the column densities of.
kernel (Kernel):
A `synthesizer.kernel_functions.Kernel` instance. Smoothed LOS
calculations require the overlap table returned by
`Kernel.get_overlap_kernel()`, so raw projected-kernel arrays
are not accepted on this path.
mask (bool):
A mask to be applied to the stars. Surface densities will only
be computed and returned for stars with True in the mask.
threshold (float):
The threshold above which the SPH kernel is 0. This sets the
effective support radius used when mapping particle pairs onto
the overlap table at runtime.
force_loop (bool):
Whether to force the use of a simple loop rather than the tree.
min_count (int):
The minimum number of particles allowed in a leaf cell when
using the tree. This can be used for tuning the tree
performance.
nthreads (int):
The number of threads to use for the calculation.
out_dtype (np.dtype):
The dtype for the output column densities.
"""
if self.coordinates is None:
raise exceptions.InconsistentArguments(
f"{self.name} object is missing coordinates!"
)
if self.smoothing_lengths is None:
raise exceptions.InconsistentArguments(
f"{self.name} object is missing smoothing lengths!"
)
if other_parts.coordinates is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing coordinates!"
)
if other_parts.smoothing_lengths is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing smoothing lengths!"
)
if self._coordinates.ndim != 2 or self._coordinates.shape[1] != 3:
raise exceptions.InconsistentArguments(
f"{self.name} coordinates must have shape (N, 3)!"
)
if (
other_parts._coordinates.ndim != 2
or other_parts._coordinates.shape[1] != 3
):
raise exceptions.InconsistentArguments(
f"{other_parts.name} coordinates must have shape (N, 3)!"
)
if self._coordinates.shape[0] != self._smoothing_lengths.shape[0]:
raise exceptions.InconsistentArguments(
f"{self.name} coordinates and smoothing lengths "
"must have matching lengths!"
)
if (
other_parts._coordinates.shape[0]
!= other_parts._smoothing_lengths.shape[0]
):
raise exceptions.InconsistentArguments(
f"{other_parts.name} coordinates and smoothing lengths "
"must have matching lengths!"
)
for attr in attrs:
if (
other_parts._coordinates.shape[0]
!= getattr(other_parts, attr).shape[0]
):
raise exceptions.InconsistentArguments(
f"{other_parts.name} coordinates and {attr} must have "
"matching lengths!"
)
if (
self._coordinates[mask, :].shape[0]
!= self._smoothing_lengths[mask].shape[0]
):
raise exceptions.InconsistentArguments(
f"{self.name} masked coordinates and smoothing lengths "
"must have matching lengths!"
)
# Smoothed LOS calculations require the overlap kernel table rather
# than the point-particle projected kernel used by the LOS machinery.
if not hasattr(kernel, "get_overlap_kernel"):
raise exceptions.InconsistentArguments(
"LOS column densities with kernel-smoothed input particles "
"require a Kernel instance so the overlap kernel table is "
"available."
)
with timer("Particles._prepare_smoothed_los_args.get_overlap_kernel"):
overlap_kernel, q_grid, u_grid, eta_grid = (
kernel.get_overlap_kernel(nthreads=nthreads)
)
# Set up the overlap-kernel inputs to the C function. The extension
# uses the tabulated coordinate arrays explicitly for trilinear
# lookup.
with timer("Particles._prepare_smoothed_los_args.pack_arguments"):
qdim = q_grid.size
udim = u_grid.size
etadim = eta_grid.size
# Set up the inputs from this particle instance.
pos_i = self._coordinates[mask, :]
input_smls = self._smoothing_lengths[mask]
# Get particle counts.
npart_i = pos_i.shape[0]
npart_j = other_parts.nparticles
# Set up the inputs from the other particle instance.
pos_j = other_parts._coordinates
smls = other_parts._smoothing_lengths
# Pass references to existing arrays; no particle data is stacked.
surf_den_vals = tuple(getattr(other_parts, attr) for attr in attrs)
return (
overlap_kernel,
q_grid,
u_grid,
eta_grid,
pos_i,
input_smls,
pos_j,
smls,
surf_den_vals,
npart_i,
npart_j,
qdim,
udim,
etadim,
threshold,
force_loop,
min_count,
nthreads,
out_dtype,
tuple(attrs),
)
[docs]
@timed("Particles.get_los_column_density")
def get_los_column_density(
self,
other_parts,
density_attr,
kernel,
as_points=True,
column_density_attr=None,
mask=None,
threshold=1,
force_loop=0,
min_count=100,
nthreads=1,
out_dtype=None,
):
"""Calculate the column density of an attribute.
This will calculate the column density of an attribute on another
Particles child instance at the positions of the particles in this
Particles instance.
Args:
other_parts (Particles):
The other particles to calculate the column density with.
density_attr (str or sequence of str):
The attribute or attributes to use to calculate column
densities. Multiple attributes are evaluated in one LOS tree
traversal.
kernel (Kernel):
A `synthesizer.kernel_functions.Kernel` instance. LOS column
densities require both the projected kernel table and the
truncated LOS kernel table.
as_points (bool):
Whether to treat the input particles in this Particles instance
as point-like when evaluating the LOS column density. If False,
the input particle kernels are accounted for via the overlap
kernel table.
column_density_attr (str or sequence of str):
The attribute or attributes to store the column densities in on
the Particles instance. A sequence must match a sequence passed
to ``density_attr``. If None, results are not stored.
mask (array-like, bool):
A mask to be applied to the stars. Surface densities will only
be computed and returned for stars with True in the mask.
threshold (float):
The threshold above which the SPH kernel is 0. This is normally
at a value of the impact parameter of q = r / h = 1.
force_loop (bool):
Whether to force the use of a simple loop rather than the tree.
min_count (int):
The minimum number of particles allowed in a leaf cell when
using the tree. This can be used for tuning the tree
performance.
nthreads (int):
The number of threads to use for the calculation.
out_dtype (dtype-like, optional):
Floating-point dtype for the returned column densities. By
default, use the global Synthesizer output dtype.
Returns:
unyt_array or tuple of unyt_array:
The column density for a string input, or one column-density
array per requested attribute for a sequence input.
"""
from synthesizer.extensions.column_density import (
compute_column_density,
compute_column_density_smoothed,
)
scalar_input = isinstance(density_attr, str)
if scalar_input:
density_attrs = (density_attr,)
else:
try:
density_attrs = tuple(density_attr)
except TypeError as exc:
raise exceptions.InconsistentArguments(
"density_attr must be a string or a sequence of strings."
) from exc
if not density_attrs or not all(
isinstance(attr, str) for attr in density_attrs
):
raise exceptions.InconsistentArguments(
"density_attr must contain at least one attribute name."
)
if column_density_attr is None:
output_attrs = None
elif scalar_input and isinstance(column_density_attr, str):
output_attrs = (column_density_attr,)
elif not scalar_input and not isinstance(column_density_attr, str):
try:
output_attrs = tuple(column_density_attr)
except TypeError as exc:
raise exceptions.InconsistentArguments(
"column_density_attr must match density_attr."
) from exc
if len(output_attrs) != len(density_attrs) or not all(
isinstance(attr, str) for attr in output_attrs
):
raise exceptions.InconsistentArguments(
"column_density_attr must match density_attr."
)
else:
raise exceptions.InconsistentArguments(
"column_density_attr must match density_attr."
)
# If we don't have a mask make a fake one for consistency
if mask is None:
mask = np.ones(self.nparticles, dtype=bool)
else:
mask = np.asarray(mask, dtype=bool)
if mask.size != self.nparticles:
raise exceptions.InconsistentArguments(
"The mask must be the same length as the number of "
f"particles. Got {mask.size} but expected {self.nparticles}."
)
masked_nparticles = np.count_nonzero(mask)
# Validate inputs before accessing their units
if other_parts.coordinates is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing coordinates!"
)
coord_units = get_quantity_unit(other_parts, "coordinates")
column_density_units = []
for attr in density_attrs:
density = getattr(other_parts, attr, None)
if density is None:
raise exceptions.InconsistentArguments(
f"{other_parts.name} object is missing {attr}!"
)
if not hasattr(density, "units"):
raise exceptions.InconsistentArguments(
f"{other_parts.name} object attribute {attr} must have "
"units to compute LOS column densities."
)
if density.ndim != 1 or density.shape[0] != other_parts.nparticles:
raise exceptions.InconsistentArguments(
f"{other_parts.name} attribute {attr} must have one value "
"per particle."
)
column_density_units.append(density.units / coord_units**2)
output_dtype = resolve_out_dtype(out_dtype)
def finalise(raw):
with timer("Particles.get_los_column_density.attach_units"):
results = tuple(
unyt_array(
raw[index],
units,
bypass_validation=True,
)
for index, units in enumerate(column_density_units)
)
if output_attrs is not None:
for attr, result in zip(output_attrs, results):
setattr(self, attr, result)
return results[0] if scalar_input else results
# If have no particles return 0
if self.nparticles == 0 or masked_nparticles == 0:
return finalise(
np.zeros(
(len(density_attrs), masked_nparticles), dtype=output_dtype
)
)
# If the other particles have no particles return 0
if other_parts.nparticles == 0:
return finalise(
np.zeros(
(len(density_attrs), masked_nparticles), dtype=output_dtype
)
)
# Compute the column density. Smoothed input particles use a dedicated
# extension path based on the overlap kernel table.
if as_points:
with timer("Particles.get_los_column_density.prepare_inputs"):
los_args = self._prepare_los_args(
other_parts,
density_attrs,
kernel,
mask,
threshold,
force_loop,
min_count,
nthreads,
output_dtype,
)
with timer("Particles.get_los_column_density.compute"):
col_den = compute_column_density(*los_args)
else:
with timer("Particles.get_los_column_density.prepare_inputs"):
smoothed_args = self._prepare_smoothed_los_args(
other_parts,
density_attrs,
kernel,
mask,
threshold,
force_loop,
min_count,
nthreads,
output_dtype,
)
with timer("Particles.get_los_column_density.compute"):
col_den = compute_column_density_smoothed(*smoothed_args)
return finalise(col_den)
[docs]
@accepts(phi=rad, theta=rad)
@timed("Particles.rotate_particles")
def rotate_particles(
self,
phi=0 * rad,
theta=0 * rad,
rot_matrix=None,
inplace=True,
):
"""Rotate coordinates.
This method can either use angles or a provided rotation matrix.
When using angles phi is the rotation around the z-axis while theta
is the rotation around the y-axis.
This can both be done in place or return a new instance, by default
this will be done in place.
Args:
phi (unyt_quantity):
The angle in radians to rotate around the z-axis. If rot_matrix
is defined this will be ignored.
theta (unyt_quantity):
The angle in radians to rotate around the y-axis. If rot_matrix
is defined this will be ignored.
rot_matrix (np.ndarray of float):
A 3x3 rotation matrix to apply to the coordinates
instead of phi and theta.
inplace (bool):
Whether to perform the rotation in place or return a new
instance.
Returns:
Particles: A new instance of the particles with the rotated
coordinates, if inplace is False.
"""
# Are we rotating in place or returning a new instance?
if inplace:
# Rotate the coordinates
self.coordinates = rotate(self.coordinates, phi, theta, rot_matrix)
if self.velocities is not None:
self.velocities = rotate(
self.velocities, phi, theta, rot_matrix
)
if self.centre is not None:
self.centre = rotate(self.centre, phi, theta, rot_matrix)
return
# Ok, we're returning a new one, make a copy
new_parts = copy.deepcopy(self)
# Rotate the coordinates
new_parts.coordinates = rotate(
new_parts.coordinates, phi, theta, rot_matrix
)
if new_parts.velocities is not None:
new_parts.velocities = rotate(
new_parts.velocities, phi, theta, rot_matrix
)
if self.centre is not None:
new_parts.centre = rotate(new_parts.centre, phi, theta, rot_matrix)
# Return the new one
return new_parts
@property
def angular_momentum(self):
"""Calculate the total angular momentum vector of the particles.
Returns:
unyt_array: The angular momentum vector of the particle system.
"""
# Ensure we have all the attributes we need
if self.coordinates is None:
raise exceptions.InconsistentArguments(
"Can't calculate angular momentum without coordinates."
)
if self.velocities is None:
raise exceptions.InconsistentArguments(
"Can't calculate angular momentum without velocities."
)
if self.masses is None:
raise exceptions.InconsistentArguments(
"Can't calculate angular momentum without masses."
)
# We have to do some unit gymnastics to make sure we return sensible
# units. Since coordinates and velocities won't necessarily agree
# on the length unit we adopt the velocity length unit which we can
# extract with some simple string manipulation.
velocity_unit = get_quantity_unit(self, "velocities")
distance_unit = str(velocity_unit).split("/")[0]
ang_mom_unit = (
f"{distance_unit} * {get_quantity_unit(self, 'masses')} * "
f"{velocity_unit}"
)
# Cross product of position and velocity, weighted by mass
return np.sum(
np.cross(self.coordinates, self.velocities) * self.masses[:, None],
axis=0,
).to(ang_mom_unit)
[docs]
@timed("Particles.rotate_edge_on")
def rotate_edge_on(self, inplace=True):
"""Rotate the particle distribution to edge-on.
This will rotate the particle distribution such that the angular
momentum vector is aligned with the y-axis in an image.
Args:
inplace (bool):
Whether to perform the rotation in place or return a new
instance.
Returns:
Particles
A new instance of the particles with rotated coordinates,
if inplace is False.
"""
# Get the rotation matrix to rotate ang_mom_hat to the y-axis
rot_matrix = get_rotation_matrix(
self.angular_momentum, np.array([1, 0, 0])
)
# Call the rotate_particles method with the computed angles
return self.rotate_particles(rot_matrix=rot_matrix, inplace=inplace)
[docs]
@timed("Particles.rotate_face_on")
def rotate_face_on(self, inplace=True):
"""Rotate the particle distribution to face-on.
This will rotate the particle distribution such that the angular
momentum vector is aligned with the z-axis in an image.
Args:
inplace (bool):
Whether to perform the rotation in place or return a new
instance.
Returns:
Particles
A new instance of the particles with rotated coordinates,
if inplace is False.
"""
# Get the rotation matrix to rotate ang_mom_hat to the z-axis
rot_matrix = get_rotation_matrix(
self.angular_momentum, np.array([0, 0, -1])
)
# Call the rotate_particles method with the computed angles
return self.rotate_particles(rot_matrix=rot_matrix, inplace=inplace)
[docs]
def get_weighted_attr(self, attr, weights, axis=None):
"""Get a weighted attribute.
This will compute the weighted average of an attribute using the
provided weights.
Args:
attr (str):
The attribute to weight.
weights (str/np.ndarray of float):
The weights to apply to the attribute. This can either be a
string to get the attribute from the particle object or an
array-like of the weights.
axis (int):
The axis to compute the weighted attribute along.
Returns:
weighted_attr (float): The weighted attribute.
"""
# Get the attribute
attr_vals = getattr(self, attr)
# If the weights are a string get the attribute
if isinstance(weights, str):
weights_vals = getattr(self, weights)
else:
weights_vals = weights
# Strip units off the weights if they have them, this can confuse
# things
if hasattr(weights_vals, "units"):
weights_vals = weights_vals.value
return np.average(attr_vals, weights=weights_vals, axis=axis)
[docs]
def get_lum_weighted_attr(
self, attr, spectra_type, filter_code, axis=None
):
"""Get a luminosity weighted attribute.
This will compute the luminosity weighted average of an attribute
using the provided weights.
Args:
attr (str):
The attribute to weight.
spectra_type (str):
The type of spectra to use to compute the luminosity.
filter_code (str):
The filter code to compute the luminosity for.
axis (int):
The axis to compute the weighted attribute along.
Returns:
weighted_attr (float):
The luminosity weighted attribute.
"""
# Get the luminosity
lum = self.particle_photo_lnu[spectra_type][filter_code]
return self.get_weighted_attr(attr, lum, axis)
[docs]
def get_flux_weighted_attr(
self, attr, spectra_type, filter_code, axis=None
):
"""Get a flux weighted attribute.
This will compute the flux weighted average of an attribute using the
provided weights.
Args:
attr (str):
The attribute to weight.
spectra_type (str):
The type of spectra to use to compute the flux.
filter_code (str):
The filter code to compute the flux for.
axis (int):
The axis to compute the weighted attribute along.
Returns:
weighted_attr (float): The flux weighted attribute.
"""
# Get the flux
flux = self.particle_photo_fnu[spectra_type][filter_code]
return self.get_weighted_attr(attr, flux, axis)
[docs]
class CoordinateGenerator:
"""A collection of functions for generating random coordinate arrays."""
[docs]
def generate_3D_gaussian(n, mean=np.zeros(3), cov=None):
"""Generate for coordinates from a 3D gaussian distribution.
Args:
n (int):
The number of coordinates to sample.
mean (np.ndarray of float):
The centre of the gaussian distribution. Must be a 3D array
containing the centre along each axis.
cov (np.ndarray of float):
The covariance of the gaussian distribution.
Returns:
coords (np.ndarray of float):
The sampled coordinates in an (n, 3) array.
"""
# If we haven't been passed a covariance make one
if cov is None:
cov = np.zeros((3, 3))
np.fill_diagonal(cov, 1.0)
# Get the coordinates
coords = multivariate_normal(mean, cov, n)
return coords
[docs]
def generate_2D_Sersic(N):
"""Generate a 2D Sersic profile."""
raise exceptions.UnimplementedFunctionality(
"Not yet implemented! Feel free to implement and raise a "
"pull request. Guidance for contributing can be found at "
"https://github.com/synthesizer-project/synthesizer/blob/main/"
"docs/CONTRIBUTING.md"
)
[docs]
def generate_3D_spline(N, kernel_func):
"""Generate a 3D spline profile."""
raise exceptions.UnimplementedFunctionality(
"Not yet implemented! Feel free to implement and raise a "
"pull request. Guidance for contributing can be found at "
"https://github.com/synthesizer-project/synthesizer/blob/main/"
"docs/CONTRIBUTING.md"
)