Source code for synthesizer.emission_models.utils

"""A submodule containing utility functions for the emission models."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

import numpy as np
from unyt import km, s, unyt_array, unyt_quantity

from synthesizer import exceptions

# ParameterFunction now lives in the parameters submodule. It is imported here
# both for the isinstance checks in get_param and to preserve the historic
# import location.
from synthesizer.emission_models.parameters import (  # noqa: F401
    VARIATION_TYPES,
    ParameterFunction,
)
from synthesizer.units import accepts
from synthesizer.utils import (
    depluralize,
    pluralize,
)

if TYPE_CHECKING:
    from synthesizer.components.component import Component
    from synthesizer.emission_models.base_model import EmissionModel


# A sentinel object for detecting if a default value was provided
_NO_DEFAULT = object()


@accepts(velocity_dispersion=km / s)
def _apply_broadening_to_model(model, label, velocity_dispersion, kwargs):
    """Wrap an existing model in a scalar Doppler broadening transformation.

    Args:
        model (EmissionModel):
            The model whose output spectrum will be broadened.
        label (str):
            The label for the broadened output model.
        velocity_dispersion (unyt.unyt_quantity):
            Scalar velocity dispersion. ``None`` disables broadening.
        kwargs (dict):
            Additional keyword arguments for the broadened model.

    Returns:
        EmissionModel:
            The original model when broadening is disabled, otherwise a model
            applying ``DopplerBroadening`` to the original model.

    """
    # Local imports avoid a cycle because base_model imports this module.
    from synthesizer.emission_models.base_model import (
        EmissionModel,
        StellarEmissionModel,
    )
    from synthesizer.emission_models.transformers import DopplerBroadening

    # If broadening is disabled, return the original model unchanged.
    if velocity_dispersion is None:
        return model

    # Keep the requested label on the public output. The unbroadened spectrum
    # remains in the graph for evaluation but is not saved separately.
    predispersion_label = f"{label}_predispersion"
    model._relabel_models({model.label: predispersion_label})
    model.set_save(False)

    # Preserve galaxy-level models when broadening a total containing dust
    # emission; component-only models retain their stellar emitter type.
    model_class = (
        StellarEmissionModel if model.emitter == "stellar" else EmissionModel
    )
    broadened = model_class(
        label=label,
        apply_to=model,
        emitter=model.emitter,
        transformer=DopplerBroadening(
            sigma_v_attr="velocity_dispersion",
        ),
        velocity_dispersion=velocity_dispersion,
        **kwargs,
    )

    return broadened


[docs] def check_removed_overrides(**overrides): """Raise an error if any removed get_spectra/get_lines override is set. Overriding the dust curves, optical depths, escape fractions, covering fractions, masks or velocity shift of an emission model at the point get_spectra or get_lines is called is no longer supported. These arguments only remain so passing them raises a clear error rather than being silently ignored. Args: **overrides (dict): The removed override arguments, keyed by name, with their passed values (None if they weren't passed). Raises: exceptions.InconsistentArguments: If any of the overrides was passed. """ # Find any overrides which were actually passed passed = [name for name, value in overrides.items() if value is not None] if len(passed) == 0: return raise exceptions.InconsistentArguments( f"Passing {', '.join(passed)} to get_spectra or get_lines is no " "longer supported. Modify the EmissionModel itself instead (e.g. " "pass the parameter when creating the model, or use " "set_vel_shift or add_mask), or set the parameter on the emitter." )
[docs] def cache_param( param: str, emitter: Component, model_label: str, value: Any, ) -> None: """Cache a parameter value on an emitter for a given model. This function stores a computed parameter value in the emitter's model_param_cache under the specified model label. NOTE: This does not duplicate the value, it simply stores a reference to it. Under the hood this just increases the reference count by one. Args: param (str): The name of the parameter to cache. emitter (Stars/Gas/BlackHoles/Galaxy): The emitter object where the parameter will be cached. model_label (str): The label of the model associated with the parameter. value: The value to cache for the parameter. """ # Cache the parameter value on the emitter emitter.model_param_cache.setdefault(model_label, {})[param] = value
[docs] def cache_model_params( model: EmissionModel, emitter: Component, ) -> None: """Cache all model specific parameters on to the emitter. This function stores all predefined parameters from the model including: - emitter: The emitter type for this model (stellar/blackhole/galaxy). - extract: The key that will extracted from the Grid. - combine: The models that will be combined to create the emission. - apply_to: The label of the model the transformation applies to. - transformer: The transformer's repr. - generator: The generator's repr. - mask parameters: Any parameters used in masking. Note that all fixed parameters that are used will automatically be associated at the point of use via calls to get_param. Args: model (EmissionModel): The model object containing the parameters to cache. emitter (Stars/Gas/BlackHoles/Galaxy): The emitter object where the parameters will be cached. """ # Cache the predefined parameters on the emitter based on the type of model if model._is_extracting: cache_param( param="extract", emitter=emitter, model_label=model.label, value=model.extract, ) elif model._is_combining: cache_param( param="combine", emitter=emitter, model_label=model.label, value=[ m if isinstance(m, str) else m.label for m in model.combine ], ) elif model._is_transforming: cache_param( param="apply_to", emitter=emitter, model_label=model.label, value=model.apply_to if isinstance(model.apply_to, str) else model.apply_to.label, ) cache_param( param="transformer", emitter=emitter, model_label=model.label, value=repr(model.transformer), ) elif model._is_generating: cache_param( param="generator", emitter=emitter, model_label=model.label, value=repr(model.generator), ) # Cache the emitter for this model cache_param( param="emitter", emitter=emitter, model_label=model.label, value=model.emitter, ) # Cache any mask parameters in the form of <attr> <op> <thresh> strings masks = [] for mask in model.masks: masks.append(f"{mask['attr']} {mask['op']} {mask['thresh']}") if len(masks) > 0: cache_param( param="masks", emitter=emitter, model_label=model.label, value="\n".join(masks), )
def _finalize_param_value( value, param, model, emission, emitter, obj, preserve_units, ): """Call parameter functions, cache values, and optionally strip units.""" if isinstance(value, ParameterFunction): value = value( model, emission, emitter, obj, preserve_units=preserve_units, ) elif model is not None and emitter is not None: cache_param( param=param, emitter=emitter, model_label=model.label, value=value, ) if not preserve_units and isinstance(value, (unyt_array, unyt_quantity)): value = value.value return value
[docs] def get_emission_label(emission): """Return the emission dictionary key for an emission. Emissions can be referred to either by their label or by the EmissionModel itself. This resolves either into the label used to key the dictionaries of generated emissions. The label is resolved lazily (rather than stored) so that relabelling a model is picked up. Args: emission (EmissionModel/str): The emission, either an EmissionModel or a label. Returns: str: The label of the emission. """ return getattr(emission, "label", emission)
[docs] def get_param( param, model, emission, emitter, obj=None, default=_NO_DEFAULT, preserve_units=False, _singular_attempted=False, _plural_attempted=False, _visited=None, ): """Extract a parameter from a model, emission, emitter, or object. The priority of extraction is: 1. Model (EmissionModel) 2. Emission (Sed/LineCollection) 3. Emitter (Stars/Gas/Galaxy) 4. Object (any object) If we find a string value this should mean the parameter points to another attribute, so we will recursively look for that attribute. Args: param (str): The parameter to extract. model (EmissionModel): The model object. emission (Sed/LineCollection): The emission object. emitter (Stars/Gas/Galaxy): The emitter object. obj (object, optional): An optional additional object to look for the parameter on last. default (object, optional): The default value to return if the parameter is not found. preserve_units (bool, optional): If True, return raw parameter values with any attached units preserved. If False, array-like values are normalised for C-backed calculations where appropriate. Defaults to False. _singular_attempted (bool, optional): Internal flag to track if singular version has been attempted. _plural_attempted (bool, optional): Internal flag to track if plural version has been attempted. _visited (set, optional): Internal set to track visited parameters and detect cycles. Returns: value The value of the parameter extracted from the appropriate object. Raises: MissingAttribute If the parameter is not found in the model, emission, or emitter. This is only raised if no default is passed. """ # Initialize the visited set to detect cycles in alias resolution if _visited is None: _visited = set() # Initialize the value to None value = None # Are we looking for a logged parameter? logged = "log10" in param # Check the model's fixed parameters first if model is not None and param in model.fixed_parameters: # A variation marker is a declaration, not a value. If one is still # here then the model tree was never expanded. if isinstance(model.fixed_parameters[param], VARIATION_TYPES): marker_type = type(model.fixed_parameters[param]).__name__ raise exceptions.InconsistentArguments( f"Found an unexpanded {marker_type} " f"for '{param}' on model '{model.label}'. Call " "expand_models() on the root model to generate the variant " "models before generating an emission." ) value = model.fixed_parameters[param] # Check the emission next elif emission is not None and hasattr(emission, param): value = getattr(emission, param) # Check the emitter elif emitter is not None and hasattr(emitter, param): value = getattr(emitter, param) # Finally, if we have an additional object, check that elif obj is not None and hasattr(obj, param): value = getattr(obj, param) # Do we need to recursively look for the parameter? (We know we're only # looking on the emitter at this point) if value is not None and isinstance(value, str): # Check for cycles before following this alias if value in _visited: # We've seen this alias before - there's a cycle if default is not _NO_DEFAULT: return default raise exceptions.MissingAttribute( f"Cyclic alias detected while resolving parameter '{param}'. " f"Alias chain: {' -> '.join(_visited)} -> {value}" ) # Add current alias to visited set and follow it new_visited = _visited | {param} value = get_param( value, None, None, emitter, default=default, preserve_units=preserve_units, _visited=new_visited, ) # If we found a value (or a ParameterFunction to produce one), finalise it elif value is not None: return _finalize_param_value( value, param, model, emission, emitter, obj, preserve_units ) # If we were finding a logged parameter but failed, try the non-logged # version and log it if logged and value is None: logless_param = param.replace("log10", "") value = get_param( logless_param, model, emission, emitter, obj, default=default, preserve_units=preserve_units, _visited=_visited, ) if value is not None: # Attach this to the emitter so we don't have to do this again value = np.log10(value) setattr(emitter, param, value) # Lets just check we don't have the singular/plural version of the # parameter if we still have nothing if value is None and not _singular_attempted: singular_param = depluralize(param) if singular_param != param: value = get_param( singular_param, model, emission, emitter, obj, default=None, preserve_units=preserve_units, _singular_attempted=True, _plural_attempted=_plural_attempted, _visited=_visited, ) if value is None and not _plural_attempted: plural_param = pluralize(param) if plural_param != param: value = get_param( plural_param, model, emission, emitter, obj, default=None, preserve_units=preserve_units, _singular_attempted=_singular_attempted, _plural_attempted=True, _visited=_visited, ) # OK, if we found nothing an have a default, now is the time to use it # NOTE: we can't use None as a default value because None could be a valid # parameter value, so we use a sentinel object instead. if value is None and default is not _NO_DEFAULT: value = default # If we found a value (or a ParameterFunction to produce one), finalise it if value is not None: return _finalize_param_value( value, param, model, emission, emitter, obj, preserve_units ) # Otherwise raise an exception else: # Report everywhere we looked, including the fallback object if one # was given searched = ( f"the model " f"({model.label if model is not None else None})," " emission (" f"{emission.__class__.__name__ if emission is not None else None}" "), or emitter (" f"{emitter.__class__.__name__ if emitter is not None else None})" ) if obj is not None: searched = searched.replace(", or emitter (", ", emitter (") searched += f", or {obj.__class__.__name__} itself" raise exceptions.MissingAttribute( f"{param} can't be found on {searched}." )
[docs] def get_params( params, model, emission, emitter, obj=None, preserve_units=False, ): """Extract a list of parameters from a model, emission, emitter, or object. The priority of extraction is: 1. Model (EmissionModel) 2. Emission (Sed/LineCollection) 3. Emitter (Stars/Gas/Galaxy) 4. Object (any object) Args: params (list): The parameters to extract. model (EmissionModel): The model object. emission (Sed/LineCollection): The emission object. emitter (Stars/BlackHoles/Gas/Galaxy): The emitter object. obj (object, optional): An optional additional object to look for parameters on last. preserve_units (bool, optional): If True, return raw parameter values with any attached units preserved. If False, array-like values are normalised for C-backed calculations where appropriate. Defaults to False. Returns: values (dict): A dictionary of the values of the parameters extracted from the appropriate object. """ values = {} for param in params: values[param] = get_param( param, model, emission, emitter, obj, preserve_units=preserve_units, ) return values