Source code for synthesizer.emission_models.generators.dust.greybody

"""A submodule defining greybody dust emission generators."""

from __future__ import annotations

from typing import TYPE_CHECKING, Optional

import numpy as np
from unyt import (
    Hz,
    angstrom,
    c,
    erg,
    s,
    um,
    unyt_array,
    unyt_quantity,
)

from synthesizer import exceptions
from synthesizer.emission_models.base_model import EmissionModel
from synthesizer.emission_models.generators.dust.dust_emission_base import (
    DustEmission,
    integrate_over_all_frequencies,
    optically_thin_luminosity,
)
from synthesizer.emissions import LineCollection, Sed
from synthesizer.units import accepts
from synthesizer.utils import planck
from synthesizer.utils.operation_timers import timed
from synthesizer.utils.precision import verify_out_precision

if TYPE_CHECKING:
    from synthesizer.components.component import Component


[docs] class Greybody(DustEmission): """A class to generate a greybody emission spectrum. This can be used to generate standalone normalised greybody spectra, or it can be used to generate scaled greybody spectra by providing either a scaler EmissionModel or an intrinsic/attenuated EmissionModel pair to scale the greybody spectrum accordingly. For more details see the base DustEmission parent class. Attributes: temperature (unyt_quantity): The temperature of the greybody. emissivity (float): The emissivity of the dust (dimensionless). optically_thin (bool): If dust is optically thin? lam_0 (unyt_quantity): Wavelength (in um) where the dust optical depth is unity. temperature and emissivity are optional. A value set on the generator is a fixed override that takes priority over any value on the emitter (only an EmissionModel's fixed_parameters take priority over it). If left as None they are read from the emitter. """ temperature: Optional[unyt_quantity] emissivity: Optional[float] optically_thin: bool lam_0: unyt_quantity def __init__( self, temperature: Optional[unyt_quantity] = None, emissivity: Optional[float] = None, optically_thin: bool = True, lam_0: unyt_quantity = 100.0 * um, do_cmb_heating: bool = False, intrinsic: Optional[EmissionModel] = None, attenuated: Optional[EmissionModel] = None, scaler: Optional[EmissionModel] = None, ) -> None: """Initialise the greybody base class. Args: temperature (unyt_quantity, optional): The temperature of the greybody. If given, this overrides any temperature on the emitter. If None, it is read from the emitter. emissivity (float, optional): The emissivity of the dust (dimensionless) [good value = 1.5]. If given, this overrides any emissivity on the emitter. If None, it is read from the emitter. optically_thin (bool): If dust is optically thin lam_0 (unyt_quantity): Wavelength (in um) where the dust optical depth is unity do_cmb_heating (bool): Should we apply cmb heating? intrinsic (EmissionModel): The name of the intrinsic emission defining the unattenuated emission for energy balance. attenuated (EmissionModel): The name of the attenuated emission defining the attenuated emission for energy balance. scaler (EmissionModel): The name of the emission to use to scale the dust emission by. """ self.temperature = temperature self.emissivity = emissivity self.optically_thin = optically_thin self.lam_0 = lam_0 DustEmission.__init__( self, intrinsic, attenuated, scaler, do_cmb_heating, required_params=("temperature", "emissivity"), ) def __repr__(self): """Return a string representation of the Greybody object.""" # Start with base class repr components parts = [] if self.is_energy_balance: parts.append( f"intrinsic={self._intrinsic.label}, " f"attenuated={self._attenuated.label}" ) elif self.is_scaled: parts.append(f"scaler={self._scaler.label}") # Add Greybody specific parameters parts.extend( [ f"temperature={self.temperature}", f"emissivity={self.emissivity}", f"optically_thin={self.optically_thin}", f"lam_0={self.lam_0}", ] ) # Add CMB heating if enabled if self.do_cmb_heating: parts.append("do_cmb_heating=True") return f"Greybody({', '.join(parts)})" @accepts(nu=Hz) def _lnu( self, nu: unyt_array, temperature: unyt_quantity, emissivity: float, ) -> unyt_array: """Generate unnormalised spectrum for given frequency (nu) grid. All model parameters are passed in explicitly (they have already been resolved from the model, generator and emitter by the caller), so the generator holds no per-call state. Args: nu (unyt_array): The frequencies at which to calculate the spectral luminosity density. temperature (unyt_quantity): The temperature to use for the greybody. emissivity (float): The emissivity to use for the greybody. Returns: lnu (unyt_array): The unnormalised spectral luminosity density. """ if self.optically_thin: return (nu / Hz) ** emissivity * planck(nu, temperature) else: _nu_0 = c / self.lam_0 optically_thick_factor = 1 - np.exp(-((nu / _nu_0) ** emissivity)) return optically_thick_factor * planck(nu, temperature) def _bolometric_luminosity( self, temperature: unyt_quantity, emissivity: float, ) -> float: """Return the integral of the unnormalised spectrum over all nu. Args: temperature (unyt_quantity): The temperature to use for the greybody. emissivity (float): The emissivity to use for the greybody. Returns: float: The bolometric luminosity in the luminosity unit of Sed.bolometric_luminosity. """ if self.optically_thin: return optically_thin_luminosity(temperature, emissivity) return integrate_over_all_frequencies( lambda nu: self._lnu(nu, temperature, emissivity), temperature ) @accepts(lams=angstrom) @timed("Greybody._generate_spectra") @verify_out_precision() def _generate_spectra( self, lams: unyt_array, emitter: Component, model: EmissionModel, emissions: dict, redshift: float = 0, out_dtype=None, ) -> Sed: """Generate the dust emission spectra. Note that the temperature and emissivity here will be extracted using this priority order: 1. From the EmissionModels fixed parameters 2. From the Greybody object itself (if not None) 3. From the emitter object This is handle internally using the Generator's _extract_params method. Args: lams (unyt_array): The wavelength grid on which to generate the spectra. emitter (Stars/Gas/BlackHole/Galaxy): The object emitting the emission. model (EmissionModel): The emission model generating the emission. emissions (dict): Dictionary containing all emissions generated so far. redshift (float): The redshift at which to calculate the CMB heating. (Ignored if not applying CMB heating). out_dtype (np.dtype): The output precision. Defaults to the global default output dtype. Returns: Sed: The generated dust emission SED. """ # Get the required parameters params = self._extract_params(model, emitter) # Unpack the parameters temperature = params["temperature"] emissivity = params["emissivity"] # Define frequencies nu = (c / lams).to(Hz) # Account for CMB heating cmb_factor, temperature = self.apply_cmb_heating( temperature=temperature, emissivity=emissivity, redshift=redshift, ) # Compute the greybody function lnu = self._lnu(nu, temperature, emissivity) # Create an SED object for convenience sed = Sed(lam=lams, lnu=lnu) # Get the bolometric luminosity over all frequencies bol_lum = self._bolometric_luminosity(temperature, emissivity) # Normalise the greybody spectrum sed._lnu /= bol_lum lnu = sed._lnu # Get the scaling we will need scaling = self.get_scaling(emitter, model, emissions) # Scale the normalised emission, at the output precision sed._lnu = self.get_scaled_emission( lnu, scaling, emitter, model, out_dtype, cmb_factor, ) return sed @accepts(line_lams=angstrom) @verify_out_precision() def _generate_lines( self, line_ids, line_lams, emitter, model, emissions, spectra, redshift=0, out_dtype=None, ) -> LineCollection: """Generate line emission spectra. Greybody emission does not produce line emission, so this method will simply return an empty Sed object. Args: line_ids (list): The IDs of the lines to generate. line_lams (unyt_array): The wavelength grid on which to generate the line spectra. emitter (Stars/Gas/BlackHole/Galaxy): The object emitting the emission. model (EmissionModel): The emission model generating the emission. emissions (dict): Dictionary containing all emissions generated so far. spectra (dict): Dictionary containing all spectra generated so far (used for scaling). redshift (float): The redshift at which to calculate the CMB heating. (Ignored if not applying CMB heating). out_dtype (np.dtype): The output precision. Defaults to the global default output dtype. Returns: LineCollection: The generated line collection. """ # If we are missing this spectra then we cannot generate lines if model.label not in spectra: raise exceptions.MissingSpectraType( f"Cannot generate lines for {model.label} as spectra are " "missing. Please generate spectra first or remove the " "generation of lines." ) # Get the required parameters params = self._extract_params(model, emitter) # Unpack the parameters temperature = params["temperature"] emissivity = params["emissivity"] # Define frequencies nu = (c / line_lams).to(Hz) # Account for CMB heating cmb_factor, temperature = self.apply_cmb_heating( temperature=temperature, emissivity=emissivity, redshift=redshift, ) # Compute the greybody function lnu = self._lnu(nu, temperature, emissivity) # Get the bolometric luminosity over all frequencies bol_lum = self._bolometric_luminosity(temperature, emissivity) # Normalise the greybody spectrum lnu /= bol_lum # Normalise the spectrum and apply scaling with proper unit handling scaling = self.get_scaling(emitter, model, spectra) # Scale the normalised emission, at the output precision lnu = self.get_scaled_emission( lnu, scaling, emitter, model, out_dtype, cmb_factor, ) # Return as LineCollection with continuum only lines = LineCollection( line_ids, line_lams, lum=np.zeros(lnu.shape, dtype=lnu.dtype) * erg / s, cont=lnu * erg / s / Hz, ) return lines
[docs] @accepts(lams=angstrom) def get_spectra(self, lams: unyt_array, redshift: float = 0) -> Sed: """Generate dust emission spectra for given wavelength grid. This will return the scaling free spectra for a given wavelength grid. It will not consider any emitter or model, so the temperature and emissivity must have been provided directly to the class (otherwise a MissingAttribute exception is raised). Args: lams (unyt_array): The wavelength grid on which to generate the spectra. redshift (float): The redshift at which to calculate the CMB heating. Returns: Sed: The generated dust emission SED. """ return self._generate_spectra(lams, None, None, {}, redshift)