Source code for synthesizer.parametric.stars

"""A module for creating and manipulating parametric stellar populations.

This is the parametric analog of particle.Stars. It not only computes and holds
the SFZH grid but everything describing a parametric Galaxy's stellar
component.

Example usage::

    stars = Stars(log10ages, metallicities, sfzh=sfzh)
    stars.get_spectra(emission_model)
    stars.plot_spectra()
"""

from copy import deepcopy

import cmasher as cmr
import matplotlib.pyplot as plt
import numpy as np
from unyt import (
    Hz,
    Msun,
    erg,
    nJy,
    s,
    unyt_array,
    unyt_quantity,
    yr,
)

from synthesizer import exceptions
from synthesizer.components.stellar import StarsComponent
from synthesizer.emission_models.utils import get_param
from synthesizer.grid import Grid
from synthesizer.parametric.metal_dist import Common as ZDistCommon
from synthesizer.parametric.sf_hist import Common as SFHCommon
from synthesizer.synth_warnings import warn
from synthesizer.units import Quantity, accepts
from synthesizer.utils.operation_timers import timed
from synthesizer.utils.plt import single_histxy
from synthesizer.utils.stats import weighted_mean, weighted_median


[docs] class Stars(StarsComponent): """The parametric stellar population object. This class holds a binned star formation and metal enrichment history describing the age and metallicity of the stellar population, an optional morphology model describing the distribution of those stars, and various other important attributes for defining a parametric stellar population. Attributes: ages (np.ndarray of float): The array of ages defining the age axis of the SFZH. metallicities (np.ndarray of float): The array of metallicitities defining the metallicity axes of the SFZH. initial_mass (unyt_quantity/float) The total initial stellar mass. This is the total mass of stars formed, i.e. the integral of the SFH over time, and is not the same as the surviving mass which accounts for stellar evolution. surviving_mass (unyt_quantity/float): The total surviving stellar mass. This is the total mass of stars currently alive, i.e. the integral of the SFH over time weighted by the fraction of stars that survive to each age, and is not the same as the initial mass which does not account for stellar evolution. morphology (morphology.* e.g. Sersic2D) An instance of one of the morphology classes describing the stellar population's morphology. This can be any of the family of morphology classes from synthesizer.morphology. sfzh (np.ndarray of float): An array describing the binned SFZH. If provided all following arguments are ignored. sf_hist (np.ndarray of float): An array describing the star formation history. metal_dist (np.ndarray of float): An array describing the metallicity distribution. sf_hist_func (SFH.*) An instance of one of the child classes of SFH. This will be used to calculate sf_hist and takes precedence over a passed sf_hist if both are present. metal_dist_func (ZH.*) An instance of one of the child classes of ZH. This will be used to calculate metal_dist and takes precedence over a passed metal_dist if both are present. instant_sf (float): An age at which to compute an instantaneous SFH, i.e. all stellar mass populating a single SFH bin. instant_metallicity (float): A metallicity at which to compute an instantaneous ZH, i.e. all stellar populating a single ZH bin. log10ages_lims (array_like_float) The log10(age) limits of the SFZH grid. metallicities_lims (np.ndarray of float): The metallicity limits of the SFZH grid. log10metallicities_lims (np.ndarray of float): The log10(metallicity) limits of the SFZH grid. metallicity_grid_type (str): The type of gridding for the metallicity axis. Either: - Regular linear ("Z") - Regular logspace ("log10Z") - Irregular (None) """ # Define quantities initial_mass = Quantity("mass") surviving_mass = Quantity("mass") age_offset = Quantity("time") @accepts( surviving_mass=Msun.in_base("galactic"), initial_mass=Msun.in_base("galactic"), ) @timed("ParametricStars.__init__") def __init__( self, log10ages, metallicities, initial_mass=None, surviving_mass=None, grid=None, morphology=None, sfzh=None, sf_hist=None, metal_dist=None, fesc=None, fesc_ly_alpha=None, **kwargs, ): """Initialise the parametric stellar population. Can either be instantiated by: - Passing a SFZH grid explictly. - Passing instant_sf and instant_metallicity to get an instantaneous SFZH. - Passing functions that describe the SFH and ZH. - Passing arrays that describe the SFH and ZH. - Passing any combination of SFH and ZH instant values, arrays or functions. Args: log10ages (np.ndarray of float): The array of ages defining the log10(age) axis of the SFZH. metallicities (np.ndarray of float): The array of metallicitities defining the metallicity axes of the SFZH. initial_mass (unyt_quantity/float): The total initial stellar mass. If provided the SFZH grid will be rescaled to obey this total mass. surviving_mass (unyt_quantity/float): The total surviving stellar mass. If provided the SFZH grid will be rescaled to obey this total mass. grid (Grid): A synthesizer Grid object. This is only used to provide stellar_fraction when initialising using a surviving mass, and is ignored if surviving_mass is not provided. morphology (morphology.* e.g. Sersic2D): An instance of one of the morphology classes describing the stellar population's morphology. This can be any of the family of morphology classes from synthesizer.morphology. sfzh (np.ndarray of float): An array describing the binned SFZH. If provided all following arguments are ignored. sf_hist (float/unyt_quantity/np.ndarray of float/SFH.*): Either: - An age at which to compute an instantaneous SFH, i.e. all stellar mass populating a single SFH bin. - An array describing the star formation history. - An instance of one of the child classes of SFH. This will be used to calculate an array describing the SFH. metal_dist (float/unyt_quantity/np.ndarray of float/ZDist.*): Either: - A metallicity at which to compute an instantaneous ZH, i.e. all stellar mass populating a single Z bin. - An array describing the metallicity distribution. - An instance of one of the child classes of ZH. This will be used to calculate an array describing the metallicity distribution. fesc (float): The escape fraction of incident radiation from the stars. fesc_ly_alpha (float): The escape fraction of Ly-alpha radiation from the stars. **kwargs (dict): Arbitrary keyword arguments to be set as attributes on the Stars instance. """ # Instantiate the parent StarsComponent.__init__( self, 10**log10ages * yr, metallicities, _star_type="parametric", fesc=fesc, fesc_ly_alpha=fesc_ly_alpha, **kwargs, ) # Set the age grid lims self.log10ages_lims = [self.log10ages[0], self.log10ages[-1]] # Set the metallicity grid lims self.metallicities_lims = [ self.metallicities[0], self.metallicities[-1], ] self.log10metallicities_lims = [ self.log10metallicities[0], self.log10metallicities[-1], ] # Store the SFH we've been given, this is either... if issubclass(type(sf_hist), SFHCommon): self.sf_hist_func = sf_hist # a SFH function self.sf_hist = None self._instant_sf = None elif isinstance(sf_hist, (unyt_quantity, float)): self._instant_sf = sf_hist # an instantaneous SFH self.sf_hist_func = None self.sf_hist = None elif isinstance(sf_hist, (unyt_array, np.ndarray)): self.sf_hist = sf_hist # a numpy array self.sf_hist_func = None self._instant_sf = None elif sf_hist is None: self.sf_hist = None # we must have been passed a SFZH self.sf_hist_func = None self._instant_sf = None else: raise exceptions.InconsistentArguments( f"Unrecognised sf_hist type ({type(sf_hist)}! This should be" " either a float, an instance of a SFH function from the " "SFH module, or a single float." ) # Store the metallicity distribution we've been given, either... if issubclass(type(metal_dist), ZDistCommon): self.metal_dist_func = metal_dist # a ZDist function self.metal_dist = None self._instant_metallicity = None elif isinstance(metal_dist, (unyt_quantity, float, np.floating)): self._instant_metallicity = metal_dist # an instantaneous SFH self.metal_dist_func = None self.metal_dist = None elif isinstance(metal_dist, (unyt_array, np.ndarray)): self.metal_dist = metal_dist # a numpy array self.metal_dist_func = None self._instant_metallicity = None elif metal_dist is None: self.metal_dist = None # we must have been passed a SFZH self.metal_dist_func = None self._instant_metallicity = None else: raise exceptions.InconsistentArguments( f"Unrecognised metal_dist type ({type(metal_dist)}! This " "should be either a float, an instance of a ZDist function " "from the ZDist module, or a single float." ) # Store the total initial stellar mass self.initial_mass = initial_mass self.surviving_mass = surviving_mass # Raise exception if both initial mass and surviving mass are # provided, this is not physically consistent and we don't want to # guess which one the user meant to provide if self.surviving_mass is not None and self.initial_mass is not None: raise exceptions.InconsistentArguments( "Cannot specify both initial_mass and surviving_mass! Please" " specify only one of these or neither." ) # Raise exception if surviving mass is provided but no grid is # provided, we need the stellar fraction from the grid to rescale # the SFZH to obey the surviving mass if self.surviving_mass is not None and grid is None: raise exceptions.InconsistentArguments( "If surviving_mass is specified then a Grid object must be " "provided to get the stellar_fraction for rescaling the SFZH!" ) # Raise exception if we have been given the surviving mass and grid # but that grid doesn't have a stellar_fraction attribute if self.surviving_mass is not None and grid is not None: if not hasattr(grid, "stellar_fraction"): raise exceptions.InconsistentArguments( "If surviving_mass is specified then a Grid object with a" "stellar_fraction attribute must be provided to rescale" "the SFZH!" ) # Get the stellar fraction from the grid if we have been given a # surviving mass, this is needed to rescale the SFZH to obey the # surviving mass constraint. This is the fraction of the initial mass # that survives to the present day, and is used to calculate the # initial mass from the surviving mass. if self.surviving_mass is not None and grid is not None: self.stellar_fraction = grid.stellar_fraction # If we have been handed an explict SFZH grid we can ignore all the # calculation methods if sfzh is not None: # Store the SFZH grid self.sfzh = sfzh else: # Compute the SFZH grid self.sfzh = self._get_sfzh() # Check the SFZH grid doesn't contain any NaN or Inf values, this can # happen if the SFH or ZH functions return NaN or Inf values for some # reason, and this will cause all kinds of problems downstream if we # don't catch it here. if np.any(~np.isfinite(self.sfzh)): raise exceptions.InconsistentArguments( "SFZH grid contains NaN or Inf values! " "Please check the input parameters." ) # We can't normalise an SFZH with no mass on the grid (e.g. an SFH # or ZDist peaking far outside the axes), doing so would silently # make it NaN if ( self.surviving_mass is not None or self.initial_mass is not None ) and np.sum(self.sfzh) <= 0: raise exceptions.InconsistentArguments( "The SFH and metallicity distribution put no mass on the " "age and metallicity axes, so the SFZH can't be normalised. " "Please check the input parameters." ) # Normalise the SFZH grid if needs be, and calculate the initial mass # if we have been given a surviving mass. If we have been given an # initial mass we just need to rescale the SFZH grid to obey this # constraint, and if we have been given neither then we can just sum # the SFZH grid to get the total initial mass. if self.surviving_mass is not None: current_surviving_mass = np.sum(self.sfzh * self.stellar_fraction) self.sfzh_normalisation = ( self._surviving_mass / current_surviving_mass ) self.sfzh *= self.sfzh_normalisation # now calculate the initial mass self.initial_mass = np.sum(self.sfzh) * Msun elif self.initial_mass is not None: self.sfzh_normalisation = self._initial_mass / np.sum(self.sfzh) self.sfzh *= self.sfzh_normalisation else: # Otherwise calculate the total initial mass by just summing the # SFZH grid self.initial_mass = np.sum(self.sfzh) * Msun # Ensure sf_hist and metal_dist reflect the rescaled sfzh self.sf_hist = np.sum(self.sfzh, axis=1) self.metal_dist = np.sum(self.sfzh, axis=0) # Attach the morphology model self.morphology = morphology # Check if metallicities are uniformly binned in log10metallicity or # linear metallicity or not at all (e.g. BPASS) if ( len(np.unique(self.metallicities[:-1] - self.metallicities[1:])) == 1 ): # Regular linearly self.metallicity_grid_type = "Z" elif ( len( np.unique( self.log10metallicities[:-1] - self.log10metallicities[1:] ) ) == 1 ): # Regular in logspace self.metallicity_grid_type = "log10Z" else: # Irregular self.metallicity_grid_type = None @timed("ParametricStars._create_sfzh") def _get_sfzh(self, age_offset=None): """Compute the SFZH for all possible combinations of input. If functions are passed for sf_hist_func and metal_dist_func then the SFH and ZH arrays are computed first. Args: age_offset (unyt_quantity): The offset to apply to the age grid when calculating the SFZH """ # Hide imports to avoid cyclic imports from synthesizer.particle import Stars as ParticleStars # If no units assume unit system if self._instant_sf is not None and not isinstance( self._instant_sf, unyt_quantity ): self._instant_sf *= self.ages.units # If arrays are passed for the SFH and ZH we can just use those if self.sf_hist is not None and self.metal_dist is not None: sf_hist = self.sf_hist metal_dist = self.metal_dist else: sf_hist = None metal_dist = None # If we have been given an age offset then we need to reset the # sf_hist and metal_dist to None so that they are recalculated if age_offset is not None: sf_hist = None metal_dist = None else: age_offset = 0.0 * yr # A delta function for metallicity is a special case # equivalent to instant_metallicity = metal_dist_func.metallicity if self.metal_dist_func is not None: if self.metal_dist_func.name == "DeltaConstant": self._instant_metallicity = ( self.metal_dist_func.get_metallicity() ) # If both are instantaneous then we can do the whole SFZH in one go if ( self._instant_sf is not None and self._instant_metallicity is not None ): inst_stars = ParticleStars( # We can just use a single star with mass 1 Msun here, the # normalisation will be applied later based on the initial # mass or surviving mass if provided, or the total mass of # the SFZH grid otherwise initial_masses=np.array([1.0]) * Msun, ages=np.array( [ self._instant_sf.to("yr").value + age_offset.to("yr").value ] ) * yr, metallicities=np.array([self._instant_metallicity]), ) # Compute the SFZH grid in one go, this will be a delta function # in both age and metallicity so will just populate a single bin # but this is the most straightforward way to do it sfzh = inst_stars.get_sfzh( self.log10ages, self.metallicities, grid_assignment_method="cic", ).sfzh # Project the SFZH to get the 1D SFH and ZH, this is a bit # redundant but it means we can use the same code for all # the different cases downstream sf_hist = np.sum(sfzh, axis=1) metal_dist = np.sum(sfzh, axis=0) # Since we are not normalising the things here we can just # return the SFZH, SFH and ZH at this point and skip the # rest of the code which is really just for normalisation and # checking consistency of the SFH and ZH arrays with the SFZH grid. return sfzh # Handle the instantaneous SFH case elif ( self._instant_sf is not None and self._instant_metallicity is None ): inst_stars = ParticleStars( # We can just use a single star with mass 1 Msun here, the # normalisation will be applied later based on the initial # mass or surviving mass if provided, or the total mass of # the SFZH grid otherwise initial_masses=np.array([1.0]) * Msun, ages=np.array( [ self._instant_sf.to("yr").value + age_offset.to("yr").value ] ) * yr, metallicities=np.array([0]), # this is a dummy value ) # Create SFH array sf_hist = inst_stars.get_sfh(self.log10ages) # Handle the instantaneous ZH case elif ( self._instant_metallicity is not None and self._instant_sf is None ): inst_stars = ParticleStars( # We can just use a single star with mass 1 Msun here, the # normalisation will be applied later based on the initial # mass or surviving mass if provided, or the total mass of # the SFZH grid otherwise initial_masses=np.array([1.0]) * Msun, ages=np.array([0.0]) * yr, # this is a dummy value metallicities=np.array([self._instant_metallicity]), ) # Create metal distribution array metal_dist = inst_stars.get_metal_dist(self.metallicities) # Calculate SFH from function if necessary if self.sf_hist_func is not None and sf_hist is None: # Get the mass in each age bin from the SFH's CDF, the bin edges # are the midpoints between grid ages and the oldest bin extends # up to the oldest grid age ages = self.ages.to("yr").value age_edges = np.concatenate( ([0.0], 0.5 * (ages[1:] + ages[:-1]), [ages[-1]]) ) sf_hist = self.sf_hist_func.get_bin_masses( age_edges + age_offset.to("yr").value ) # Calculate ZH from function if necessary if self.metal_dist_func is not None and metal_dist is None: # Get the mass in each metallicity bin from the ZDist's CDF, the # bin edges are the midpoints between grid metallicities and the # most metal rich bin extends up to the highest grid metallicity metals = np.asarray(self.metallicities, dtype=np.float64) metal_edges = np.concatenate( ([0.0], 0.5 * (metals[1:] + metals[:-1]), [metals[-1]]) ) metal_dist = self.metal_dist_func.get_bin_weights(metal_edges) # Ensure that by this point we have an array for SFH and ZH if sf_hist is None or metal_dist is None: raise exceptions.InconsistentArguments( "A method for defining both the SFH and ZH must be provided!\n" "For each either an instantaneous" " value, a SFH/ZH object, or an array must be passed" ) # Finally, calculate the SFZH grid based on the above calculations return sf_hist[:, np.newaxis] * metal_dist def _get_normalised_sfzh(self, age_offset): """Get the correctly mass-scaled SFZH grid at an earlier lookback time. If this object has a SFZH constructed from continuous functions the shape is re-integrated exactly and scaled by the precomputed normalisation. If continuous functions are not available, assume each age bin is uniformly populated and remap the retained mass onto the shifted age grid. Resolution is limited to the object's existing age bins in this case and the two approaches will deviate. Args: age_offset (unyt_quantity): The offset to apply to the age grid when calculating the SFZH. Returns: sfzh (np.ndarray): The SFZH grid at the earlier lookback time. """ # Re-integrate the SFZH over the shifted age bins if it is # function based. if self.sf_hist_func is not None and self.metal_dist_func is not None: sfzh = self._get_sfzh(age_offset=age_offset) if getattr(self, "sfzh_normalisation", None) is not None: sfzh = sfzh * self.sfzh_normalisation # Otherwise, remap the existing SFZH onto the shifted age bins. else: # Construct linear age bins. self.ages.convert_to_units("yr") ages = self.ages.ndview age_edges = np.empty(len(ages) + 1) age_edges[0] = 0.0 age_edges[1:-1] = 0.5 * (ages[1:] + ages[:-1]) age_edges[-1] = ages[-1] offset = age_offset.to("yr").value sfzh = np.zeros_like(self.sfzh) # Loop over each bin in the original SFZH. for source_index in range(len(ages)): source_start = age_edges[source_index] source_end = age_edges[source_index + 1] source_width = source_end - source_start # Bins entirely younger than age_offset will not contribute. if source_end <= offset: continue # Shift the bin by age_offset. retained_start = max(source_start, offset) shifted_start = retained_start - offset shifted_end = source_end - offset # Loop over each bin in the new SFZH and compute the # overlap with the shifted source bin. for destination_index in range(len(ages)): destination_start = age_edges[destination_index] destination_end = age_edges[destination_index + 1] overlap_start = max(shifted_start, destination_start) overlap_end = min(shifted_end, destination_end) overlap_width = max(0, overlap_end - overlap_start) # If there is overlap, add the appropriate fraction # of the SFZH. if overlap_width > 0: sfzh[destination_index] += ( self.sfzh[source_index] * overlap_width / source_width ) return sfzh
[docs] @accepts(age_offset=yr) def get_at_earlier_time(self, age_offset): """Get a Stars object representing the population at an earlier time. Apply an age_offset to the SFZH age grid and use the precomputed normalisation to so the new Stars object will have the correct total masses. Args: age_offset (unyt_quantity): The offset to apply to the age grid. Returns: Stars: New Stars object on the requested grid. """ # Simply get the normalised SFZH at the earlier time and use it # to construct a new Stars object. sfzh = self._get_normalised_sfzh(age_offset) return Stars(self.log10ages, self.metallicities, sfzh=sfzh)
[docs] @timed("Stars.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 = get_param(attr, attr_override_obj, None, self) # Resolve a string threshold as an attribute alias on the emitter if isinstance(thresh, str): thresh = get_param(thresh, attr_override_obj, None, self) # 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}" ) # Broadcast the mask to get a mask for SFZH bins if new_mask.size == self.sfzh.shape[0]: new_mask = np.outer( new_mask, np.ones(self.sfzh.shape[1], dtype=bool) ) elif new_mask.size == self.sfzh.shape[1]: new_mask = np.outer( np.ones(self.sfzh.shape[0], dtype=bool), new_mask ) elif new_mask.shape == self.sfzh.shape: pass # nothing to do here else: raise exceptions.InconsistentArguments( "Masking array must be the same shape as the SFZH grid " f"or an axis (mask.shape={new_mask.shape}, " f"sfzh.shape={self.sfzh.shape})" ) # Combine with the existing mask if mask is not None: if mask.shape == new_mask.shape: new_mask = np.logical_and(new_mask, mask) else: raise exceptions.InconsistentArguments( "Masking array must be the same shape as the SFZH grid " f"or an axis (mask.shape={new_mask.shape}, " f"sfzh.shape={self.sfzh.shape})" ) return new_mask
[docs] def calculate_median_age(self): """Calculate the median age of the stellar population.""" return weighted_median(self.ages, self.sf_hist) * self.ages.units
[docs] def calculate_mean_age(self): """Calculate the mean age of the stellar population.""" return weighted_mean(self.ages, self.sf_hist)
[docs] def calculate_mean_metallicity(self): """Calculate the mean metallicity of the stellar population.""" return weighted_mean(self.metallicities, self.metal_dist)
def __add__(self, other_stars): """Add two Stars instances together. In simple terms this sums the SFZH grids of both Stars instances. This will only work for Stars objects with the same SFZH grid axes. Args: other_stars (parametric.Stars): The other instance of Stars to add to this one. """ if np.all(self.log10ages == other_stars.log10ages) and np.all( self.metallicities == other_stars.metallicities ): new_sfzh = self.sfzh + other_stars.sfzh else: raise exceptions.InconsistentAddition( "SFZH must be the same shape" ) # Carry over the attributes both populations share. Differing values # can't be combined into a single population so they are dropped. shared = {} for name in ("fesc", "fesc_ly_alpha", "morphology"): this = getattr(self, name, None) other = getattr(other_stars, name, None) if this is other or (name != "morphology" and this == other): shared[name] = this else: warn( f"The added Stars have different {name} values, " f"the combined Stars will use the default {name}." ) return Stars( self.log10ages, self.metallicities, sfzh=new_sfzh, **shared, ) def __radd__(self, other_stars): """Add two Stars instances together (reflected addition). Overloads "reflected" addition to allow two Stars instances to be added together when in reverse order, i.e. second_stars + self. This will only work for Stars objects with the same SFZH grid axes. Args: other_stars (parametric.Stars): The other instance of Stars to add to this one. """ return self.__add__(other_stars)
[docs] @accepts(lum=erg / s / Hz) def scale_mass_by_luminosity(self, lum, scale_filter, spectra_type): """Scale the stellar mass to match a luminosity in a specific filter. NOTE: This will overwrite the initial mass attribute. Args: lum (unyt_quantity): The desired luminosity in scale_filter. scale_filter (Filter): The filter in which lum is measured. spectra_type (str): The spectra key with which to do this scaling, e.g. "incident" or "emergent". Raises: MissingSpectraType If the requested spectra doesn't exist an error is thrown. """ # Check we have the spectra if spectra_type not in self.spectra: raise exceptions.MissingSpectraType( f"The requested spectra type ({spectra_type}) does not exist" " in this stellar population. Have you called the " "corresponding spectra method?" ) # Calculate the current luminosity in scale_filter sed = self.spectra[spectra_type] current_lum = ( scale_filter.apply_filter(sed.lnu, nu=sed.nu) * sed.lnu.units ) # Calculate the conversion ratio between the requested and current # luminosity conversion = lum / current_lum # Apply conversion to the masses self._initial_mass *= conversion # Apply the conversion to all spectra for key in self.spectra: self.spectra[key]._lnu *= conversion if self.spectra[key]._fnu is not None: self.spectra[key]._fnu *= conversion # Apply correction to the SFZH self.sfzh *= conversion # Ensure sf_hist and metal_dist reflect the rescaled sfzh self.sf_hist = np.sum(self.sfzh, axis=1) self.metal_dist = np.sum(self.sfzh, axis=0)
[docs] @accepts(flux=nJy) def scale_mass_by_flux(self, flux, scale_filter, spectra_type): """Scale the stellar mass to match a flux in a specific filter. NOTE: This will overwrite the initial mass attribute. Args: flux (unyt_quantity): The desired flux in scale_filter. scale_filter (Filter): The filter in which flux is measured. spectra_type (str): The spectra key with which to do this scaling, e.g. "incident" or "emergent". Raises: MissingSpectraType If the requested spectra doesn't exist an error is thrown. """ # Check we have the spectra if spectra_type not in self.spectra: raise exceptions.MissingSpectraType( f"The requested spectra type ({spectra_type}) does not exist" " in this stellar population. Have you called the " "corresponding spectra method?" ) # Get the sed object sed = self.spectra[spectra_type] # Ensure we have a flux if sed.fnu is None: raise exceptions.MissingSpectraType( "{spectra_type} does not have a flux! Make sure to" " run Sed.get_fnu or Galaxy.get_observed_spectra" ) # Calculate the current flux in scale_filter current_flux = ( scale_filter.apply_filter(sed.fnu, nu=sed.obsnu) * sed.fnu.units ) # Calculate the conversion ratio between the requested and current # flux conversion = flux / current_flux # Apply conversion to the masses self._initial_mass *= conversion # Apply the conversion to all spectra for key in self.spectra: self.spectra[key]._lnu *= conversion if self.spectra[key]._fnu is not None: self.spectra[key]._fnu *= conversion # Apply correction to the SFZH self.sfzh *= conversion # Ensure sf_hist and metal_dist reflect the rescaled sfzh self.sf_hist = np.sum(self.sfzh, axis=1) self.metal_dist = np.sum(self.sfzh, axis=0)
[docs] @timed("ParametricStars.get_sfzh") def get_sfzh( self, log10ages, metallicities, grid_assignment_method="cic", nthreads=0, ): """Get the binned SFZH at the provided axes. This method remaps the parametric SFZH onto a new grid defined by log10ages and metallicities. To do so, it first goes through a particle Stars object to perform the remapping using a conservative remap. TODO: Along with spectra generation, this should be improved going forward to use a "cookie cutter" approach based on the bins overlaid on the existing grid. Args: log10ages (np.ndarray of float): The log10 ages of the desired SFZH (bin centers, strictly monotonic). metallicities (np.ndarray of float): The metallicities of the desired SFZH (bin centers, strictly monotonic). grid_assignment_method (str): The grid assignment method to use when remapping from the particle Stars to the parametric Stars. Options are: - "cic": Cloud-in-cell assignment. - "ngp": Nearest grid point assignment. nthreads (int): The number of threads to use for the remapping. If -1 all available threads are used. Returns: Stars: New Stars object on the requested grid. """ # If the axes are the same as our existing ones just return our SFZH # (the lengths must be checked first since allclose broadcasts) if ( len(log10ages) == len(self.log10ages) and len(metallicities) == len(self.metallicities) and np.allclose(log10ages, self.log10ages) and np.allclose(metallicities, self.metallicities) ): return deepcopy(self) # Avoid cyclic imports from synthesizer.particle import Stars as ParticleStars # OK, we have different grids so we need to remap. For now, the best # way to do this is use a particle Stars object to do the remapping # for us initial_masses = self.sfzh.flatten() * Msun ages, metals = np.meshgrid( self.ages, self.metallicities, indexing="ij", ) part_stars = ParticleStars( initial_masses=initial_masses, ages=ages.flatten(), metallicities=metals.flatten(), ) return part_stars.get_sfzh( log10ages, metallicities, grid_assignment_method=grid_assignment_method, nthreads=nthreads, )
[docs] def plot_sfzh( self, show=True, ): """Plot the binned SZFH. Args: show (bool): Should we invoke plt.show()? Returns: fig The Figure object contain the plot axes. ax The Axes object containing the plotted data. """ # Create the figure and extra axes for histograms fig, ax, haxx, haxy = single_histxy() # Visulise the SFZH grid ax.pcolormesh( self.log10ages, self.log10metallicities, self.sfzh.T, cmap=cmr.sunburst, ) # Add binned Z to right of the plot metal_dist = np.sum(self.sfzh, axis=0) haxy.fill_betweenx( self.log10metallicities, metal_dist / np.max(metal_dist), step="mid", color="k", alpha=0.3, ) # Add binned SF_HIST to top of the plot sf_hist = np.sum(self.sfzh, axis=1) haxx.fill_between( self.log10ages, sf_hist / np.max(sf_hist), step="mid", color="k", alpha=0.3, ) # Set plot limits haxy.set_xlim([0.0, 1.2]) haxy.set_ylim(self.log10metallicities[0], self.log10metallicities[-1]) haxx.set_ylim([0.0, 1.2]) haxx.set_xlim(self.log10ages[0], self.log10ages[-1]) # Set labels ax.set_xlabel(r"$\log_{10}(\mathrm{age}/\mathrm{yr})$") ax.set_ylabel(r"$\log_{10}(Z)$") # Set the limits so all axes line up ax.set_ylim(self.log10metallicities[0], self.log10metallicities[-1]) ax.set_xlim(self.log10ages[0], self.log10ages[-1]) # Shall we show it? if show: plt.show() return fig, ax
[docs] def get_sfh(self): """Get the star formation history of the stellar population. Returns: unyt_array: The star formation history of the stellar population. """ return self.sf_hist
@property def sfh(self): """Alias for get_sfh.""" return self.get_sfh()
[docs] def plot_sfh( self, xlimits=(), ylimits=(), show=True, ): """Plot the star formation history of the stellar population. Args: xlimits (tuple): The limits of the x-axis. ylimits (tuple): The limits of the y-axis. show (bool): Should we invoke plt.show()? Returns: fig The Figure object contain the plot axes. ax The Axes object containing the plotted data. """ fig, ax = plt.subplots() ax.semilogy() ax.step(self.log10ages, self.sf_hist, where="mid", color="blue") ax.fill_between( self.log10ages, self.sf_hist, step="mid", color="blue", alpha=0.5, ) ax.set_xlabel(r"$\log_{10}(\mathrm{age}/\mathrm{yr})$") ax.set_ylabel(r"SFH / M$_\odot$") if show: plt.show() return fig, ax
[docs] def get_metal_dist(self): """Get the metallicity distribution of the stellar population. Returns: unyt_array: The metallicity distribution of the stellar population. """ return self.metal_dist
[docs] def plot_metal_dist( self, xlimits=(), ylimits=(), show=True, ): """Plot the metallicity distribution of the stellar population. Args: xlimits (tuple): The limits of the x-axis. ylimits (tuple): The limits of the y-axis. show (bool): Should we invoke plt.show()? Returns: fig The Figure object contain the plot axes. ax The Axes object containing the plotted data. """ fig, ax = plt.subplots() ax.semilogy() ax.step(self.metallicities, self.metal_dist, where="mid", color="red") ax.fill_between( self.metallicities, self.metal_dist, step="mid", color="red", alpha=0.5, ) ax.set_xlabel(r"$Z$") ax.set_ylabel(r"Z_D / M$_\odot$") # Apply limits if provided if len(ylimits) > 0: ax.set_ylim(ylimits) if len(xlimits) > 0: ax.set_xlim(xlimits) if show: plt.show() return fig, ax
[docs] def get_weighted_attr(self, attr): """Get a weighted attribute of the stellar population. Args: attr (str): The attribute to get. Returns: unyt_quantity: The weighted attribute. """ # For now we need to raise an error if this is not an axis of the # SFZH grid if "age" not in attr and "metal" not in attr: raise exceptions.InconsistentArguments( "The attribute must be an axis of the SFZH grid" ) # Get the attribute and the weights if "age" in attr: weight = self.sf_hist else: weight = self.metal_dist attr = getattr(self, attr) return weighted_mean(attr, weight)
[docs] def calculate_average_sfr(self, t_range: tuple = (0, 1e8)): """Calculate the average SFR over a given age range. This method assumes that stars form at discrete time points given by `self.ages`, with the mass in `self.get_sfh()`. To calculate a continuous rate, it treats this mass as having formed uniformly in bins constructed around each age point. Args: t_range (tuple[float, float]): The lookback age limits (t_start, t_end) in years over which to calculate the average SFR. Returns: unyt_quantity: The average SFR over the specified time range in Msun/yr. """ # --- Input Validation and Setup --- sfh_mass = np.asarray(self.get_sfh()) age_points = np.asarray(self.ages) if sfh_mass.size != age_points.size: raise ValueError( "Mass array and age points array must have the same size." ) if age_points.size == 0: return unyt_quantity(0, units="Msun/yr") # Support unyt quantities in t_range t_start, t_end = t_range if hasattr(t_start, "to"): t_start = t_start.to("yr").value if hasattr(t_end, "to"): t_end = t_end.to("yr").value # Ensure consistent ordering order = np.argsort(age_points) age_points = age_points[order] sfh_mass = sfh_mass[order] if t_start >= t_end: raise ValueError("Start of t_range must be less than its end.") # --- Construct Bins from Age Points --- if age_points.size == 1: # For a single point, the bin runs from 0 up to that age, # matching the bin used when integrating the SFZH. age_edges = np.array([0, age_points[0]]) else: # Bin edges are the midpoints between age points. internal_edges = (age_points[:-1] + age_points[1:]) / 2.0 # Extrapolate the first edge to define the lower bound, the last # edge is the oldest age, matching the bin used when integrating # the SFZH. first_edge = age_points[0] - (age_points[1] - age_points[0]) / 2.0 last_edge = age_points[-1] age_edges = np.concatenate( ([first_edge], internal_edges, [last_edge]) ) # Ensure the first edge isn't negative for lookback time. age_edges[0] = max(0, age_edges[0]) bin_starts = age_edges[:-1] bin_ends = age_edges[1:] bin_widths = bin_ends - bin_starts rates = np.divide( sfh_mass, bin_widths, out=np.zeros_like(sfh_mass, dtype=float), where=(bin_widths > 0), ) overlap_starts = np.maximum(bin_starts, t_start) overlap_ends = np.minimum(bin_ends, t_end) overlap_durations = np.maximum(0, overlap_ends - overlap_starts) total_mass_in_range = np.sum(rates * overlap_durations) * Msun range_duration = (t_end - t_start) * yr average_sfr = total_mass_in_range / range_duration return average_sfr.to("Msun/yr")
[docs] def calculate_surviving_sfzh(self, grid: Grid): """Calculate the surviving SFZH of the stellar population. This is the distribution of surviving stars in age and metallicity given the star formation and metal enrichment history. Args: grid (Grid): The grid to use for calculating the surviving SFZH. This is used to get the stellar fraction at each SFZH bin. Returns: np.ndarray: The surviving SFZH grid in Msun. """ surviving_sfzh = self.sfzh * grid.stellar_fraction return surviving_sfzh
[docs] def calculate_surviving_sfh(self, grid: Grid): """Calculate the surviving SFH of the stellar population. This is the distribution of surviving stars in age. Args: grid (Grid): The grid to use for calculating the surviving SFH. This is used to get the stellar fraction at each SFH bin. Returns: np.ndarray: The surviving SFH grid in Msun. """ surviving_sfh = np.sum(self.calculate_surviving_sfzh(grid), axis=1) return surviving_sfh
[docs] def calculate_surviving_mass(self, grid: Grid): """Calculate the surviving mass of the stellar population. This is the total mass of stars that have survived to the present day given the star formation and metal enrichment history. Args: grid (Grid): The grid to use for calculating the surviving mass. This is used to get the stellar fraction at each SFZH bin. Returns: unyt_quantity: The total surviving mass of the stellar population in Msun. """ surviving_mass = np.sum(self.calculate_surviving_sfzh(grid)) return surviving_mass * Msun
[docs] def get_ionising_photon_luminosity( self, grid: Grid, ion: str = "HI", ) -> float: """Calculate the ionising photon luminosity from the grid. Args: grid (object, Grid): The SPS Grid object from which to extract spectra. ion (str): The ion for which to calculate the ionising photon luminosity. Must be a recognised ion in the grid's log10_specific_ionising_lum dictionary. Returns: The ionising photon luminosity summed over the grid dimensions. """ if ion not in grid.log10_specific_ionising_lum: raise exceptions.MissingGridProperty( f"The provided grid does not contain {ion} " "ionising luminosities" ) return np.sum( 10 ** grid.log10_specific_ionising_lum[ion] * self.sfzh, axis=(0, 1), )
[docs] @accepts(age=yr) def calculate_initial_mass_at_age(self, age): """Calculate the initial mass of the stellar population at a given age. This is the total mass of stars formed that are older than the specified age. Args: age (float or unyt_quantity): The age at which to calculate the initial mass. This can be a float in years or a unyt quantity with time units. Returns: unyt_quantity: The total initial mass formed prior to this age. """ # Calculate the normalised SFZH grid and return the total mass. sfzh = self._get_normalised_sfzh(age) return np.sum(sfzh) * Msun
[docs] @accepts(age=yr) def calculate_surviving_mass_at_age(self, age, grid: Grid): """Calculate the surviving mass at a given age. This is the mass of stars older than the specified age that are surviving at the specified lookback time. Args: age (float or unyt_quantity): The age at which to calculate the surviving mass. This can be a float in years or a unyt quantity with time units. grid (Grid): The grid to use for calculating the surviving mass. This is used to get the stellar fraction at each SFZH bin. Returns: unyt_quantity: The surviving mass formed prior to this age. """ # Calculate the normalised SFZH grid and return the total # surviving mass. sfzh = self._get_normalised_sfzh(age) return np.sum(sfzh * grid.stellar_fraction) * Msun