Skip to content

API reference

This reference is generated from source docstrings. The symbols listed here form the public API; other symbols are internal.

Stellar populations

ceridwen.ssps.SSPData dataclass

SSPData(
    ssp_lgmet,
    ssp_lg_age_gyr,
    ssp_wave,
    ssp_flux,
    ssp_resolution=None,
    resolution_source=None,
    ssp_stellar_mass=None,
    stellar_mass_source=None,
    stellar_mass_refused=None,
    isoc_type=None,
    spec_library=None,
    imf_type=None,
    fsps_version=None,
    fsps_kwargs=dict(),
    wave_min=None,
    wave_max=None,
    schema_version=None,
    log10_zsun=None,
    zsun_nominal=None,
    axis_meaning=None,
    zsun_source=None,
    chash=None,
    refused_cells=(),
    refused_reason=None,
    zsun=None,
    _chash_hint=None,
    _extra_datasets=(),
)

Immutable container for the SSP interpolation grids plus static provenance.

Parameters:

Name Type Description Default
ssp_lgmet array (n_met,) -- the grid's NATIVE metallicity axis, log10 Z: absolute Z for

BPASS, the FSPS label log10(zsun 10^[Fe/H]) for MIST/aMIST (not MIST's physical initial Z)

required
ssp_lg_age_gyr array(n_ages) - -log10(age / Gyr)
required
ssp_wave (array(n_wave), Angstrom)
required
ssp_flux ndarray (n_met, n_ages, n_wave), L_sun/Hz per M_sun formed -- kept in HOST memory as a

read-only NumPy array (a JAX array given here is copied to the host); the CSP puts only its float32 copy on the device

required
ssp_resolution ndarray (n_wave,), km/s -- library sigma_v(lambda) on ssp_wave, NaN where unknown; optional in memory, required by save()/load()
None
ssp_stellar_mass ndarray (n_met, n_ages) or None -- surviving mass (stars + remnants) per

M_sun formed of each SSP, FSPS stellar_mass (schema 3.0, optional); None when the grid carries no table, or its table was refused at load (stellar_mass_refused)

None
stellar_mass_source str or None -- provenance of ``ssp_stellar_mass``
None
stellar_mass_refused str or None -- why the file's table was refused at load (values

above STELLAR_MASS_MAX); None otherwise

None
zsun float, init-only -- the grid's solar metallicity (mass fraction) when it is neither

recorded (log10_zsun) nor in grid_metadata.CHASH_TABLE; must match a node

None
log10_zsun float -- resolved: the grid's solar node (exact), so logzsol = ssp_lgmet - log10_zsun
None
axis_meaning (feh, log_z_over_zsun)
"feh"

logzsol_axis property

logzsol_axis

The metallicity axis in logzsol = ssp_lgmet - log10_zsun (float64).

with_stellar_mass

with_stellar_mass(mass, *, source)

Return a copy carrying the surviving stellar-mass table mass (shape ssp_flux.shape[:-1], M_sun per M_sun formed) with its provenance source.

Source code in ceridwen/ssps/ssp_data.py
def with_stellar_mass(self, mass, *, source):
    """Return a copy carrying the surviving stellar-mass table ``mass`` (shape
    ``ssp_flux.shape[:-1]``, M_sun per M_sun formed) with its provenance ``source``."""
    import dataclasses as _dc
    if not source:
        raise ValueError("with_stellar_mass: pass source= (where the masses come from)")
    return _dc.replace(self, ssp_stellar_mass=self._checked_stellar_mass(mass),
                       stellar_mass_source=str(source), schema_version=self._schema_version())

require_stellar_mass

require_stellar_mass()

The surviving stellar-mass table; ValueError saying how to get a grid with one.

Source code in ceridwen/ssps/ssp_data.py
def require_stellar_mass(self) -> np.ndarray:
    """The surviving stellar-mass table; ValueError saying how to get a grid with one."""
    if self.ssp_stellar_mass is None:
        raise ValueError(missing_stellar_mass_message(type(self).__name__, chash=self.chash,
                                                      refused=self.stellar_mass_refused))
    return self.ssp_stellar_mass

with_resolution

with_resolution(
    *, sigma_v=None, segments=None, source=None
)

Return a copy carrying a library resolution curve from exactly one of sigma_v (km/s on ssp_wave, NaN where unknown) or segments.

Source code in ceridwen/ssps/ssp_data.py
def with_resolution(self, *, sigma_v=None, segments=None, source=None):
    """Return a copy carrying a library resolution curve from exactly one of ``sigma_v`` (km/s on ssp_wave, NaN where unknown) or ``segments``."""
    import dataclasses as _dc
    from .library_resolution import sigma_v_from_segments
    if (sigma_v is None) == (segments is None):
        raise ValueError(
            "with_resolution: pass exactly one of sigma_v= or segments=")
    if segments is not None:
        sigma_v = sigma_v_from_segments(
            np.asarray(self.ssp_wave), segments)
    return _dc.replace(
        self,
        ssp_resolution=np.asarray(sigma_v, dtype=np.float64),
        resolution_source=(str(source) if source is not None else None),
    )

display

display(*, return_str=False, file=None)

Print (or return as str when return_str) a summary of the grid and its provenance.

Source code in ceridwen/ssps/ssp_data.py
def display(self, *, return_str: bool = False, file=None):
    """Print (or return as str when ``return_str``) a summary of the grid and its provenance."""
    import sys as _sys

    wave  = np.asarray(self.ssp_wave)

    def _fmt(v, na="—"):
        return na if v is None else str(v)

    size = float(np.asarray(self.ssp_flux).nbytes)
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if size < 1024.0 or unit == "TB":
            size_str = f"{size:.1f} {unit}"
            break
        size /= 1024.0

    lines = [
        self._display_title,
        "-" * 66,
        "provenance",
        f"  isochrones (isoc_type)   : {_fmt(self.isoc_type)}",
        f"  spectral library         : {_fmt(self.spec_library)}",
        f"  IMF (imf_type)           : {_fmt(self.imf_type)}",
        f"  FSPS version             : {_fmt(self.fsps_version)}",
        f"  schema version           : {_fmt(self.schema_version)}",
        f"  recorded wave_min/max    : {_fmt(self.wave_min)} / {_fmt(self.wave_max)}",
        f"  build kwargs             : {self.fsps_kwargs or '{}'}",
        "grids",
    ] + self._display_grid_lines(size_str)
    if self.ssp_resolution is None:
        lines += ["  library resolution       : MISSING "
                  "(cannot be saved; attach with with_resolution)"]
    else:
        res = np.asarray(self.ssp_resolution, dtype=np.float64)
        fin = np.isfinite(res)
        if fin.any():
            cov_lo = wave[fin].min(); cov_hi = wave[fin].max()
            lines += [
                f"  library resolution       : sigma_v "
                f"[{res[fin].min():.1f}, {res[fin].max():.1f}] km/s over "
                f"[{cov_lo:.0f}, {cov_hi:.0f}] AA "
                f"({100.0 * fin.mean():.0f}% of pixels; NaN elsewhere)",
            ]
        else:
            lines += ["  library resolution       : all-NaN "
                      "(unknown everywhere; no subtraction will occur)"]
        if self.resolution_source:
            lines += [f"  resolution source        : {self.resolution_source}"]
    if self.stellar_mass_refused:
        lines += ["  surviving stellar mass   : REFUSED at load (mfrac and the surviving "
                  "mass unavailable; everything else works)",
                  f"    {self.stellar_mass_refused}"]
    elif self.ssp_stellar_mass is None:
        name = published_grid_name(self.chash)
        which = (f"the published grid {name!r} has none yet" if name is not None
                 else "no ssp_stellar_mass table")
        lines += [f"  surviving stellar mass   : not available ({which}): mfrac and the "
                  "surviving mass are unavailable; everything else works"]
    else:
        m = self.ssp_stellar_mass
        lines += [f"  surviving stellar mass   : [{m.min():.4g}, {m.max():.4g}] M_sun per "
                  f"M_sun formed ({self.stellar_mass_source or 'source not recorded'})"]
    lines += self._display_note_lines()

    txt = "\n".join(lines)
    if return_str:
        return txt
    print(txt, file=file or _sys.stdout)
    return None

save

save(filename)

Write grids, resolution curve and provenance attrs to HDF5 (overwrites); raises ValueError if ssp_resolution is None.

Source code in ceridwen/ssps/ssp_data.py
def save(self, filename):
    """Write grids, resolution curve and provenance attrs to HDF5 (overwrites); raises ValueError if ``ssp_resolution`` is None."""
    if self.ssp_resolution is None:
        raise ValueError(
            f"{type(self).__name__}.save(): this grid carries no library "
            f"resolution curve (ssp_resolution is None).  "
            f"{self._schema_label} files require one — attach it with "
            "with_resolution(segments=...) or with_resolution(sigma_v=...) "
            "before saving."
        )
    with h5py.File(filename, 'w') as f:
        f.create_dataset('ssp_lgmet',      data=np.array(self.ssp_lgmet))
        f.create_dataset('ssp_lg_age_gyr', data=np.array(self.ssp_lg_age_gyr))
        f.create_dataset('ssp_wave',       data=np.array(self.ssp_wave))
        f.create_dataset('ssp_flux',       data=np.array(self.ssp_flux))
        f.create_dataset('ssp_resolution',
                         data=np.asarray(self.ssp_resolution,
                                         dtype=np.float64))

        f.attrs['description']        = 'FSPS SSP interpolation grids'
        f.attrs['units_lgmet']        = self._units_lgmet()
        f.attrs['units_lg_age_gyr']   = 'log10(age/Gyr)'
        f.attrs['units_wave']         = 'Angstrom'
        f.attrs['units_flux']         = 'L_sun Hz^-1 M_sun^-1'
        f.attrs['units_resolution']   = 'sigma_v [km/s]; NaN = unknown'
        self._save_extra(f)
        if self.ssp_stellar_mass is not None:
            f.create_dataset('ssp_stellar_mass',
                             data=np.asarray(self.ssp_stellar_mass, dtype=np.float64))
            f.attrs['units_stellar_mass'] = ('M_sun surviving (stars + remnants) per '
                                             'M_sun formed, per SSP')
            if self.stellar_mass_source is not None:
                f.attrs['stellar_mass_source'] = str(self.stellar_mass_source)
        if self.resolution_source is not None:
            f.attrs['resolution_source'] = str(self.resolution_source)

        for key in ('schema_version', 'isoc_type', 'spec_library',
                    'fsps_version'):
            val = getattr(self, key)
            if val is not None:
                f.attrs[key] = str(val)
        if self.imf_type is not None:
            f.attrs['imf_type'] = int(self.imf_type)
        if self.wave_min is not None:
            f.attrs['wave_min'] = float(self.wave_min)
        if self.wave_max is not None:
            f.attrs['wave_max'] = float(self.wave_max)
        f.attrs['fsps_kwargs_json'] = json.dumps(self.fsps_kwargs or {})
        f.attrs['log10_zsun'] = float(self.log10_zsun)
        f.attrs['zsun_nominal'] = float(self.zsun_nominal)
        if self.axis_meaning is not None:
            f.attrs['axis_meaning'] = str(self.axis_meaning)
        f.attrs['chash'] = str(self.chash)
        if self.refused_cells:
            f.attrs['refused_cells_json'] = json.dumps([list(c) for c in self.refused_cells])

load classmethod

load(filename, flux_dtype=None, zsun=None)

Load a grid from HDF5; raises ValueError if the file lacks ssp_resolution. flux_dtype casts the flux cube on read. zsun supplies the grid's solar metallicity when it is neither recorded in the file nor in grid_metadata.CHASH_TABLE.

Source code in ceridwen/ssps/ssp_data.py
@classmethod
def load(cls, filename, flux_dtype=None, zsun=None):
    """Load a grid from HDF5; raises ValueError if the file lacks ``ssp_resolution``. ``flux_dtype`` casts the flux cube on read.
    ``zsun`` supplies the grid's solar metallicity when it is neither recorded in the file nor in ``grid_metadata.CHASH_TABLE``."""
    arrays, _extra, meta = cls._read_h5(filename, flux_dtype=flux_dtype)
    return cls(**arrays, **meta, zsun=zsun)

from_fsps classmethod

from_fsps(
    save_to=None,
    resolution_segments=None,
    resolution_source=None,
    **fsps_kwargs
)

Build a grid from the SPS backend, attach the library resolution curve and record provenance.

Only library/IMF-defining kwargs (LIBRARY_IMF_KWARGS) are accepted. The resolution curve is the element-wise maximum of the 2-pixel sampling floor of ssp_wave and resolution_segments (if given, which then require resolution_source). Raises ValueError otherwise.

Source code in ceridwen/ssps/ssp_data.py
@classmethod
def from_fsps(cls, save_to: Optional[str] = None,
              resolution_segments=None,
              resolution_source: Optional[str] = None,
              **fsps_kwargs) -> "SSPData":
    """Build a grid from the SPS backend, attach the library resolution curve and record provenance.

    Only library/IMF-defining kwargs (``LIBRARY_IMF_KWARGS``) are accepted.
    The resolution curve is the element-wise maximum of the 2-pixel sampling
    floor of ``ssp_wave`` and ``resolution_segments`` (if given, which then
    require ``resolution_source``). Raises ValueError otherwise.
    """
    if resolution_source is not None and resolution_segments is None:
        raise ValueError(
            "from_fsps(): resolution_source was given without "
            "resolution_segments.  The sampling-floor provenance is "
            "recorded automatically; a source note only accompanies "
            "explicit library-LSF segments."
        )
    if resolution_segments is not None and resolution_source is None:
        raise ValueError(
            "from_fsps(): resolution_segments were given without "
            "resolution_source.  Cite where the LSF numbers come from "
            "(e.g. resolution_source='MILES FWHM 2.54A "
            "(Falcon-Barroso et al. 2011)') — uncited resolution "
            "numbers must not ship in a released grid."
        )
    from .library_resolution import combined_sigma_v, combined_source
    data = collect_ssp_data_wrapper(**fsps_kwargs)
    sigma_v = combined_sigma_v(np.asarray(data.ssp_wave),
                               segments=resolution_segments)
    data = data.with_resolution(
        sigma_v=sigma_v, source=combined_source(resolution_source))
    if save_to is not None:
        data.save(save_to)
    return data

ceridwen.ssps.SSPDataAfe dataclass

SSPDataAfe(
    ssp_lgmet,
    ssp_lg_age_gyr,
    ssp_wave,
    ssp_flux,
    ssp_resolution=None,
    resolution_source=None,
    ssp_stellar_mass=None,
    stellar_mass_source=None,
    stellar_mass_refused=None,
    isoc_type=None,
    spec_library=None,
    imf_type=None,
    fsps_version=None,
    fsps_kwargs=dict(),
    wave_min=None,
    wave_max=None,
    schema_version=None,
    log10_zsun=None,
    zsun_nominal=None,
    axis_meaning=None,
    zsun_source=None,
    chash=None,
    refused_cells=(),
    refused_reason=None,
    zsun=None,
    _chash_hint=None,
    _extra_datasets=(),
    *,
    ssp_afe
)

Bases: SSPData

Immutable alpha-enhanced SSP grid: an SSPData whose flux cube has a leading [alpha/Fe] axis.

Parameters:

Name Type Description Default
ssp_lgmet jnp.ndarray (n_met,) -- native axis [Fe/H] + log10(Z_sun), the SAME on every [alpha/Fe] required
ssp_afe jnp.ndarray (n_afe,), keyword-only -- [alpha/Fe] grid, strictly increasing
required
ssp_lg_age_gyr ndarray(n_ages) - -log10(age / Gyr)
required
ssp_wave ndarray(n_wave) - -Angstrom
required
ssp_flux np.ndarray (n_afe, n_met, n_ages, n_wave) -- Lsun / Hz per Msun formed; host NumPy,

read-only, as in SSPData

required
ssp_resolution np.ndarray (n_wave,) or None -- sigma_v(lambda) [km/s] on ``ssp_wave``; required by save/load
None
ssp_stellar_mass np.ndarray (n_afe, n_met, n_ages) or None -- surviving mass per M_sun formed (optional)
None

load classmethod

load(filename, flux_dtype=None, zsun=None)

Load from HDF5; a 3-D grid without ssp_afe is promoted to n_afe = 1 at [alpha/Fe] = 0. zsun as for :meth:SSPData.load.

Source code in ceridwen/ssps/ssp_data_afe.py
@classmethod
def load(cls, filename, flux_dtype=None, zsun=None):
    """Load from HDF5; a 3-D grid without ``ssp_afe`` is promoted to n_afe = 1 at [alpha/Fe] = 0.
    ``zsun`` as for :meth:`SSPData.load`."""
    arrays, extra, meta = cls._read_h5(filename, flux_dtype=flux_dtype)
    ssp_afe = extra['ssp_afe']
    if ssp_afe is None:
        ssp_afe = jnp.zeros(1)
        arrays['ssp_flux'] = arrays['ssp_flux'][None, ...]
        if meta.get('ssp_stellar_mass') is not None:
            meta['ssp_stellar_mass'] = meta['ssp_stellar_mass'][None, ...]
    return cls(**arrays, ssp_afe=ssp_afe, **meta, zsun=zsun)

from_fsps classmethod

from_fsps(
    save_to=None,
    afe_values=None,
    resolution_segments=None,
    resolution_source=None,
    **fsps_kwargs
)

Build the grid by looping get_spectrum(tage=0, zmet=i) over the [alpha/Fe] planes.

Parameters:

Name Type Description Default
afe_values array-like, optional -- [alpha/Fe] of each plane in ``afeindx`` order; defaults exist for n_afe 5 and 1 only
None
resolution_segments list, optional -- documented library LSF segments, max-combined with the 2-pixel sampling floor
None
resolution_source str, optional -- citation for ``resolution_segments``; each raises if given without the other
None
Source code in ceridwen/ssps/ssp_data_afe.py
@classmethod
def from_fsps(cls, save_to: Optional[str] = None,
              afe_values=None,
              resolution_segments=None,
              resolution_source: Optional[str] = None,
              **fsps_kwargs) -> "SSPDataAfe":
    """Build the grid by looping ``get_spectrum(tage=0, zmet=i)`` over the [alpha/Fe] planes.

    Parameters
    ----------
    afe_values : array-like, optional -- [alpha/Fe] of each plane in ``afeindx`` order; defaults exist for n_afe 5 and 1 only
    resolution_segments : list, optional -- documented library LSF segments, max-combined with the 2-pixel sampling floor
    resolution_source : str, optional -- citation for ``resolution_segments``; each raises if given without the other
    """
    if resolution_source is not None and resolution_segments is None:
        raise ValueError(
            "from_fsps(): resolution_source was given without "
            "resolution_segments.  The sampling-floor provenance is "
            "recorded automatically; a source note only accompanies "
            "explicit library-LSF segments."
        )
    if resolution_segments is not None and resolution_source is None:
        raise ValueError(
            "from_fsps(): resolution_segments were given without "
            "resolution_source.  Cite where the LSF numbers come from "
            "— uncited resolution numbers must not ship in a released "
            "grid."
        )
    for bad in ('afe', 'afeindx'):
        if bad in fsps_kwargs:
            raise ValueError(
                f"from_fsps() rejects the FSPS kwarg {bad!r}: the "
                f"[alpha/Fe] axis is spanned by the grid itself "
                f"(ssp_afe); CSPBasis_afe samples it through "
                f"theta['afe'], so a fixed alpha must not be set at "
                f"build time."
            )
    kwargs = _validate_fsps_kwargs(fsps_kwargs)

    fsps = _import_fsps(
        "SSPDataAfe.load(ceridwen.ssps.fetch_grid('amist_c3k_hr_krou_afe'))")

    ssp = fsps.StellarPopulation(zcontinuous=0, sfh=0, **kwargs)

    n_afe = int(getattr(ssp, "n_afe", 1))
    if afe_values is not None:
        ssp_afe = np.atleast_1d(np.asarray(afe_values, dtype=float))
        if ssp_afe.size != n_afe:
            raise ValueError(
                f"afe_values has {ssp_afe.size} entries but the "
                f"compiled FSPS grid has n_afe = {n_afe}."
            )
    elif n_afe == 5:
        ssp_afe = FSPS_AFE_VALUES_NAFE5.copy()
    elif n_afe == 1:
        ssp_afe = np.zeros(1)
    else:
        raise ValueError(
            f"Compiled FSPS grid has n_afe = {n_afe}, which does not "
            f"match the documented aMIST/C3K layout (5) or a "
            f"solar-scaled build (1); pass afe_values= explicitly "
            f"(the [alpha/Fe] of each afeindx plane, in order)."
        )

    ssp_lgmet      = jnp.log10(ssp.zlegend)
    nzmet          = int(ssp_lgmet.size)
    ssp_lg_age_gyr = jnp.array(ssp.log_age - 9.0)

    planes = []
    mass_planes = []
    iso_planes = []
    _wave = None
    for afe_indx in range(1, n_afe + 1):               # afeindx is 1-based
        if n_afe > 1:
            ssp.params["afeindx"] = afe_indx
            print(f"[alpha/Fe] plane {afe_indx}/{n_afe} "
                  f"(afe = {ssp_afe[afe_indx - 1]:+.1f})")
        spectrum_collector = []
        mass_collector = []
        iso_collector = []
        for zmet_indx in range(1, nzmet + 1):
            print(f"...retrieving metallicity {zmet_indx}/{nzmet} "
                  f"[Z = {ssp.zlegend[zmet_indx - 1]:.4f}]")
            _wave, _fluxes = ssp.get_spectrum(
                tage=0.0, zmet=zmet_indx, peraa=False)
            spectrum_collector.append(_fluxes)
            mass_collector.append(np.array(ssp.stellar_mass, dtype=np.float64))
            iso_collector.append(isochrone_points_or_none(ssp))
        planes.append(np.array(spectrum_collector))
        mass_planes.append(np.array(mass_collector))
        iso_planes.append(iso_collector)

        _z_now = np.log10(np.asarray(ssp.zlegend))
        if not np.allclose(_z_now, np.asarray(ssp_lgmet)):
            raise RuntimeError(
                f"zlegend changed between alpha planes (afeindx="
                f"{afe_indx}); the Z grids are ragged across "
                f"[alpha/Fe] and cannot form a rectangular "
                f"(afe, Z, age, wave) grid."
            )

    ssp_wave = jnp.array(_wave)
    ssp_flux = np.stack(planes, axis=0)                # host NumPy (SSPData keeps it there)

    meta = _read_fsps_provenance(ssp, kwargs, ssp_wave, ssp_lgmet)
    meta['schema_version'] = SSP_AFE_SCHEMA_VERSION
    iso = (None if iso_planes[0][0] is None
           else np.array(iso_planes, dtype=np.float64))
    meta['ssp_stellar_mass'], note = corrected_table(ssp, np.stack(mass_planes, axis=0), iso)
    meta['stellar_mass_source'] = fsps_stellar_mass_source(meta['fsps_version']) + note
    if n_afe > 1 and meta.get('isoc_type') == 'mist':
        meta['refused_cells'] = _duplicated_isochrone_cells(n_afe, int(nzmet))

    from .library_resolution import combined_sigma_v, combined_source
    sigma_v = combined_sigma_v(np.asarray(ssp_wave),
                               segments=resolution_segments)

    data = cls(ssp_lgmet, ssp_lg_age_gyr, ssp_wave, ssp_flux,
               ssp_afe=jnp.array(ssp_afe),
               ssp_resolution=sigma_v,
               resolution_source=combined_source(resolution_source),
               **meta)
    if save_to is not None:
        data.save(save_to)
    return data

ceridwen.ssps.fetch_grid

fetch_grid(name, *, force=False, quiet=False)

Return a local, checksum-verified path to the registry grid name, downloading into :func:grid_cache_dir on first use (force re-downloads).

Source code in ceridwen/ssps/grid_fetch.py
def fetch_grid(name: str, *, force: bool = False, quiet: bool = False) -> Path:
    """Return a local, checksum-verified path to the registry grid ``name``,
    downloading into :func:`grid_cache_dir` on first use (``force`` re-downloads)."""
    if name not in REGISTRY:
        raise KeyError(
            f"Unknown grid {name!r}. Available: {sorted(REGISTRY)}."
        )
    entry = REGISTRY[name]
    if entry["url"] is None:
        raise RuntimeError(
            f"Grid {name!r} is defined but not yet published (no URL in the "
            f"registry). Notes: {entry['notes']}"
        )

    dest = grid_cache_dir() / f"{name}.h5"

    if dest.exists() and not force:
        _verify_cached(name, dest)
        return dest

    if not quiet:
        size = f" (~{entry['size_mb']} MB)" if entry.get("size_mb") else ""
        print(f"[ceridwen] fetching grid {name!r}{size} -> {dest}",
              file=sys.stderr)

    fd, tmp = tempfile.mkstemp(dir=dest.parent, suffix=".part")
    os.close(fd)
    tmp = Path(tmp)
    try:
        _download(entry["url"], tmp)
        got = _sha256(tmp)
        if entry["sha256"] and got != entry["sha256"]:
            raise RuntimeError(
                f"Downloaded grid {name!r} fails its checksum "
                f"(got {got[:12]}..., expected {entry['sha256'][:12]}...). "
                f"The remote file changed or the download was corrupted; "
                f"not installing it."
            )
        tmp.replace(dest)
    finally:
        if tmp.exists():
            tmp.unlink()

    return dest

ceridwen.ssps.available_grids

available_grids(published_only=False)

Map of grid name -> one-line description.

Source code in ceridwen/ssps/grid_fetch.py
def available_grids(published_only: bool = False) -> dict[str, str]:
    """Map of grid name -> one-line description."""
    return {
        k: v["notes"] for k, v in REGISTRY.items()
        if v["url"] is not None or not published_only
    }

Grid metallicity metadata

ceridwen.ssps.grid_metadata.logzsol_total

logzsol_total(logzsol, afe, x=X_ALPHA_MIST25)

Total metallicity [Z/H] (Z/X definition) from logzsol = [Fe/H] on an alpha grid.

Source code in ceridwen/ssps/grid_metadata.py
def logzsol_total(logzsol, afe, x: float = X_ALPHA_MIST25):
    """Total metallicity [Z/H] (Z/X definition) from ``logzsol`` = [Fe/H] on an alpha grid."""
    return logzsol + f_alpha(afe, x)

ceridwen.ssps.grid_metadata.f_alpha

f_alpha(afe, x=X_ALPHA_MIST25)

[Z/H] - [Fe/H] at [alpha/Fe] = afe (jnp- and numpy-compatible, differentiable).

Source code in ceridwen/ssps/grid_metadata.py
def f_alpha(afe, x: float = X_ALPHA_MIST25):
    """[Z/H] - [Fe/H] at [alpha/Fe] = ``afe`` (jnp- and numpy-compatible, differentiable)."""
    try:
        import jax.numpy as xp
    except ImportError:          # pragma: no cover
        xp = np
    return xp.log10(1.0 - x + x * 10.0 ** afe)

ceridwen.ssps.grid_metadata.chash_arrays

chash_arrays(
    ssp_wave,
    ssp_lg_age_gyr,
    ssp_lgmet,
    ssp_flux,
    ssp_afe=None,
)

chash-v1 of a grid's arrays (see the module docstring).

Source code in ceridwen/ssps/grid_metadata.py
def chash_arrays(ssp_wave, ssp_lg_age_gyr, ssp_lgmet, ssp_flux, ssp_afe=None) -> str:
    """``chash-v1`` of a grid's arrays (see the module docstring)."""
    h = hashlib.sha256()
    _update(h, "ssp_wave", ssp_wave)
    _update(h, "ssp_lg_age_gyr", ssp_lg_age_gyr)
    _update(h, "ssp_lgmet", ssp_lgmet)
    if ssp_afe is not None:
        _update(h, "ssp_afe", ssp_afe)
    _update(h, "ssp_flux", ssp_flux)
    return f"{CHASH_VERSION}:{h.hexdigest()}"

Composite stellar population (forward model)

ceridwen.csp.CSPBasis

CSPBasis(
    SSPData,
    theta=None,
    tiny_logt=-70,
    zh_const=False,
    add_neb=True,
    init_neb_params=None,
    nebemlineinspec=False,
    add_dust=True,
    add_diffuse_dust=True,
    add_dust_emission=False,
    add_igm=False,
    igm_model="madau1995",
    igm_factor=1.0,
    sps_home=None,
    init_dust_params=None,
    diffuse_law="kriek_conroy",
    verbose=True,
    sfh_interp="step",
    track_zred_age=False,
    lookback_time=None,
    sfh_per_bin=None,
    fesc_geometry="runaway_bc",
    duste_model="DL07",
    cosmo=None,
    gas_tied=False,
    wavelength_support=False,
    agn=None,
    fixed=None,
    **kwargs
)

Composite stellar population basis. predict(theta, observations) projects the model onto observations.

Parameters:

Name Type Description Default
SSPData SSPData -- SSP grids (wave, flux, ages, metallicities, optional resolution curve).
required
theta dict -- initial values; must contain "lookback_time" (Gyr, increasing, index 0 = today,

= 2 nodes) and "sfh", plus "logzsol" (zh_const=True, shape (1,)) or "logzsol_bins" (zh_const=False, shape (n_time-1,), one value per SFH bin, index 0 = youngest), both log10(Z/Z_sun) of the grid. Mutually exclusive with lookback_time=.

None
lookback_time array -- shortcut for ``theta``: the node grid only, neutral initial values

(sfh = 1, metallicity = grid median).

None
sfh_per_bin bool or None -- with ``lookback_time=``, the shape of the default "sfh". "step"

always takes one SFR per bin (n_time-1,), as Prospector's FastStepBasis (False is refused); "linear" takes one per node (n_time,), or with True one per bin, mapped to nodes (interior nodes the mean of their two bins, the end nodes the end bins).

None
zh_const bool -- constant metallicity ("logzsol") or one metallicity per SFH bin

("logzsol_bins", constant within each bin). The removed per-node "logzsol_hist" entered only through its bin means 0.5*(zh[k] + zh[k+1]); "logzsol_bins" gives them directly.

False
gas_tied bool -- gas-phase metallicity follows the stellar one, gas_logz := logzsol (or

logzsol_bins[0], the youngest bin's), as Prospector ties them; "gas_logz" is then not a parameter. The two are the SAME NUMBER, not the same absolute Z: logzsol uses the SSP grid's Z_sun (e.g. 0.0185 for MIST) and gas_logz the CLOUDY grid's own reference (Byler+2017; its node set is 0.019- or 0.020-based), which is the FSPS/Prospector convention.

False
add_neb bool -- physics switches.
True
add_dust bool -- physics switches.
True
add_diffuse_dust bool -- physics switches.
True
add_dust_emission bool -- physics switches.
True
add_igm bool -- physics switches.
True
duste_model (DL07, THEMIS)

Draine & Li (2007) or THEMIS (Jones et al. 2013, 2017), both from $SPS_HOME/dust/dustem with FSPS's (qPAH, Umin) axes. THEMIS's duste_qpah axis spans 0.91-18.2 (the FSPS mass-fraction nodes x 100/2.2), DL07's 0.47-4.58.

'DL07'
sps_home str -- data directory for the nebular and dust-emission grids; defaults to $SPS_HOME.
None
init_neb_params dict -- forwarded to NebularModel / Dust. ``isoc_type`` is

taken from the SSP grid's provenance when recorded. cloudy_dust (default False) picks the CLOUDY grids without dust in the H II region (ZAU_ND, the FSPS / Prospector default); True the dusty ones (ZAU_WD), whose lines differ from ND by a grid-dependent factor (constant SFH 0-1 Gyr, solar, logU -2.5: MIST H-alpha x0.78, Ly-alpha x0.17, [O III] 5007 x1.13; BPASS x0.95, x0.40, x0.99).

None
init_dust_params dict -- forwarded to NebularModel / Dust. ``isoc_type`` is

taken from the SSP grid's provenance when recorded. cloudy_dust (default False) picks the CLOUDY grids without dust in the H II region (ZAU_ND, the FSPS / Prospector default); True the dusty ones (ZAU_WD), whose lines differ from ND by a grid-dependent factor (constant SFH 0-1 Gyr, solar, logU -2.5: MIST H-alpha x0.78, Ly-alpha x0.17, [O III] 5007 x1.13; BPASS x0.95, x0.40, x0.99).

None
sfh_interp (step, linear)

piecewise-linear (analytic log-age integral, small negative weights clipped) SFH.

'step'
track_zred_age bool -- with a sampled ``zred``, rescale the lookback grid so its oldest node

is the age of the Universe at that redshift, keeping the mass theta["sfh"] forms on the construction grid (the SFR is scaled by T_grid / age(zred)).

False
fesc_geometry (runaway_bc, picket)

'runaway_bc': a fraction frac_obrun of EVERY age row skips that row's age-bin attenuation (the diffuse dust still applies); with several attenuated age bins old stars escape too. The nebular ages emit a fraction frac_obrun of their LyC and power 1 - frac_obrun of the nebular emission. 'picket': a fraction frac_obrun of the young light (the nebular grid's ages, young_mask), LyC included, meets no dust or gas at all (no age-bin or diffuse dust, no nebular reprocessing, no dust heating); needs add_neb=True.

'runaway_bc'
cosmo Cosmology -- required; used for the flux factor and for the age of the Universe.
None
nebemlineinspec bool -- default of ``include_lines`` in ``get_spectrum`` only.
False
wavelength_support bool -- opt-in (default False): ``predict`` synthesises only the model

pixels the observations read (_support_for: Photometry's filter columns and sigma_gal window, a Spectrum's projector window) and zero-fills the rest after the mass, flux and IGM scaling; ~2.5-3x faster likelihood on CPU for a JWST photometry (+ grating) model on the 1 A - 1e8 A BPASS grid. Not byte-identical to the whole grid: XLA's reductions change their summation order with the array length, so predictions differ in the last float32 bit (relative ~1e-7). Ignored (whole grid) for dust emission, painted lines and a Photometry at a sampled redshift.

False
agn ceridwen.agn.AGNConfig, True, a mode name, or None -- the AGN (Nenkova+08 torus,

Temple+21 disc, dust4 screen, narrow lines), off by default (None: every path unchanged, byte for byte). AGNConfig() / True = "corrected" (exact fagn * L_bol, clamped agn_tau, before the IGM, energy balance with dust emission); AGNConfig(agn_mode="fsps") / "fsps" reproduces FSPS add_agn_dust, "prospector" Prospector's AGNSSPBasis + AGNSpecModel; see ceridwen.agn and docs/agn.md. The theta keys (fagn, agn_tau, ...) get their defaults here.

None
Source code in ceridwen/csp/csp.py
def __init__(
    self,
    SSPData,
    theta=None,
    tiny_logt=-70,
    zh_const=False,
    add_neb=True,
    init_neb_params=None,
    nebemlineinspec=False,
    add_dust=True,
    add_diffuse_dust=True,
    add_dust_emission=False,
    add_igm=False,
    igm_model="madau1995",
    igm_factor=1.0,
    sps_home=None,
    init_dust_params=None,
    diffuse_law='kriek_conroy',
    verbose=True,
    sfh_interp='step',
    track_zred_age=False,
    lookback_time=None,
    sfh_per_bin=None,
    fesc_geometry="runaway_bc",
    duste_model="DL07",
    cosmo=None,
    gas_tied=False,
    wavelength_support=False,
    agn=None,
    fixed=None,
    **kwargs,
):
    self.verbose = bool(verbose)
    self.gas_tied = bool(gas_tied)
    self._wave_support = bool(wavelength_support)
    if self.gas_tied and not add_neb:
        raise ValueError("gas_tied=True ties the nebular gas metallicity to the stars, "
                         "but add_neb=False: there is no nebular model to tie")
    if kwargs:
        hint = ""
        if "sigma_losvd_kms" in kwargs:
            hint = (" ('sigma_losvd_kms' is not an argument: the galaxy velocity "
                    "dispersion is set once on the model, "
                    "SedModel(kinematics=Kinematics(sigma_gal=...)))")
        elif "tuniv" in kwargs:
            hint = (" ('tuniv' is not an argument: the age of the Universe comes from "
                    "the cosmology, csp.age_at(z) / cosmo.age(z))")
        raise TypeError(
            f"CSPBasis got unexpected keyword argument(s) {sorted(kwargs)}{hint}")
    if lookback_time is not None:
        if theta is not None:
            raise ValueError(
                "Pass either theta= (full control over the initial "
                "parameter values) or the lookback_time= shortcut, not "
                "both."
            )
        _lb = jnp.atleast_1d(jnp.asarray(lookback_time, dtype=float))
        _n = int(_lb.size)
        theta = {
            'lookback_time': _lb,
            'sfh': jnp.ones(max(_n - 1, 1) if _sfh_per_bin(sfh_interp, sfh_per_bin) else _n),
        }
        _lz_mid = _default_logzsol(SSPData)
        if zh_const:
            theta['logzsol'] = jnp.array([_lz_mid])
        else:
            theta['logzsol_bins'] = jnp.full((max(_n - 1, 1),), _lz_mid)
    if theta is None:
        raise ValueError(
            "CSPBasis needs the static SFH grid structure. Pass either\n"
            "  lookback_time=jnp.linspace(0.0, T_oldest, n_nodes)   "
            "(shortcut; neutral initial values), or\n"
            "  theta={'lookback_time': ..., 'sfh': ..., 'logzsol' or 'logzsol_bins': ...} "
            "(full control).\n"
            "lookback_time is in Gyr, monotonically increasing, index 0 = "
            "today, >= 2 nodes."
        )
    # copies: initialize_neb pops / adds keys, and the caller may reuse the dict (B1-015)
    init_neb_params = {"cloudy_dust": False, **(init_neb_params or {})}
    init_dust_params = ({'bin_edges': [(-jnp.inf, -1.97)], 'laws': ['powerlaw']}
                        if init_dust_params is None else dict(init_dust_params))

    # the grid's cube is host NumPy; the float32 cast runs on the device (XLA's convert,
    # which flushes float32 subnormals, as before) from a transient float64 copy that is
    # freed at once, so the device keeps only the float32 cube
    _f64 = jnp.asarray(SSPData.ssp_flux)
    self.flux      = _f64.astype(jnp.float32)          # (n_z, n_age, n_wave)
    del _f64
    self.wave      = jnp.array(SSPData.ssp_wave)       # (n_wave,)
    # the attenuation curves are evaluated on this float32 copy: the kernels use them in
    # float32 (the wavelengths that place lines and pixels stay float64, self.wave)
    self._wave32   = self.wave.astype(jnp.float32)
    self.ages      = jnp.array(SSPData.ssp_lg_age_gyr) # (n_age,)  log10(Gyr)
    self._setup_metallicity(SSPData)                   # self.zmet: logzsol axis
    self.lib_resolution = (
        (np.asarray(SSPData.ssp_wave, dtype=np.float64),
         np.asarray(SSPData.ssp_resolution, dtype=np.float64))
        if getattr(SSPData, "ssp_resolution", None) is not None else None)
    self.ssp_ages_lgyr = self.ages + 9                 # log10(yr)
    # surviving mass per M_sun formed (SSP schema 3); post-processing only, never traced
    # by the forward model
    _m = getattr(SSPData, "ssp_stellar_mass", None)
    self.ssp_stellar_mass = None if _m is None else np.asarray(_m, dtype=np.float64)
    self.stellar_mass_source = getattr(SSPData, "stellar_mass_source", None)
    self.stellar_mass_refused = getattr(SSPData, "stellar_mass_refused", None)

    self._ssp_isoc_type    = getattr(SSPData, "isoc_type", None)
    self._ssp_spec_library = getattr(SSPData, "spec_library", None)
    self._ssp_imf_type     = getattr(SSPData, "imf_type", None)   # FSPS imf_type (display only)

    if fesc_geometry not in ("runaway_bc", "picket"):
        raise ValueError(
            f"fesc_geometry must be 'runaway_bc' or 'picket', got {fesc_geometry!r}")
    if fesc_geometry == "picket" and not add_neb:
        raise ValueError(
            "fesc_geometry='picket' needs add_neb=True: its clear channel is defined on the "
            "ages of the nebular (CLOUDY) grid and the covered ionising photons power the "
            "nebular emission.  Without a nebular model use fesc_geometry='runaway_bc'.")
    self.fesc_geometry = str(fesc_geometry)

    self._logage_lo  = self.ssp_ages_lgyr[1:]
    self._logage_hi  = self.ssp_ages_lgyr[:-1]
    self._dlogage    = jnp.diff(self.ssp_ages_lgyr)
    self._j_range    = jnp.arange(self.ssp_ages_lgyr.size)
    self._age_clip_lo = 10.0 ** (-70)                  # floor for log-time clipping
    self._age_clip_hi = 10.0 ** self.ssp_ages_lgyr[-1] # ceiling
    self._n_z   = len(self.zmet)
    self._n_age = len(self.ages)

    self._ssp_lo_yr = 10.0 ** self._logage_hi   # (n_age-1,)
    self._ssp_hi_yr = 10.0 ** self._logage_lo   # (n_age-1,)

    _ssp_age_yr  = 10.0 ** self.ssp_ages_lgyr           # (n_age,) linear yr
    _voro_mid    = 0.5 * (_ssp_age_yr[:-1] + _ssp_age_yr[1:])  # (n_age-1,)
    _voro_hi_ext = _ssp_age_yr[-1] + (_ssp_age_yr[-1] - _ssp_age_yr[-2])
    self._ssp_voronoi_lo = jnp.concatenate(
        [jnp.zeros(1), _voro_mid]
    )
    self._ssp_voronoi_hi = jnp.concatenate(
        [_voro_mid, jnp.array([_voro_hi_ext])]
    )

    self.tiny_logt  = tiny_logt
    if sps_home is None:
        sps_home = os.environ.get("SPS_HOME")
    if (add_neb or add_dust_emission) and not sps_home:
        raise ValueError(
            "sps_home is required for nebular / dust emission but was not "
            "given and $SPS_HOME is unset. Set `export SPS_HOME=/path/to/fsps` "
            "(your FSPS data directory) or pass sps_home=... explicitly."
        )
    self.sps_home   = sps_home
    self.duste_model = _check_duste_model(duste_model, add_dust_emission)
    from ..cosmology import Cosmology as _Cosmology
    if cosmo is None:
        raise TypeError(
            f"{type(self).__name__} needs an explicit cosmology: pass "
            "cosmo=Cosmology.planck18(), Cosmology.wmap9(), "
            "Cosmology.flat(H0, Om0), Cosmology.from_name(...) or "
            "Cosmology.from_astropy(...)  (from ceridwen import Cosmology)")
    if not isinstance(cosmo, _Cosmology):
        raise TypeError(
            f"cosmo must be a ceridwen Cosmology, got {type(cosmo).__name__}; "
            "for an astropy cosmology use Cosmology.from_astropy(...)")
    self._cosmo = cosmo
    self.track_zred_age = bool(track_zred_age)
    self.nebemlineinspec = bool(nebemlineinspec)

    self._setup_igm(add_igm, igm_model, igm_factor)

    if add_diffuse_dust or add_dust:
        self.set_attenuation_function(add_diffuse_dust, add_dust)

    theta = self.initialize_dust_components(
        add_dust, add_diffuse_dust, add_dust_emission,
        theta, init_dust_params, diffuse_law, sps_home,
    )
    theta = self.initialize_neb(add_neb, theta, init_neb_params, sps_home)

    self.configure_spectrum_model(
        add_dust, add_diffuse_dust, add_dust_emission, add_neb, sps_home
    )
    theta = self._install_agn(agn, theta, SSPData, add_dust_emission, sps_home)

    if sfh_interp not in ('step', 'linear'):
        raise ValueError(
            f"sfh_interp must be 'step' or 'linear', got {sfh_interp!r}"
        )
    self.sfh_interp = sfh_interp
    self.zh_const = bool(zh_const)
    if zh_const:
        if sfh_interp == 'step':
            self.calculate_ssp_weights = self.calculate_ssp_weights_const_zh_step
        else:
            self.calculate_ssp_weights = self.calculate_ssp_weights_const_zh
    else:
        if sfh_interp == 'step':
            self.calculate_ssp_weights = self.calculate_ssp_weights_var_zh_step
        else:
            self.calculate_ssp_weights = self.calculate_ssp_weights_var_zh
    if verbose:
        print(f"SFH integration scheme : {sfh_interp}")

    self.initialize_model_structure(theta)
    self._set_fixed(fixed)

    if verbose:
        print("\nCSPBasis (dict theta) — registered parameters:")
        pprint.pprint({k: v.shape for k, v in self.theta_init.items()})

    self.check_param_ranges(self.theta_init)

all_params property

all_params

Return the initial theta dict (one entry per free parameter).

cosmo property writable

cosmo

The cosmology; fixed at construction (assignment raises).

initialize_model_structure

initialize_model_structure(theta)

Validate theta (grid, sfh shape, metallicity key) and build theta_init / param_names.

Source code in ceridwen/csp/csp.py
def initialize_model_structure(self, theta):
    """Validate ``theta`` (grid, sfh shape, metallicity key) and build ``theta_init`` / ``param_names``."""
    if 'lookback_time' not in theta:
        raise ValueError(
            "theta must contain 'lookback_time' — the static SFH node grid "
            "(Gyr, monotonically increasing, index 0 = today). It is "
            "required even when the redshift is a free parameter: with "
            "track_zred_age=True the grid is rescaled inside the forward "
            "pass to track age(zred), but its LENGTH and RELATIVE spacing "
            "come from this construction-time grid, so it defines n_time "
            "and the bin structure rather than a fixed absolute age range."
        )
    if 'sfh' not in theta:
        raise ValueError(
            "theta must contain 'sfh' — star-formation-rate values, either "
            "one per lookback node (shape (n_time,)) or one per bin "
            "(shape (n_time-1,), FastStepBasis convention), where n_time = "
            "len(theta['lookback_time'])."
        )

    self.sfh_times = jnp.atleast_1d(
        jnp.asarray(theta['lookback_time'], dtype=float)
    ) * 1e9   # Gyr → yr
    self.n_time = self.sfh_times.size

    if self.n_time < 2:
        raise ValueError(
            f"theta['lookback_time'] has {self.n_time} node(s); at least "
            "2 are required (n_time nodes define n_time-1 SFH bins). "
            "Typical fits use 5-10 nodes, e.g. "
            "jnp.linspace(0.0, T_UNIV, 6)."
        )

    _lb = np.asarray(self.sfh_times, dtype=np.float64)
    _diffs = np.diff(_lb)
    if not (np.all(_diffs > 0.0) and _lb[0] >= 0.0 and _lb[0] < 1e8):
        raise ValueError(
            "theta['lookback_time'] must be monotonically *increasing*:\n"
            f"  - index 0 = today (≈ 0 Gyr): got {_lb[0]/1e9:.3f} Gyr\n"
            f"  - index -1 = oldest (≈ T_univ): got {_lb[-1]/1e9:.3f} Gyr\n"
            f"  - first three values [Gyr]: {(_lb[:3]/1e9).tolist()}\n"
            "If your grid runs from oldest to today, replace e.g.\n"
            "    lookback = T_UNIV - jnp.linspace(eps, T_UNIV, N)\n"
            "with\n"
            "    lookback = jnp.linspace(0.0, T_UNIV, N)\n"
            "and reverse theta['sfh'] (and theta['logzsol_bins'] if present) to match."
        )

    sfh = jnp.atleast_1d(jnp.asarray(theta['sfh'], dtype=float))
    if sfh.shape == (self.n_time,) and self.sfh_interp == "step":
        s = np.asarray(sfh, dtype=np.float64)
        raise ValueError(
            f"theta['sfh'] has one value per NODE, shape {sfh.shape}. " + _STEP_PER_NODE_NOTE
            + f"  The same step model is theta['sfh'] = 0.5*(sfh[:-1] + sfh[1:]) = "
            f"{np.array2string(0.5 * (s[:-1] + s[1:]), precision=4)}.")
    if sfh.shape == (self.n_time,):
        self.sfh_per_bin = False
    elif sfh.shape == (self.n_time - 1,):
        self.sfh_per_bin = True
    else:
        raise AssertionError(
            f"'sfh' shape {sfh.shape} must be ({self.n_time - 1},) (one SFR per bin; "
            f"sfh_interp='step' or 'linear') or ({self.n_time},) (one per node; "
            f"sfh_interp='linear' only) for {self.n_time} lookback nodes."
        )

    sfh_np = np.asarray(sfh)
    if not np.all(np.isfinite(sfh_np)):
        raise ValueError(
            "theta['sfh'] contains non-finite (NaN/Inf) values; this would "
            "silently produce a NaN spectrum."
        )
    if np.any(sfh_np < 0):
        warnings.warn(
            "theta['sfh'] contains negative values. SFR is clipped to >=0 "
            "internally, so negative bins contribute ~zero flux (no error is "
            "raised at evaluation time).",
            stacklevel=3,
        )

    for old in REMOVED_THETA_KEYS:
        if old in theta:
            raise removed_metallicity_key_error(old, theta[old], self.log10_zsun,
                                                self.axis_meaning)
    if self.zh_const:
        if 'logzsol' not in theta:
            raise ValueError(
                "zh_const=True requires a constant metallicity theta['logzsol'] "
                "(shape-(1,) array, log10(Z/Z_sun) of the SSP grid, e.g. 0.0 = solar); "
                "none was provided. Either add theta['logzsol'], or construct with "
                "zh_const=False and provide theta['logzsol_bins'] of shape "
                "(n_time-1,), one value per SFH bin."
            )
        if 'logzsol_bins' in theta:
            raise ValueError(
                "zh_const=True but theta also contains 'logzsol_bins'; a constant-"
                "metallicity basis reads only 'logzsol'. Remove 'logzsol_bins' or "
                "construct with zh_const=False.")
    else:
        if 'logzsol_bins' not in theta:
            raise ValueError(
                "zh_const=False requires a metallicity history theta['logzsol_bins'] of "
                "shape (n_time-1,) (log10(Z/Z_sun) of the SSP grid, one per SFH bin, "
                "index 0 = youngest); none was provided. Either add it, or construct "
                "with zh_const=True and provide theta['logzsol']."
            )
        if 'logzsol' in theta:
            raise ValueError(
                "zh_const=False but theta also contains 'logzsol'; a metallicity-"
                "history basis reads only 'logzsol_bins'. Remove 'logzsol' or "
                "construct with zh_const=True.")
    if self.gas_tied and 'gas_logz' in theta:
        raise ValueError(
            "gas_tied=True sets gas_logz from the stellar logzsol, but theta also "
            "gives 'gas_logz'; remove one (a tied gas metallicity is not a parameter).")

    self.zh_is_scalar = None
    # the metallicity key this configuration reads (static; used by every key reader)
    self.zh_key = 'logzsol' if self.zh_const else 'logzsol_bins'
    if 'logzsol_bins' in theta:
        zb = jnp.atleast_1d(jnp.asarray(theta['logzsol_bins'], dtype=float))
        if zb.shape != (self.n_time - 1,):
            raise ValueError(
                f"theta['logzsol_bins'] has shape {zb.shape}; it holds one metallicity per "
                f"SFH bin, shape ({self.n_time - 1},) for {self.n_time} lookback nodes "
                "(index 0 = youngest bin).")
        if not np.all(np.isfinite(np.asarray(zb))):
            raise ValueError(f"theta['logzsol_bins'] = {np.asarray(zb)} is not finite")
        self.zh_is_scalar = False
    elif 'logzsol' in theta:
        Z = jnp.atleast_1d(jnp.asarray(theta['logzsol'], dtype=float))
        assert Z.shape == (1,), "'logzsol' must be a scalar (wrapped in shape-(1,) array)"
        self.zh_is_scalar = True


    self.theta_init = {}
    for k, v in theta.items():
        if k == 'lookback_time':
            continue   # static grid — not a free parameter
        arr = jnp.atleast_1d(jnp.asarray(v, dtype=float))
        self.theta_init[k] = arr

    self.theta_init['sfh'] = sfh

    self.param_names = list(self.theta_init.keys())

    self._known_theta_keys = set(self.param_names) | {
        'lookback_time', 'logzsol', 'logzsol_bins',
        'logmass', 'zred', 'lumdist_mpc', 'igm_factor', 'eline_scaling',
        'frac_obrun', 'spectrum_scaling', 'spectrum_calib',
    } | set(getattr(getattr(self, "igm", None), "param_names", ())) \
      | set(getattr(self._agn, "param_names", ()))
    self._apply_fixed()

register_known_theta_keys

register_known_theta_keys(keys)

Add keys that _warn_unknown_theta_keys must accept (model-level parameters consumed by transforms).

Source code in ceridwen/csp/csp.py
def register_known_theta_keys(self, keys):
    """Add keys that ``_warn_unknown_theta_keys`` must accept (model-level parameters consumed by transforms)."""
    self._known_theta_keys |= set(keys)

check_param_ranges

check_param_ranges(theta=None, warn=True)

Messages (and warnings) for metallicity / nebular parameters outside the interpolation grids, where the model clamps silently.

Source code in ceridwen/csp/csp.py
def check_param_ranges(self, theta=None, warn=True):
    """Messages (and warnings) for metallicity / nebular parameters outside the interpolation grids, where the model clamps silently."""
    if theta is None:
        theta = self.theta_init
    msgs = []

    for old in REMOVED_THETA_KEYS:
        if old in theta:
            raise removed_metallicity_key_error(old, theta[old], self.log10_zsun,
                                                self.axis_meaning)
    zlo, zhi = float(self.zmet.min()), float(self.zmet.max())
    zs = (f"Z_sun = {self.zsun_nominal:.6g}, log10 Z_sun = {self.log10_zsun:.6f}"
          if self.zsun_nominal is not None else f"log10 Z_sun = {self.log10_zsun:.6f}")
    for key in LOGZSOL_KEYS:
        if key in theta:
            v = np.asarray(theta[key], float)
            if v.size and (np.nanmin(v) < zlo or np.nanmax(v) > zhi):
                msgs.append(
                    f"theta['{key}'] = {np.array2string(v, precision=3)} is outside the "
                    f"SSP metallicity grid, logzsol in [{zlo:+.3f}, {zhi:+.3f}] "
                    f"({zs}); the interpolation clamps to the edge node there."
                )
            if v.size and np.nanmax(v) < ABSOLUTE_LOOKING_LOGZSOL:
                msgs.append(
                    f"theta['{key}'] = {np.array2string(v, precision=3)} is below "
                    f"{ABSOLUTE_LOOKING_LOGZSOL} everywhere: is it an OLD absolute log10 Z? "
                    f"logzsol = log10(Z/Z_sun) is 0 at solar on this grid ({zs}); an "
                    f"absolute log10 Z = {float(np.nanmax(v)):+.3f} would be logzsol = "
                    f"{float(np.nanmax(v)) - self.log10_zsun:+.3f}.  Ignore this if a "
                    "metal-poor population is intended."
                )

    neb = getattr(self, 'neb', None)
    if neb is not None:
        for key, attrs in (
            ('gas_logz', ('logZ_grid', 'logz_grid', '_logZ', 'nebem_logz')),
            ('gas_logu', ('logU_grid', 'logu_grid', '_logU', 'nebem_logu')),
        ):
            if key == 'gas_logz' and self.gas_tied:
                src = self.zh_key
                if src not in theta:
                    continue
                g = np.asarray(neb.nebem_logz, float)
                v = np.asarray(theta[src], float)
                v = v if self.zh_const else v[:1]
                which = {"logzsol": "", "logzsol_bins": "[0] (the youngest bin's value)"}[src]
                if v.size and (np.nanmin(v) < g.min() or np.nanmax(v) > g.max()):
                    msgs.append(
                        f"gas_tied=True: the gas metallicity follows theta['{src}']{which} = "
                        f"{np.array2string(v, precision=3)}, outside the nebular grid "
                        f"[{g.min():.3f}, {g.max():.3f}] (log10 Z_gas/Z_sun of the "
                        "CLOUDY grid); the nebular emission clamps there.")
                continue
            if key in theta:
                grid = next((getattr(neb, a) for a in attrs if hasattr(neb, a)),
                            None)
                if grid is not None:
                    g = np.asarray(grid, float)
                    glo, ghi = float(g.min()), float(g.max())
                    v = np.asarray(theta[key], float)
                    if v.size and (np.nanmin(v) < glo or np.nanmax(v) > ghi):
                        msgs.append(
                            f"theta['{key}'] = {np.array2string(v, precision=3)} outside "
                            f"the nebular grid [{glo:.3f}, {ghi:.3f}]"
                            + (" (log10 Z_gas/Z_sun of the CLOUDY grid)"
                               if key == 'gas_logz' else "")
                            + "; the nebular emission clamps there."
                        )

    if self._agn is not None:
        msgs += self._agn.range_messages(theta)

    if warn:
        for m in msgs:
            warnings.warn(m, stacklevel=2)
    return msgs

set_attenuation_function

set_attenuation_function(add_diffuse_dust, add_dust)

Assign self.attenuate_dust(wave, theta) -> (attn_birthcloud (n_bins, n_wave), attn_diffuse (n_wave,)) as optical depths.

The attribute is a BOUND METHOD of this instance (one of _attenuate_*), not a closure over self: a shallow copy whose stored bound methods are re-bound to the copy then reads the COPY's dust models. The expressions are unchanged (bit-identical). It is set only when dust is configured, so hasattr(csp, "attenuate_dust") keeps meaning "this CSP attenuates" (model.py, _agn_galaxy_ldust).

Source code in ceridwen/csp/csp.py
def set_attenuation_function(self, add_diffuse_dust, add_dust):
    """Assign ``self.attenuate_dust(wave, theta) -> (attn_birthcloud (n_bins, n_wave), attn_diffuse (n_wave,))`` as optical depths.

    The attribute is a BOUND METHOD of this instance (one of ``_attenuate_*``), not a closure
    over ``self``: a shallow copy whose stored bound methods are re-bound to the copy then
    reads the COPY's dust models.  The expressions are unchanged (bit-identical).  It is set
    only when dust is configured, so ``hasattr(csp, "attenuate_dust")`` keeps meaning
    "this CSP attenuates" (``model.py``, ``_agn_galaxy_ldust``)."""
    if add_diffuse_dust and add_dust:
        if self.verbose:
            print("Using combined (binwise + diffuse) dust attenuation.")
        self.attenuate_dust = types.MethodType(CSPBasis._attenuate_bc_and_diffuse, self)

    elif add_dust and not add_diffuse_dust:
        if self.verbose:
            print("Using only binwise dust attenuation.")
        self.attenuate_dust = types.MethodType(CSPBasis._attenuate_bc_only, self)

    elif add_diffuse_dust and not add_dust:
        self.bin_low  = jnp.array([-jnp.inf])
        self.bin_high = jnp.array([jnp.inf])
        if self.verbose:
            print("Using only diffuse dust attenuation.")
        self.attenuate_dust = types.MethodType(CSPBasis._attenuate_diffuse_only, self)

get_spectrum_components

get_spectrum_components(theta)

(continuum, lines) on the rest-frame grid, unscaled (no mass, distance or IGM): continuum is get_spectrum(include_lines=False) and lines the difference to the full spectrum: the attenuated painted lines. With dust emission the dust re-emission of the lines' absorbed energy is in continuum, as on every path.

Source code in ceridwen/csp/csp.py
def get_spectrum_components(self, theta: dict) -> tuple:
    """``(continuum, lines)`` on the rest-frame grid, unscaled (no mass, distance or IGM):
    ``continuum`` is ``get_spectrum(include_lines=False)`` and ``lines`` the difference to the
    full spectrum: the attenuated painted lines.  With dust emission the dust re-emission of
    the lines' absorbed energy is in ``continuum``, as on every path.
    """
    self._warn_unknown_theta_keys(theta)
    continuum = self.get_spectrum(theta=theta, include_lines=False)
    full      = self.get_spectrum(theta=theta, include_lines=True)
    return continuum, full - continuum

predict

predict(
    theta,
    observations,
    *,
    kinematics=None,
    broaden_photometry=False,
    eline_system=None
)

{obs.name: prediction}: Photometry -> maggies (n_filters,), Spectrum -> F_nu [erg/s/cm^2/Hz] on the observed pixels, Lines -> integrated fluxes (n_lines,). Observed-frame only when theta carries zred.

kinematics (Kinematics or None) supplies sigma_gal / sigma_gas; broaden_photometry applies them to the spectrum entering each Photometry's _broadener. The lines are not painted on the model grid (only with _force_paint_lines, a reference path): Photometry adds each line's flux through each filter (obs._line_photometry: delta lines, or Gaussians of the gas width with broaden_photometry), Spectrum paints them on the observed pixels and Lines reads them from the grid.

eline_system (ElineSystem of SedModel, line marginalisation): returns (predictions, aux) with the fitted lines removed from every prediction and aux = {"prior_mean": CLOUDY fluxes of the fitted lines, "cols": {obs.name: design}}.

Source code in ceridwen/csp/csp.py
def predict(self, theta: dict, observations: list, *, kinematics=None,
            broaden_photometry=False, eline_system=None) -> dict:
    """``{obs.name: prediction}``: Photometry -> maggies (n_filters,), Spectrum -> F_nu [erg/s/cm^2/Hz]
    on the observed pixels, Lines -> integrated fluxes (n_lines,).  Observed-frame only when
    ``theta`` carries ``zred``.

    ``kinematics`` (``Kinematics`` or None) supplies sigma_gal / sigma_gas; ``broaden_photometry``
    applies them to the spectrum entering each Photometry's ``_broadener``.  The lines are not
    painted on the model grid (only with ``_force_paint_lines``, a reference path): Photometry
    adds each line's flux through each filter (``obs._line_photometry``: delta lines, or
    Gaussians of the gas width with ``broaden_photometry``), Spectrum paints them on the
    observed pixels and Lines reads them from the grid.

    ``eline_system`` (``ElineSystem`` of ``SedModel``, line marginalisation): returns
    ``(predictions, aux)`` with the fitted lines removed from every prediction and
    ``aux = {"prior_mean": CLOUDY fluxes of the fitted lines, "cols": {obs.name: design}}``.
    """
    if kinematics is not None:
        self._known_theta_keys |= set(kinematics.free_keys)
    has_neb = getattr(self, "neb", None) is not None
    paint_lines = has_neb and bool(getattr(self, "_force_paint_lines", False))
    support = self._support_for(observations, theta, paint_lines)
    if support is None:
        cont, lines = self._assemble_components(theta, paint_lines)
    else:
        self._warn_unknown_theta_keys(theta)
        cont = self.get_spectrum(theta=theta, include_lines=False, support=support)
        lines = None
    # mass and flux factor first; the IGM separately, so the kinematic kernels can act
    # before it (galaxy kinematics -> redshift -> IGM -> instrument)
    cont0, lines0 = self._apply_mass_redshift_igm(
        cont, cont if lines is None else lines, theta, igm=False)
    trans = None
    agn_corr = None
    if self.igm is not None and "zred" in theta:
        trans = self._igm_transmission(
            jnp.ravel(theta["zred"])[0], theta).astype(cont0.dtype)
        # on the whole grid, then the support: Madau's tau is capped at its peak (argmax)
        trans = _sel(trans, support)
        cont, lines_s = cont0 * trans, lines0 * trans
        agn_corr = self._agn_after_igm(theta, trans, cont0.dtype, support)
        if agn_corr is not None:
            cont = cont + agn_corr
    else:
        cont, lines_s = cont0, lines0
    if support is not None:
        # zeros on the pixels no observation reads, only after every scaling (XLA CPU
        # returns zeros for a pad inside that fusion)
        width = (support.start, self.wave.shape[0] - support.stop)
        cont, cont0 = jnp.pad(cont, width), jnp.pad(cont0, width)
        if agn_corr is not None:
            agn_corr = jnp.pad(agn_corr, width)
    return self._project_observations(
        cont if lines is None else cont + lines_s, cont,
        observations, theta, paint_lines=paint_lines,
        line_component=None if lines is None else lines_s,
        kinematics=kinematics, broaden_photometry=broaden_photometry,
        eline_system=eline_system,
        before_igm=None if trans is None else (cont0, None if lines is None else lines0),
        **({} if agn_corr is None else {"agn_after_igm": agn_corr}),
    )

predict_line_fluxes

predict_line_fluxes(
    theta, *, for_photometry=False, for_spectrum=False
)

Observed-frame fluxes of every nebular grid line (n_lines,), through the same weights, dust, escape, mass and distance factors as the spectrum.

Default: integrated fluxes [erg/s/cm^2] with the 1/(1+z) Jacobian, the IGM transmission averaged over the line's painted profile and eline_scaling (the Lines observation). for_spectrum: the same without eline_scaling (painted by the Spectrum projector). for_photometry: per-Hz amplitudes with the full f_nu flux factor and no IGM (applied inside the photometric line basis) and no eline_scaling.

Source code in ceridwen/csp/csp.py
def predict_line_fluxes(self, theta, *, for_photometry=False, for_spectrum=False):
    """Observed-frame fluxes of every nebular grid line (n_lines,), through the same weights,
    dust, escape, mass and distance factors as the spectrum.

    Default: integrated fluxes [erg/s/cm^2] with the 1/(1+z) Jacobian, the IGM transmission
    averaged over the line's painted profile and ``eline_scaling`` (the Lines observation).  ``for_spectrum``: the same
    without ``eline_scaling`` (painted by the Spectrum projector).  ``for_photometry``: per-Hz
    amplitudes with the full f_nu flux factor and no IGM (applied inside the photometric line
    basis) and no ``eline_scaling``.
    """
    W = self.calculate_ssp_weights(theta=theta)          # (n_z, n_age)
    logZ_gas = self._gas_logz(theta)
    logU     = theta["gas_logu"]
    line_lum = self.neb.evaluate_batch_line_lum(
        logZ_gas, logU, self._neb_ages_young, self._neb_logqq_young,
    )                                                    # (n_z, n_young, n_lines)
    if "frac_obrun" in theta:
        f_esc = jnp.ravel(theta["frac_obrun"])[0]
        line_lum = line_lum * (1.0 - f_esc)

    lam = self.neb.nebem_line_pos                        # (n_lines,)
    li = jnp.clip(jnp.searchsorted(self.wave, lam) - 1,
                  0, self.wave.shape[0] - 2)
    lf = jnp.clip((lam - self.wave[li])
                  / (self.wave[li + 1] - self.wave[li]), 0.0, 1.0)

    n_young = self._neb_young_idx.shape[0]
    attn_age_lines = jnp.ones((n_young, lam.shape[0]))
    diff_lines = jnp.ones(lam.shape[0])
    if hasattr(self, "attenuate_dust"):
        attn, attn_diffuse = self.attenuate_dust(self._wave32, theta)
        if hasattr(self, "_age_bin_mix"):
            M = self._age_bin_mix
            tau_age = jnp.einsum("ab,bw->aw", M, attn)   # (n_age, n_wave)
            tau_lines = ((1.0 - lf)[None, :] * tau_age[:, li]
                         +        lf[None, :] * tau_age[:, li + 1])
            aal = jnp.exp(-tau_lines)                    # (n_age, n_lines)
            if "frac_obrun" in theta and self.fesc_geometry != "picket":
                fo = jnp.ravel(theta["frac_obrun"])[0]
                aal = (1.0 - fo) * aal + fo
            attn_age_lines = aal[self._neb_young_idx, :]
        diff_lines = jnp.exp(-((1.0 - lf) * attn_diffuse[li]
                               + lf * attn_diffuse[li + 1]))

    # float64 (a handful of numbers: free on any GPU): the line luminosities span ~1e-51 to
    # ~1e2 L_sun, the AGN line sets add to these fluxes, and the painters and apertures that
    # spread them over pixels work in float32 (docs/conventions.md "Precision")
    F = jnp.einsum("zy,zyl,yl->l",
                   W[:, self._neb_young_idx], line_lum, attn_age_lines)
    F = F * diff_lines

    if "logmass" in theta:
        F = F * 10.0 ** jnp.ravel(theta["logmass"])[0]
    if "zred" in theta:
        z_scalar = jnp.ravel(theta["zred"])[0]
        ff = self._flux_factor(theta)
        F = F * (ff if for_photometry else ff / (1.0 + z_scalar))
        if self.igm is not None and not for_photometry:
            # averaged over the painted profile, as the painted path applies it (the IGM
            # can jump inside a line: Madau at Ly-alpha)
            trans = self._igm_transmission(z_scalar, theta)
            F = F * jnp.where(self._neb_line_on_grid, self._neb_line_profile_w @ trans,
                              (1.0 - lf) * trans[li] + lf * trans[li + 1])
    if not for_photometry and not for_spectrum and "eline_scaling" in theta:
        F = F * jnp.ravel(theta["eline_scaling"])[0]
    return F

get_line_spec

get_line_spec(theta)

Painted line component alone on the rest-frame grid, scaled by mass, flux factor and IGM as in predict, times eline_scaling (the Lines-observation aperture factor).

Source code in ceridwen/csp/csp.py
def get_line_spec(self, theta):
    """Painted line component alone on the rest-frame grid, scaled by mass, flux factor and IGM as in
    ``predict``, times ``eline_scaling`` (the Lines-observation aperture factor)."""
    if not hasattr(self, "neb") or self.neb is None:
        return jnp.zeros_like(self.wave)

    _continuum, line_only = self.get_spectrum_components(theta)

    if "logmass" in theta:
        mass_scale = jnp.float32(10.0 ** jnp.ravel(theta["logmass"])[0])
        line_only = line_only * mass_scale
    if "zred" in theta:
        z_scalar = jnp.ravel(theta["zred"])[0]
        line_only = line_only * jnp.float32(self._flux_factor(theta))
        if self.igm is not None:
            transmission = self._igm_transmission(z_scalar, theta)
            line_only = line_only * transmission.astype(line_only.dtype)
    if "eline_scaling" in theta:
        line_only = line_only * jnp.ravel(theta["eline_scaling"])[0]
    return line_only

age_at

age_at(z)

Age of the Universe [Gyr] at redshift z under self.cosmo (a float for a scalar, a JAX array otherwise).

Source code in ceridwen/csp/csp.py
def age_at(self, z):
    """Age of the Universe [Gyr] at redshift ``z`` under ``self.cosmo``
    (a float for a scalar, a JAX array otherwise)."""
    from ceridwen.cosmology import age_gyr
    out = age_gyr(jnp.asarray(z, dtype=float), self.cosmo)
    return float(out) if jnp.ndim(out) == 0 else out

display_sfh

display_sfh(
    theta=None,
    ax=None,
    *,
    overlay_nodes=True,
    show_bin_edges=False,
    units="Gyr",
    **plot_kwargs
)

Plot the SFH exactly as _ssp_weights interprets it (step: constant per bin; linear: chords between nodes); theta defaults to theta_init, units in {"Gyr", "Myr", "yr"}. Returns the axes.

Source code in ceridwen/csp/csp.py
def display_sfh(self, theta=None, ax=None, *,
                overlay_nodes=True, show_bin_edges=False,
                units="Gyr", **plot_kwargs):
    """Plot the SFH exactly as ``_ssp_weights`` interprets it (step: constant per bin; linear:
    chords between nodes); ``theta`` defaults to ``theta_init``, ``units`` in {"Gyr", "Myr", "yr"}.
    Returns the axes.
    """
    import matplotlib.pyplot as plt

    theta = self.theta_init if theta is None else theta

    T_ref = None
    if "lookback_time" in theta:
        T_gyr = np.asarray(theta["lookback_time"], dtype=float)
    elif self.track_zred_age and "zred" in theta:   # the zred-tracked grid (_sfh_grids)
        T_yr, T_ref = (np.asarray(g, dtype=float) for g in self._sfh_grids(theta))
        T_gyr = T_yr / 1e9
    else:
        T_gyr = np.asarray(self.sfh_times, dtype=float) / 1e9
    T_gyr = np.atleast_1d(T_gyr).ravel()
    n_time = T_gyr.size

    psi = np.atleast_1d(np.asarray(theta["sfh"], dtype=float)).ravel()
    if psi.size not in (n_time, n_time - 1):
        raise AssertionError(
            f"theta['sfh'] has length {psi.size}; expected {n_time} "
            f"(per-node) or {n_time - 1} (per-bin, FastStepBasis)."
        )
    per_bin = (psi.size == n_time - 1)

    T_yr = T_gyr * 1e9
    dt_yr = T_yr[1:] - T_yr[:-1]
    if not np.all(dt_yr > 0):
        raise AssertionError(
            "lookback-time grid must be strictly increasing (today at "
            f"index 0, oldest last); got dt_yr = {dt_yr}"
        )

    if per_bin:
        bar_psi = psi
    else:
        bar_psi = 0.5 * (psi[:-1] + psi[1:])

    if per_bin:
        psi_nodes = np.empty(n_time, dtype=float)
        psi_nodes[0]    = psi[0]
        psi_nodes[-1]   = psi[-1]
        psi_nodes[1:-1] = 0.5 * (psi[:-1] + psi[1:])
    else:
        psi_nodes = psi

    if T_ref is not None:   # the SFR the forward model forms: the construction-grid mass kept
        f = np.sum(bar_psi * np.diff(T_ref)) / np.sum(bar_psi * dt_yr)
        bar_psi, psi_nodes = bar_psi * f, psi_nodes * f

    if units == "Gyr":
        scale, xlabel = 1.0,   "Lookback time [Gyr]"
    elif units == "Myr":
        scale, xlabel = 1e3,   "Lookback time [Myr]"
    elif units == "yr":
        scale, xlabel = 1e9,   "Lookback time [yr]"
    else:
        raise ValueError(
            f"units must be 'Gyr', 'Myr', or 'yr'; got {units!r}"
        )
    T_plot = T_gyr * scale

    if ax is None:
        _, ax = plt.subplots(figsize=(6.0, 4.0))

    style = {"color": "C0", "lw": 1.5}
    style.update(plot_kwargs)
    marker_color = style.get("color", "C0")

    n_bin = n_time - 1

    if self.sfh_interp == "step":
        for i in range(n_bin):
            ax.plot([T_plot[i + 1], T_plot[i]],
                    [bar_psi[i],   bar_psi[i]],
                    **style)
        if overlay_nodes:
            T_mid = 0.5 * (T_plot[:-1] + T_plot[1:])
            ax.scatter(T_mid, bar_psi, marker="o",
                       color=marker_color, s=20, zorder=3)
    else:  # "linear"
        for i in range(n_bin):
            ax.plot([T_plot[i + 1], T_plot[i]],
                    [psi_nodes[i + 1], psi_nodes[i]],
                    **style)
        if overlay_nodes:
            ax.scatter(T_plot, psi_nodes, marker="o",
                       color=marker_color, s=20, zorder=3)

    if show_bin_edges:
        for t in T_plot:
            ax.axvline(t, color="grey", lw=0.5, linestyle=":")

    ax.set_xlabel(xlabel)
    ax.set_ylabel(r"$\dot{M}_\star\;[\mathrm{M_\odot\,yr^{-1}}]$")


    total_mass = float(np.sum(bar_psi * dt_yr))
    ax.set_title(
        f"sfh_interp={self.sfh_interp!r}, n_time={n_time}, "
        f"M_total = {total_mass:.3e} M_sun"
    )

    return ax

calculate_ssp_weights_const_zh

calculate_ssp_weights_const_zh(theta)

Weights for constant metallicity, piecewise-linear SFH.

Source code in ceridwen/csp/csp.py
def calculate_ssp_weights_const_zh(self, theta):
    """Weights for constant metallicity, piecewise-linear SFH."""
    return self._ssp_weights(theta, zh_mode="const", sfh_mode="linear")

calculate_ssp_weights_const_zh_step

calculate_ssp_weights_const_zh_step(theta)

Weights for constant metallicity, piecewise-constant SFH.

Source code in ceridwen/csp/csp.py
def calculate_ssp_weights_const_zh_step(self, theta):
    """Weights for constant metallicity, piecewise-constant SFH."""
    return self._ssp_weights(theta, zh_mode="const", sfh_mode="step")

calculate_ssp_weights_var_zh

calculate_ssp_weights_var_zh(theta)

Weights for a metallicity history, piecewise-linear SFH.

Source code in ceridwen/csp/csp.py
def calculate_ssp_weights_var_zh(self, theta):
    """Weights for a metallicity history, piecewise-linear SFH."""
    return self._ssp_weights(theta, zh_mode="var", sfh_mode="linear")

calculate_ssp_weights_var_zh_step

calculate_ssp_weights_var_zh_step(theta)

Weights for a metallicity history, piecewise-constant SFH.

Source code in ceridwen/csp/csp.py
def calculate_ssp_weights_var_zh_step(self, theta):
    """Weights for a metallicity history, piecewise-constant SFH."""
    return self._ssp_weights(theta, zh_mode="var", sfh_mode="step")

surviving_mass_fraction

surviving_mass_fraction(theta)

mfrac = M_surviving / M_formed of the population theta describes: the grid's surviving-mass table weighted by the same SSP weights as the spectrum, sum(W m) / sum(W). Post-processing only (PostProcess); needs a grid with ssp_stellar_mass (SSP schema 3), else ValueError.

Source code in ceridwen/csp/csp.py
def surviving_mass_fraction(self, theta):
    """mfrac = M_surviving / M_formed of the population ``theta`` describes: the grid's
    surviving-mass table weighted by the same SSP weights as the spectrum,
    sum(W m) / sum(W).  Post-processing only (``PostProcess``); needs a grid with
    ``ssp_stellar_mass`` (SSP schema 3), else ValueError."""
    if self.ssp_stellar_mass is None:
        from ceridwen.ssps.ssp_data import missing_stellar_mass_message
        raise ValueError(missing_stellar_mass_message("the SSP grid of this CSPBasis",
                                                      chash=self.grid_chash,
                                                      refused=self.stellar_mass_refused))
    W = self.calculate_ssp_weights(theta)
    m = self._stellar_mass_at(theta)
    return jnp.sum(W * m) / jnp.maximum(jnp.sum(W), 1e-300)

get_spectrum_dattn_nodem_neb

get_spectrum_dattn_nodem_neb(
    theta, *, include_lines=None, support=None
)

Dust attenuation + nebular emission. include_lines None -> self.nebemlineinspec; support (static slice): those model pixels only.

Source code in ceridwen/csp/csp.py
@_per_pixel
def get_spectrum_dattn_nodem_neb(self, theta, *, include_lines=None, support=None):
    """Dust attenuation + nebular emission.  ``include_lines`` None -> ``self.nebemlineinspec``;
    ``support`` (static slice): those model pixels only."""
    if include_lines is None:
        include_lines = self.nebemlineinspec
    W = self.calculate_ssp_weights(theta=theta)   # (n_z, n_age)

    if self.fesc_geometry == "picket" and "frac_obrun" in theta:
        return self._spectrum_picket_nodem(theta, include_lines, support)

    ion_mult, neb_amp = self._ion_multiplier(theta, support)

    attn, attn_diffuse = self.attenuate_dust(_sel(self._wave32, support), theta)
    M        = self._age_bin_mix
    tau_age  = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age = jnp.exp(-tau_age)

    attn_star = attn_age
    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo   # runaway fraction skips the birth cloud
        # escaped stellar LyC: no birth-cloud dust at all; the nebular term keeps attn_age
        attn_star = jnp.where(_sel(self.kill_ion, support), jnp.float32(1.0), attn_age)

    W_f32 = W.astype(jnp.float32)
    spectrum = jnp.einsum("za,zaw,aw->w", W_f32, _sel(self.flux, support),
                          ion_mult * attn_star)
    spectrum = spectrum + self._neb_spectrum_term(
        W_f32, theta, include_lines=include_lines,
        attn_age=attn_age, amplitude=neb_amp, support=support)
    spectrum = spectrum * jnp.exp(-attn_diffuse.astype(jnp.float32))

    return spectrum.reshape((-1,))

get_spectrum_dattn_dem_neb

get_spectrum_dattn_dem_neb(theta, *, include_lines=None)

Dust attenuation + nebular emission + dust emission. The energy balance always counts the lines' absorbed energy; include_lines only decides whether the attenuated lines are in the output (False: attenuated continuum + the full dust emission).

Source code in ceridwen/csp/csp.py
def get_spectrum_dattn_dem_neb(self, theta, *, include_lines=None):
    """Dust attenuation + nebular emission + dust emission.  The energy balance always counts
    the lines' absorbed energy; ``include_lines`` only decides whether the attenuated lines are
    in the output (False: attenuated continuum + the full dust emission)."""
    if include_lines is None:
        include_lines = self.nebemlineinspec
    W = self.calculate_ssp_weights(theta=theta)   # (n_z, n_age)

    if self.fesc_geometry == "picket" and "frac_obrun" in theta:
        return self._spectrum_picket_dem(theta, include_lines)

    ion_mult, neb_amp = self._ion_multiplier(theta)

    attn, attn_diffuse = self.attenuate_dust(self._wave32, theta)
    M             = self._age_bin_mix
    tau_age       = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age      = jnp.exp(-tau_age)
    diffuse_curve = jnp.exp(-attn_diffuse.astype(jnp.float32))

    attn_star = attn_age
    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo   # runaway fraction skips the birth cloud
        # escaped stellar LyC: no birth-cloud dust at all; the nebular term keeps attn_age
        attn_star = jnp.where(self.kill_ion, jnp.float32(1.0), attn_age)

    W_f32 = W.astype(jnp.float32)
    neb_v, (base_cont, neb_base) = self._neb_weights_and_base(
        W_f32, theta, include_lines="both", amplitude=neb_amp)
    yi = self._neb_young_idx
    stellar_attenuated = jnp.einsum("za,zaw,aw->w", W_f32, self.flux, ion_mult * attn_star)
    spectrum_dust_free = (
        jnp.einsum("za,zaw,aw->w", W_f32, self.flux, ion_mult)
        + jnp.einsum("y,yw->w", neb_v, neb_base))
    attenuated = (
        stellar_attenuated
        + jnp.einsum("y,yw,yw->w", neb_v, neb_base, attn_age[yi, :]))
    attenuated         = attenuated * diffuse_curve

    dust_emi_spectrum, _mdust, tduste = self.dust_emi.compute_dust_emission(
        spec_attn     = attenuated,
        spec_dustfree = spectrum_dust_free,
        spec_lambda   = self.wave,
        diffuse_curve = diffuse_curve,
        duste_qpah    = theta["duste_qpah"],
        duste_umin    = theta["duste_umin"],
        duste_gamma   = theta["duste_gamma"],
    )
    if include_lines:
        return dust_emi_spectrum
    return ((stellar_attenuated
             + jnp.einsum("y,yw,yw->w", neb_v, base_cont, attn_age[yi, :])) * diffuse_curve
            + tduste)

get_spectrum_dattn_nodem_noneb

get_spectrum_dattn_nodem_noneb(
    theta, *, include_lines=None, support=None
)

Dust attenuation only (include_lines ignored); support: those pixels only.

Source code in ceridwen/csp/csp.py
@_per_pixel
def get_spectrum_dattn_nodem_noneb(self, theta, *, include_lines=None, support=None):
    """Dust attenuation only (``include_lines`` ignored); ``support``: those pixels only."""
    _ = include_lines
    attn, attn_diffuse = self.attenuate_dust(_sel(self._wave32, support), theta)

    M       = self._age_bin_mix
    tau_age = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age= jnp.exp(-tau_age)

    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo

    weights  = self.calculate_ssp_weights(theta).astype(jnp.float32)
    spectrum = jnp.einsum("za,zaw,aw->w", weights, _sel(self.flux, support), attn_age)
    spectrum *= jnp.exp(-attn_diffuse.astype(jnp.float32))

    return spectrum.reshape((-1,))

get_spectrum_dattn_dem_noneb

get_spectrum_dattn_dem_noneb(theta, *, include_lines=None)

Dust attenuation + dust emission, no nebular (include_lines ignored).

Source code in ceridwen/csp/csp.py
def get_spectrum_dattn_dem_noneb(self, theta, *, include_lines=None):
    """Dust attenuation + dust emission, no nebular (``include_lines`` ignored)."""
    _ = include_lines
    attn, attn_diffuse = self.attenuate_dust(self._wave32, theta)

    M             = self._age_bin_mix
    tau_age       = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age      = jnp.exp(-tau_age)
    diffuse_curve = jnp.exp(-attn_diffuse.astype(jnp.float32))

    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo

    weights           = self.calculate_ssp_weights(theta).astype(jnp.float32)
    spectrum_dust_free= jnp.einsum("za,zaw->w", weights, self.flux)
    attenuated        = jnp.einsum("za,zaw,aw->w", weights, self.flux, attn_age)
    attenuated       *= diffuse_curve

    dust_emi_spectrum, _mdust, _tduste = self.dust_emi.compute_dust_emission(
        spec_attn      = attenuated,
        spec_dustfree  = spectrum_dust_free,
        spec_lambda    = self.wave,
        diffuse_curve  = diffuse_curve,
        duste_qpah     = theta["duste_qpah"],
        duste_umin     = theta["duste_umin"],
        duste_gamma    = theta["duste_gamma"],
    )
    return dust_emi_spectrum

get_spectrum_nodattn_nodem_noneb

get_spectrum_nodattn_nodem_noneb(
    theta, *, include_lines=None, support=None
)

Stellar continuum only; support: those pixels only.

Source code in ceridwen/csp/csp.py
@_per_pixel
def get_spectrum_nodattn_nodem_noneb(self, theta, *, include_lines=None, support=None):
    """Stellar continuum only; ``support``: those pixels only."""
    _ = include_lines
    weights  = self.calculate_ssp_weights(theta=theta).astype(jnp.float32)
    return jnp.einsum("za,zaw->w", weights, _sel(self.flux, support))

get_spectrum_nodattn_nodem_neb

get_spectrum_nodattn_nodem_neb(
    theta, *, include_lines=None, support=None
)

Nebular emission, no dust; support: those pixels only.

Source code in ceridwen/csp/csp.py
@_per_pixel
def get_spectrum_nodattn_nodem_neb(self, theta, *, include_lines=None, support=None):
    """Nebular emission, no dust; ``support``: those pixels only."""
    if include_lines is None:
        include_lines = self.nebemlineinspec
    W = self.calculate_ssp_weights(theta=theta)   # (n_z, n_age)

    ion_mult, neb_amp = self._ion_multiplier(theta, support)

    W_f32 = W.astype(jnp.float32)
    return (jnp.einsum("za,zaw,aw->w", W_f32, _sel(self.flux, support), ion_mult)
            + self._neb_spectrum_term(W_f32, theta,
                                      include_lines=include_lines,
                                      amplitude=neb_amp, support=support))

ceridwen.csp.CSPBasis_afe

CSPBasis_afe(
    SSPData,
    theta=None,
    tiny_logt=-70,
    zh_const=False,
    add_dust=True,
    add_diffuse_dust=True,
    add_dust_emission=False,
    add_igm=False,
    igm_model="madau1995",
    igm_factor=1.0,
    sps_home=None,
    init_dust_params=None,
    diffuse_law="kriek_conroy",
    verbose=True,
    sfh_interp="step",
    track_zred_age=False,
    lookback_time=None,
    sfh_per_bin=None,
    cosmo=None,
    duste_model="DL07",
    wavelength_support=False,
    agn=None,
    fixed=None,
    **kwargs
)

Bases: CSPBasis

Composite stellar population basis with [alpha/Fe] interpolation and no nebular model.

Same constructor and interface as CSPBasis minus the nebular arguments; requires an SSPDataAfe grid (4-D ssp_flux with an ssp_afe axis). theta["afe"] is optional: absent, the plane closest to [alpha/Fe] = 0 is used. The SFH weights, dust, projection, flux factor and cosmology are those of CSPBasis, and so are wavelength_support (opt-in) and agn (see CSPBasis; L_bol and the dust-free galaxy spectrum are taken at theta['afe'] like the flux cube).

Source code in ceridwen/csp/csp_afe.py
def __init__(
    self,
    SSPData,
    theta=None,
    tiny_logt=-70,
    zh_const=False,
    add_dust=True,
    add_diffuse_dust=True,
    add_dust_emission=False,
    add_igm=False,
    igm_model="madau1995",
    igm_factor=1.0,
    sps_home=None,
    init_dust_params=None,
    diffuse_law='kriek_conroy',
    verbose=True,
    sfh_interp='step',
    track_zred_age=False,
    lookback_time=None,
    sfh_per_bin=None,
    cosmo=None,
    duste_model="DL07",
    wavelength_support=False,
    agn=None,
    fixed=None,
    **kwargs,
):
    self.verbose = bool(verbose)
    self.gas_tied = False          # no nebular model on alpha grids
    self._wave_support = bool(wavelength_support)
    if kwargs:
        hint = ""
        if "sigma_losvd_kms" in kwargs:
            hint = (" ('sigma_losvd_kms' is not an argument: the galaxy velocity "
                    "dispersion is set once on the model, "
                    "SedModel(kinematics=Kinematics(sigma_gal=...)))")
        elif "tuniv" in kwargs:
            hint = (" ('tuniv' is not an argument: the age of the Universe comes from "
                    "the cosmology, csp.age_at(z) / cosmo.age(z))")
        raise TypeError(
            f"CSPBasis_afe got unexpected keyword argument(s) {sorted(kwargs)}{hint}")
    if lookback_time is not None:
        if theta is not None:
            raise ValueError(
                "Pass either theta= (full control over the initial "
                "parameter values) or the lookback_time= shortcut, not "
                "both."
            )
        _lb = jnp.atleast_1d(jnp.asarray(lookback_time, dtype=float))
        _n = int(_lb.size)
        theta = {
            'lookback_time': _lb,
            'sfh': jnp.ones(max(_n - 1, 1) if _sfh_per_bin(sfh_interp, sfh_per_bin) else _n),
        }
        _lz_mid = _default_logzsol(SSPData)
        if zh_const:
            theta['logzsol'] = jnp.array([_lz_mid])
        else:
            theta['logzsol_bins'] = jnp.full((max(_n - 1, 1),), _lz_mid)
    if theta is None:
        raise ValueError(
            "CSPBasis needs the static SFH grid structure. Pass either\n"
            "  lookback_time=jnp.linspace(0.0, T_oldest, n_nodes)   "
            "(shortcut; neutral initial values), or\n"
            "  theta={'lookback_time': ..., 'sfh': ..., 'logzsol' or 'logzsol_bins': ...} "
            "(full control).\n"
            "lookback_time is in Gyr, monotonically increasing, index 0 = "
            "today, >= 2 nodes."
        )
    init_dust_params = ({'bin_edges': [(-jnp.inf, -1.97)], 'laws': ['powerlaw']}
                        if init_dust_params is None else dict(init_dust_params))
    if isinstance(fixed, dict) and 'afe' in fixed and 'afe' not in theta:
        theta = {**theta, 'afe': fixed['afe']}    # afe is a parameter only when given

    _flux_in = np.asarray(SSPData.ssp_flux)            # host NumPy (SSPData keeps it there)
    _afe_in  = getattr(SSPData, "ssp_afe", None)
    if _flux_in.ndim != 4 or _afe_in is None:
        raise TypeError(
            "CSPBasis_afe requires an alpha-enhanced SSP grid: a 4-D "
            "ssp_flux (n_afe, n_z, n_age, n_wave) WITH an ssp_afe axis "
            "(ceridwen.ssps.ssp_data_afe.SSPDataAfe). Got "
            f"ssp_flux.ndim={_flux_in.ndim} and ssp_afe="
            f"{'absent' if _afe_in is None else 'present'} "
            f"({type(SSPData).__name__}). For solar-scaled 3-D grids "
            "switch to the matching basis:\n"
            "    from ceridwen.csp import CSPBasis   # solar-scaled, "
            "with nebular model\n"
            "or rebuild the grid with SSPDataAfe.from_fsps (python-fsps "
            ">= 4.0, AFE_FLAG=1) to fit [alpha/Fe]."
        )
    _afe_in = jnp.atleast_1d(jnp.asarray(_afe_in, dtype=float))
    if _afe_in.size != _flux_in.shape[0]:
        raise ValueError(
            f"ssp_afe has {_afe_in.size} points but ssp_flux leads "
            f"with {_flux_in.shape[0]}; grid is inconsistent."
        )
    if _afe_in.size > 1 and not bool(np.all(np.diff(np.asarray(_afe_in)) > 0)):
        raise ValueError(
            "ssp_afe must be strictly increasing (required by the "
            "searchsorted-based interpolation in _flux_at_afe); got "
            f"{np.asarray(_afe_in).tolist()}."
        )
    # the float32 cast on the device (as CSPBasis: XLA's convert) from a transient copy
    _f64 = jnp.asarray(_flux_in)
    self.flux      = _f64.astype(jnp.float32)          # (n_afe, n_z, n_age, n_wave)
    del _f64
    self.afe_grid  = _afe_in                           # (n_afe,) [alpha/Fe]
    self._n_afe    = int(_afe_in.size)
    # the same cube laid out (n_age, n_afe * n_z, n_wave) for _contract: a sampled afe is
    # folded into the SSP weights, so no interpolated plane is built per sample under vmap
    self._flux_afe_t = None if self._n_afe == 1 else jnp.asarray(np.ascontiguousarray(
        np.transpose(np.asarray(self.flux), (2, 0, 1, 3)).reshape(
            self.flux.shape[2], -1, self.flux.shape[3])))
    self._afe_solar_idx = int(np.argmin(np.abs(np.asarray(_afe_in))))
    self.wave      = jnp.array(SSPData.ssp_wave)       # (n_wave,)
    # the attenuation curves are evaluated on this float32 copy: the kernels use them in
    # float32 (the wavelengths that place lines and pixels stay float64, self.wave)
    self._wave32   = self.wave.astype(jnp.float32)
    self.ages      = jnp.array(SSPData.ssp_lg_age_gyr) # (n_age,)  log10(Gyr)
    self._setup_metallicity(SSPData)                   # self.zmet: logzsol axis
    self.lib_resolution = (
        (np.asarray(SSPData.ssp_wave, dtype=np.float64),
         np.asarray(SSPData.ssp_resolution, dtype=np.float64))
        if getattr(SSPData, "ssp_resolution", None) is not None else None)
    self.ssp_ages_lgyr = self.ages + 9                 # log10(yr)
    # surviving mass per M_sun formed (SSP schema 3); post-processing only, never traced
    # by the forward model
    _m = getattr(SSPData, "ssp_stellar_mass", None)
    self.ssp_stellar_mass = None if _m is None else np.asarray(_m, dtype=np.float64)
    self.stellar_mass_source = getattr(SSPData, "stellar_mass_source", None)
    self.stellar_mass_refused = getattr(SSPData, "stellar_mass_refused", None)

    self._ssp_isoc_type    = getattr(SSPData, "isoc_type", None)
    self._ssp_spec_library = getattr(SSPData, "spec_library", None)

    self._logage_lo  = self.ssp_ages_lgyr[1:]
    self._logage_hi  = self.ssp_ages_lgyr[:-1]
    self._dlogage    = jnp.diff(self.ssp_ages_lgyr)
    self._j_range    = jnp.arange(self.ssp_ages_lgyr.size)
    self._age_clip_lo = 10.0 ** (-70)                  # floor for log-time clipping
    self._age_clip_hi = 10.0 ** self.ssp_ages_lgyr[-1] # ceiling
    self._n_z   = len(self.zmet)
    self._n_age = len(self.ages)

    self._ssp_lo_yr = 10.0 ** self._logage_hi   # (n_age-1,)
    self._ssp_hi_yr = 10.0 ** self._logage_lo   # (n_age-1,)

    _ssp_age_yr  = 10.0 ** self.ssp_ages_lgyr           # (n_age,) linear yr
    _voro_mid    = 0.5 * (_ssp_age_yr[:-1] + _ssp_age_yr[1:])  # (n_age-1,)
    _voro_hi_ext = _ssp_age_yr[-1] + (_ssp_age_yr[-1] - _ssp_age_yr[-2])
    self._ssp_voronoi_lo = jnp.concatenate(
        [jnp.zeros(1), _voro_mid]
    )
    self._ssp_voronoi_hi = jnp.concatenate(
        [_voro_mid, jnp.array([_voro_hi_ext])]
    )

    self.tiny_logt  = tiny_logt
    if sps_home is None:
        sps_home = os.environ.get("SPS_HOME")
    if add_dust_emission and not sps_home:
        raise ValueError(
            "sps_home is required for dust emission but was not "
            "given and $SPS_HOME is unset. Set `export SPS_HOME=/path/to/fsps` "
            "(your FSPS data directory) or pass sps_home=... explicitly."
        )
    self.sps_home   = sps_home
    from ..cosmology import Cosmology as _Cosmology
    if cosmo is None:
        raise TypeError(
            f"{type(self).__name__} needs an explicit cosmology: pass "
            "cosmo=Cosmology.planck18(), Cosmology.wmap9(), "
            "Cosmology.flat(H0, Om0), Cosmology.from_name(...) or "
            "Cosmology.from_astropy(...)  (from ceridwen import Cosmology)")
    if not isinstance(cosmo, _Cosmology):
        raise TypeError(
            f"cosmo must be a ceridwen Cosmology, got {type(cosmo).__name__}; "
            "for an astropy cosmology use Cosmology.from_astropy(...)")
    self._cosmo = cosmo
    self.track_zred_age = bool(track_zred_age)
    self._setup_igm(add_igm, igm_model, igm_factor)
    self.duste_model = _check_duste_model(duste_model, add_dust_emission)

    if add_diffuse_dust or add_dust:
        self.set_attenuation_function(add_diffuse_dust, add_dust)

    theta = self.initialize_dust_components(
        add_dust, add_diffuse_dust, add_dust_emission,
        theta, init_dust_params, diffuse_law, sps_home,
    )

    self.configure_spectrum_model(
        add_dust, add_diffuse_dust, add_dust_emission, sps_home
    )
    theta = self._install_agn(agn, theta, SSPData, add_dust_emission, sps_home)

    if sfh_interp not in ('step', 'linear'):
        raise ValueError(
            f"sfh_interp must be 'step' or 'linear', got {sfh_interp!r}"
        )
    self.sfh_interp = sfh_interp
    self.zh_const = bool(zh_const)
    if zh_const:
        if sfh_interp == 'step':
            self.calculate_ssp_weights = self.calculate_ssp_weights_const_zh_step
        else:
            self.calculate_ssp_weights = self.calculate_ssp_weights_const_zh
    else:
        if sfh_interp == 'step':
            self.calculate_ssp_weights = self.calculate_ssp_weights_var_zh_step
        else:
            self.calculate_ssp_weights = self.calculate_ssp_weights_var_zh
    if verbose:
        print(f"SFH integration scheme : {sfh_interp}")

    self.initialize_model_structure(theta)
    self._set_fixed(fixed)

    if verbose:
        print("\nCSPBasis (dict theta) — registered parameters:")
        pprint.pprint({k: v.shape for k, v in self.theta_init.items()})

    self.check_param_ranges(self.theta_init)

initialize_model_structure

initialize_model_structure(theta)

CSPBasis.initialize_model_structure plus the optional scalar theta['afe'].

Source code in ceridwen/csp/csp_afe.py
def initialize_model_structure(self, theta):
    """``CSPBasis.initialize_model_structure`` plus the optional scalar theta['afe']."""
    super().initialize_model_structure(theta)
    if 'afe' in theta:
        afe = jnp.atleast_1d(jnp.asarray(theta['afe'], dtype=float))
        assert afe.shape == (1,), \
            "'afe' must be a scalar (wrapped in shape-(1,) array)"
        if self._n_afe == 1:
            warnings.warn(
                "theta contains 'afe' but the SSP grid has a single "
                "[alpha/Fe] plane (n_afe=1, legacy or AFE_FLAG=0 grid); "
                "'afe' is IGNORED. Build an alpha-enhanced grid with "
                "SSPDataAfe.from_fsps to fit alpha enhancement.",
                stacklevel=3,
            )
    self._known_theta_keys = (self._known_theta_keys | {'afe'}) - {'eline_scaling'}
    self._apply_fixed()

check_param_ranges

check_param_ranges(theta=None, warn=True)

CSPBasis.check_param_ranges plus theta['afe'] against the [alpha/Fe] grid.

Source code in ceridwen/csp/csp_afe.py
def check_param_ranges(self, theta=None, warn=True):
    """``CSPBasis.check_param_ranges`` plus theta['afe'] against the [alpha/Fe] grid."""
    if theta is None:
        theta = self.theta_init
    msgs = super().check_param_ranges(theta, warn=False)
    self._check_refused_cells_theta(theta)
    if 'afe' in theta and self._n_afe > 1:
        alo = float(self.afe_grid.min())
        ahi = float(self.afe_grid.max())
        v = np.asarray(theta['afe'], float)
        if v.size and (np.nanmin(v) < alo or np.nanmax(v) > ahi):
            msgs.append(
                f"theta['afe'] has values outside the SSP [alpha/Fe] grid "
                f"[{alo:+.2f}, {ahi:+.2f}]; these are silently clamped to "
                f"the nearest grid edge (aMIST/C3K support is "
                f"-0.2 .. +0.6)."
            )
    if warn:
        for m in msgs:
            warnings.warn(m, stacklevel=2)
    return msgs

logzsol_total

logzsol_total(theta)

[Z/H] = logzsol + f([alpha/Fe]) for this theta (Z/X definition; grid_metadata), elementwise for a per-bin history (self.zh_key).

Source code in ceridwen/csp/csp_afe.py
def logzsol_total(self, theta):
    """[Z/H] = logzsol + f([alpha/Fe]) for this theta (Z/X definition; grid_metadata),
    elementwise for a per-bin history (``self.zh_key``)."""
    key = self.zh_key
    afe = jnp.ravel(theta['afe'])[0] if 'afe' in theta else self.afe_grid[self._afe_solar_idx]
    return _logzsol_total(theta[key], afe)

refused_cells_logzsol

refused_cells_logzsol()

[(logzsol_lo, logzsol_hi, afe_lo, afe_hi, reason)] of the refused interpolation cells.

Taken from the GRID (SSPData.refused_cells), which is filled from the metadata table, from the file's own refused_cells_json provenance, or by the duplicate- isochrone detection in SSPDataAfe.from_fsps -- so a re-saved, converted or freshly built alpha grid keeps its refusals even when its content hash is not a table key.

Source code in ceridwen/csp/csp_afe.py
def refused_cells_logzsol(self):
    """[(logzsol_lo, logzsol_hi, afe_lo, afe_hi, reason)] of the refused interpolation cells.

    Taken from the GRID (``SSPData.refused_cells``), which is filled from the metadata
    table, from the file's own ``refused_cells_json`` provenance, or by the duplicate-
    isochrone detection in ``SSPDataAfe.from_fsps`` -- so a re-saved, converted or freshly
    built alpha grid keeps its refusals even when its content hash is not a table key."""
    return refused_cell_bounds(self._refused_cells, self._refused_reason,
                               np.asarray(self.zmet), np.asarray(self.afe_grid))

get_spectrum_components

get_spectrum_components(theta)

(continuum, zeros): no nebular model, so the line component is identically zero.

Source code in ceridwen/csp/csp_afe.py
def get_spectrum_components(self, theta: dict) -> tuple:
    """``(continuum, zeros)``: no nebular model, so the line component is identically zero."""
    self._warn_unknown_theta_keys(theta)
    continuum = self.get_spectrum(theta=theta, include_lines=False)
    return continuum, jnp.zeros_like(continuum)

get_line_spec

get_line_spec(theta)

Zeros (no nebular model).

Source code in ceridwen/csp/csp_afe.py
def get_line_spec(self, theta):
    """Zeros (no nebular model)."""
    _ = theta
    return jnp.zeros_like(self.wave)

get_spectrum_dattn_nodem_noneb

get_spectrum_dattn_nodem_noneb(
    theta, *, include_lines=None, support=None
)

Dust attenuation only (include_lines ignored); support: those pixels only.

Source code in ceridwen/csp/csp_afe.py
@_per_pixel
def get_spectrum_dattn_nodem_noneb(self, theta, *, include_lines=None, support=None):
    """Dust attenuation only (``include_lines`` ignored); ``support``: those pixels only."""
    _ = include_lines
    attn, attn_diffuse = self.attenuate_dust(_sel(self._wave32, support), theta)

    M       = self._age_bin_mix
    tau_age = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age= jnp.exp(-tau_age)

    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo

    weights  = self.calculate_ssp_weights(theta).astype(jnp.float32)
    spectrum = self._contract(theta, weights, attn_age, support)
    spectrum *= jnp.exp(-attn_diffuse.astype(jnp.float32))

    return spectrum.reshape((-1,))

get_spectrum_dattn_dem_noneb

get_spectrum_dattn_dem_noneb(theta, *, include_lines=None)

Dust attenuation + dust emission (include_lines ignored).

Source code in ceridwen/csp/csp_afe.py
def get_spectrum_dattn_dem_noneb(self, theta, *, include_lines=None):
    """Dust attenuation + dust emission (``include_lines`` ignored)."""
    _ = include_lines
    attn, attn_diffuse = self.attenuate_dust(self._wave32, theta)

    M             = self._age_bin_mix
    tau_age       = jnp.einsum("ab,bw->aw", M, attn.astype(jnp.float32))
    attn_age      = jnp.exp(-tau_age)
    diffuse_curve = jnp.exp(-attn_diffuse.astype(jnp.float32))

    if "frac_obrun" in theta:
        fo = jnp.ravel(theta["frac_obrun"])[0].astype(jnp.float32)
        attn_age = (jnp.float32(1.0) - fo) * attn_age + fo

    weights           = self.calculate_ssp_weights(theta).astype(jnp.float32)
    spectrum_dust_free= self._contract(theta, weights)
    attenuated        = self._contract(theta, weights, attn_age)
    attenuated       *= diffuse_curve

    dust_emi_spectrum, _mdust, _tduste = self.dust_emi.compute_dust_emission(
        spec_attn      = attenuated,
        spec_dustfree  = spectrum_dust_free,
        spec_lambda    = self.wave,
        diffuse_curve  = diffuse_curve,
        duste_qpah     = theta["duste_qpah"],
        duste_umin     = theta["duste_umin"],
        duste_gamma    = theta["duste_gamma"],
    )
    return dust_emi_spectrum

get_spectrum_nodattn_nodem_noneb

get_spectrum_nodattn_nodem_noneb(
    theta, *, include_lines=None, support=None
)

Stellar continuum only; support: those pixels only.

Source code in ceridwen/csp/csp_afe.py
@_per_pixel
def get_spectrum_nodattn_nodem_noneb(self, theta, *, include_lines=None, support=None):
    """Stellar continuum only; ``support``: those pixels only."""
    _ = include_lines
    weights  = self.calculate_ssp_weights(theta=theta).astype(jnp.float32)
    return self._contract(theta, weights, support=support)

AGN

ceridwen.agn.AGNConfig dataclass

AGNConfig(
    agn_mode=AGN_MODE_CORRECTED,
    torus=None,
    disk=None,
    lines=None,
    dust4_type=0,
    tau_interp="linear",
    agn_energy_balance=None,
    torus_file=None,
    torus_model="nenkova08",
    polar_dust=False,
    polar_law=None,
    nlr_model="a42",
    blr=False,
    skirtor_R=None,
    skirtor_file=None,
    nlr_file=None,
    blr_file=None,
)

Static AGN configuration, validated on construction.

Parameters:

Name Type Description Default
agn_mode ('corrected', 'fsps', 'prospector')

"corrected" is the physically consistent model; "fsps" and "prospector" reproduce those codes (defects included) for comparison with existing fits.

"corrected"
torus bool or None

Which components exist. None = the mode's default: "fsps" -> torus only; "prospector" / "corrected" -> all three. Their shapes are static, so a component switched off costs nothing; one switched on with its amplitude at 0 (fagn, fagn_bbb, agn_elum) adds exactly zero.

None
disk bool or None

Which components exist. None = the mode's default: "fsps" -> torus only; "prospector" / "corrected" -> all three. Their shapes are static, so a component switched off costs nothing; one switched on with its amplitude at 0 (fagn, fagn_bbb, agn_elum) adds exactly zero.

None
lines bool or None

Which components exist. None = the mode's default: "fsps" -> torus only; "prospector" / "corrected" -> all three. Their shapes are static, so a component switched off costs nothing; one switched on with its amplitude at 0 (fagn, fagn_bbb, agn_elum) adds exactly zero.

None
dust4_type (0, 1)

AGN screen: 0 none, 1 diffuse dust2 curve times a dust4 power law. 2 is refused (Prospector raises NotImplementedError for it).

0
tau_interp ('linear', 'log')

Interpolation of the torus templates in agn_tau ("linear" = FSPS). Only "corrected" mode may use "log".

"linear"
agn_energy_balance bool or None

Re-emit the AGN light absorbed by the galaxy screen through DL07. None = ON in "corrected" mode when add_dust_emission=True, OFF otherwise. True is refused in the reproduction modes (FSPS and Prospector have no AGN energy balance) and, at CSP setup, without dust emission.

None
torus_file str or None

Nenkova+08 template file; default $SPS_HOME/dust/Nenkova08_y010_torusg_n10_q2.0.dat.

None
torus_model ('nenkova08', 'skirtor16')

Which torus torus switches on. "skirtor16" (Stalevski+2012, 2016, CIGALE's skirtor2016) carries its own anisotropic disc, so the Temple disc is off by default and refused when asked for (disk=True).

"nenkova08"
polar_dust bool

CIGALE's polar dust (extinction of the SKIRTOR disc and its grey-body re-emission). Needs torus_model="skirtor16".

False
polar_law ('smc', 'calzetti', 'gaskell')

Extinction law of the polar dust; None = CIGALE's default (POLAR_LAW_DEFAULT). Only with polar_dust=True.

"smc"
nlr_model ('a42', 'feltre16')

The narrow-line set lines switches on: Richardson+14 fixed ratios or the Feltre+16 photoionisation grid.

"a42"
blr bool

Broad lines with their own amplitude (blr_lum) and width (blr_sigma).

False
skirtor_R float or None

Static ratio of outer to inner torus radius (a node of the SKIRTOR grid; None = the component's default). Only with torus_model="skirtor16".

None
skirtor_file str or None

Data files of the AGN2 components (default: under $CERIDWEN_AGN_DATA, resolved by each component). Each only with its component switched on.

None
nlr_file str or None

Data files of the AGN2 components (default: under $CERIDWEN_AGN_DATA, resolved by each component). Each only with its component switched on.

None
blr_file str or None

Data files of the AGN2 components (default: under $CERIDWEN_AGN_DATA, resolved by each component). Each only with its component switched on.

None
Every
required

use_lines property

use_lines

The narrow lines (nlr_model) are on.

use_any_lines property

use_any_lines

Any AGN line set (narrow or broad) is on.

uses_agn2 property

uses_agn2

Any AGN2 component is on (the hook then takes its AGN2 branches).

energy_balance

energy_balance(add_dust_emission)

Resolved energy-balance switch for a CSP with/without dust emission.

Source code in ceridwen/agn/__init__.py
def energy_balance(self, add_dust_emission: bool) -> bool:
    """Resolved energy-balance switch for a CSP with/without dust emission."""
    if self.agn_energy_balance is None:
        return self.agn_mode == AGN_MODE_CORRECTED and bool(add_dust_emission)
    if self.agn_energy_balance and not add_dust_emission:
        raise ValueError(
            "AGNConfig(agn_energy_balance=True) needs CSPBasis(add_dust_emission=True): "
            "the absorbed AGN light is re-emitted through DL07. Without dust emission "
            "it is lost, exactly as absorbed starlight is.")
    return self.agn_energy_balance

ceridwen.agn.torus.NenkovaTorus

NenkovaTorus(
    wave,
    *,
    mode,
    tau_interp="linear",
    torus_file=None,
    sps_home=None
)

Bases: Component

Nenkova+08 torus: rest_spectrum = fagn * L_bol_star * T(agn_tau) [L_sun/Hz per M_formed], before any attenuation. T integrates to 1 over frequency exactly in "corrected" mode and to the FSPS/Prospector resampled value otherwise.

Attributes: templates (n_wave, 9) jnp float64, tau_grid (9,), native_integrals (9,) = sum(T_j |w|) of the resampled columns before any renormalisation (on this grid), file_integrals (9,) the trapezoid on the file's own 125 points (the "unity" of the file header, 0.9993), dense_integrals (9,) the log-log SED on a dense log grid over the whole template (0.989-0.996: the file's unity is a coarse-trapezoid artefact), path.

Source code in ceridwen/agn/torus.py
def __init__(self, wave, *, mode, tau_interp="linear", torus_file=None, sps_home=None):
    if mode not in AGN_MODES:
        raise ValueError(f"NenkovaTorus(mode={mode!r}): choose one of {AGN_MODES}")
    if tau_interp not in ("linear", "log"):
        raise ValueError(f"NenkovaTorus(tau_interp={tau_interp!r}): 'linear' or 'log'")
    if tau_interp == "log" and mode != AGN_MODE_CORRECTED:
        raise ValueError("tau_interp='log' exists only in agn_mode='corrected'")
    self.mode = mode
    self.tau_interp = tau_interp
    self.path = Path(torus_file) if torus_file is not None else default_torus_path(sps_home)
    wave_np = np.asarray(wave, dtype=np.float64)
    if wave_np.ndim != 1 or not np.all(np.diff(wave_np) > 0):
        raise ValueError("NenkovaTorus: wave must be 1-D and strictly increasing")

    key = (mode, str(self.path), wave_np.shape, wave_np.tobytes())
    hit = _TORUS_CACHE.get(key)
    if hit is None:
        hit = self._build(wave_np)
        _TORUS_CACHE[key] = hit
    tau, T, native, file_int, dense = hit
    self.tau_grid_np = tau
    self.tau_grid = jnp.asarray(tau)
    self.log_tau_grid = jnp.asarray(np.log10(tau))
    self.n_tau = tau.size
    self.templates = jnp.asarray(T)
    self.native_integrals = native
    self.file_integrals = file_int
    self.dense_integrals = dense
    if mode == AGN_MODE_CORRECTED:
        frac = native / dense
        if np.any(frac < 1.0 - NORM_WARN):
            warnings.warn(
                "NenkovaTorus: the model wavelength grid holds only "
                f"{np.array2string(frac, precision=4)} of the torus energy "
                f"(tau = {tau.tolist()}; 1 = the templates' own integral on a dense log "
                "grid); 'corrected' mode renormalises to L_torus = fagn * L_bol, but the "
                "torus SED is truncated on this grid.", stacklevel=3)

template

template(agn_tau)

(n_wave,) T(agn_tau): unit-normalised SED shape (pure JAX).

Source code in ceridwen/agn/torus.py
def template(self, agn_tau):
    """(n_wave,) T(agn_tau): unit-normalised SED shape (pure JAX)."""
    t = jnp.ravel(jnp.asarray(agn_tau, dtype=self.templates.dtype))[0]
    n = self.n_tau
    if self.mode == AGN_MODE_PROSPECTOR:
        # scipy interp1d(kind="linear", fill_value="extrapolate"), its own expression
        hi = jnp.clip(jnp.searchsorted(self.tau_grid, t, side="left"), 1, n - 1)
        lo = hi - 1
        x_lo, x_hi = self.tau_grid[lo], self.tau_grid[hi]
        y_lo, y_hi = self.templates[:, lo], self.templates[:, hi]
        slope = (y_hi - y_lo) / (x_hi - x_lo)
        return slope * (t - x_lo) + y_lo
    grid = self.tau_grid
    if self.tau_interp == "log":
        grid = self.log_tau_grid
        t = jnp.log10(jnp.maximum(t, 1e-300))
    # agn_dust.f90:17-23 (locate: grid[jlo] <= t < grid[jlo+1]), dj clamped to [0, 1]
    jlo = jnp.clip(jnp.searchsorted(grid, t, side="right") - 1, 0, n - 2)
    dj = jnp.clip((t - grid[jlo]) / (grid[jlo + 1] - grid[jlo]), 0.0, 1.0)
    return (1.0 - dj) * self.templates[:, jlo] + dj * self.templates[:, jlo + 1]

ceridwen.agn.disk.TempleDisk

TempleDisk(wave, *, mode, template_file=None)

Bases: Component

Accretion disc: fagn_bbb x Temple+21 template, normalised to the galaxy at 5500 A.

Parameters:

Name Type Description Default
wave (n_wave,) array

Rest-frame model wavelength grid [A], ascending. Static.

required
mode ('fsps', 'prospector', 'corrected')

Template resampling (see module docstring). "fsps" behaves as "prospector" (FSPS has no disc; AGNConfig refuses one in that mode).

"fsps"
template_file str

Two-column (wave [A], F_nu) file; default the bundled temple21.txt.

None
Source code in ceridwen/agn/disk.py
def __init__(self, wave, *, mode, template_file=None):
    if mode not in AGN_MODES:
        raise ValueError(f"TempleDisk(mode={mode!r}): choose one of {AGN_MODES}.")
    wave = np.asarray(wave, dtype=np.float64)
    if wave.ndim != 1 or wave.size < 2 or not np.all(np.diff(wave) > 0):
        raise ValueError("TempleDisk: wave must be a 1-D strictly ascending grid [A].")
    if not np.all(np.isfinite(wave)) or wave[0] <= 0:
        raise ValueError("TempleDisk: wave must be finite and positive [A].")
    self.mode = mode
    self.template_file = TEMPLE21_FILE if template_file is None else template_file
    w_t, f_t = load_temple21(self.template_file)
    if not (np.all(np.diff(w_t) > 0) and np.all(f_t >= 0) and np.all(np.isfinite(f_t))):
        raise ValueError(f"TempleDisk: template {self.template_file} must have ascending "
                         "wavelengths and finite, non-negative F_nu.")
    self.template_range = (float(w_t[0]), float(w_t[-1]))

    tmpl = np.interp(wave, w_t, f_t)
    if mode == AGN_MODE_CORRECTED:
        tmpl = np.where((wave >= w_t[0]) & (wave <= w_t[-1]), tmpl, 0.0)

    lo, hi = NORM_WINDOW
    win = (wave >= lo) & (wave <= hi)
    if not win.any():
        raise ValueError(
            f"TempleDisk: the model grid has no pixel in [{lo:g}, {hi:g}] A, where "
            "fagn_bbb is defined (F_nu,disc / F_nu,galaxy at rest 5500 A, Prospector's "
            f"median over that window). Grid spacing near 5500 A must be < {hi - lo:g} A.")
    if not np.all(tmpl[win] > 0):
        raise ValueError("TempleDisk: the template is not positive in the 5500 A window.")
    self.win_idx = np.flatnonzero(win)          # static index array
    self.template = jnp.asarray(tmpl)            # (n_wave,) float64
    self.template_win = jnp.asarray(tmpl[win])   # (n_win,) float64

norm_scale

norm_scale(gal_nodust_young_old)

Prospector's scale = median(template / galaxy) over the 5500 A window, and a bool that is False when the galaxy is not positive in every window pixel.

Source code in ceridwen/agn/disk.py
def norm_scale(self, gal_nodust_young_old):
    """Prospector's ``scale`` = median(template / galaxy) over the 5500 A window,
    and a bool that is False when the galaxy is not positive in every window pixel."""
    g = jnp.take(jnp.asarray(gal_nodust_young_old), self.win_idx, axis=-1)
    ok = jnp.all(g > 0)
    g_safe = jnp.where(g > 0, g, 1.0)
    return jnp.median(self.template_win / g_safe), ok

rest_spectrum

rest_spectrum(theta, ctx)

(n_wave,) disc F_nu [units of ctx.gal_nodust_young_old], before attenuation.

Source code in ceridwen/agn/disk.py
def rest_spectrum(self, theta, ctx):
    """(n_wave,) disc F_nu [units of ``ctx.gal_nodust_young_old``], before attenuation."""
    fagn_bbb = jnp.asarray(theta.get("fagn_bbb", AGN_THETA_DEFAULTS["fagn_bbb"]))
    scale, ok = self.norm_scale(ctx.gal_nodust_young_old)
    ok = ok & (scale > 0)
    scale_safe = jnp.where(ok, scale, 1.0)
    disc = (self.template / scale_safe) * fagn_bbb
    return jnp.where(ok, disc, 0.0)

ceridwen.agn.screen.AGNScreen

AGNScreen(wave, *, dust4_type=1)

Bases: Screen

Attenuation of the AGN disc: spec * diffuse_curve * exp(-(lam/5500)**dust4_index * dust4).

Parameters:

Name Type Description Default
wave (n_wave,) array

Rest-frame model grid [A]. Static.

required
dust4_type (0, 1)

0: diffuse curve only (dust4 / dust4_index are not read). 1: also the dust4 power law. 2 is refused (NotImplementedError, as in Prospector).

0
Source code in ceridwen/agn/screen.py
def __init__(self, wave, *, dust4_type=1):
    if dust4_type == 2:
        raise NotImplementedError(
            "AGNScreen(dust4_type=2): Prospector raises NotImplementedError for it "
            "(prospect/sources/agnssp_basis.py) and so does CERIDWEN. Use 0 (diffuse "
            "curve only) or 1 (diffuse curve times the dust4 power law).")
    if isinstance(dust4_type, bool) or dust4_type not in DUST4_TYPES:
        raise ValueError(f"AGNScreen(dust4_type={dust4_type!r}): choose 0 or 1.")
    self.dust4_type = int(dust4_type)
    self.wave = jnp.asarray(_check_wave(wave, "AGNScreen"))
    self._x = self.wave / LAMV                    # lam / lamv, static
    self.param_names = ("dust4", "dust4_index") if self.dust4_type == 1 else ()

dust4_transmission

dust4_transmission(theta)

exp(-(lam/5500)**dust4_index * dust4) (all ones for dust4_type=0).

Source code in ceridwen/agn/screen.py
def dust4_transmission(self, theta):
    """``exp(-(lam/5500)**dust4_index * dust4)`` (all ones for ``dust4_type=0``)."""
    if self.dust4_type == 0:                       # static branch
        return jnp.ones_like(self.wave)
    d4 = jnp.asarray(theta.get("dust4", AGN_THETA_DEFAULTS["dust4"]))
    d4_index = jnp.asarray(theta.get("dust4_index", AGN_THETA_DEFAULTS["dust4_index"]))
    return jnp.exp(-(self._x ** d4_index * d4))

transmission

transmission(theta, ctx)

F(obs)/F(emitted) of the AGN screen: ctx.diffuse_curve * dust4_ext.

Source code in ceridwen/agn/screen.py
def transmission(self, theta, ctx):
    """F(obs)/F(emitted) of the AGN screen: ``ctx.diffuse_curve * dust4_ext``."""
    return ctx.diffuse_curve * self.dust4_transmission(theta)

attenuate

attenuate(spec, theta, ctx)

spec (n_wave,) attenuated by the diffuse curve and the dust4 screen.

Source code in ceridwen/agn/screen.py
def attenuate(self, spec, theta, ctx):
    """``spec`` (n_wave,) attenuated by the diffuse curve and the dust4 screen."""
    return spec * self.transmission(theta, ctx)

ceridwen.agn.lines.AGNLines

AGNLines(*, mode, sps_home=None, table_file=None)

Bases: LineComponent

The AGN narrow-line set (static: 23 lines, fixed at setup).

Parameters:

Name Type Description Default
mode one of ``AGN_MODES`` -- selects the painter (see the module docstring)
required
sps_home FSPS directory holding ``data/emlines_info.dat`` (default ``$SPS_HOME``)
None
table_file the ratio table (default ``data/richardson14_a42.csv``)
None

Attributes:

Name Type Description
line_names tuple of FSPS names; ``line_wave`` (n,) vacuum rest wavelengths [A] from the
FSPS list in use; ``ratios`` (n,) L_line / L_Hbeta; ``fsps_index`` (n,) the rows of that list;
``emlines_wave`` / ``emlines_names`` the whole FSPS list (for matching observed lines by name).
Source code in ceridwen/agn/lines.py
def __init__(self, *, mode, sps_home=None, table_file=None):
    if mode not in AGN_MODES:
        raise ValueError(f"AGNLines(mode={mode!r}): choose one of {AGN_MODES}")
    self.mode = mode
    tab = load_a42_table(table_file)
    wave, names, path = read_emlines_info(sps_home)
    self.emlines_file = str(path)
    if wave.size <= HBETA_INDEX or abs(wave[HBETA_INDEX] - 4863.0) >= 2.0:
        raise ValueError(
            f"{path}: line {HBETA_INDEX} is not H beta "
            f"({'missing' if wave.size <= HBETA_INDEX else f'{wave[HBETA_INDEX]:.2f} A'}). "
            "Prospector's AGN line ratios sit on fixed indices of FSPS's line list and assert "
            "that index 59 is H beta; this $SPS_HOME has a different list, so the AGN lines "
            "would land on the wrong lines. Use the FSPS version the table was built from "
            "(see the header of ceridwen/agn/data/richardson14_a42.csv)")
    bad = []
    for n, i, w in zip(tab["names"], tab["fsps_index"], tab["wave_vac"]):
        if i >= wave.size or names[i] != n or abs(wave[i] - w) > 1.0:
            got = "nothing" if i >= wave.size else f"{names[i]!r} at {wave[i]:.2f} A"
            bad.append(f"index {i}: table {n!r} at {w:.2f} A, FSPS {got}")
    if bad:
        raise ValueError(
            f"{path} differs from the FSPS line list the AGN line table was built from "
            f"({len(bad)} of {len(tab['names'])} lines): " + "; ".join(bad) + ". Prospector "
            "applies its ratios by index, so with this list it would put them on other "
            "lines; CERIDWEN refuses instead. Use the matching FSPS data directory")
    self.line_names = tab["names"]
    self.fsps_index = tab["fsps_index"]
    self.line_wave = wave[tab["fsps_index"]].copy()
    self.ratios = tab["ratio"]
    self.emlines_wave = wave
    self.emlines_names = names
    self._ratios_j = jnp.asarray(self.ratios)

line_luminosity

line_luminosity(theta)

(n_lines,) agn_elum * ratio [L_sun per M_formed], in the order of line_names.

Source code in ceridwen/agn/lines.py
def line_luminosity(self, theta):
    """(n_lines,) ``agn_elum * ratio`` [L_sun per M_formed], in the order of ``line_names``."""
    return self._scalar(theta, "agn_elum") * self._ratios_j

sigma_kms

sigma_kms(theta)

agn_eline_sigma [km/s] (scalar).

Source code in ceridwen/agn/lines.py
def sigma_kms(self, theta):
    """``agn_eline_sigma`` [km/s] (scalar)."""
    return self._scalar(theta, "agn_eline_sigma")

rows_for

rows_for(wave_rest, tol=1.0)

For each rest wavelength in wave_rest: the index of the AGN line it is, or -1.

Matched BY NAME: each wavelength is first resolved to the nearest line of the FSPS list (within tol A, else ValueError, the tolerance of the nebular cube matching), and that line's name is looked up in line_names. So two FSPS lines closer than tol (He I 3889 and H 8 3890) are never confused.

Source code in ceridwen/agn/lines.py
def rows_for(self, wave_rest, tol=1.0) -> np.ndarray:
    """For each rest wavelength in ``wave_rest``: the index of the AGN line it is, or -1.

    Matched BY NAME: each wavelength is first resolved to the nearest line of the FSPS list
    (within ``tol`` A, else ValueError, the tolerance of the nebular cube matching), and that
    line's name is looked up in ``line_names``. So two FSPS lines closer than ``tol`` (He I 3889
    and H 8 3890) are never confused."""
    lam = np.atleast_1d(np.asarray(wave_rest, dtype=np.float64))
    out = np.full(lam.size, -1, dtype=np.int64)
    pos = {n: k for k, n in enumerate(self.line_names)}
    for i, l in enumerate(lam):
        j = int(np.argmin(np.abs(self.emlines_wave - l)))
        if abs(self.emlines_wave[j] - l) > tol:
            raise ValueError(
                f"line at {l:.2f} A has no FSPS line within {tol:g} A (nearest "
                f"{self.emlines_names[j]!r} at {self.emlines_wave[j]:.2f} A in "
                f"{self.emlines_file})")
        out[i] = pos.get(self.emlines_names[j], -1)
    return out

observed_fluxes

observed_fluxes(
    theta,
    flux_factor_over_opz,
    *,
    mass=None,
    transmission=None
)

(n_lines,) observed integrated fluxes [erg/s/cm^2]: line_luminosity * mass * flux_factor_over_opz times transmission (n_lines,) when given. mass defaults to 10**theta['logmass'] (1 without it); flux_factor_over_opz is the CSP's _flux_factor(theta) / (1 + z) (L_sun -> erg/s/cm^2), the factor its nebular lines use.

Source code in ceridwen/agn/lines.py
def observed_fluxes(self, theta, flux_factor_over_opz, *, mass=None, transmission=None):
    """(n_lines,) observed integrated fluxes [erg/s/cm^2]: ``line_luminosity * mass *
    flux_factor_over_opz`` times ``transmission`` (n_lines,) when given. ``mass`` defaults to
    ``10**theta['logmass']`` (1 without it); ``flux_factor_over_opz`` is the CSP's
    ``_flux_factor(theta) / (1 + z)`` (L_sun -> erg/s/cm^2), the factor its nebular lines use."""
    L = self.line_luminosity(theta)
    if mass is None:
        mass = 10.0 ** jnp.ravel(theta["logmass"])[0] if "logmass" in theta else 1.0
    F = L * mass * flux_factor_over_opz
    if transmission is not None:
        F = F * transmission
    return F

ceridwen.agn.hook.AGNHook

AGNHook(config, wave, *, add_dust_emission, sps_home=None)

Static AGN wiring for one CSP.

Parameters:

Name Type Description Default
config AGNConfig
required
wave (n_wave,) rest-frame model grid [A]
required
add_dust_emission bool -- whether the CSP has DL07 (decides the energy balance)
required
sps_home str or None
None
Source code in ceridwen/agn/hook.py
def __init__(self, config: AGNConfig, wave, *, add_dust_emission, sps_home=None):
    if not isinstance(config, AGNConfig):
        raise TypeError(
            f"agn= expects ceridwen.agn.AGNConfig(agn_mode=...), got {type(config).__name__}")
    self.config = config
    self.mode = config.agn_mode
    self.energy_balance = config.energy_balance(add_dust_emission)
    self.own_igm = self.mode in (AGN_MODE_FSPS, AGN_MODE_PROSPECTOR)
    self.model = AGNModel(config, wave, sps_home=sps_home)
    self.wave = wave
    # |DL07 trapezoid weights| (positive): integrates F_nu over frequency
    self._w = -trapezoid_nu_weights(wave)
    self.need_galaxy = "disk" in self.model.components or any(
        getattr(c, "needs_galaxy", False) for c in self.model.components.values())
    self.need_ldust_gal = any(getattr(c, "needs_ldust_gal", False)
                              for c in self.model.components.values())
    self.uses_agn2 = config.uses_agn2
    self.param_names = self.model.param_names
    self._defaults = self.model.default_params()
    # spec_dustfree of unit absorbed luminosity for DL07 (one pixel, 1/|w|; spec_attn = 0)
    w_np = np.asarray(self._w, dtype=np.float64)
    j = int(np.argmax(w_np))
    unit = np.zeros_like(w_np)
    unit[j] = 1.0 / w_np[j]
    self._unit_absorbed = jnp.asarray(unit)

filled

filled(theta)

The AGN theta keys, each from theta when present else its default (static).

Source code in ceridwen/agn/hook.py
def filled(self, theta) -> dict:
    """The AGN theta keys, each from ``theta`` when present else its default (static)."""
    return {k: (theta[k] if k in theta else self._defaults[k]) for k in self.param_names}

provenance

provenance()

Static facts a result file should record (INT writes them into fit.py).

Source code in ceridwen/agn/hook.py
def provenance(self) -> dict:
    """Static facts a result file should record (INT writes them into fit.py)."""
    out = {"agn_mode": self.mode, "tau_interp": self.config.tau_interp,
           "agn_energy_balance": bool(self.energy_balance),
           "dust4_type": int(self.config.dust4_type),
           "agn_components": ",".join(sorted(self.model.components))
           + (",lines" if self.model.lines is not None else "")
           + (",polar" if self.model.polar is not None else "")
           + (",blr" if self.model.blr is not None else "")}
    torus = self.model.components.get("torus")
    if torus is not None:
        import hashlib
        out["agn_torus_file"] = str(torus.path)
        out["agn_torus_sha256"] = hashlib.sha256(torus.path.read_bytes()).hexdigest()
        out["agn_torus_native_integrals"] = np.asarray(torus.native_integrals).tolist()
    disk = self.model.components.get("disk")
    if disk is not None:
        out["agn_disk_file"] = str(disk.template_file)
        out["agn_disk_sha256"] = _sha256(disk.template_file)
    if self.model.screen is not None:
        out["agn_dust4"] = "dust2 diffuse curve x exp(-dust4 (lam/5500)^dust4_index)"
    lines = self.model.lines
    if lines is not None:
        from .lines import A42_FILE
        out["agn_lines_table"] = str(A42_FILE)
        out["agn_lines_table_sha256"] = _sha256(A42_FILE)
        out["agn_lines_emlines_file"] = str(lines.emlines_file)
        out["agn_lines_emlines_sha256"] = _sha256(lines.emlines_file)
    if self.uses_agn2:
        cfg = self.config
        out.update({"agn_torus_model": cfg.torus_model if cfg.use_torus else "none",
                    "agn_polar_dust": bool(cfg.polar_dust),
                    "agn_polar_law": cfg.polar_law_resolved if cfg.polar_dust else "none",
                    "agn_nlr_model": cfg.nlr_model if cfg.use_lines else "none",
                    "agn_blr": bool(cfg.blr)})
        for name, part in (("skirtor", self.model.components.get("skirtor")),
                           ("polar", self.model.polar), ("blr", self.model.blr),
                           ("nlr", self.model.lines if cfg.nlr_model == "feltre16"
                            else None)):
            prov = getattr(part, "provenance", None)
            if part is not None and prov is not None:
                out.update({f"agn_{name}_{k}": v for k, v in prov().items()})
    return out

range_messages

range_messages(theta)

check_param_ranges messages for the AGN keys (setup-time, NumPy).

Source code in ceridwen/agn/hook.py
def range_messages(self, theta) -> list:
    """``check_param_ranges`` messages for the AGN keys (setup-time, NumPy)."""
    msgs = []
    if "agn_tau" in theta and "torus" in self.model.components:
        v = np.asarray(theta["agn_tau"], float)
        lo, hi = AGN_TAU_RANGE
        if v.size and (np.nanmin(v) < lo or np.nanmax(v) > hi):
            what = ("EXTRApolated linearly with the end segments, as Prospector's "
                    "fake_fsps.agn_torus does (the SED can go negative)"
                    if self.mode == AGN_MODE_PROSPECTOR else
                    "clamped to the edge template (FSPS agn_dust.f90), so the likelihood "
                    "is flat in agn_tau there")
            msgs.append(f"theta['agn_tau'] = {np.array2string(v, precision=3)} is outside "
                        f"the Nenkova+08 grid [{lo:g}, {hi:g}]; it is {what}.")
    for key in ("fagn", "fagn_bbb", "agn_elum", "dust4"):
        if key in theta and key in self.param_names:
            v = np.asarray(theta[key], float)
            if v.size and np.nanmin(v) < 0:
                msgs.append(f"theta['{key}'] = {np.array2string(v, precision=3)} is "
                            "negative; the AGN term is linear in it and goes negative.")
    if self.uses_agn2:
        if "blr_lum" in theta and "blr_lum" in self.param_names:
            v = np.asarray(theta["blr_lum"], float)
            if v.size and np.nanmin(v) < 0:
                msgs.append(f"theta['blr_lum'] = {np.array2string(v, precision=3)} is "
                            "negative; the broad lines are linear in it and go negative.")
        for part in self.model._parts():
            rm = getattr(part, "range_messages", None)
            if rm is not None and part is not self.model.screen:
                msgs += list(rm(theta))
    return msgs

agn_transmission

agn_transmission(zred, igm_factor)

(n_wave,) T_agn of the reproduction modes (see the module docstring).

Source code in ceridwen/agn/hook.py
def agn_transmission(self, zred, igm_factor):
    """(n_wave,) T_agn of the reproduction modes (see the module docstring)."""
    if self.mode == AGN_MODE_FSPS:
        return jnp.ones(self.wave.shape, dtype=float_dtype())
    return prospector_igm_transmission(self.wave, zred, igm_factor)

components

components(theta, ctx)

(intrinsic, attenuated) (n_wave,) float64 sums over the continuum components.

Source code in ceridwen/agn/hook.py
def components(self, theta, ctx: AGNContext):
    """``(intrinsic, attenuated)`` (n_wave,) float64 sums over the continuum components."""
    th = self.filled(theta)
    dc = ctx.diffuse_curve
    intrinsic = jnp.zeros_like(self.wave, dtype=float_dtype())
    attenuated = jnp.zeros_like(self.wave, dtype=float_dtype())
    for name, comp in self.model.components.items():
        if name == "skirtor":
            continue                      # AGN2: nuclear_parts below
        s = comp.rest_spectrum(th, ctx)
        intrinsic = intrinsic + s
        if name == "torus":
            att = s if self.mode == AGN_MODE_PROSPECTOR else s * dc
        elif self.model.screen is not None:
            att = s * self.model.screen.transmission(th, ctx)
        else:
            att = s * dc
        attenuated = attenuated + att
    if "skirtor" in self.model.components:
        nuc = self.nuclear_parts(th, ctx)["nuclear"]
        intrinsic = intrinsic + nuc
        attenuated = attenuated + nuc * self.galaxy_curve(ctx.diffuse_curve)
    return intrinsic, attenuated

galaxy_curve

galaxy_curve(diffuse_curve)

The galaxy-dust transmission the AGN2 parts see: the diffuse curve in "corrected", 1 in "cigale" (CIGALE adds the AGN after its dust attenuation modules).

Source code in ceridwen/agn/hook.py
def galaxy_curve(self, diffuse_curve):
    """The galaxy-dust transmission the AGN2 parts see: the diffuse curve in "corrected",
    1 in "cigale" (CIGALE adds the AGN after its dust attenuation modules)."""
    if self.mode == AGN_MODE_CIGALE:
        return jnp.ones_like(diffuse_curve)
    return diffuse_curve

nuclear_parts

nuclear_parts(theta, ctx)

AGN2 continuum before the galaxy's dust, (n_wave,) float64 each: disk (SKIRTOR disc, unattenuated), dust (SKIRTOR torus dust), polar_t (the polar-dust transmission, ones without polar dust), polar_ir (its re-emission), nuclear = disk * polar_t + dust + polar_ir. theta is the filled AGN theta.

A SKIRTOR class that composes the polar dust itself (CIGALE renormalises disc, dust and grey body together and re-emits the angle-averaged absorption, NOTE_TORUS_contract) defines nuclear_parts(theta, ctx, polar) returning the same keys; it is used as is.

Source code in ceridwen/agn/hook.py
def nuclear_parts(self, theta, ctx: AGNContext):
    """AGN2 continuum before the galaxy's dust, (n_wave,) float64 each: ``disk`` (SKIRTOR
    disc, unattenuated), ``dust`` (SKIRTOR torus dust), ``polar_t`` (the polar-dust
    transmission, ones without polar dust), ``polar_ir`` (its re-emission), ``nuclear`` =
    disk * polar_t + dust + polar_ir. ``theta`` is the filled AGN theta.

    A SKIRTOR class that composes the polar dust itself (CIGALE renormalises disc, dust and
    grey body together and re-emits the angle-averaged absorption, NOTE_TORUS_contract)
    defines ``nuclear_parts(theta, ctx, polar)`` returning the same keys; it is used as is."""
    sk = self.model.components["skirtor"]
    own = getattr(sk, "nuclear_parts", None)
    if own is not None:
        p = own(theta, ctx, self.model.polar)
        return {k: jnp.asarray(p[k], dtype=float_dtype())
                for k in ("disk", "dust", "polar_t", "polar_ir", "nuclear")}
    parts = sk.rest_parts(theta, ctx)
    disk = jnp.asarray(parts["disk"], dtype=float_dtype())
    dust = jnp.asarray(parts["dust"], dtype=float_dtype())
    polar = self.model.polar
    if polar is None:
        t = jnp.ones_like(disk)
        ir = jnp.zeros_like(disk)
    else:
        t = jnp.asarray(polar.transmission(theta), dtype=float_dtype())
        ir = jnp.asarray(polar.reemission(theta, disk, t, ctx), dtype=float_dtype())
    return {"disk": disk, "dust": dust, "polar_t": t, "polar_ir": ir,
            "nuclear": disk * t + dust + ir}

__call__

__call__(
    theta,
    ctx,
    dust_emission=None,
    dust_theta=None,
    formed_mass=1.0,
)

(agn_continuum_rest (n_wave,) float64, agn_absorbed_lum scalar).

dust_emission: the CSP's DustEmission (needed when energy_balance); dust_theta: its (qpah, umin, gamma) values; formed_mass: the formed mass of the SFH in the units of ctx (sum of the SSP weights), which the AGN line luminosities (per M_formed) are multiplied by before their absorbed part joins the balance.

Source code in ceridwen/agn/hook.py
def __call__(self, theta, ctx: AGNContext, dust_emission=None, dust_theta=None,
             formed_mass=1.0):
    """``(agn_continuum_rest (n_wave,) float64, agn_absorbed_lum scalar)``.

    ``dust_emission``: the CSP's ``DustEmission`` (needed when ``energy_balance``);
    ``dust_theta``: its (qpah, umin, gamma) values; ``formed_mass``: the formed mass of the
    SFH in the units of ``ctx`` (sum of the SSP weights), which the AGN line luminosities
    (per M_formed) are multiplied by before their absorbed part joins the balance."""
    intrinsic, attenuated = self.components(theta, ctx)
    absorbed = jnp.dot(intrinsic - attenuated, self._w)
    if self.energy_balance and self.model.lines is not None:
        # the AGN line light the galaxy screen absorbs joins the re-emitted luminosity
        th = self.filled(theta)
        L = self.model.lines.line_luminosity(th) * formed_mass
        absorbed = absorbed + jnp.sum(
            L * (1.0 - self.line_dust_transmission(ctx.diffuse_curve)))
    if self.energy_balance and self.model.blr is not None:
        absorbed = absorbed + self.blr_absorbed(self.filled(theta), ctx, formed_mass)
    if not self.energy_balance:
        return attenuated, absorbed
    _unit, tduste = self.dust_response(ctx, dust_emission, dust_theta)
    return attenuated + absorbed * tduste, absorbed

line_dust_transmission

line_dust_transmission(diffuse_curve)

(n_lines,) dust transmission of the AGN lines, or None. "corrected": the galaxy's diffuse curve at each line (the narrow-line region lies outside the nuclear dust4 screen, so only the galaxy's diffuse dust acts on it). "fsps" / "prospector": None, Prospector's AGNSpecModel attenuates its AGN lines by nothing.

Source code in ceridwen/agn/hook.py
def line_dust_transmission(self, diffuse_curve):
    """(n_lines,) dust transmission of the AGN lines, or None. ``"corrected"``: the galaxy's
    diffuse curve at each line (the narrow-line region lies outside the nuclear ``dust4``
    screen, so only the galaxy's diffuse dust acts on it). ``"fsps"`` / ``"prospector"``:
    None, Prospector's ``AGNSpecModel`` attenuates its AGN lines by nothing."""
    if self.mode != AGN_MODE_CORRECTED or self.model.lines is None:
        return None
    return jnp.interp(jnp.asarray(self.model.lines.line_wave), self.wave, diffuse_curve)

line_set_transmission

line_set_transmission(key, theta, diffuse_curve)

(n_lines,) float64 transmission of line set key ("nlr" / "blr") at its lines, or None (no attenuation). theta: the filled AGN theta. The NLR keeps line_dust_transmission (the a42 path is unchanged); the BLR sees the nuclear screen (polar dust, or the dust4 power law) and, in "corrected", the galaxy's diffuse curve.

Source code in ceridwen/agn/hook.py
def line_set_transmission(self, key, theta, diffuse_curve):
    """(n_lines,) float64 transmission of line set ``key`` ("nlr" / "blr") at its lines, or
    None (no attenuation). ``theta``: the filled AGN theta. The NLR keeps
    ``line_dust_transmission`` (the a42 path is unchanged); the BLR sees the nuclear screen
    (polar dust, or the dust4 power law) and, in "corrected", the galaxy's diffuse curve."""
    if key == "nlr":
        return self.line_dust_transmission(diffuse_curve)
    lam = jnp.asarray(self.model.line_sets[key].line_wave)
    t = self._nuclear_line_transmission(theta, lam)
    if self.mode == AGN_MODE_CORRECTED:
        g = jnp.interp(lam, self.wave, diffuse_curve)
        t = g if t is None else t * g
    return t

blr_absorbed

blr_absorbed(theta, ctx, formed_mass)

Broad-line light the GALAXY's dust absorbs (joins DL07): L x T_nuc x (1 - T_gal) at each line ("corrected"; 0 otherwise). What the nuclear screen removes is not galaxy dust and is not re-emitted (the polar re-emission is fed by the disc only).

Source code in ceridwen/agn/hook.py
def blr_absorbed(self, theta, ctx, formed_mass):
    """Broad-line light the GALAXY's dust absorbs (joins DL07): L x T_nuc x (1 - T_gal) at
    each line ("corrected"; 0 otherwise). What the nuclear screen removes is not galaxy
    dust and is not re-emitted (the polar re-emission is fed by the disc only)."""
    if self.mode != AGN_MODE_CORRECTED:
        return jnp.zeros((), dtype=float_dtype())
    blr = self.model.blr
    L = blr.line_luminosity(theta) * formed_mass
    lam = jnp.asarray(blr.line_wave)
    t_nuc = self._nuclear_line_transmission(theta, lam)
    if t_nuc is not None:
        L = L * t_nuc
    return jnp.sum(L * (1.0 - jnp.interp(lam, self.wave, ctx.diffuse_curve)))

dust_response

dust_response(ctx, dust_emission, dust_theta)

(mdust, tduste) of DL07 for an absorbed luminosity of exactly 1 L_sun (per M_formed): the CSP's own compute_dust_emission on a one-pixel unit input.

Source code in ceridwen/agn/hook.py
def dust_response(self, ctx, dust_emission, dust_theta):
    """``(mdust, tduste)`` of DL07 for an absorbed luminosity of exactly 1 L_sun (per
    M_formed): the CSP's own ``compute_dust_emission`` on a one-pixel unit input."""
    qpah, umin, gamma = dust_theta
    _spec, mdust, tduste = dust_emission.compute_dust_emission(
        spec_attn=jnp.zeros_like(self._unit_absorbed), spec_dustfree=self._unit_absorbed,
        spec_lambda=self.wave, diffuse_curve=ctx.diffuse_curve,
        duste_qpah=qpah, duste_umin=umin, duste_gamma=gamma)
    return mdust, tduste

Broadening

ceridwen.broadening.Kinematics dataclass

Kinematics(sigma_gal, sigma_gas=TIED, sigma_max=2000.0)

Galaxy velocity dispersions [km/s]; set once on the model, shared by all observations.

sigma_gal : float (fixed) or str (theta key of a free parameter). No default here; SedModel defaults to DEFAULT_KINEMATICS (300 km/s, stars and gas). sigma_gas : float, str, or TIED (= sigma_gal). sigma_max : largest value the compiled kernels support; free values are clipped to it.

validate_theta

validate_theta(theta, priors=None)

Free keys are in theta (a dict or a set of names); a bounded prior on a free key stays within sigma_max; fixed widths are not also in theta.

Source code in ceridwen/broadening.py
def validate_theta(self, theta, priors: Optional[dict] = None) -> None:
    """Free keys are in ``theta`` (a dict or a set of names); a bounded prior on a
    free key stays within sigma_max; fixed widths are not also in theta."""
    for k in self.free_keys:
        if k not in theta:
            raise KeyError(
                f"Kinematics expects theta['{k}'] (free width) but it is not "
                f"in theta; add it (with a prior) or give a float to fix it")
        if priors is not None and k in priors:
            b = getattr(priors[k], "bounds", None)
            if callable(b):
                b = b()
            if b is not None:
                hi = float(np.max(np.asarray(b[1], dtype=float)))
                if np.isfinite(hi) and hi > self.sigma_max:
                    raise ValueError(
                        f"prior on '{k}' allows up to {hi} km/s > "
                        f"sigma_max={self.sigma_max}; raise sigma_max")
    for name, v in (("sigma_gal", self.sigma_gal),
                    ("sigma_gas", self.effective_sigma_gas)):
        if not isinstance(v, str) and name in theta:
            raise ValueError(
                f"{name} is fixed to {v} km/s in Kinematics but theta also "
                f"contains '{name}'; remove one of them")

resolve

resolve(theta)

(sigma_gal, sigma_gas) as JAX scalars; branching on Python types only.

Source code in ceridwen/broadening.py
def resolve(self, theta: dict):
    """(sigma_gal, sigma_gas) as JAX scalars; branching on Python types only."""
    def _get(v):
        if isinstance(v, str):
            return jnp.clip(jnp.ravel(jnp.asarray(theta[v]))[0], 0.0, self.sigma_max)
        return jnp.asarray(float(v))
    return _get(self.sigma_gal), _get(self.effective_sigma_gas)

ceridwen.broadening.Instrument dataclass

Instrument(
    kind, value, wave=None, scale=1.0, scale_range=None
)

Line-spread function of a spectrograph; unit and convention are in the constructor name.

Instrument.R_fwhm(2700)                  R = lambda/FWHM   (datasheet)
Instrument.R_sigma(6358)                 R = lambda/sigma  (same LSF as R_fwhm(2700))
Instrument.fwhm_aa(2.5)                  FWHM [A], observed frame
Instrument.sigma_aa(1.06)                sigma [A], observed frame
Instrument.sigma_kms(47.0)               sigma [km/s]
Instrument.fwhm_kms(111.0)               FWHM [km/s]
Instrument.<any>(array, wave=obs_wave)   per-pixel value on observed wavelengths

LSF scale (every constructor takes scale= and scale_range=): the instrumental dispersion in force is s * sigma_inst(lambda), in the continuum kernel (sigma_cont^2 = sigma_gal^2 + s^2 sigma_inst^2 - sigma_lib^2) and in the line width (sigma_line^2 = sigma_gas^2 + s^2 sigma_inst^2) alike.

scale=1.0 (default)     the nominal LSF; the code path is the one without a scale
scale=1.1 (float > 0)   fixed: identical to building the Instrument with the width x 1.1
                        (folded into the static response at setup, no runtime cost)
scale="lsf_scale"       sampled theta key (give it a prior and a free_param_init); the
                        continuum response weights are recomputed per call from the
                        static band geometry, exactly, for any wavelength dependence of
                        sigma_inst; values are clipped to the supported range
scale_range=(lo, hi)    the range the compiled kernel supports for a sampled scale,
                        0 < lo < hi; default: the finite bounds of the key's prior.
                        Needed when the key is a transform.

Prospector's resolution_jitter_parameter (prospect/models/sedmodel.py:289-295, a78d153) multiplies obs.resolution by the parameter too, but differs: (1) it rescales the continuum only: the line widths are cached from the unscaled obs.resolution just before (cache_eline_parameters, sedmodel.py:283, 575-583), so a jittered LSF broadens the absorption features but not the emission lines; here both. (2) It overwrites obs.padded_resolution in place on every call (state that outlives the call); here the Instrument is immutable and the scale is a pure function argument (jit / vmap / grad). (3) No validation: a value <= 0, or one that takes the instrument below the library, fails an assert inside the likelihood call (observation.py:454); here a non-positive scale, an unbounded or non-positive prior, or a prior beyond scale_range raises at construction, and instrument-below-library pixels follow the usual rule (the continuum stays at library resolution there, with the setup warning evaluated at the lower end of the range).

free_keys property

free_keys

Theta keys this instrument reads (the sampled LSF scale), or ().

sigma_kms_at

sigma_kms_at(wave_obs)

sigma [km/s] at each observed wavelength (NumPy, setup only): the width in force for a fixed scale (nominal x scale), the nominal width (scale 1) for a sampled one, which the projector multiplies by theta[scale] per call.

Source code in ceridwen/broadening.py
def sigma_kms_at(self, wave_obs) -> np.ndarray:
    """sigma [km/s] at each observed wavelength (NumPy, setup only): the width in force
    for a fixed ``scale`` (nominal x scale), the nominal width (scale 1) for a sampled
    one, which the projector multiplies by ``theta[scale]`` per call."""
    v = self._nominal_sigma_kms_at(wave_obs)
    if isinstance(self.scale, str) or self.scale == 1.0:
        return v
    return v * self.scale

ceridwen.broadening.DEFAULT_KINEMATICS module-attribute

DEFAULT_KINEMATICS = Kinematics(sigma_gal=300.0)

ceridwen.broadening.SpectralProjector dataclass

SpectralProjector(
    kinematics,
    instrument,
    subtract_library,
    window,
    J,
    W,
    paint,
    line_idx,
    sigma_inst_kms,
    sigma_lib_kms,
    sigma_fix_kms,
    zred_range=None,
    opz_ref=1.0,
    wave_obs=None,
    line_wave_rest=None,
    line_sigma_table_kms=None,
    inst_scale_key=None,
    inst_scale_range=None,
    scaled=None,
    line_window=None,
)

Built once per Spectrum by setup_for_model; predict() is the per-likelihood call.

With zred_range the projector serves a sampled redshift: the log grid is the one of the reference redshift extended at the same dv to cover every z in the range (so at opz_ref it reproduces the fixed-z projector), the response is built at opz_ref and the model is read at wave_log * opz_ref / opz per call (the sigma_gal kernel commutes with the shift); the lines are painted at line_wave_rest * opz. The library width in the fixed kernel is the one at opz_ref.

With a sampled instrument scale (Instrument(scale="<key>"), inst_scale_key) the continuum weights come from scaled (a :class:ScaledResponse, band sized for the top of inst_scale_range) per call, the lines are painted with s * sigma_inst, and sigma_inst_kms / line_sigma_table_kms hold the NOMINAL (s = 1) widths; W and sigma_fix_kms are then the values at the reference scale (1 clipped into the range). A fixed scale is folded into sigma_inst_kms by Instrument.sigma_kms_at.

inst_scale

inst_scale(theta)

The sampled LSF scale from theta clipped to inst_scale_range (a JAX scalar), or None when the scale is fixed (the static response is used).

Source code in ceridwen/broadening.py
def inst_scale(self, theta):
    """The sampled LSF scale from ``theta`` clipped to ``inst_scale_range`` (a JAX
    scalar), or None when the scale is fixed (the static response is used)."""
    if self.inst_scale_key is None:
        return None
    k = self.inst_scale_key
    if k not in theta:
        raise KeyError(f"the Spectrum's Instrument samples its LSF scale as theta['{k}'], "
                       "which is not in theta")
    lo, hi = self.inst_scale_range
    return jnp.clip(jnp.ravel(jnp.asarray(theta[k]))[0], lo, hi)

enable_line_windows

enable_line_windows()

Opt in to the windowed line basis in :meth:predict_with_line_basis (off by default: on CPU it measured slower than the dense one; it targets GPUs). Each line profile is then evaluated on a static window of +-40 of its largest sigma only; the values are bitwise those of the dense :meth:line_basis (gradients agree to 1-2 ulp: the reverse pass sums over the window): the bounds are Kinematics.sigma_max for a sampled sigma_gas (Kinematics.resolve clips to it), the top of inst_scale_range and the line centres over zred_range. A sampled redshift outside zred_range (beyond the projector's support) truncates the lines; eline_delta_zred in theta always takes the dense path. Call before the first trace: the setting is read when jit traces; a rebuilt projector (SedModel.setup_observations, fitSED(observations=...)) starts with it off again. Sets and returns line_window ((start, width), or None when a window would cover the whole spectrum).

Source code in ceridwen/broadening.py
def enable_line_windows(self) -> Optional[tuple]:
    """Opt in to the windowed line basis in :meth:`predict_with_line_basis` (off by default:
    on CPU it measured slower than the dense one; it targets GPUs).  Each line profile is
    then evaluated on a static window of +-40 of its largest sigma only; the values are
    bitwise those of the dense :meth:`line_basis` (gradients agree to 1-2 ulp: the reverse
    pass sums over the window): the bounds are ``Kinematics.sigma_max`` for a sampled
    sigma_gas (``Kinematics.resolve`` clips to it), the top of ``inst_scale_range`` and the
    line centres over ``zred_range``.  A sampled redshift outside ``zred_range`` (beyond the
    projector's support) truncates the lines; ``eline_delta_zred`` in theta always takes the
    dense path.  Call before the first trace: the setting is read when jit traces; a rebuilt
    projector (``SedModel.setup_observations``, ``fitSED(observations=...)``) starts with it
    off again.  Sets and returns ``line_window`` ((start, width), or None when a window would
    cover the whole spectrum)."""
    if self.line_wave_rest is None or self.line_idx.size == 0:
        self.line_window = None
        return None
    b = self.kinematics
    gas = b.effective_sigma_gas
    opz_lo, opz_hi = ((self.opz_ref, self.opz_ref) if self.zred_range is None
                      else (1.0 + self.zred_range[0], 1.0 + self.zred_range[1]))
    self.line_window = _line_windows(
        self.wave_obs, self.line_wave_rest, self.line_sigma_table_kms,
        b.sigma_max if isinstance(gas, str) else float(gas), opz_lo, opz_hi,
        1.0 if self.inst_scale_range is None else self.inst_scale_range[1])
    return self.line_window

build classmethod

build(
    kinematics,
    instrument,
    wave_model,
    wave_obs,
    zred,
    lib_sigma_kms=None,
    line_wave_rest=None,
    subtract_library=True,
    zred_range=None,
    inst_scale_range=None,
)

wave_model rest-frame model grid [A] wave_obs observed pixel centres [A] zred fixed redshift, or the reference redshift inside zred_range lib_sigma_kms SSPData.ssp_resolution on wave_model, NaN = unknown (or None) line_wave_rest rest wavelengths of all model lines, in predict_line_fluxes order (or None) zred_range (z_min, z_max) of a SAMPLED redshift (None: fixed at zred) inst_scale_range (lo, hi) of a SAMPLED instrument scale when the Instrument carries no scale_range (SedModel passes the prior bounds); the kernel band and window margins are sized for hi

Source code in ceridwen/broadening.py
@classmethod
def build(cls, kinematics: Kinematics, instrument: Optional[Instrument],
          wave_model, wave_obs, zred, lib_sigma_kms=None,
          line_wave_rest=None, subtract_library=True, zred_range=None,
          inst_scale_range=None):
    """
    wave_model      rest-frame model grid [A]
    wave_obs        observed pixel centres [A]
    zred            fixed redshift, or the reference redshift inside ``zred_range``
    lib_sigma_kms   SSPData.ssp_resolution on wave_model, NaN = unknown (or None)
    line_wave_rest  rest wavelengths of all model lines, in predict_line_fluxes order (or None)
    zred_range      (z_min, z_max) of a SAMPLED redshift (None: fixed at ``zred``)
    inst_scale_range (lo, hi) of a SAMPLED instrument scale when the Instrument carries no
                    ``scale_range`` (SedModel passes the prior bounds); the kernel band
                    and window margins are sized for ``hi``
    """
    b = kinematics
    if instrument is not None and not isinstance(instrument, Instrument):
        raise TypeError("instrument must be an Instrument (Instrument.R_fwhm(...), "
                        "Instrument.fwhm_aa(...), ...) or None")
    wave_model = np.asarray(wave_model, dtype=np.float64)
    wave_obs = np.asarray(wave_obs, dtype=np.float64)
    if np.any(np.diff(wave_obs) <= 0.0):
        raise ValueError("observed wavelengths must be strictly increasing")
    opz = 1.0 + float(zred)
    if zred_range is not None:
        z_lo, z_hi = float(zred_range[0]), float(zred_range[1])
        if not (np.isfinite(z_lo) and np.isfinite(z_hi) and -1.0 < z_lo < z_hi):
            raise ValueError(f"zred_range must be finite with -1 < z_min < z_max, got {zred_range}")
        if not (z_lo <= float(zred) <= z_hi):
            raise ValueError(f"the reference redshift {float(zred):g} lies outside "
                             f"zred_range = ({z_lo:g}, {z_hi:g})")
        zred_range = (z_lo, z_hi)
        opz_lo, opz_hi = 1.0 + z_lo, 1.0 + z_hi
    else:
        opz_lo = opz_hi = opz

    scale_key = scale_rng = None
    if instrument is not None and isinstance(instrument.scale, str):
        scale_key = instrument.scale
        scale_rng = instrument.scale_range
        if scale_rng is None:
            if inst_scale_range is None:
                raise ValueError(
                    f"the Instrument samples its LSF scale as theta['{scale_key}'] but no "
                    "range is known for it: give its prior finite bounds (Uniform / "
                    "ClippedNormal, lower bound > 0) or pass Instrument(..., "
                    "scale_range=(lo, hi))")
            scale_rng = check_scale_range(inst_scale_range, f"prior on '{scale_key}'")
    if instrument is None:
        s_inst = np.zeros_like(wave_obs)
        subtract_library = False
    else:
        s_inst = instrument.sigma_kms_at(wave_obs)
    # the narrowest (diagnostics) and widest (kernel sizing) instrument in force
    s_inst_lo = s_inst if scale_key is None else scale_rng[0] * s_inst
    s_inst_hi = s_inst if scale_key is None else scale_rng[1] * s_inst
    if subtract_library and lib_sigma_kms is not None:
        lib = np.asarray(lib_sigma_kms, dtype=np.float64)
        if lib.shape != wave_model.shape:
            raise ValueError("lib_sigma_kms must be on the model grid")
        lib = np.nan_to_num(lib, nan=0.0)
        s_lib = np.interp(wave_obs / opz, wave_model, lib)
    else:
        lib = None
        s_lib = np.zeros_like(wave_obs)
    s_fix2 = s_inst_lo ** 2 - s_lib ** 2
    n_bad = int(np.sum(s_fix2 < 0.0))
    if n_bad:
        warnings.warn(
            ("" if scale_key is None else
             f"at the lower end of the '{scale_key}' range ({scale_rng[0]:g}): ")
            + f"instrument narrower than the SSP library at {n_bad} of "
            f"{wave_obs.size} pixels ({100 * n_bad / wave_obs.size:.1f} %, "
            f"{wave_obs[s_fix2 < 0].min():.0f}-{wave_obs[s_fix2 < 0].max():.0f} A): "
            "the continuum is delivered at library resolution there, which is "
            "correct for a coarse grid; if the instrument is really finer, use a "
            "finer grid; if the number is wrong, check the Instrument unit")
    s_fix = np.sqrt(np.clip(s_fix2, 0.0, None))
    if zred_range is not None and lib is not None:
        worst = 0.0
        for o in (opz_lo, opz_hi):
            s_end = np.sqrt(np.clip(s_inst_lo ** 2 - np.interp(wave_obs / o, wave_model, lib) ** 2,
                                    0.0, None))
            worst = max(worst, float(np.max(np.abs(s_end - s_fix) / np.maximum(s_fix, 1e-3))))
        if worst > 0.1:
            warnings.warn(
                f"the library width in the fixed kernel is taken at z = {opz - 1:g}; over "
                f"zred_range it changes the kernel by up to {100 * worst:.0f} % at some "
                "pixel. Narrow the redshift prior or accept the approximation")

    s_fix_hi = (s_fix if scale_key is None
                else np.sqrt(np.clip(s_inst_hi ** 2 - s_lib ** 2, 0.0, None)))
    marg = BAND_NSIGMA * (b.sigma_max + float(s_fix_hi.max())) / CKMS
    wmin_ref = wave_obs[0] / opz * np.exp(-marg)
    wmax_ref = wave_obs[-1] / opz * np.exp(+marg)
    wmin = wave_obs[0] / opz_hi * np.exp(-marg)
    wmax = wave_obs[-1] / opz_lo * np.exp(+marg)
    if wmin < wave_model[0] or wmax > wave_model[-1]:
        raise ValueError(
            f"model grid [{wave_model[0]:.0f}, {wave_model[-1]:.0f}] A does not "
            f"cover the observed window plus kernel margin "
            f"[{wmin:.0f}, {wmax:.0f}] A (rest"
            + (f", zred in [{z_lo:g}, {z_hi:g}]" if zred_range else "")
            + "); trim the observation, narrow the redshift range or reduce sigma_max")
    window = WindowSmoother(LogGrid.build(
        wave_model, wmin_ref, wmax_ref, b.sigma_max,
        extend_to=None if zred_range is None else (wmin, wmax)))
    scaled = None
    if scale_key is None:
        J, W = build_response(window.grid, np.log(wave_obs) - np.log(opz), s_fix)
    else:
        scaled = ScaledResponse(window.grid, np.log(wave_obs) - np.log(opz), s_inst,
                                s_lib, scale_rng[1])
        s_ref = float(np.clip(1.0, *scale_rng))
        J, W = scaled.J_np, scaled.weights_np(s_ref)
        s_fix = np.sqrt(np.clip((s_ref * s_inst) ** 2 - s_lib ** 2, 0.0, None))
        n_sw = scaled.n_rows_switching(*scale_rng)
        if n_sw:
            warnings.warn(
                f"over the '{scale_key}' range {scale_rng} the continuum kernel of {n_sw} "
                f"of {wave_obs.size} pixels crosses half a log-grid pixel "
                f"({0.5 * window.grid.dv:.1f} km/s), where the response switches between "
                "linear interpolation and a Gaussian: the prediction steps slightly in the "
                "scale there (instrument close to the library resolution). Narrow the "
                "range, or check the Instrument / subtract_library")

    paint, line_idx = None, np.zeros(0, dtype=np.int64)
    lw_kept = s_table = None
    if line_wave_rest is not None:
        lwr = np.asarray(line_wave_rest, dtype=np.float64)
        marg_l = BAND_NSIGMA * (b.sigma_max + float(s_inst_hi.max())) / CKMS
        keep = ((lwr * opz_hi > wave_obs[0] * np.exp(-marg_l))
                & (lwr * opz_lo < wave_obs[-1] * np.exp(marg_l)))
        line_idx = np.flatnonzero(keep)
        if line_idx.size:
            if instrument is None:
                # no LSF: a line cannot be narrower than the pixel it lands on
                s_table = 0.5 * CKMS * np.gradient(np.log(wave_obs))
            else:
                s_table = s_inst
            lw_kept = lwr[keep]
            if zred_range is None:
                lw = lwr[keep] * opz
                paint = make_line_painter(wave_obs, lw, np.interp(lw, wave_obs, s_table))
            else:
                paint = make_line_painter_free_z(wave_obs, lwr[keep], s_table)

    return cls(kinematics=b, instrument=instrument,
               subtract_library=bool(subtract_library), window=window,
               J=jnp.asarray(J), W=jnp.asarray(W), paint=paint,
               line_idx=line_idx, sigma_inst_kms=s_inst,
               sigma_lib_kms=s_lib, sigma_fix_kms=s_fix,
               zred_range=zred_range, opz_ref=opz, wave_obs=wave_obs,
               line_wave_rest=lw_kept, line_sigma_table_kms=s_table,
               inst_scale_key=scale_key, inst_scale_range=scale_rng, scaled=scaled)

continuum

continuum(
    spec_rest,
    sigma_gal_kms,
    opz=None,
    inst_scale=None,
    transmission=None,
)

Continuum on the observed pixels; opz = 1 + z (traced) when free_z, inst_scale (traced) when the instrument scale is sampled. transmission: a callable T(rest wavelengths) (the IGM) applied after the sigma_gal kernel and before the instrument, on the log grid; spec_rest is then the spectrum before the IGM.

Source code in ceridwen/broadening.py
def continuum(self, spec_rest, sigma_gal_kms, opz=None, inst_scale=None, transmission=None):
    """Continuum on the observed pixels; ``opz`` = 1 + z (traced) when ``free_z``,
    ``inst_scale`` (traced) when the instrument scale is sampled.  ``transmission``: a
    callable ``T(rest wavelengths)`` (the IGM) applied after the sigma_gal kernel and before
    the instrument, on the log grid; ``spec_rest`` is then the spectrum before the IGM."""
    scale = None if opz is None else self.opz_ref / opz

    def project(x):                       # linear in x; float32 for a float32 spectrum
        spec_log = self.window.smooth(self.window.to_log(x, scale), sigma_gal_kms)
        if transmission is not None:
            w_log = self.window._wave_log if scale is None else self.window._wave_log * scale
            spec_log = spec_log * transmission(w_log).astype(spec_log.dtype)
        if inst_scale is None:
            return apply_response(self.J, self.W, spec_log)
        return apply_response(self.scaled.J, self.scaled.weights(inst_scale), spec_log)
    # float64 out, the float32 work scaled (the likelihood's cotangent must not enter
    # float32 unscaled: _scaled_to_float64)
    return _scaled_to_float64(project, spec_rest)

line_basis

line_basis(sigma_gas_kms, opz_line, inst_scale=None)

(n_pix, n_kept) f_nu of UNIT-flux lines on the observed pixels, centred at line_wave_rest * opz_line (traced), width sqrt(sigma_gas^2 + sigma_inst^2) with the instrument width interpolated at the line (times inst_scale when given); the painter's profile, one column per line.

Source code in ceridwen/broadening.py
def line_basis(self, sigma_gas_kms, opz_line, inst_scale=None):
    """(n_pix, n_kept) f_nu of UNIT-flux lines on the observed pixels, centred at
    ``line_wave_rest * opz_line`` (traced), width sqrt(sigma_gas^2 + sigma_inst^2) with the
    instrument width interpolated at the line (times ``inst_scale`` when given); the
    painter's profile, one column per line."""
    wo = np.asarray(self.wave_obs, dtype=np.float64)
    lam = jnp.asarray(np.asarray(self.line_wave_rest, dtype=np.float64))
    lnl = jnp.log(lam) + jnp.log(opz_line)
    s_inst = jnp.interp(lam * opz_line, jnp.asarray(wo),
                        jnp.asarray(np.asarray(self.line_sigma_table_kms, dtype=np.float64)))
    if inst_scale is not None:
        s_inst = s_inst * inst_scale
    s = jnp.sqrt(sigma_gas_kms ** 2 + s_inst ** 2) / CKMS
    x = (jnp.asarray(np.log(wo))[:, None] - lnl[None, :]) / s[None, :]
    phi = jnp.exp(-0.5 * x * x) / (jnp.sqrt(2.0 * jnp.pi) * s[None, :])
    return phi * jnp.asarray(wo / C_AA_S)[:, None]

predict_with_line_basis

predict_with_line_basis(
    spec_rest,
    line_flux_obs_all,
    theta,
    fit_pos=None,
    basis=None,
    transmission=None,
)

(prediction, A): continuum plus the lines of line_flux_obs_all painted with :meth:line_basis at (1 + zred + eline_delta_zred) (theta key, default 0), and the unit-flux columns A (n_pix, len(fit_pos)) of the kept lines at positions fit_pos (None when fit_pos is None).

Source code in ceridwen/broadening.py
def predict_with_line_basis(self, spec_rest, line_flux_obs_all, theta, fit_pos=None,
                            basis=None, transmission=None):
    """``(prediction, A)``: continuum plus the lines of ``line_flux_obs_all`` painted with
    :meth:`line_basis` at ``(1 + zred + eline_delta_zred)`` (theta key, default 0), and the
    unit-flux columns ``A`` (n_pix, len(fit_pos)) of the kept lines at positions ``fit_pos``
    (None when ``fit_pos`` is None)."""
    s_gal, s_gas = self.kinematics.resolve(theta)
    opz = None
    if self.free_z:
        if "zred" not in theta:
            raise KeyError("projector built with zred_range needs theta['zred']")
        opz = 1.0 + jnp.ravel(jnp.asarray(theta["zred"]))[0]
    s_ins = self.inst_scale(theta)
    out = self.continuum(spec_rest, s_gal, opz, s_ins, transmission)
    if self.line_wave_rest is None or self.line_idx.size == 0:
        return out, None
    if basis is None:   # a precomputed basis is only passed for fixed z, widths, dz = 0
        opz_line = self.opz_ref if opz is None else opz
        if "eline_delta_zred" in theta:
            # unbounded shift: the static windows do not hold, the dense basis does
            opz_line = opz_line + jnp.ravel(jnp.asarray(theta["eline_delta_zred"]))[0]
            basis = self.line_basis(s_gas, opz_line, s_ins)
        elif self.line_window is not None:
            basis = self._line_basis_windowed(s_gas, opz_line, s_ins)
        else:
            basis = self.line_basis(s_gas, opz_line, s_ins)
    else:
        basis = jnp.asarray(basis)
    if line_flux_obs_all is not None:
        out = out + (basis @ line_flux_obs_all[self._line_idx_j]).astype(out.dtype)
    # A stays float64 (the likelihood's linear algebra): the line marginal solves normal
    # equations in it whose condition number may reach COND_MAX = 1e10
    # (likelihood/eline_marginal.py), where float32 columns would leave few correct digits
    A = None if fit_pos is None else basis[:, np.asarray(fit_pos, dtype=np.int64)]
    return out, A

has_agn_lines

has_agn_lines(key='nlr')

True when the painter of AGN line set key has been built.

Source code in ceridwen/broadening.py
def has_agn_lines(self, key="nlr") -> bool:
    """True when the painter of AGN line set ``key`` has been built."""
    if key == "nlr":
        return self._agn is not None
    return self._agn_sets is not None and key in self._agn_sets

setup_agn_lines

setup_agn_lines(
    agn_line_wave_rest,
    *,
    mode,
    sf_line_wave_rest=None,
    agn_sf_rows=None,
    pixel_mask=None,
    key="nlr"
)

Build the AGN-line painter for this projector (setup time, NumPy).

key: the line set ("nlr", the default, is stored where it always was; any other set, e.g. "blr", only with mode="corrected", the nebular painter's profile with the set's own width).

mode "corrected": the nebular painter's profile (Gaussian in ln lambda, unit area, width sqrt(agn_eline_sigma^2 + sigma_inst^2) with the instrument at the line, times the sampled instrument scale). "prospector" / "fsps": Prospector's AGNSpecModel painter (:func:make_agn_line_painter_prospector), which needs every nebular line (sf_line_wave_rest, rest A), the nebular row of each AGN line (agn_sf_rows) and the Spectrum's pixel_mask.

Source code in ceridwen/broadening.py
def setup_agn_lines(self, agn_line_wave_rest, *, mode, sf_line_wave_rest=None,
                    agn_sf_rows=None, pixel_mask=None, key="nlr"):
    """Build the AGN-line painter for this projector (setup time, NumPy).

    ``key``: the line set ("nlr", the default, is stored where it always was; any other
    set, e.g. "blr", only with ``mode="corrected"``, the nebular painter's profile with the
    set's own width).

    ``mode`` "corrected": the nebular painter's profile (Gaussian in ln lambda, unit area,
    width sqrt(agn_eline_sigma^2 + sigma_inst^2) with the instrument at the line, times the
    sampled instrument scale). "prospector" / "fsps": Prospector's ``AGNSpecModel`` painter
    (:func:`make_agn_line_painter_prospector`), which needs every nebular line
    (``sf_line_wave_rest``, rest A), the nebular row of each AGN line (``agn_sf_rows``) and
    the Spectrum's ``pixel_mask``."""
    lam = np.asarray(agn_line_wave_rest, dtype=np.float64)
    if self.instrument is None:
        s_table = 0.5 * CKMS * np.gradient(np.log(self.wave_obs))
    else:
        s_table = np.asarray(self.sigma_inst_kms, dtype=np.float64)
    if mode == "corrected":
        paint = make_line_painter_free_z(self.wave_obs, lam, s_table)
        if key == "nlr":
            self._agn = {"mode": mode, "paint": paint}
        else:
            if self._agn_sets is None:
                self._agn_sets = {}
            self._agn_sets[key] = {"mode": mode, "paint": paint}
        return
    if key != "nlr":
        raise ValueError(f"setup_agn_lines(key={key!r}, mode={mode!r}): only the narrow "
                         "lines have Prospector's painter; other line sets use 'corrected'")
    if mode not in ("prospector", "fsps"):
        raise ValueError(f"setup_agn_lines(mode={mode!r}): 'corrected', 'prospector' or 'fsps'")
    if sf_line_wave_rest is None or agn_sf_rows is None:
        raise ValueError(
            "the Prospector AGN-line painter selects its pixels from the nebular lines "
            "(AGNSpecModel asserts 'must add agn and nebular lines'): pass "
            "sf_line_wave_rest and agn_sf_rows (a CSP with add_neb=True)")
    sf = np.asarray(sf_line_wave_rest, dtype=np.float64)
    # library width of each nebular line at its rest wavelength (Prospector interpolates the
    # library resolution at the rest line wavelength); sigma_lib_kms is on wave_obs at opz_ref
    lib = np.interp(sf * self.opz_ref, self.wave_obs,
                    np.asarray(self.sigma_lib_kms, dtype=np.float64))
    self._agn = {
        "mode": mode,
        "paint": make_agn_line_painter_prospector(self.wave_obs, lam, sf, agn_sf_rows,
                                                  pixel_mask),
        "sf_rest": jnp.asarray(sf), "lib": jnp.asarray(lib),
        "inst": None if self.instrument is None else jnp.asarray(s_table),
    }

agn_lines

agn_lines(line_flux_obs, sigma_agn_kms, theta, key='nlr')

f_nu of the AGN lines on the observed pixels (add to :meth:predict): line_flux_obs (n_agn,) observed integrated fluxes, sigma_agn_kms the set's width (agn_eline_sigma, blr_sigma); centres at rest x (1 + zred + eline_delta_zred). key: the line set (see :meth:setup_agn_lines).

Source code in ceridwen/broadening.py
def agn_lines(self, line_flux_obs, sigma_agn_kms, theta, key="nlr"):
    """f_nu of the AGN lines on the observed pixels (add to :meth:`predict`):
    ``line_flux_obs`` (n_agn,) observed integrated fluxes, ``sigma_agn_kms`` the set's width
    (``agn_eline_sigma``, ``blr_sigma``); centres at rest x (1 + zred +
    ``eline_delta_zred``). ``key``: the line set (see :meth:`setup_agn_lines`)."""
    if not self.has_agn_lines(key):
        raise RuntimeError(f"SpectralProjector.agn_lines(key={key!r}) before setup_agn_lines")
    s_gal, s_gas = self.kinematics.resolve(theta)
    opz = self.opz_ref
    if self.free_z:
        if "zred" not in theta:
            raise KeyError("projector built with zred_range needs theta['zred']")
        opz = 1.0 + jnp.ravel(jnp.asarray(theta["zred"]))[0]
    if "eline_delta_zred" in theta:
        opz = opz + jnp.ravel(jnp.asarray(theta["eline_delta_zred"]))[0]
    s_ins = self.inst_scale(theta)
    a = self._agn if key == "nlr" else self._agn_sets[key]
    if a["mode"] == "corrected":                  # float32 profiles: float64 out, scaled
        return _scaled_to_float64(
            lambda f: a["paint"](f, sigma_agn_kms, opz, s_ins), line_flux_obs)
    # Prospector's nebular widths (cache_eline_parameters): hypot(eline_sigma, lib), then
    # hypot with sqrt(inst^2 - lib^2) (0 where negative) when the spectrum has a resolution
    lib = a["lib"]
    e = jnp.hypot(s_gas, lib)
    if a["inst"] is not None:
        inst = jnp.interp(a["sf_rest"] * opz, jnp.asarray(self.wave_obs), a["inst"])
        if s_ins is not None:
            inst = inst * s_ins
        d2 = inst ** 2 - lib ** 2
        e = jnp.hypot(e, jnp.where(d2 > 0.0, jnp.sqrt(jnp.where(d2 > 0.0, d2, 1.0)), 0.0))
    return a["paint"](line_flux_obs, sigma_agn_kms, e, s_gas, opz)

ceridwen.broadening.PhotometricBroadener dataclass

PhotometricBroadener(window)

sigma_gal broadening of spec_rest over the rest range the filters cover; pixels outside pass through.

Observations

ceridwen.observation.Photometry

Photometry(
    filters=[],
    name=None,
    upper_limit=None,
    filter_directory=None,
    **kwargs
)

Bases: Observation

Broadband photometric observation; flux and uncertainty in AB maggies (1 maggie = 3631 Jy).

Parameters:

Name Type Description Default
filters list of str or Filter -- names are looked up in ``filter_directory`` when it is given,

otherwise in $CERIDWEN_FILTER_DIR and then the bundled library; a Filter must come from the file its name resolves to (else ValueError)

[]
filter_directory str or path, optional -- directory of ``<name>.par`` files; only it is searched
None
upper_limit bool array (n_filters,) -- True = one-sided (model > data only) chi-squared penalty
None

Attributes:

Name Type Description
flux array (n_filters,), maggies (keyword argument)
uncertainty array (n_filters,), maggies -- 1-sigma (keyword argument)
mask bool array (n_filters,) -- True = used in the fit (keyword argument)
Source code in ceridwen/observation/photometry.py
def __init__(self, filters=[], name=None, upper_limit=None, filter_directory=None, **kwargs):
    self.filter_directory = _filter_directory(filter_directory)
    self.set_filters(filters)
    self.upper_limit = (
        None if upper_limit is None
        else jnp.asarray(np.atleast_1d(upper_limit), dtype=bool)
    )
    super().__init__(name=name, **kwargs)

wavelength property

wavelength

Effective wavelengths of the filters [Å], shape (n_filters,).

model_support property

model_support

(lo, hi): the model-grid indices predict reads at the fixed redshift of setup_for_model (the non-zero columns of _T, joined with the sigma_gal broadener's window when there is one); None before setup. A Photometry projected at a sampled redshift reads the whole grid (CSPBasis._support_for checks free_z).

set_filters

set_filters(filters)

Set the filter list from filter-name strings or Filter objects (read from self.filter_directory when set).

Source code in ceridwen/observation/photometry.py
def set_filters(self, filters):
    """Set the filter list from filter-name strings or ``Filter`` objects (read from
    ``self.filter_directory`` when set)."""
    directory = getattr(self, "filter_directory", None)
    if not filters:
        self.filters     = []
        self.filternames = []
        self.filterfiles = []
        self.filterset   = None
        return

    self.filternames = [_filter_name(f, directory) for f in filters]

    self.filterset = _filterset(self.filternames, directory)
    self.filters   = list(self.filterset.filters)
    self.filterfiles = [os.path.abspath(p) for p in self.filterset.filterfiles]
    self.wave_eff = [f.wave_effective for f in self.filters]
    self._wavelength = jnp.asarray([f.wave_effective for f in self.filters])

get_maggies

get_maggies(model_wave, model_fnu)

Synthetic maggies, shape (n_filters,), of an F_nu spectrum on model_wave [Å] (reference path; normalisation follows the input flux units).

Source code in ceridwen/observation/photometry.py
def get_maggies(self, model_wave, model_fnu):
    """Synthetic maggies, shape (n_filters,), of an F_nu spectrum on ``model_wave`` [Å]
    (reference path; normalisation follows the input flux units)."""
    if self.filterset is None:
        raise ValueError("No FilterSet configured; call set_filters() first.")
    _c         = jnp.array(2.998e18)
    wave       = jnp.asarray(model_wave,  dtype=float)
    flux_flam  = jnp.asarray(model_fnu,   dtype=float) * _c / wave**2
    return self.filterset.get_sed_maggies(flux_flam, sourcewave=wave)

setup_for_model

setup_for_model(wave_model, zred=0.0)

Precompute the (n_filters, n_wave) float32 projection matrix _T (F_nu -> maggies) for the rest-frame grid wave_model [Å] observed at fixed zred; required before predict.

Source code in ceridwen/observation/photometry.py
def setup_for_model(self, wave_model, zred: float = 0.0):
    """Precompute the ``(n_filters, n_wave)`` float32 projection matrix ``_T`` (F_nu -> maggies)
    for the rest-frame grid ``wave_model`` [Å] observed at fixed ``zred``; required before ``predict``."""
    wm_rest = np.asarray(wave_model, dtype=np.float64)
    self._setup_zred = float(zred)
    opz = 1.0 + float(zred)
    wm = opz * wm_rest
    n_wave = len(wm)
    _c = 2.998e18

    fnu_to_flam = _c / wm**2

    # the exact integral over the model pixels (FilterSet.flux_weights): flux-conserving
    # for lines narrower than the filter grid
    T = self.filterset.flux_weights(wm, xp=np) * fnu_to_flam[None, :]
    # static window lengths for predict_at_redshift (a sampled redshift up to
    # filters.FLUX_WINDOW_ZMAX), on this rest-frame grid
    self._flux_windows = self.filterset.flux_window_widths(wm_rest)
    self._flux_windows_n = int(wm_rest.size)

    T32 = T.astype(np.float32)
    self._T = jnp.array(T32)
    self._has_precomputed_T = True
    self._broadener = None
    self._line_photometry = None
    cols = np.flatnonzero(np.any(T32 != 0.0, axis=0))
    self._T_support = (int(cols[0]), int(cols[-1]) + 1) if cols.size else (0, 0)

setup_broadening

setup_broadening(
    wave_model, zred, kinematics, *, free_z=False, neb=None
)

Build the sigma_gal broadener over the rest range the filters cover (the whole 912-25000 A window when free_z; None for Kinematics.none() or no kinematics) and, when neb is given, the line term _line_photometry (observation.line_photometry.LinePhotometry): each nebular line's flux through each filter, without painting it, as a delta line without kinematics (broaden_photometry=False) and as a Gaussian of the gas width with it. Call after setup_for_model.

Source code in ceridwen/observation/photometry.py
def setup_broadening(self, wave_model, zred, kinematics, *, free_z=False, neb=None):
    """Build the sigma_gal broadener over the rest range the filters cover (the
    whole 912-25000 A window when ``free_z``; None for ``Kinematics.none()`` or no
    ``kinematics``) and, when ``neb`` is given, the line term ``_line_photometry``
    (``observation.line_photometry.LinePhotometry``): each nebular line's flux through
    each filter, without painting it, as a delta line without ``kinematics``
    (``broaden_photometry=False``) and as a Gaussian of the gas width with it.  Call after
    ``setup_for_model``."""
    from ..broadening import PhotometricBroadener
    from .line_photometry import LinePhotometry
    self._broadener = None
    self._line_photometry = None
    if neb is not None and self.filterset is not None:
        gas = None if kinematics is None else kinematics.effective_sigma_gas
        self._line_photometry = LinePhotometry(
            self.filterset, np.asarray(neb.nebem_line_pos, dtype=np.float64),
            zred=zred, free_z=free_z,
            sigma="sampled" if isinstance(gas, str) else gas,
            sigma_max_kms=None if kinematics is None else kinematics.sigma_max)
    if kinematics is None:
        return
    wm = np.asarray(wave_model, dtype=np.float64)
    static_zero = (kinematics.is_static
                   and float(kinematics.sigma_gal) == 0.0
                   and float(kinematics.effective_sigma_gas) == 0.0)
    if not static_zero:
        if free_z or self.filterset is None:
            wmin, wmax = max(912.0, wm[0]), min(25000.0, wm[-1])
        else:
            opz = 1.0 + float(zred)
            lam = np.asarray(self.filterset.lam, dtype=np.float64)
            wmin = max(lam.min() / opz, wm[0])
            wmax = min(lam.max() / opz, wm[-1])
        if wmin < wmax:
            self._broadener = PhotometricBroadener.build(kinematics, wm, wmin, wmax)

predict

predict(spectrum, wave_model)

Synthetic AB maggies, shape (n_filters,), as _T @ spectrum (F_nu on wave_model).

Source code in ceridwen/observation/photometry.py
def predict(self, spectrum, wave_model):
    """Synthetic AB maggies, shape (n_filters,), as ``_T @ spectrum`` (F_nu on ``wave_model``)."""
    if not getattr(self, "_has_precomputed_T", False):
        raise RuntimeError(
            "Photometry.predict() called before setup_for_model(): call "
            "phot.setup_for_model(wave_model, zred=...) once before the first "
            "predict / JIT trace (get_maggies(wave, spectrum) is the "
            "rest-frame reference path).")
    return self._T @ spectrum

predict_at_redshift

predict_at_redshift(spectrum_fnu_observed, wave_rest, zred)

Observer-frame AB maggies, shape (n_filters,), for a traced zred: spectrum_fnu_observed must already be observer-frame F_nu (flux factor and IGM applied) on the rest-frame grid wave_rest [Å].

Source code in ceridwen/observation/photometry.py
def predict_at_redshift(self, spectrum_fnu_observed, wave_rest, zred):
    """Observer-frame AB maggies, shape (n_filters,), for a traced ``zred``: ``spectrum_fnu_observed``
    must already be observer-frame F_nu (flux factor and IGM applied) on the rest-frame grid ``wave_rest`` [Å]."""
    if self.filterset is None:
        raise ValueError("No FilterSet configured; call set_filters() first.")
    wave_obs = (1.0 + jnp.asarray(zred)) * jnp.asarray(wave_rest)
    flux_flam = spectrum_fnu_observed * (2.998e18 / (wave_obs * wave_obs))
    widths = getattr(self, "_flux_windows", None)
    if widths is not None and jnp.shape(wave_rest)[0] == self._flux_windows_n:
        # each filter's window of model pixels only (static lengths from setup_for_model)
        return self.filterset.windowed_maggies(flux_flam, wave_obs, widths)
    return self.filterset.get_sed_maggies(flux_flam, sourcewave=wave_obs)

chi_sq

chi_sq(model_maggies)

Chi-squared (float) over unmasked bands; upper-limit bands are penalised only when model > data.

Source code in ceridwen/observation/photometry.py
def chi_sq(self, model_maggies):
    """Chi-squared (float) over unmasked bands; upper-limit bands are penalised only when model > data."""
    mf    = jnp.asarray(model_maggies, dtype=float)
    resid = (self.flux - mf) / self.uncertainty

    if self.upper_limit is not None:
        resid_sq = jnp.where(
            self.upper_limit,
            jnp.where(resid < 0.0, resid ** 2, 0.0),
            resid ** 2,
        )
    else:
        resid_sq = resid ** 2

    return float(jnp.sum(jnp.where(self.mask, resid_sq, 0.0)))

residuals

residuals(model_maggies)

Per-filter (data - model) / sigma, shape (n_filters,); masked bands NaN, upper-limit bands 0 when model < data.

Source code in ceridwen/observation/photometry.py
def residuals(self, model_maggies):
    """Per-filter (data - model) / sigma, shape (n_filters,); masked bands NaN, upper-limit bands 0 when model < data."""
    res = (self.flux - jnp.asarray(model_maggies, dtype=float)) / self.uncertainty

    if self.upper_limit is not None:
        res = jnp.where(
            self.upper_limit & (res >= 0.0),
            0.0,
            res,
        )
    return jnp.where(self.mask, res, jnp.nan)

ceridwen.observation.Spectrum

Spectrum(
    wavelength=None,
    flux=None,
    uncertainty=None,
    mask=slice(None),
    noise=None,
    name=None,
    instrument=None,
    subtract_library=True,
    calibration=None,
    logify_spectrum=False,
    sky=None,
    noise_floor=0.0,
    zred_range=None,
    marginalize_elines=False,
    eline_prior_width=0.0,
    elines_to_fit=None,
    elines_to_fix=None,
    elines_to_ignore=None,
    polynomial_order=0,
    polynomial_regularization=0.0,
    polynomial_mode="profile",
    polynomial_prior_sigma=None,
    **kwargs
)

Bases: Observation

Spectroscopic observation on an observed-frame pixel grid.

Parameters:

Name Type Description Default
wavelength array-like (n_pix,), Å, vacuum, OBSERVED frame.
None
flux array-like (n_pix,) -- same units as the model spectra

passed to chi_sq / residuals.

None
uncertainty array-like (n_pix,) -- same units as the model spectra

passed to chi_sq / residuals.

None
mask array-like of bool or slice -- True for pixels that are USED.
slice(None)
instrument Instrument or None -- the spectrograph LSF; unit and convention

are the constructor name (Instrument.R_fwhm(2700), Instrument.fwhm_aa(2.5), Instrument.sigma_kms(arr, wave=w), ...). None = no instrumental broadening (and no library subtraction). scale= on the Instrument multiplies its width (fixed float, or a sampled theta key with a bounded prior), in the continuum and the lines alike.

None
subtract_library bool -- remove the SSP library resolution in quadrature

from the instrument width (default True; needs the grid's resolution curve).

True
calibration array-like (n_pix,) -- multiplicative model correction

(model * calibration ~ data), applied in chi_sq/residuals/log_likelihood.

None
logify_spectrum bool -- residuals in log-flux space.
False
sky array-like (n_pix,) -- subtracted from data in chi_sq/residuals/

log_likelihood only (not in predict).

None
noise_floor float -- fractional floor: sigma_eff^2 = sigma^2 + (floor*|model|)^2.
0.0
noise GaussianProcess -- squared-exponential GP on the whitened residuals with FIXED

hyperparameters, used by log_likelihood and by fitSED (GPGaussianLikelihood); to sample them, leave it None and sample log_gp_amp_spec / log_gp_length_spec (docs/gp_likelihood.md).

None
zred_range (z_min, z_max) -- support of a SAMPLED redshift; otherwise taken from

the finite bounds of the model's zred prior.

None
marginalize_elines bool -- marginalise analytically over the fluxes of the nebular

lines in this spectrum (jointly with the model's Photometry and Lines), instead of fixing them at the CLOUDY prediction; needs an instrument; with a nebular model its parameters must not be sampled, without one (add_neb=False, CSPBasis_afe) the lines come from $SPS_HOME/data/emlines_info.dat and the prior is flat. See docs/eline_marginalisation.md.

False
eline_prior_width float -- 0 (default): flat prior on each fitted line flux;

0: Gaussian prior centred on the CLOUDY flux with this FRACTIONAL width. Ly-alpha is always flat.

0.0
elines_to_fit sequences of FSPS line names

($SPS_HOME/data/emlines_info.dat, e.g. "[O III] 5007"). Default: fit every grid line covered by the spectrum; fixed lines keep their CLOUDY flux; ignored lines are removed from every observation.

None
elines_to_fix sequences of FSPS line names

($SPS_HOME/data/emlines_info.dat, e.g. "[O III] 5007"). Default: fit every grid line covered by the spectrum; fixed lines keep their CLOUDY flux; ignored lines are removed from every observation.

None
elines_to_ignore sequences of FSPS line names

($SPS_HOME/data/emlines_info.dat, e.g. "[O III] 5007"). Default: fit every grid line covered by the spectrum; fixed lines keep their CLOUDY flux; ignored lines are removed from every observation.

None
polynomial_order int -- 0 (default): no profiled calibration. M > 0: the likelihood

multiplies the model by 1 + sum_{m=0}^{M} c_m T_m(x) with the coefficients solved by weighted least squares at every call (Prospector's PolyOptCal; Chebyshev over the unmasked wavelength range, weights from the noise model), so no dimension is sampled. Opt-in; the sampled spectrum_scaling / spectrum_calib stay the default route and cannot be combined with it on the same spectrum.

0
polynomial_regularization float or array (M+1,) -- ridge term reg_m^2 c_m^2 (default 0);

profile mode only.

0.0
polynomial_mode "profile" (default) or "marginalize" -- how the polynomial of

polynomial_order > 0 enters the likelihood: profiled (solved, as above) or integrated out analytically under the Gaussian prior c_m ~ N(0, s_m^2) (ceridwen/likelihood/poly_marginal.py; exact marginal likelihood, conditional coefficients reported per draw by PostProcess). T_0 is then a grey scale with prior width s_0, degenerate with the mass unless photometry anchors the level.

'profile'
polynomial_prior_sigma float or array (M+1,) -- the prior widths s (finite, >= 0; 0 pins

a coefficient at 0); required with polynomial_mode="marginalize", refused otherwise.

None
Notes

The galaxy's velocity dispersions are not a property of the observation: they are set once on the model (SedModel(kinematics=Kinematics(...))).

Source code in ceridwen/observation/spectrum.py
def __init__(
    self,
    wavelength   = None,
    flux         = None,
    uncertainty  = None,
    mask         = slice(None),
    noise        = None,
    name         = None,
    instrument   = None,
    subtract_library = True,
    calibration  = None,
    logify_spectrum = False,
    sky          = None,
    noise_floor  = 0.0,
    zred_range   = None,
    marginalize_elines = False,
    eline_prior_width  = 0.0,
    elines_to_fit      = None,
    elines_to_fix      = None,
    elines_to_ignore   = None,
    polynomial_order   = 0,
    polynomial_regularization = 0.0,
    polynomial_mode    = "profile",
    polynomial_prior_sigma = None,
    **kwargs,
):
    for k in list(kwargs):
        if k in self._removed_kwargs:
            raise TypeError(
                f"Spectrum(): '{k}' is not an argument; use {self._removed_kwargs[k]}")
    if "eline_sigma" in kwargs:
        raise TypeError(
            "Spectrum(): there is no eline_sigma. The marginalised lines have the same "
            "width as every other line, sqrt(sigma_gas^2 + sigma_inst^2): set sigma_gas "
            "(a velocity DISPERSION in km/s, not a FWHM) once on the model, "
            "SedModel(kinematics=Kinematics(sigma_gal=..., sigma_gas=...))")
    if instrument is not None and not isinstance(instrument, Instrument):
        raise TypeError(
            "Spectrum(instrument=...) takes a ceridwen.broadening.Instrument "
            "(Instrument.R_fwhm(2700), Instrument.fwhm_aa(2.5), "
            "Instrument.sigma_kms(120.0), ...), got "
            f"{type(instrument).__name__}")
    self._wavelength    = (
        None if wavelength is None
        else jnp.asarray(wavelength, dtype=float)
    )
    self.instrument       = instrument
    self.subtract_library = bool(subtract_library)
    self.calibration    = (
        None if calibration is None
        else jnp.asarray(calibration, dtype=float)
    )
    self.logify_spectrum = logify_spectrum
    self.sky             = (None if sky is None
                            else jnp.asarray(sky, dtype=float))
    self.noise_floor     = float(noise_floor)
    if (isinstance(polynomial_order, bool) or not isinstance(polynomial_order, (int, np.integer))
            or polynomial_order < 0):
        raise ValueError(f"Spectrum(): polynomial_order must be an integer >= 0 (0 = off), "
                         f"got {polynomial_order!r}")
    self.polynomial_order = int(polynomial_order)
    reg = np.asarray(polynomial_regularization, dtype=float)
    if reg.ndim > 1 or (reg.ndim == 1 and reg.size != self.polynomial_order + 1) \
            or np.any(~np.isfinite(reg)) or np.any(reg < 0):
        raise ValueError("Spectrum(): polynomial_regularization must be a float >= 0 or "
                         f"one value >= 0 per coefficient ({self.polynomial_order + 1}), "
                         f"got {polynomial_regularization!r}")
    self.polynomial_regularization = reg
    self._set_polynomial_mode(polynomial_mode, polynomial_prior_sigma)
    self.zred_range      = (None if zred_range is None
                            else (float(zred_range[0]), float(zred_range[1])))
    self._proj = None
    self._set_eline_options(marginalize_elines, eline_prior_width,
                            elines_to_fit, elines_to_fix, elines_to_ignore, noise)
    if self.polynomial_mode == "marginalize":
        self._check_marginal_polynomial(noise)

    super().__init__(
        flux        = flux,
        uncertainty = uncertainty,
        mask        = mask,
        noise       = noise,
        name        = name,
        **kwargs,
    )

model_support property

model_support

(lo, hi): the model-grid indices the projector reads (its log-grid window, which for a sampled redshift covers the whole zred_range); None before setup.

setup_for_model

setup_for_model(
    wave_model,
    zred=0.0,
    kinematics=None,
    lib_resolution=None,
    line_wave_rest=None,
    zred_range=None,
    inst_scale_range=None,
)

Build the projector from the rest-frame model grid wave_model [Å] redshifted by (1 + zred) onto self.wavelength; call once, outside JIT.

kinematics : Kinematics -- galaxy widths (None = Kinematics.none()) lib_resolution : (wave_rest [Å], sigma_v [km/s]) -- SSP library resolution curve on wave_model (NaN = unknown); used when subtract_library and an instrument are set line_wave_rest : (n_lines,) rest wavelengths of the nebular grid lines in predict_line_fluxes order, or None (no lines painted) zred_range : (z_min, z_max) -- for a SAMPLED redshift (default self.zred_range): the projection is then read at theta['zred'] on every call and zred is the reference redshift inside the range inst_scale_range : (lo, hi) -- for an Instrument with a SAMPLED scale (Instrument(..., scale="<key>")) and no scale_range of its own: the range the kernel must support (SedModel passes the key's prior bounds)

Source code in ceridwen/observation/spectrum.py
def setup_for_model(self, wave_model, zred: float = 0.0,
                    kinematics=None, lib_resolution=None,
                    line_wave_rest=None, zred_range=None, inst_scale_range=None):
    """Build the projector from the rest-frame model grid ``wave_model`` [Å]
    redshifted by (1 + zred) onto ``self.wavelength``; call once, outside JIT.

    kinematics : Kinematics -- galaxy widths (None = ``Kinematics.none()``)
    lib_resolution : (wave_rest [Å], sigma_v [km/s]) -- SSP library
        resolution curve on ``wave_model`` (NaN = unknown); used when
        ``subtract_library`` and an instrument are set
    line_wave_rest : (n_lines,) rest wavelengths of the nebular grid lines
        in ``predict_line_fluxes`` order, or None (no lines painted)
    zred_range : (z_min, z_max) -- for a SAMPLED redshift (default ``self.zred_range``):
        the projection is then read at ``theta['zred']`` on every call and ``zred``
        is the reference redshift inside the range
    inst_scale_range : (lo, hi) -- for an Instrument with a SAMPLED scale
        (``Instrument(..., scale="<key>")``) and no ``scale_range`` of its own: the
        range the kernel must support (SedModel passes the key's prior bounds)
    """
    if self._wavelength is None:
        raise ValueError(
            "Spectrum.setup_for_model() needs the observed pixel "
            "wavelength grid, but this Spectrum has wavelength=None. "
            "Pass wavelength= (Å, vacuum, observed frame) at "
            "construction — flux/uncertainty may be added later (e.g. a "
            "predictive container for mock generation)."
        )
    if kinematics is None:
        kinematics = Kinematics.none()
    if zred_range is None:
        zred_range = self.zred_range
    lib = None
    if lib_resolution is not None and self.instrument is not None and self.subtract_library:
        lw = np.asarray(lib_resolution[0], dtype=np.float64)
        ls = np.asarray(lib_resolution[1], dtype=np.float64)
        wm = np.asarray(wave_model, dtype=np.float64)
        if lw.shape == wm.shape and np.allclose(lw, wm):
            lib = ls
        else:
            fin = np.isfinite(ls)
            lib = (np.interp(wm, lw[fin], ls[fin], left=np.nan, right=np.nan)
                   if fin.any() else None)
    self._proj = SpectralProjector.build(
        kinematics, self.instrument, wave_model, self._wavelength, zred,
        lib_sigma_kms=lib, line_wave_rest=line_wave_rest,
        subtract_library=self.subtract_library, zred_range=zred_range,
        inst_scale_range=inst_scale_range)

predict

predict(
    spectrum,
    wave_model=None,
    line_flux=None,
    theta=None,
    transmission=None,
)

Model F_nu on the observed pixels (n_pix,): the rest-frame CONTINUUM spectrum (n_wave,) broadened by sigma_gal, the instrument LSF (library width removed) and resampled, plus the emission lines painted from their observed-frame integrated fluxes line_flux (all grid lines, or None) with sigma_gas + instrument. theta supplies the free widths and, for a projector built with zred_range, the redshift. transmission (a callable of the rest wavelength, the IGM): applied after the galaxy's sigma_gal and before the instrument; spectrum is then the continuum before the IGM.

Source code in ceridwen/observation/spectrum.py
def predict(self, spectrum, wave_model=None, line_flux=None, theta=None, transmission=None):
    """Model F_nu on the observed pixels (n_pix,): the rest-frame CONTINUUM
    ``spectrum`` (n_wave,) broadened by sigma_gal, the instrument LSF (library
    width removed) and resampled, plus the emission lines painted from their
    observed-frame integrated fluxes ``line_flux`` (all grid lines, or None)
    with sigma_gas + instrument.  ``theta`` supplies the free widths and, for a
    projector built with ``zred_range``, the redshift.  ``transmission`` (a callable of the
    rest wavelength, the IGM): applied after the galaxy's sigma_gal and before the
    instrument; ``spectrum`` is then the continuum before the IGM."""
    if self._proj is None:
        raise RuntimeError(
            "Spectrum.predict() called before setup_for_model(): the "
            "projector has not been built. Call "
            "spec.setup_for_model(wave_model, zred=..., kinematics=...) once "
            "(before the first predict / JIT trace)."
        )
    return self._proj.predict(spectrum, line_flux, {} if theta is None else theta,
                              transmission=transmission)

synthetic_photometry

synthetic_photometry(filterset)

Synthetic maggies (n_filters,) of this F_nu spectrum through filterset; None if there is no data.

Source code in ceridwen/observation/spectrum.py
def synthetic_photometry(self, filterset):
    """Synthetic maggies (n_filters,) of this F_nu spectrum through
    ``filterset``; None if there is no data."""
    if self.flux is None or self._wavelength is None:
        return None
    _c        = jnp.array(2.998e18)   # Å/s
    flux_flam = self.flux * _c / self._wavelength**2
    return filterset.get_sed_maggies(flux_flam, sourcewave=self._wavelength)

mask_wavelength_range

mask_wavelength_range(wave_min, wave_max)

Mask pixels with wavelength in [wave_min, wave_max] Å (inclusive).

Source code in ceridwen/observation/spectrum.py
def mask_wavelength_range(self, wave_min, wave_max):
    """Mask pixels with wavelength in [wave_min, wave_max] Å (inclusive)."""
    if self._wavelength is None:
        return
    in_range  = (self._wavelength >= wave_min) & (self._wavelength <= wave_max)
    self.mask = self.mask & ~in_range

mask_lines

mask_lines(line_waves, dv=1000.0, zred=None)

Mask +/- dv km/s around each rest-frame line wavelength [Å], redshifted by (1 + zred) onto the observed grid. Pass zred (the source redshift; 0.0 for rest-frame data): without it the rest wavelengths are masked on the observed grid, with a warning.

Source code in ceridwen/observation/spectrum.py
def mask_lines(self, line_waves, dv=1000.0, zred=None):
    """Mask +/- ``dv`` km/s around each rest-frame line wavelength [Å],
    redshifted by (1 + zred) onto the observed grid.  Pass ``zred`` (the source
    redshift; 0.0 for rest-frame data): without it the rest wavelengths are masked on the
    observed grid, with a warning."""
    if self._wavelength is None:
        return
    if zred is None:
        warnings.warn(
            "Spectrum.mask_lines without zred masks the REST wavelengths on the observed "
            "pixel grid; pass zred=<source redshift> (zred=0.0 if the data are rest frame)",
            stacklevel=2)
        zred = 0.0
    c_kms = 2.998e5
    opz   = 1.0 + float(zred)
    for lam0_rest in np.asarray(line_waves).ravel():
        lam0_obs = opz * float(lam0_rest)
        dlam     = lam0_obs * dv / c_kms
        self.mask_wavelength_range(lam0_obs - dlam, lam0_obs + dlam)

chi_sq

chi_sq(model_flux)

Sum of squared normalised residuals over unmasked pixels for model_flux (n_pix,) on the observed grid: the DIAGONAL chi^2 (sigma_eff with the noise floor only), without the GP of self.noise even when one is set.

Source code in ceridwen/observation/spectrum.py
def chi_sq(self, model_flux):
    """Sum of squared normalised residuals over unmasked pixels for
    ``model_flux`` (n_pix,) on the observed grid: the DIAGONAL chi^2 (sigma_eff with the
    noise floor only), without the GP of ``self.noise`` even when one is set."""
    resid = self._compute_residuals(model_flux)
    return float(jnp.sum(jnp.where(self.mask, resid ** 2, 0.0)))

residuals

residuals(model_flux)

Per-pixel normalised residuals (n_pix,); masked pixels are NaN.

Source code in ceridwen/observation/spectrum.py
def residuals(self, model_flux):
    """Per-pixel normalised residuals (n_pix,); masked pixels are NaN."""
    resid = self._compute_residuals(model_flux)
    return jnp.where(self.mask, resid, jnp.nan)

log_likelihood

log_likelihood(model_flux)

Gaussian log-likelihood of model_flux (n_pix,), including the sigma_eff normalisation; with self.noise a GaussianProcess it is the full GP likelihood (the value fitSED's GPGaussianLikelihood gives for the same fixed hyperparameters and noise_floor), otherwise the diagonal one. Host-side floats, for use after a fit; the samplers use the compiled likelihood.

Source code in ceridwen/observation/spectrum.py
def log_likelihood(self, model_flux):
    """Gaussian log-likelihood of ``model_flux`` (n_pix,), including the
    sigma_eff normalisation; with ``self.noise`` a GaussianProcess it is the full GP
    likelihood (the value ``fitSED``'s ``GPGaussianLikelihood`` gives for the same fixed
    hyperparameters and noise_floor), otherwise the diagonal one.  Host-side floats,
    for use after a fit; the samplers use the compiled likelihood."""
    resid, sigma_r = self._compute_residuals(model_flux, return_sigma=True)
    mask = self.mask

    safe_sigma = jnp.where(mask, sigma_r, 1.0)
    lognorm    = float(
        -0.5 * jnp.sum(jnp.where(mask, jnp.log(safe_sigma ** 2), 0.0))
    )

    if self.noise is not None and self._wavelength is not None:
        # GP term already includes the white-noise identity and -n/2 ln(2 pi)
        lnL_struct = float(self.noise.log_likelihood(
            np.array(resid),
            np.array(self._wavelength),
            np.array(mask),
        ))
    else:
        r = jnp.where(mask, resid, 0.0)
        n = float(jnp.sum(mask))
        lnL_struct = float(
            -0.5 * jnp.sum(r ** 2) - 0.5 * n * jnp.log(2.0 * jnp.pi)
        )

    return float(lnL_struct + lognorm)

fit_polynomial_calibration

fit_polynomial_calibration(model_flux, order=3)

Weighted least-squares Chebyshev calibration P(lambda) with data ~ P * model_flux over unmasked pixels; returns (coeffs (order+1,), P * model_flux (n_pix,)).

Source code in ceridwen/observation/spectrum.py
def fit_polynomial_calibration(self, model_flux, order: int = 3):
    """Weighted least-squares Chebyshev calibration P(lambda) with
    data ~ P * model_flux over unmasked pixels; returns
    (coeffs (order+1,), P * model_flux (n_pix,))."""
    mf     = np.asarray(model_flux, dtype=np.float64)
    data   = np.asarray(self._sky_corrected_data(), dtype=np.float64)
    sigma  = np.asarray(self.uncertainty, dtype=np.float64)
    wav    = np.asarray(self._wavelength,  dtype=np.float64)
    mask   = np.asarray(self.mask,         dtype=bool)

    wav_mid  = 0.5 * (wav.max() + wav.min())
    wav_half = 0.5 * (wav.max() - wav.min())
    x        = (wav - wav_mid) / (wav_half if wav_half > 0 else 1.0)

    A = np.polynomial.chebyshev.chebvander(x, order)  # (n_pix, order+1)

    A_w = (A * mf[:, None]) / sigma[:, None]
    y_w = data / sigma

    A_wm = A_w[mask]
    y_wm = y_w[mask]

    coeffs, _, _, _ = np.linalg.lstsq(A_wm, y_wm, rcond=None)

    poly_vals       = A @ coeffs
    calibrated_flux = jnp.asarray(poly_vals * mf)

    return coeffs, calibrated_flux

ceridwen.observation.Lines

Lines(
    line_ind,
    line_names=None,
    wavelength=None,
    name=None,
    upper_limit=None,
    components=None,
    sigma_v=200.0,
    **kwargs
)

Bases: Observation

Observed emission-line fluxes with line indices, rest wavelengths and uncertainties.

Parameters:

Name Type Description Default
line_ind array-like of int -- indices of the observed lines in the SPS emission-line array
required
line_names list of str, optional -- one name per line; needed by ``mask_by_name`` / ``select_by_name``
None
wavelength array-like of float, vacuum rest-frame Angstrom
None
components list of sequences of float, optional -- per observed line, the vacuum rest wavelengths

[Angstrom] of all grid lines summed into that measurement (unresolved doublets); default one per line

None
upper_limit array-like of bool, optional -- True treats the line as a non-detection: chi^2 penalises

only model > data

None
sigma_v float, km/s -- Gaussian aperture width of ``predict`` (integration of a painted

spectrum); CSPBasis.predict does not use it, it reads the line fluxes from the grid

200.0

Attributes:

Name Type Description
flux, uncertainty array-like of float, same units as the model prediction (typically

erg/s/cm^2) (keyword arguments)

Source code in ceridwen/observation/lines.py
def __init__(
    self,
    line_ind,
    line_names  = None,
    wavelength  = None,
    name        = None,
    upper_limit = None,
    components  = None,
    sigma_v     = 200.0,
    **kwargs,
):
    self.sigma_v = float(sigma_v)
    if line_ind is None:
        raise ValueError(
            "line_ind is required: pass the indices of the observed lines "
            "in the FSPS emline_luminosity array."
        )
    if wavelength is None:
        raise ValueError(
            "wavelength is required: pass the wavelengths of the observed lines."
        )
    self.line_ind   = jnp.asarray(np.atleast_1d(line_ind), dtype=int)
    self.line_names = list(line_names) if line_names is not None else None
    self._wavelength = (
        None if wavelength is None
        else jnp.asarray(np.atleast_1d(wavelength), dtype=float)
    )
    self.upper_limit = (
        None if upper_limit is None
        else jnp.asarray(np.atleast_1d(upper_limit), dtype=bool)
    )
    n_lines = int(np.atleast_1d(line_ind).size)
    if components is None:
        self.line_components = [
            (float(w),) for w in np.atleast_1d(np.asarray(wavelength, dtype=float))
        ]
    else:
        comps = [tuple(float(x) for x in np.atleast_1d(c)) for c in components]
        if len(comps) != n_lines:
            raise ValueError(
                f"components has {len(comps)} entries but there are "
                f"{n_lines} lines")
        if any(len(c) == 0 for c in comps):
            raise ValueError("every components entry needs >= 1 wavelength")
        self.line_components = comps
    super().__init__(name=name, **kwargs)

has_blends property

has_blends

True when at least one observed line sums several grid lines.

to_json

to_json()

Base JSON plus line_names and line_components.

Source code in ceridwen/observation/lines.py
def to_json(self):
    """Base JSON plus ``line_names`` and ``line_components``."""
    d = json.loads(super().to_json())
    d["line_names"] = self.line_names
    d["line_components"] = [list(c) for c in self.line_components]
    return json.dumps(d)

agn_line_matrix

agn_line_matrix(agn_lines)

(n_lines, n_agn) float64 NumPy 0/1 matrix: row k sums the AGN lines (ceridwen.agn.lines.AGNLines) that observed line k holds, every component of a blend included. Matched BY NAME: each component wavelength is resolved to the nearest line of FSPS's list within 1 A (ValueError otherwise) and that name is looked up among the AGN lines (AGNLines.rows_for); a line that is not an AGN line gets a zero row. Cached on the observation (NumPy, so a first use inside a jit trace never caches a tracer), one entry per line set (AGN2: the NLR and the BLR each have their own).

Source code in ceridwen/observation/lines.py
def agn_line_matrix(self, agn_lines) -> np.ndarray:
    """(n_lines, n_agn) float64 NumPy 0/1 matrix: row ``k`` sums the AGN lines
    (``ceridwen.agn.lines.AGNLines``) that observed line ``k`` holds, every component of a
    blend included. Matched BY NAME: each component wavelength is resolved to the nearest line
    of FSPS's list within 1 A (ValueError otherwise) and that name is looked up among the AGN
    lines (``AGNLines.rows_for``); a line that is not an AGN line gets a zero row. Cached on the
    observation (NumPy, so a first use inside a jit trace never caches a tracer), one entry per
    line set (AGN2: the NLR and the BLR each have their own)."""
    cache = self.__dict__.setdefault("_agn_line_matrix", {})
    cached = cache.get(id(agn_lines))
    if cached is not None and cached[0] is agn_lines:
        return cached[1]
    M = np.zeros((len(self.line_components), agn_lines.n_lines), dtype=np.float64)
    for k, comp in enumerate(self.line_components):
        for j in agn_lines.rows_for(comp):
            if j >= 0:
                M[k, j] += 1.0
    cache[id(agn_lines)] = (agn_lines, M)
    return M

setup_for_model

setup_for_model(wave_model, zred=0.0, sigma_v=None)

Record the model wavelength grid [Angstrom, rest, increasing], aperture sigma_v [km/s] and redshift used to build the _W aperture matrix; must precede predict.

Source code in ceridwen/observation/lines.py
def setup_for_model(self, wave_model, zred: float = 0.0, sigma_v=None):
    """Record the model wavelength grid [Angstrom, rest, increasing], aperture ``sigma_v`` [km/s]
    and redshift used to build the ``_W`` aperture matrix; must precede ``predict``."""
    self._W_args = (np.asarray(wave_model, dtype=np.float64),
                    float(self.sigma_v if sigma_v is None else sigma_v), float(zred))
    self.__dict__.pop("_W", None)

predict

predict(spectrum, wave_model)

Return _W @ spectrum: Gaussian-aperture line fluxes, shape (n_lines,), from an F_nu model spectrum; wave_model is unused, setup_for_model must have been called.

Source code in ceridwen/observation/lines.py
def predict(self, spectrum, wave_model):
    """Return ``_W @ spectrum``: Gaussian-aperture line fluxes, shape (n_lines,), from an F_nu
    model spectrum; ``wave_model`` is unused, ``setup_for_model`` must have been called."""
    if getattr(self, "_W_args", None) is None:
        raise RuntimeError(
            "Lines.predict() called before setup_for_model(): call "
            "lines.setup_for_model(wave_model) once before the first "
            "predict / JIT trace.")
    return jnp.asarray(self._W) @ spectrum

chi_sq

chi_sq(model_fluxes)

Return chi^2 over unmasked lines; upper-limit lines are penalised only when model > data.

Source code in ceridwen/observation/lines.py
def chi_sq(self, model_fluxes):
    """Return chi^2 over unmasked lines; upper-limit lines are penalised only when model > data."""
    mf    = jnp.asarray(model_fluxes, dtype=float)
    resid = (self.flux - mf) / self.uncertainty

    if self.upper_limit is not None:
        resid_sq = jnp.where(
            self.upper_limit,
            jnp.where(resid < 0.0, resid ** 2, 0.0),
            resid ** 2,
        )
    else:
        resid_sq = resid ** 2

    return float(jnp.sum(jnp.where(self.mask, resid_sq, 0.0)))

residuals

residuals(model_fluxes)

Return per-line (data - model) / sigma, shape (n_lines,); masked lines NaN, upper-limit lines with model <= data set to 0.

Source code in ceridwen/observation/lines.py
def residuals(self, model_fluxes):
    """Return per-line ``(data - model) / sigma``, shape (n_lines,); masked lines NaN,
    upper-limit lines with model <= data set to 0."""
    mf    = jnp.asarray(model_fluxes, dtype=float)
    resid = (self.flux - mf) / self.uncertainty

    if self.upper_limit is not None:
        resid = jnp.where(
            self.upper_limit & (resid >= 0.0),
            0.0,
            resid,
        )

    return jnp.where(self.mask, resid, jnp.nan)

mask_by_name

mask_by_name(names)

Set mask = False for lines whose name is in names; no-op without line_names.

Source code in ceridwen/observation/lines.py
def mask_by_name(self, names):
    """Set ``mask = False`` for lines whose name is in ``names``; no-op without ``line_names``."""
    if self.line_names is None:
        return
    names_set = set(names)
    exclude = jnp.array(
        [n in names_set for n in self.line_names], dtype=bool
    )
    self.mask = self.mask & ~exclude

select_by_name

select_by_name(names)

Return a new Lines containing only the named lines (KeyError on an unknown name).

Source code in ceridwen/observation/lines.py
def select_by_name(self, names):
    """Return a new ``Lines`` containing only the named lines (KeyError on an unknown name)."""
    if self.line_names is None:
        raise ValueError(
            "line_names not set on this Lines object; "
            "cannot select by name."
        )
    idx = []
    for n in names:
        if n not in self.line_names:
            raise KeyError(
                f"Line '{n}' not found.  Available: {self.line_names}"
            )
        idx.append(self.line_names.index(n))
    idx = np.array(idx)

    def _pick(arr):
        return None if arr is None else np.array(arr)[idx]

    return Lines(
        line_ind    = np.array(self.line_ind)[idx],
        line_names  = [self.line_names[i] for i in idx],
        wavelength  = _pick(self._wavelength),
        flux        = _pick(self.flux),
        uncertainty = _pick(self.uncertainty),
        mask        = np.array(self.mask)[idx],
        upper_limit = _pick(self.upper_limit) if self.upper_limit is not None else None,
        components  = [self.line_components[i] for i in idx],
        name        = self.name + "_sel",
    )

Model

ceridwen.model.SedModel

SedModel(
    csp,
    observations,
    priors=None,
    transforms=None,
    free_param_init=None,
    zred=0.0,
    cosmo=None,
    lumdist_mpc=None,
    kinematics=None,
    broaden_photometry=True,
)

Parameter manager and prediction layer: predict(theta) returns a dict keyed by observation name, log_prob(theta) the summed log-prior on free parameters.

Parameters:

Name Type Description Default
priors dict[str, Prior] -- free-parameter name -> prior; absent names get a flat improper prior
None
transforms dict[str, callable] -- derived CSP parameter name -> ``fn(free_theta)``; derived names leave the free set
None
free_param_init dict[str, Array] -- initial values of the free parameters replacing derived ones
None
zred float -- fixed redshift; zred = 0 without ``lumdist_mpc`` applies NO flux factor, so predictions

are L_sun/Hz x 10^logmass, not maggies

0.0
cosmo
None
lumdist_mpc float, Mpc -- explicit luminosity distance replacing D_L(zred) in the flux factor
None
kinematics Kinematics -- the galaxy's stellar / gas velocity dispersions [km/s], fixed

(float) or sampled (theta key); default DEFAULT_KINEMATICS = 300 km/s, stars and gas

None
broaden_photometry bool -- apply the kinematic broadening to the spectrum entering the

filters (default True; below 5e-4 mag for broad bands, per cent for a narrow band on a line)

True
Source code in ceridwen/model/model.py
def __init__(
    self,
    csp,
    observations: Sequence[Observation],
    priors: dict[str, Any] | None = None,
    transforms: dict[str, Callable] | None = None,
    free_param_init: dict[str, Any] | None = None,
    zred: float = 0.0,
    cosmo=None,
    lumdist_mpc: float | None = None,
    kinematics: Kinematics | None = None,
    broaden_photometry: bool = True,
):
    self.csp          = csp
    self.observations = list(observations)
    self.priors       = dict(priors) if priors is not None else {}
    self.transforms   = dict(transforms) if transforms is not None else {}
    self.fixed        = dict(getattr(csp, "fixed", None) or {})
    for name, value in self.fixed.items():
        for where, given in (("priors", self.priors), ("transforms", self.transforms),
                             ("free_param_init", free_param_init or {})):
            if name in given:
                raise ValueError(
                    f"{name!r} is fixed on the CSP (CSPBasis(fixed={{{name!r}: "
                    f"{value.tolist() if value.size > 1 else float(value[0])}}})) and is "
                    f"also in {where}.  To sample it, build the CSP without it in fixed= "
                    "and give it a prior; to derive it, drop it from fixed= and keep the "
                    "transform.")
        self.transforms[name] = FixedValue(name, value)
    self.zred         = float(zred)
    if kinematics is None:
        kinematics = DEFAULT_KINEMATICS
    if not isinstance(kinematics, Kinematics):
        raise TypeError("kinematics must be a ceridwen.broadening.Kinematics "
                        f"(e.g. Kinematics(sigma_gal=250.0)), got {type(kinematics).__name__}")
    self.kinematics   = kinematics
    self.broaden_photometry = bool(broaden_photometry)

    if not hasattr(csp, "cosmo"):
        raise TypeError(
            f"{type(csp).__name__} carries no .cosmo; build the CSP with "
            "cosmo=Cosmology.planck18() (or another Cosmology)")
    if cosmo is not None and cosmo != csp.cosmo:
        raise ValueError(
            "SedModel(cosmo=...) differs from the CSP's cosmology, and the "
            "CSP is what evaluates distances and ages:\n"
            f"    CSP     : {csp.cosmo.describe()}\n"
            f"    SedModel: {cosmo.describe()}\n"
            "Set it once, at CSP construction: CSPBasis(ssp, ..., cosmo=...)"
        )

    self.lumdist_mpc = None
    if lumdist_mpc is not None:
        self.lumdist_mpc = float(lumdist_mpc)
        if not (self.lumdist_mpc > 0.0) or self.lumdist_mpc != self.lumdist_mpc:
            raise ValueError(f"lumdist_mpc must be a finite positive distance "
                             f"in Mpc, got {lumdist_mpc}")
        if "zred" in self.transforms:
            raise ValueError("lumdist_mpc cannot be combined with a 'zred' transform")
        if self.zred > 0.0:
            warnings.warn(
                f"lumdist_mpc = {self.lumdist_mpc:g} Mpc replaces D_L(zred = "
                f"{self.zred:g}) = {float(csp.cosmo.luminosity_distance(self.zred)):.1f} "
                "Mpc in the flux factor; (1+zred) still comes from zred",
                stacklevel=2)

    names = [obs.name for obs in self.observations]
    if len(names) != len(set(names)):
        dups = [n for n in names if names.count(n) > 1]
        raise ValueError(
            f"Observation names must be unique.  Duplicates found: {dups}"
        )

    self.theta_init  = dict(csp.theta_init)
    self.param_names = list(csp.param_names)
    self.wave        = csp.wave

    if self.transforms:
        _derived = set(self.transforms.keys())
        for p in _derived:
            if p in self.theta_init:
                del self.theta_init[p]
            if p in self.param_names:
                self.param_names.remove(p)

    # logmass with a prior and no start value is sampled, from the prior's median
    if ("logmass" in self.priors and "logmass" not in self.param_names
            and "logmass" not in self.transforms
            and "logmass" not in (free_param_init or {})):
        self.theta_init["logmass"] = jnp.atleast_1d(jnp.asarray(
            _prior_median(self.priors["logmass"]), dtype=float))
        self.param_names.append("logmass")

    if free_param_init is not None:
        for p, v in free_param_init.items():
            arr = jnp.atleast_1d(jnp.asarray(v, dtype=float))
            self.theta_init[p] = arr
            if p not in self.param_names:
                self.param_names.append(p)

    self._check_metallicity_setup(free_param_init)
    self._check_sfh_transform_shape(csp)
    self._check_agn_eline_sigma_range()
    self._check_agn2_prior_ranges()

    unknown = sorted(set(self.priors) - set(self.param_names))
    if unknown:
        raise ValueError(
            f"priors given for {unknown}, which are not sampled parameters "
            f"(a prior on a derived or misspelled name would be silently ignored); "
            f"the sampled parameters are {self.param_names}.  A new name that a "
            f"transform reads (e.g. log_fagn for fagn) must also be in free_param_init")
    unpriored = [p for p in self.param_names if p not in self.priors]
    if unpriored:
        warnings.warn(
            f"no prior for sampled parameter(s) {unpriored}: NUTS treats them as "
            "improper flat, nested sampling refuses them.  Give each a prior, or fix it "
            "with a constant transform", stacklevel=2)

    self.kinematics.validate_theta(set(self.theta_init) | set(self.transforms), self.priors)
    self._check_instrument_scales()
    if hasattr(self.csp, "register_known_theta_keys"):
        self.csp.register_known_theta_keys(
            set(self.param_names) | set(self.priors) | set(self.transforms)
            | set(self.kinematics.free_keys) | set(self._instrument_scale_keys())
        )

    if float(self.zred) < 0.0 and self.lumdist_mpc is None and "zred" not in self.transforms:
        raise ValueError(
            f"SedModel(zred={float(self.zred):g}): a negative redshift has no luminosity "
            "distance (the flux factor would put the source at 10 pc).  For a nearby, "
            "blueshifted galaxy give its distance, SedModel(zred=..., lumdist_mpc=D), or "
            "use its cosmological redshift")
    self._zred_fixed = None
    self._lumdist_fixed = None
    if (self.zred != 0.0 or self.lumdist_mpc is not None) and "zred" not in self.transforms:
        self._zred_fixed = jnp.array([self.zred])
        if self.lumdist_mpc is not None:
            self._lumdist_fixed = jnp.array([self.lumdist_mpc])

    self.zred_is_free = ("zred" in self.param_names) or ("zred" in self.transforms)
    grid_rescaled = (bool(getattr(csp, "track_zred_age", False))
                     and self._zred_fixed is not None) or ("lookback_time" in self.transforms)
    if (not self.zred_is_free and not grid_rescaled
            and hasattr(csp, "sfh_times") and hasattr(csp, "age_at")):
        oldest = float(csp.sfh_times[-1]) / 1e9
        age = float(csp.age_at(self.zred))
        if oldest > age * (1.0 + 5e-3):
            raise ValueError(
                f"the oldest SFH node, {oldest:.3f} Gyr of lookback time, "
                f"predates the Universe at zred = {self.zred:g}: age = "
                f"{age:.3f} Gyr under {csp.cosmo.describe()}.  Build the "
                f"grid from csp.age_at(zred) (or cosmo.age(zred)), e.g. "
                f"lookback_time=jnp.linspace(0.0, {age:.3f}, n)"
            )

    if ("zred" in self.param_names and not bool(getattr(csp, "track_zred_age", False))
            and "lookback_time" not in self.transforms and "zred" in self.priors
            and hasattr(csp, "sfh_times") and hasattr(csp, "age_at")):
        from ..csp.csp import prior_support
        zlo, zhi = prior_support(self.priors["zred"])
        if np.isfinite(zhi) and zhi > 0:
            oldest = float(csp.sfh_times[-1]) / 1e9
            age_hi = float(csp.age_at(float(zhi)))
            if oldest > age_hi * (1.0 + 5e-3):
                age_lo = float(csp.age_at(max(float(zlo), 0.0)))
                where = ("at every zred the prior allows" if oldest > age_lo * (1.0 + 5e-3)
                         else "at the high-zred end of the prior")
                warnings.warn(
                    f"the oldest SFH node, {oldest:.3f} Gyr of lookback time, predates the "
                    f"Universe {where} (age {age_hi:.3f} Gyr at zred = {zhi:g}); with "
                    "track_zred_age=False the grid is not rescaled with the sampled "
                    "redshift.  Use CSPBasis(track_zred_age=True) or a grid within "
                    "csp.age_at(zred_max)", stacklevel=2)

    self.setup_observations()

    if (self.zred == 0.0 and self.lumdist_mpc is None and not self.zred_is_free
            and "zred" not in self.transforms and self.observations):
        warnings.warn(
            "SedModel(zred=0) applies NO flux factor: predictions are in "
            "L_sun/Hz x 10^logmass, not maggies.  Give zred= (Hubble flow) or "
            "lumdist_mpc= (nearby object) for physical units, or ignore this if "
            "the data are in the same unitless convention",
            stacklevel=2)

cosmo property

cosmo

The CSP's cosmology (read-only).

obs_dict property

obs_dict

Observations keyed by obs.name.

n_obs property

n_obs

Number of registered observation objects.

setup_observations

setup_observations()

Build every observation's projection for this model's grid, redshift and kinematics (called by __init__ and by fitSED when it replaces the observations); drops the cached jitted predictors.

Source code in ceridwen/model/model.py
def setup_observations(self):
    """Build every observation's projection for this model's grid, redshift and
    kinematics (called by ``__init__`` and by ``fitSED`` when it replaces the
    observations); drops the cached jitted predictors."""
    names = [o.name for o in self.observations]
    if len(set(names)) != len(names):
        raise ValueError(f"observation names must be unique, got {names}")
    self._check_calibration_names()
    neb = getattr(self.csp, "neb", None)
    lib = getattr(self.csp, "lib_resolution", None)
    for obs in self.observations:
        kind = getattr(obs, "_kind", None)
        if kind == "spectrum":
            zr = self._spectrum_zred_range(obs) if self.zred_is_free else None
            lines_rest = None if neb is None else neb.nebem_line_pos
            if neb is None and getattr(obs, "marginalize_elines", False):
                # no nebular grid: the marginalised lines come from FSPS's line list
                from ..likelihood.eline_marginal import line_table_for, refuse_without_grid
                refuse_without_grid(self.csp, obs, self.observations)
                lines_rest = line_table_for(self.csp)["wave"]
            kw = {}
            if self._prior_scale_range(obs) is not None:
                kw["inst_scale_range"] = self._prior_scale_range(obs)
            obs.setup_for_model(
                self.wave, zred=(self._spectrum_zred_ref(zr) if zr else self.zred),
                kinematics=self.kinematics, lib_resolution=lib,
                line_wave_rest=lines_rest,
                zred_range=zr, **kw)
            if getattr(self.csp, "_agn", None) is not None:   # CSPBasis(agn=...) lines
                self.csp._setup_agn_spectrum(obs)
        elif kind == "photometry":
            obs.setup_for_model(self.wave, zred=self.zred)
            obs.free_z = bool(self.zred_is_free)
            obs.setup_broadening(
                self.wave, self.zred,
                self.kinematics if self.broaden_photometry else None,
                free_z=bool(getattr(obs, "free_z", False)), neb=neb)
        else:
            obs.setup_for_model(self.wave, zred=self.zred)
    for cached in ("_predict_jit_fn", "_predict_vmap_fn"):
        self.__dict__.pop(cached, None)
    from ..likelihood.eline_marginal import build_eline_system
    self._eline_system = build_eline_system(self)
    self._check_agn_eline_sigma_resolved()
    if self._eline_system is not None:
        from ..precision import is_x64
        if not is_x64():
            raise ValueError(
                "Spectrum(marginalize_elines=True) needs float64: the line-flux marginal "
                "forms A^T W A in flux units, which float32 cannot hold (docs/mac_gpu.md).  "
                "Run this model in float64 (JAX_PLATFORMS=cpu on a Mac), or fit the lines "
                "with the nebular grid instead")

apply_transforms

apply_transforms(free_theta)

Return free_theta plus every derived parameter fn(free_theta).

Source code in ceridwen/model/model.py
def apply_transforms(self, free_theta: dict[str, Array]) -> dict[str, Array]:
    """Return ``free_theta`` plus every derived parameter ``fn(free_theta)``."""
    if not self.transforms:
        return free_theta
    model_theta = dict(free_theta)
    for derived_param, fn in self.transforms.items():
        model_theta[derived_param] = fn(free_theta)
    return model_theta

predict

predict(theta)

Predictions keyed by observation name from the free-parameter dict. A fixed zred/lumdist_mpc is injected into the CSP theta here; without a 'zred' the CSP applies no flux factor and the outputs are not maggies.

Source code in ceridwen/model/model.py
def predict(self, theta: dict[str, Array]) -> dict[str, Array]:
    """Predictions keyed by observation name from the free-parameter dict.
    A fixed zred/lumdist_mpc is injected into the CSP theta here; without a
    'zred' the CSP applies no flux factor and the outputs are not maggies."""
    model_theta = self.apply_transforms(theta)
    if self._zred_fixed is not None and "zred" not in model_theta:
        if model_theta is theta:
            model_theta = dict(model_theta)
        model_theta["zred"] = self._zred_fixed
    if self._lumdist_fixed is not None and "lumdist_mpc" not in model_theta:
        if model_theta is theta:
            model_theta = dict(model_theta)
        model_theta["lumdist_mpc"] = self._lumdist_fixed
    return self.csp.predict(model_theta, self.observations,
                            kinematics=self.kinematics,
                            broaden_photometry=self.broaden_photometry)

predict_with_elines

predict_with_elines(theta)

(predictions, aux) for the emission-line marginalisation: the predictions with the fitted lines removed, and aux = {"prior_mean", "cols"} (their CLOUDY fluxes and the per-observation design columns). Needs a Spectrum with marginalize_elines=True.

Source code in ceridwen/model/model.py
def predict_with_elines(self, theta: dict[str, Array]):
    """``(predictions, aux)`` for the emission-line marginalisation: the predictions with
    the fitted lines removed, and ``aux = {"prior_mean", "cols"}`` (their CLOUDY fluxes and
    the per-observation design columns).  Needs a Spectrum with marginalize_elines=True."""
    if getattr(self, "_eline_system", None) is None:
        raise ValueError("no Spectrum of this model has marginalize_elines=True")
    model_theta = self.apply_transforms(theta)
    if self._zred_fixed is not None and "zred" not in model_theta:
        model_theta = dict(model_theta)
        model_theta["zred"] = self._zred_fixed
    if self._lumdist_fixed is not None and "lumdist_mpc" not in model_theta:
        model_theta = dict(model_theta)
        model_theta["lumdist_mpc"] = self._lumdist_fixed
    return self.csp.predict(model_theta, self.observations,
                            kinematics=self.kinematics,
                            broaden_photometry=self.broaden_photometry,
                            eline_system=self._eline_system)

predict_jit

predict_jit(theta)

JIT-compiled :meth:predict (compiled on first call).

Source code in ceridwen/model/model.py
def predict_jit(self, theta: dict[str, Array]) -> dict[str, Array]:
    """JIT-compiled :meth:`predict` (compiled on first call)."""
    return self._predict_jit_fn(theta)

predict_vmap

predict_vmap(theta_batch)

Vectorised :meth:predict over a leading batch axis of every theta entry.

Source code in ceridwen/model/model.py
def predict_vmap(
    self,
    theta_batch: dict[str, Array],
) -> dict[str, Array]:
    """Vectorised :meth:`predict` over a leading batch axis of every theta entry."""
    return self._predict_vmap_fn(theta_batch)

ln_prior

ln_prior(theta)

Scalar sum of prior.logpdf(theta[p]) over registered priors.

Source code in ceridwen/model/model.py
def ln_prior(self, theta: dict[str, Array]) -> Array:
    """Scalar sum of ``prior.logpdf(theta[p])`` over registered priors."""
    lnp = jnp.zeros(())
    for param_name, prior in self.priors.items():
        if param_name in theta:
            lnp = lnp + jnp.sum(prior.logpdf(theta[param_name]))
    return lnp

log_prob

log_prob(theta)

Alias for ln_prior.

Source code in ceridwen/model/model.py
def log_prob(self, theta: dict[str, Array]) -> Array:
    """Alias for ``ln_prior``."""
    return self.ln_prior(theta)

summary

summary()

Multi-line summary of parameters, transforms, observations and CSP setup.

Source code in ceridwen/model/model.py
def summary(self) -> str:
    """Multi-line summary of parameters, transforms, observations and CSP setup."""
    lines = [
        "SedModel",
        "=" * 50,
        f"CSP spectrum model : {_spectrum_model_name(self.csp)}",
        f"Wavelength range   : {float(self.wave.min()):.0f} – "
                               f"{float(self.wave.max()):.0f} Å",
        f"Cosmology          : {self.cosmo.describe()}",
        f"Redshift           : {self._redshift_line()}",
        f"Kinematics         : {self._kinematics_line()}",
        "",
        "Free Parameters",
        "-" * 40,
    ]
    for name in self.param_names:
        val   = self.theta_init.get(name)
        shape = getattr(val, "shape", "(scalar)")
        prior = self.priors.get(name)
        prior_str = repr(prior) if prior is not None else "flat (no prior)"
        lines.append(f"  {name:<28s}: shape {shape}  |  {prior_str}")

    if self.transforms:
        lines += ["", "Transforms  (free → derived)", "-" * 40]
        for derived, fn in self.transforms.items():
            fn_name = getattr(fn, "__name__", repr(fn))
            lines.append(f"  {derived:<20s} ← {fn_name}")

    if "logmass" in self.param_names:
        lines += [
            "",
            "Mass scaling",
            "-" * 40,
            "  logmass ∈ free params → predicted flux × 10^logmass",
            "  (SFH transform `logsfr_ratios_to_sfh` enforces "
            "∫SFR dt = 1 M⊙ on the construction grid;",
            "   the CSP keeps that mass on a track_zred_age grid, so logmass",
            "   equals log10 of the total formed stellar mass at any redshift.)",
        ]

    lines += ["", "Observations", "-" * 40]
    for obs in self.observations:
        lines.append(f"  {obs!r}")
    es = getattr(self, "_eline_system", None)
    if es is not None:
        lines += ["", "Emission lines", "-" * 40, f"  {es.describe()}"]

    return "\n".join(lines)

latex

latex(
    *,
    caption=None,
    label="tab:sedmodel",
    settings=True,
    table=True
)

A LaTeX table (booktabs) of the model: every free parameter with its prior, every derived parameter with the transform and free parameters it is computed from, every fixed parameter (a constant transform) with its value, and (settings) the fixed model settings: SSP grid and IMF, SFH grid, dust laws, redshift, kinematics, the observations, cosmology. table=False returns the tabular alone. Needs \usepackage{booktabs} and amsmath.

Source code in ceridwen/model/model.py
def latex(self, *, caption: str | None = None, label: str = "tab:sedmodel",
          settings: bool = True, table: bool = True) -> str:
    """A LaTeX table (``booktabs``) of the model: every free parameter with its prior, every
    derived parameter with the transform and free parameters it is computed from, every
    fixed parameter (a constant transform) with its value, and (``settings``) the fixed
    model settings: SSP grid and IMF, SFH grid, dust laws, redshift, kinematics, the
    observations, cosmology.  ``table=False`` returns the ``tabular`` alone.  Needs
    ``\\usepackage{booktabs}`` and ``amsmath``."""
    from .describe import latex
    return latex(self, caption=caption, label=label, settings=settings, table=table)

display

display(
    ax=None,
    figsize=None,
    return_fig=False,
    *,
    predictive=True,
    n_draws=64,
    seed=0,
    title=None
)

Draw the model: free parameters with their prior densities, the derived and fixed parameters, the forward model's stages in the order they are applied, and the observations; an edge joins each parameter to the transform or stage that reads it (a transform's inputs are traced from its code). Below, predictive adds the 68 and 95 per cent range of n_draws prior draws pushed through the model, with the data (it compiles the model once). With ax only the diagram is drawn, into it. The figure uses smplotlib's Hershey fonts when smplotlib is installed (pip install smplotlib; it is not imported, so other figures keep their style) and a serif face otherwise. Returns (fig, ax) when return_fig.

Source code in ceridwen/model/model.py
def display(
    self,
    ax=None,
    figsize: tuple[float, float] | None = None,
    return_fig: bool = False,
    *,
    predictive: bool = True,
    n_draws: int = 64,
    seed: int = 0,
    title: str | None = None,
):
    """Draw the model: free parameters with their prior densities, the derived and fixed
    parameters, the forward model's stages in the order they are applied, and the
    observations; an edge joins each parameter to the transform or stage that reads it
    (a transform's inputs are traced from its code).  Below, ``predictive`` adds the 68 and
    95 per cent range of ``n_draws`` prior draws pushed through the model, with the data
    (it compiles the model once).  With ``ax`` only the diagram is drawn, into it.
    The figure uses smplotlib's Hershey fonts when smplotlib is installed (``pip install
    smplotlib``; it is not imported, so other figures keep their style) and a serif face
    otherwise.  Returns ``(fig, ax)`` when ``return_fig``."""
    from .describe import display
    return display(self, ax=ax, figsize=figsize, return_fig=return_fig,
                   predictive=predictive, n_draws=n_draws, seed=seed, title=title)

ceridwen.model.transforms.logsfr_ratios_to_sfh

logsfr_ratios_to_sfh(logsfr_ratios, sfh_times_yr=None)

Unit-mass SFH from logsfr_ratios[i] = log10(SFR[i]/SFR[i+1]), index 0 = today.

The length of sfh_times_yr (the lookback NODES in yr, e.g. csp.sfh_times) decides what the SFR values are:

  • len(sfh_times_yr) == len(logsfr_ratios) + 2: one SFR per BIN, shape (n_time-1,), for sfh_interp="step". Normalised so sum_i SFR_i * dt_i = 1 Msun: with logmass the mass formed in bin i is 10**logmass * SFR_i * dt_i, which is Prospector's continuity SFH (prospect.models.transforms.logsfr_ratios_to_masses: ratios of adjacent BIN SFRs).
  • len(sfh_times_yr) == len(logsfr_ratios) + 1: one SFR per NODE, shape (n_time,), for sfh_interp="linear" (FSPS's tabular SFH, linear between nodes); the trapezoidal integral is normalised to 1 Msun.

Without sfh_times_yr, sum(sfh) = 1.

Source code in ceridwen/model/transforms.py
def logsfr_ratios_to_sfh(
    logsfr_ratios,
    sfh_times_yr=None,
):
    """Unit-mass SFH from ``logsfr_ratios[i] = log10(SFR[i]/SFR[i+1])``, index 0 = today.

    The length of ``sfh_times_yr`` (the lookback NODES in yr, e.g. ``csp.sfh_times``) decides
    what the SFR values are:

    * ``len(sfh_times_yr) == len(logsfr_ratios) + 2``: one SFR per BIN, shape (n_time-1,), for
      ``sfh_interp="step"``.  Normalised so sum_i SFR_i * dt_i = 1 Msun: with ``logmass`` the
      mass formed in bin i is 10**logmass * SFR_i * dt_i, which is Prospector's continuity SFH
      (``prospect.models.transforms.logsfr_ratios_to_masses``: ratios of adjacent BIN SFRs).
    * ``len(sfh_times_yr) == len(logsfr_ratios) + 1``: one SFR per NODE, shape (n_time,), for
      ``sfh_interp="linear"`` (FSPS's tabular SFH, linear between nodes); the trapezoidal
      integral is normalised to 1 Msun.

    Without ``sfh_times_yr``, sum(sfh) = 1."""
    ratios  = jnp.asarray(logsfr_ratios, dtype=float)
    log_sfr = jnp.concatenate([jnp.zeros(1),
                                -jnp.cumsum(ratios)])
    if log_sfr.dtype == jnp.float32:
        # float32 mode (docs/mac_gpu.md): 10**x overflows above x ~ 38.5, which the StudentT(df=2)
        # prior reaches in ~0.2% of draws, and inf/inf = NaN.  The normalisation below divides
        # out any constant, so shift the peak to 0; float64 keeps the unshifted (bit-identical) path
        log_sfr = log_sfr - jnp.max(log_sfr)
    sfr     = 10.0 ** log_sfr

    if sfh_times_yr is not None:
        times = jnp.asarray(sfh_times_yr, dtype=float)
        dt    = jnp.abs(jnp.diff(times))
        n_sfr = ratios.shape[-1] + 1
        if times.shape[-1] == n_sfr + 1:            # one SFR per bin: sum_i SFR_i dt_i = 1
            return sfr / jnp.sum(sfr * dt)
        if times.shape[-1] != n_sfr:
            raise ValueError(
                f"logsfr_ratios_to_sfh: {ratios.shape[-1]} ratios give {n_sfr} SFR values, but "
                f"sfh_times_yr has {times.shape[-1]} nodes; give {n_sfr + 1} nodes for one SFR "
                f"per bin (sfh_interp='step') or {n_sfr} for one per node ('linear').")
        w_lo  = jnp.concatenate([jnp.zeros(1), dt])
        w_hi  = jnp.concatenate([dt, jnp.zeros(1)])
        w     = 0.5 * (w_lo + w_hi)
        # normalise to total mass (1 Msun), NOT to mean SFR
        total_mass = jnp.sum(sfr * w)
        sfh   = sfr / total_mass
    else:
        sfh = sfr / jnp.sum(sfr)

    return sfh

Priors

ceridwen.priors

Prior distributions for CERIDWEN models.

A clean, discoverable import path for the priors (implemented in ceridwen.sampler.priors)::

from ceridwen.priors import Uniform, Normal, ClippedNormal, LogNormal, LogUniform, StudentT

Each prior exposes logpdf (also __call__), sample, unit_transform (inverse CDF) and inverse_unit_transform (CDF); bounds gives the support.

Prior dataclass

Prior(parnames=(), name='', **kwargs)

Bases: ABC

Prior base class delegating to a TFP-JAX distribution; subclasses define prior_params and implement tfp_dist().

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

serialize

serialize()

JSON-ready description: type, parameters (lists for arrays), name.

Source code in ceridwen/sampler/priors.py
def serialize(self) -> dict:
    """JSON-ready description: type, parameters (lists for arrays), name."""
    out = {"type": type(self).__name__, "name": self.name}
    for k, v in self.params.items():
        out[k] = _scalar_or_list(v)
    return out

tfp_dist abstractmethod

tfp_dist()

Return the TFP-JAX distribution built from self.params.

Source code in ceridwen/sampler/priors.py
@abc.abstractmethod
def tfp_dist(self) -> tfd.Distribution:
    """Return the TFP-JAX distribution built from ``self.params``."""
    raise NotImplementedError

Uniform dataclass

Uniform(parnames=(), name='', **kwargs)

Bases: Prior

Uniform distribution on [low, high].

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

TopHat dataclass

TopHat(parnames=(), name='', **kwargs)

Bases: Uniform

Alias of Uniform kept for backwards compatibility.

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

Normal dataclass

Normal(parnames=(), name='', **kwargs)

Bases: Prior

Gaussian prior with parameters mean, sigma.

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

MultivariateNormalPrior dataclass

MultivariateNormalPrior(parnames=(), name='', **kwargs)

Bases: Prior

Multivariate Gaussian prior.

Keyword arguments: mean (d,) and Sigma (d, d), the covariance matrix.

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

range property

range

Mean -/+ 4 sigma per dimension (plotting range).

ClippedNormal dataclass

ClippedNormal(parnames=(), name='', **kwargs)

Bases: Prior

Gaussian prior truncated to [low, high]; parameters mean, sigma, low, high.

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

LogNormal dataclass

LogNormal(parnames=(), name='', **kwargs)

Bases: Prior

Log-normal prior; mode and sigma are the mean and std of ln(x).

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

LogUniform

LogUniform(parnames=(), name='', **kwargs)

Bases: Prior

Log-uniform (reciprocal, Jeffreys) prior on [mini, maxi], 0 < mini < maxi < inf.

pdf 1 / (x ln(maxi/mini)) on [mini, maxi] (-inf log-density outside), CDF ln(x/mini) / ln(maxi/mini): uniform in log x, whatever the base. Same parameter names and distribution as Prospector's LogUniform(mini, maxi) (scipy.stats.reciprocal(mini, maxi)). The parameter itself (not its log) is sampled; fitSED's NUTS path maps it to (mini, maxi) with a logit.

logpdf/cdf/ppf/sample are analytic jnp (exact, in the working float dtype, jit/grad/vmap-safe); tfp_dist() gives the equivalent TFP distribution (Exp of a Uniform(ln mini, ln maxi)) for interoperability.

Source code in ceridwen/sampler/priors.py
def __init__(self, parnames: Sequence[str] = (), name: str = "", **kwargs: Any):
    super().__init__(parnames=parnames, name=name, **kwargs)
    mini = np.asarray(self.params["mini"], dtype=np.float64)
    maxi = np.asarray(self.params["maxi"], dtype=np.float64)
    if not (np.all(np.isfinite(mini)) and np.all(np.isfinite(maxi))
            and np.all(mini > 0.0) and np.all(maxi > mini)):
        raise ValueError(
            f"LogUniform needs 0 < mini < maxi < inf (finite, elementwise), got "
            f"mini={mini.tolist()}, maxi={maxi.tolist()}.  For a parameter that can be "
            "<= 0 sample its log with a Uniform instead.")
    object.__setattr__(self, "params", {"mini": jnp.asarray(mini), "maxi": jnp.asarray(maxi)})

StudentT dataclass

StudentT(parnames=(), name='', **kwargs)

Bases: Prior

Student's t prior with parameters mean, scale, df (degrees of freedom).

Source code in ceridwen/sampler/priors.py
def __init__(self,
             parnames: Sequence[str] = (),
             name: str = "",
             **kwargs: Any):

    prior_params: Tuple[str, ...] = getattr(type(self), "prior_params", None)
    if prior_params is None:
        raise ValueError(
            f"{type(self).__name__} must define class attribute "
            "`prior_params = (\"param1\", \"param2\", ...)`."
        )

    if not parnames:
        parnames = prior_params

    if len(parnames) != len(prior_params):
        raise ValueError(
            f"parnames has length {len(parnames)} but prior_params has "
            f"length {len(prior_params)}"
        )

    alias = dict(zip(prior_params, parnames))

    params: Dict[str, Array] = {}
    for intrinsic, external in alias.items():
        if external in kwargs:
            params[intrinsic] = jnp.asarray(kwargs.pop(external))
    if kwargs:
        raise TypeError(
            f"{type(self).__name__} got unknown argument(s) {sorted(kwargs)}; "
            f"it takes {list(alias.values())}")
    missing = [external for intrinsic, external in alias.items() if intrinsic not in params]
    if missing:
        raise TypeError(f"{type(self).__name__} is missing argument(s) {missing}")

    object.__setattr__(self, "alias", alias)
    object.__setattr__(self, "params", params)
    object.__setattr__(self, "name", name)

Likelihood

ceridwen.likelihood.DiagonalGaussianLikelihood dataclass

DiagonalGaussianLikelihood(
    noise_model=DiagonalNoiseModel(), poly_calibration=None
)

Bases: LikelihoodBase

Gaussian log-likelihood with an independent (diagonal) noise model; with noise_model.f_outlier set, the outlier mixture :func:lnlike_diag_outlier.

__call__

__call__(y, mu, sigma_obs, mask, params=None)

Return (lnl_total, LikelihoodOutput).

Source code in ceridwen/likelihood/likelihood.py
def __call__(
    self,
    y         : Array,
    mu        : Array,
    sigma_obs : Array,
    mask      : Array,
    params    : Optional[dict[str, Array]] = None,
) -> tuple[Array, LikelihoodOutput]:
    """Return ``(lnl_total, LikelihoodOutput)``."""
    mu = self._calibrated(y, mu, sigma_obs, mask, params)
    noise_out: NoiseModelOutput = self.noise_model.compute(
        sigma_obs, mu, mask, params, data=y
    )
    if getattr(self.noise_model, "use_outlier", False):
        f, nsigma = self.noise_model.outlier_params(params)
        return lnlike_diag_outlier(
            y, mu, noise_out.inv_var, noise_out.log_det, mask, f, nsigma
        )
    return lnlike_diag_gaussian(
        y, mu, noise_out.inv_var, noise_out.log_det, mask
    )

outlier_probability

outlier_probability(y, mu, sigma_obs, mask, params=None)

Per-datum probability of being an outlier (see :func:outlier_probability); raises when the mixture is off.

Source code in ceridwen/likelihood/likelihood.py
def outlier_probability(
    self,
    y         : Array,
    mu        : Array,
    sigma_obs : Array,
    mask      : Array,
    params    : Optional[dict[str, Array]] = None,
) -> Array:
    """Per-datum probability of being an outlier (see :func:`outlier_probability`);
    raises when the mixture is off."""
    if not getattr(self.noise_model, "use_outlier", False):
        raise ValueError("the outlier mixture is off (noise_model.f_outlier is None)")
    noise_out = self.noise_model.compute(sigma_obs, mu, mask, params, data=y)
    f, nsigma = self.noise_model.outlier_params(params)
    return outlier_probability(
        y, mu, noise_out.inv_var, noise_out.log_det, mask, f, nsigma
    )

make_lnprobfn

make_lnprobfn(observations, model, prior)

Return a jitted log-posterior for one observation (needs .flux, .uncertainty, .mask; honours sky and calibration as MultiObservationLikelihood does, and refuses flagged upper limits).

Source code in ceridwen/likelihood/likelihood.py
def make_lnprobfn(
    self,
    observations : Any,
    model        : Any,
    prior        : Any,
) -> Callable[[dict[str, Array]], Array]:
    """Return a jitted log-posterior for one observation (needs ``.flux``, ``.uncertainty``,
    ``.mask``; honours ``sky`` and ``calibration`` as MultiObservationLikelihood does, and
    refuses flagged upper limits)."""
    y, sigma_obs, mask, calib, _ = single_observation_data(
        observations, "DiagonalGaussianLikelihood")
    noise_model       = self.noise_model
    calibrate         = self._calibrated
    rescaling         = float32_rescaling(observations, self)   # None under float64

    if getattr(noise_model, "use_outlier", False):
        @jax.jit
        def lnprobfn_outlier(theta: dict[str, Array]) -> Array:
            th = rescaled_params(theta, rescaling)
            mu = calibrate(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                           th)
            noise_out = noise_model.compute(sigma_obs, mu, mask, th, data=y)
            f, nsigma = noise_model.outlier_params(th)
            lnl, _    = lnlike_diag_outlier(
                y, mu, noise_out.inv_var, noise_out.log_det, mask, f, nsigma
            )
            return lnl + prior.log_prob(theta)

        return lnprobfn_outlier

    @jax.jit
    def lnprobfn(theta: dict[str, Array]) -> Array:
        th = rescaled_params(theta, rescaling)
        mu = calibrate(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                           th)
        noise_out = noise_model.compute(sigma_obs, mu, mask, th, data=y)
        lnl, _    = lnlike_diag_gaussian(
            y, mu, noise_out.inv_var, noise_out.log_det, mask
        )
        lnp = prior.log_prob(theta)
        return lnl + lnp

    return lnprobfn

ceridwen.likelihood.DiagonalGaussianLikelihoodWithUpperLimits dataclass

DiagonalGaussianLikelihoodWithUpperLimits(
    noise_model=DiagonalNoiseModel(), poly_calibration=None
)

Bases: LikelihoodBase

Diagonal Gaussian log-likelihood honouring per-datum upper-limit flags (one-sided penalty; reduces to :class:DiagonalGaussianLikelihood when no flags are set). With noise_model.f_outlier set, the detections use the outlier mixture and the limits keep the one-sided penalty (:func:lnlike_diag_outlier_with_upper_limits).

__call__

__call__(
    y, mu, sigma_obs, mask, params=None, is_upper_limit=None
)

Return (lnl_total, LikelihoodOutput); is_upper_limit=None means all detections.

Source code in ceridwen/likelihood/likelihood.py
def __call__(
    self,
    y               : Array,
    mu              : Array,
    sigma_obs       : Array,
    mask            : Array,
    params          : Optional[dict[str, Array]] = None,
    is_upper_limit  : Optional[Array]            = None,
) -> tuple[Array, LikelihoodOutput]:
    """Return ``(lnl_total, LikelihoodOutput)``; ``is_upper_limit=None`` means all detections."""
    mu = self._calibrated(y, mu, sigma_obs, mask, params)
    noise_out: NoiseModelOutput = self.noise_model.compute(
        sigma_obs, mu, mask, params, data=y
    )
    if is_upper_limit is None:
        is_upper_limit = jnp.zeros_like(mask, dtype=bool)
    if getattr(self.noise_model, "use_outlier", False):
        f, nsigma = self.noise_model.outlier_params(params)
        return lnlike_diag_outlier_with_upper_limits(
            y, mu, noise_out.inv_var, noise_out.log_det, mask, is_upper_limit, f, nsigma,
        )
    return lnlike_diag_gaussian_with_upper_limits(
        y, mu, noise_out.inv_var, noise_out.log_det, mask, is_upper_limit,
    )

make_lnprobfn

make_lnprobfn(observations, model, prior)

Return a jitted log-posterior using observations.upper_limit (all-False if absent); honours sky and calibration as MultiObservationLikelihood does.

Source code in ceridwen/likelihood/likelihood.py
def make_lnprobfn(
    self,
    observations : Any,
    model        : Any,
    prior        : Any,
) -> Callable[[dict[str, Array]], Array]:
    """Return a jitted log-posterior using ``observations.upper_limit`` (all-False if absent);
    honours ``sky`` and ``calibration`` as MultiObservationLikelihood does."""
    y, sigma_obs, mask, calib, _ = single_observation_data(
        observations, "DiagonalGaussianLikelihoodWithUpperLimits", upper_limits=True)
    is_ul = getattr(observations, "upper_limit", None)
    if is_ul is None:
        is_ul = jnp.zeros_like(mask, dtype=bool)
    else:
        is_ul = jnp.asarray(is_ul, dtype=bool)
    noise_model = self.noise_model
    calibrate   = self._calibrated
    rescaling   = float32_rescaling(observations, self)   # None under float64

    if getattr(noise_model, "use_outlier", False):
        @jax.jit
        def lnprobfn_outlier(theta: dict[str, Array]) -> Array:
            th = rescaled_params(theta, rescaling)
            mu = calibrate(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                           th)
            noise_out = noise_model.compute(sigma_obs, mu, mask, th, data=y)
            f, nsigma = noise_model.outlier_params(th)
            lnl, _    = lnlike_diag_outlier_with_upper_limits(
                y, mu, noise_out.inv_var, noise_out.log_det, mask, is_ul, f, nsigma,
            )
            return lnl + prior.log_prob(theta)

        return lnprobfn_outlier

    @jax.jit
    def lnprobfn(theta: dict[str, Array]) -> Array:
        th = rescaled_params(theta, rescaling)
        mu = calibrate(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                           th)
        noise_out = noise_model.compute(sigma_obs, mu, mask, th, data=y)
        lnl, _    = lnlike_diag_gaussian_with_upper_limits(
            y, mu, noise_out.inv_var, noise_out.log_det, mask, is_ul,
        )
        lnp = prior.log_prob(theta)
        return lnl + lnp

    return lnprobfn

ceridwen.likelihood.MultiObservationLikelihood dataclass

MultiObservationLikelihood(
    keys=tuple(), likelihoods=tuple()
)

Bases: LikelihoodBase

Sum of independent likelihoods over several observation keys.

Parameters:

Name Type Description Default
keys tuple of str -- observation keys, e.g. ``("phot", "spec", "lines")``
tuple()
likelihoods tuple of LikelihoodBase -- one per key, same order
tuple()

__call__

__call__(
    y, mu, sigma_obs, mask, params=None, is_upper_limit=None
)

Return (lnl_total, {key: LikelihoodOutput}); all inputs are dicts keyed like self.keys (is_upper_limit only needs the keys whose likelihood honours upper limits).

Source code in ceridwen/likelihood/likelihood.py
def __call__(
    self,
    y         : dict[str, Array],
    mu        : dict[str, Array],
    sigma_obs : dict[str, Array],
    mask      : dict[str, Array],
    params    : Optional[dict[str, Array]] = None,
    is_upper_limit : Optional[dict[str, Array]] = None,
) -> tuple[Array, dict[str, LikelihoodOutput]]:
    """Return ``(lnl_total, {key: LikelihoodOutput})``; all inputs are dicts keyed like ``self.keys``
    (``is_upper_limit`` only needs the keys whose likelihood honours upper limits)."""
    lnl_total = jnp.zeros(())
    aux: dict[str, LikelihoodOutput] = {}
    for key, lhood in zip(self.keys, self.likelihoods):
        ul = None if is_upper_limit is None else is_upper_limit.get(key)
        if ul is not None:
            lnl_i, aux_i = lhood(y[key], mu[key], sigma_obs[key], mask[key], params,
                                 is_upper_limit=ul)
        else:
            lnl_i, aux_i = lhood(y[key], mu[key], sigma_obs[key], mask[key], params)
        lnl_total    = lnl_total + lnl_i
        aux[key]     = aux_i
    return lnl_total, aux

make_lnprobfn

make_lnprobfn(observations, model, prior)

Return a jitted log-posterior; observations and model.predict(theta) are dicts keyed like self.keys. Each observation's sky, calibration and upper_limit are honoured as in ceridwen.sampler.runner.run_sampler. In float32 mode the value is offset by -loglike_offset(...) (a constant of the observations, see :func:float32_rescaling).

Source code in ceridwen/likelihood/likelihood.py
def make_lnprobfn(
    self,
    observations : dict[str, Any],
    model        : Any,
    prior        : Any,
) -> Callable[[dict[str, Array]], Array]:
    """Return a jitted log-posterior; ``observations`` and ``model.predict(theta)`` are dicts keyed
    like ``self.keys``.  Each observation's ``sky``, ``calibration`` and ``upper_limit`` are honoured
    as in ``ceridwen.sampler.runner.run_sampler``.  In float32 mode the value is offset by
    ``-loglike_offset(...)`` (a constant of the observations, see :func:`float32_rescaling`)."""
    static_data = {key: observation_data(observations[key]) for key in self.keys}
    keys        = self.keys
    likelihoods = self.likelihoods
    rescalings  = {key: float32_rescaling(observations[key], lh)      # None under float64
                   for key, lh in zip(keys, likelihoods)}

    if getattr(model, "_eline_system", None) is not None:
        from .eline_marginal import joint_loglike

        @jax.jit
        def lnprobfn_elines(theta: dict[str, Array]) -> Array:
            return (joint_loglike(model, keys, likelihoods, static_data, theta)
                    + prior.log_prob(theta))

        return lnprobfn_elines

    @jax.jit
    def lnprobfn(theta: dict[str, Array]) -> Array:
        predictions: dict[str, Array] = model.predict(theta)
        lnl = jnp.zeros(())

        for key, lhood in zip(keys, likelihoods):
            y_k, sig_k, mask_k, calib_k, ul_k = static_data[key]
            th = rescaled_params(theta, rescalings[key])
            mu_k = predictions[key]
            if calib_k is not None:
                mu_k = mu_k * calib_k
            if ul_k is not None:
                lnl_k, _ = lhood(y_k, mu_k, sig_k, mask_k, params=th, is_upper_limit=ul_k)
            else:
                lnl_k, _ = lhood(y_k, mu_k, sig_k, mask_k, params=th)
            lnl = lnl + lnl_k

        lnp = prior.log_prob(theta)
        return lnl + lnp

    return lnprobfn

The outlier mixture is disabled by default (f_outlier=None, equivalent to 0). See Outlier model to enable it.

ceridwen.likelihood.DiagonalNoiseModel dataclass

DiagonalNoiseModel(
    use_jitter=False,
    use_fractional=False,
    use_data_fractional=False,
    noise_floor=0.0,
    use_error_scale=False,
    f_outlier=None,
    nsigma_outlier=50.0,
    err_scale_key="log_err_scale",
    jitter_key="log_jitter",
    f_calib_key="log_f_calib",
    f_data_key="log_f_data",
)

Bases: NoiseModelBase

Independent Gaussian noise: sigma_obs^2 (optionally rescaled by a common factor) plus optional (f_calib*|mu|)^2, (f_data*|y|)^2 and jitter^2 terms, nuisance parameters sampled in log space.

Parameters:

Name Type Description Default
use_error_scale bool -- multiply sigma_obs^2 by exp(params[err_scale_key])^2, a

common rescaling of the quoted uncertainties (the log-normalisation term keeps it from running away)

False
use_jitter bool -- add exp(params[jitter_key])^2 (data units)
False
use_fractional bool -- add (exp(params[f_calib_key]) * |mu|)^2, model-anchored
False
use_data_fractional bool -- add (exp(params[f_data_key]) * |y|)^2, data-anchored, needs ``data``
False
noise_floor float -- fixed fractional floor on |mu|
0.0
f_outlier None, float or str -- outlier mixture (Hogg, Bovy & Lang 2010): the fraction

of data drawn from a Gaussian nsigma_outlier times broader than sigma_eff. Default None = 0 = off: the mixture is on only when switched on explicitly, with a float in (0, 1) (fixed; 0.0 means off) or a str (the theta key of a sampled fraction). Applied by the likelihood classes, not by compute.

None
nsigma_outlier float or str -- width of the outlier Gaussian in units of sigma_eff,

fixed (default 50, Prospector's) or a theta key

50.0
err_scale_key str or float -- where each switched-on

term reads its (log) value: a theta key (default log_err_scale / log_jitter / log_f_calib / log_f_data; fitSED passes the per-observation names log_jitter_<kind>[_<obs>]) or a fixed float

'log_err_scale'
jitter_key str or float -- where each switched-on

term reads its (log) value: a theta key (default log_err_scale / log_jitter / log_f_calib / log_f_data; fitSED passes the per-observation names log_jitter_<kind>[_<obs>]) or a fixed float

'log_err_scale'
f_calib_key str or float -- where each switched-on

term reads its (log) value: a theta key (default log_err_scale / log_jitter / log_f_calib / log_f_data; fitSED passes the per-observation names log_jitter_<kind>[_<obs>]) or a fixed float

'log_err_scale'
f_data_key str or float -- where each switched-on

term reads its (log) value: a theta key (default log_err_scale / log_jitter / log_f_calib / log_f_data; fitSED passes the per-observation names log_jitter_<kind>[_<obs>]) or a fixed float

'log_err_scale'

use_outlier property

use_outlier

True when the outlier mixture is on (static: it selects the likelihood kernel).

outlier_param_names property

outlier_param_names

theta keys of the sampled outlier parameters (empty when fixed or off).

nuisance_param_names property

nuisance_param_names

Names of nuisance parameters expected in params at compute time.

outlier_params

outlier_params(params)

(f, nsigma) for the mixture kernel: the fixed values, or looked up in params.

Source code in ceridwen/likelihood/noise_model.py
def outlier_params(self, params: Optional[dict[str, Array]]) -> tuple[Array, Array]:
    """``(f, nsigma)`` for the mixture kernel: the fixed values, or looked up in ``params``."""
    def get(v, what):
        if not isinstance(v, str):
            return v
        if params is None or v not in params:
            raise KeyError(f"the outlier model reads {what} from theta[{v!r}], which is "
                           "missing: sample it (with a prior) or give a fixed value")
        return params[v]
    return get(self.f_outlier, "f_outlier"), get(self.nsigma_outlier, "nsigma_outlier")

compute

compute(sigma_obs, mu, mask, params=None, data=None)

Return NoiseModelOutput; params holds the theta keys err_scale_key / jitter_key / f_calib_key / f_data_key of the switched-on terms (a float key is a fixed value), data (observed y) required when use_data_fractional.

Source code in ceridwen/likelihood/noise_model.py
def compute(
    self,
    sigma_obs : Array,
    mu        : Array,
    mask      : Array,
    params    : Optional[dict[str, Array]] = None,
    data      : Optional[Array] = None,
) -> NoiseModelOutput:
    """Return ``NoiseModelOutput``; ``params`` holds the theta keys ``err_scale_key`` /
    ``jitter_key`` / ``f_calib_key`` / ``f_data_key`` of the switched-on terms (a float key
    is a fixed value), ``data`` (observed y) required when ``use_data_fractional``."""
    if params is None:
        params = {}

    def get(key):
        return params[key] if isinstance(key, str) else key

    # float64 (dynamic range that underflows when squared): the predictions are float32,
    # and at cgs scale (|mu| ~ 1e-30) (noise_floor * |mu|)**2 is below float32's smallest
    # number; mu takes sigma_obs's dtype (float64: the Observation constructors store data so)
    mu = jnp.asarray(mu, dtype=jnp.result_type(sigma_obs, mu))
    var: Array = sigma_obs ** 2
    if self.use_error_scale:
        var = var * jnp.exp(2.0 * get(self.err_scale_key))
    if self.noise_floor > 0.0:
        var = var + (self.noise_floor * jnp.abs(mu)) ** 2

    if self.use_fractional:
        f_calib = jnp.exp(get(self.f_calib_key))
        var = var + (f_calib * jnp.abs(mu)) ** 2

    if self.use_data_fractional:
        if data is None:
            raise ValueError(
                "DiagonalNoiseModel(use_data_fractional=True) requires the "
                "observed data array; call compute(..., data=y)."
            )
        f_data = jnp.exp(get(self.f_data_key))
        var = var + (f_data * jnp.abs(data)) ** 2

    if self.use_jitter:
        jitter = jnp.exp(get(self.jitter_key))
        var = var + jitter ** 2

    var = jnp.where(mask, var, jnp.ones_like(var))

    var = jnp.maximum(var, jnp.finfo(var.dtype).tiny)

    inv_var = 1.0 / var
    log_det = 0.5 * jnp.log(var) + _HALF_LOG_2PI

    return NoiseModelOutput(inv_var=inv_var, log_det=log_det)

ceridwen.likelihood.lnlike_diag_outlier

lnlike_diag_outlier(
    y, mu, inv_var, log_det, mask, f, nsigma
)

Outlier mixture (Hogg, Bovy & Lang 2010), Prospector's NoiseModel.lnlike branch f_outlier > 0: per datum

lnl_i = logaddexp(log(1 - f) + lnp_good_i, log(f) + lnp_bad_i)
lnp_good_i = -0.5 chi_i^2 - log_det_i
lnp_bad_i  = -0.5 chi_i^2 / nsigma^2 - log_det_i - log(nsigma)

with sigma_eff (inv_var, log_det) from the noise model after every term, as Prospector uses its noise model's Sigma. As f -> 0 it tends to :func:lnlike_diag_gaussian, NOT to Prospector's f_outlier == 0 value, whose NoiseModel.lnlikelihood multiplies chi^2 by ln(2 pi) and drops n ln(2 pi). lnl_pointwise holds the mixture terms (summing to lnl_total); chi and residuals are those of the inlier Gaussian. Masked data contribute 0 with finite gradients; the derivative in f is the exact (e^b - e^a)/L, finite at f = 0 unless a datum sits beyond ~38 sigma (nsigma = 50) (then +inf: the likelihood rises that steeply).

Source code in ceridwen/likelihood/likelihood.py
def lnlike_diag_outlier(
    y       : Array,
    mu      : Array,
    inv_var : Array,
    log_det : Array,
    mask    : Array,
    f       : Array,
    nsigma  : Array,
) -> tuple[Array, LikelihoodOutput]:
    """Outlier mixture (Hogg, Bovy & Lang 2010), Prospector's ``NoiseModel.lnlike`` branch
    ``f_outlier > 0``: per datum

        lnl_i = logaddexp(log(1 - f) + lnp_good_i, log(f) + lnp_bad_i)
        lnp_good_i = -0.5 chi_i^2 - log_det_i
        lnp_bad_i  = -0.5 chi_i^2 / nsigma^2 - log_det_i - log(nsigma)

    with ``sigma_eff`` (``inv_var``, ``log_det``) from the noise model after every term, as
    Prospector uses its noise model's ``Sigma``.  As f -> 0 it tends to
    :func:`lnlike_diag_gaussian`, NOT to Prospector's ``f_outlier == 0`` value, whose
    ``NoiseModel.lnlikelihood`` multiplies chi^2 by ln(2 pi) and drops n ln(2 pi).
    ``lnl_pointwise`` holds the mixture terms (summing to ``lnl_total``); ``chi`` and
    ``residuals`` are those of the inlier Gaussian.  Masked data contribute 0 with finite
    gradients; the derivative in f is the exact ``(e^b - e^a)/L``, finite at f = 0 unless a
    datum sits beyond ~38 sigma (nsigma = 50) (then +inf: the likelihood rises that steeply)."""
    resid, chi, lnl_i = _outlier_terms(y, mu, inv_var, log_det, mask, f, nsigma)

    lnl_masked = jnp.where(mask, lnl_i, 0.0)
    lnl_total  = jnp.sum(lnl_masked)

    aux = LikelihoodOutput(
        lnl_total     = lnl_total,
        lnl_pointwise = lnl_masked,
        residuals     = resid,
        chi           = chi,
        ndof          = jnp.sum(mask),
    )
    return lnl_total, aux

ceridwen.likelihood.lnlike_diag_outlier_with_upper_limits

lnlike_diag_outlier_with_upper_limits(
    y, mu, inv_var, log_det, mask, is_upper_limit, f, nsigma
)

:func:lnlike_diag_outlier on the detections and the one-sided penalty of :func:lnlike_diag_gaussian_with_upper_limits (unchanged, no mixture) on data flagged is_upper_limit. With no flags it equals :func:lnlike_diag_outlier.

Source code in ceridwen/likelihood/likelihood.py
def lnlike_diag_outlier_with_upper_limits(
    y               : Array,
    mu              : Array,
    inv_var         : Array,
    log_det         : Array,
    mask            : Array,
    is_upper_limit  : Array,
    f               : Array,
    nsigma          : Array,
) -> tuple[Array, LikelihoodOutput]:
    """:func:`lnlike_diag_outlier` on the detections and the one-sided penalty of
    :func:`lnlike_diag_gaussian_with_upper_limits` (unchanged, no mixture) on data flagged
    ``is_upper_limit``.  With no flags it equals :func:`lnlike_diag_outlier`."""
    resid, chi, lnl_mix = _outlier_terms(y, mu, inv_var, log_det, mask, f, nsigma)
    lnl_ul = -0.5 * jnp.maximum(-chi, 0.0) ** 2 - log_det
    lnl_i  = jnp.where(is_upper_limit, lnl_ul, lnl_mix)

    lnl_masked = jnp.where(mask, lnl_i, 0.0)
    lnl_total  = jnp.sum(lnl_masked)

    aux = LikelihoodOutput(
        lnl_total     = lnl_total,
        lnl_pointwise = lnl_masked,
        residuals     = resid,
        chi           = chi,
        ndof          = jnp.sum(mask),
    )
    return lnl_total, aux

ceridwen.likelihood.outlier_probability

outlier_probability(
    y, mu, inv_var, log_det, mask, f, nsigma
)

Per-datum posterior probability of belonging to the outlier component, exp(log f + lnp_bad_i - lnl_i); 0 for masked data. A diagnostic: the sampled likelihood never computes it.

Source code in ceridwen/likelihood/likelihood.py
def outlier_probability(
    y       : Array,
    mu      : Array,
    inv_var : Array,
    log_det : Array,
    mask    : Array,
    f       : Array,
    nsigma  : Array,
) -> Array:
    """Per-datum posterior probability of belonging to the outlier component,
    ``exp(log f + lnp_bad_i - lnl_i)``; 0 for masked data.  A diagnostic: the sampled
    likelihood never computes it."""
    resid = jnp.where(mask, y - mu, 0.0)
    chi2  = (resid * jnp.sqrt(inv_var)) ** 2
    lnp_good = -0.5 * chi2 - log_det
    lnp_bad  = -0.5 * chi2 / nsigma ** 2 - log_det - jnp.log(nsigma)
    a = jnp.log1p(-f) + lnp_good
    b = jnp.log(f) + lnp_bad
    return jnp.where(mask, jnp.exp(b - jnp.logaddexp(a, b)), 0.0)

ceridwen.likelihood.poly_calibration.PolynomialCalibration

PolynomialCalibration(design, regularization=0.0)

Static description of the profiled polynomial of one spectrum: the design matrix A (n_pix, order+1) and the regularisation (scalar or one per coefficient). Hashable (by value), so it can sit in a likelihood's static pytree data.

Source code in ceridwen/likelihood/poly_calibration.py
def __init__(self, design, regularization=0.0):
    A = np.asarray(design, dtype=np.float64)
    if A.ndim != 2 or A.shape[1] < 2:
        raise ValueError("the calibration design matrix must be (n_pix, order + 1), order >= 1")
    reg = np.broadcast_to(np.asarray(regularization, dtype=np.float64), (A.shape[1],)).copy()
    if np.any(~np.isfinite(reg)) or np.any(reg < 0.0):
        raise ValueError(f"polynomial_regularization must be finite and >= 0, got {reg}")
    self.A = A
    self.reg = reg
    self._key = hashlib.sha256(A.tobytes() + reg.tobytes()).hexdigest()

for_spectrum classmethod

for_spectrum(obs)

From Spectrum(polynomial_order=..., polynomial_regularization=...); None when off or when the polynomial is marginalised (polynomial_mode="marginalize", see :class:~ceridwen.likelihood.poly_marginal.PolynomialMarginal).

Source code in ceridwen/likelihood/poly_calibration.py
@classmethod
def for_spectrum(cls, obs):
    """From ``Spectrum(polynomial_order=..., polynomial_regularization=...)``; None when off
    or when the polynomial is marginalised (``polynomial_mode="marginalize"``, see
    :class:`~ceridwen.likelihood.poly_marginal.PolynomialMarginal`)."""
    order = int(getattr(obs, "polynomial_order", 0) or 0)
    if order <= 0 or getattr(obs, "polynomial_mode", "profile") != "profile":
        return None
    return cls(chebyshev_design_matrix(obs.wavelength, obs.mask, order),
               getattr(obs, "polynomial_regularization", 0.0))

solve

solve(y, mu, inv_var, mask)

(coefficients (order+1,), response (n_pix,)) maximising the likelihood; a column-scaled normal-equation solve, differentiable in mu and inv_var.

Source code in ceridwen/likelihood/poly_calibration.py
def solve(self, y, mu, inv_var, mask):
    """``(coefficients (order+1,), response (n_pix,))`` maximising the likelihood; a
    column-scaled normal-equation solve, differentiable in ``mu`` and ``inv_var``."""
    # the normal equations in the data's float64 (the likelihood's linear algebra), whatever
    # the prediction's dtype: mu**2 * inv_var spans ~1e-60 * 1e60 at cgs scale
    mu = jnp.asarray(mu, dtype=jnp.result_type(y, mu))
    A = jnp.asarray(self.A, dtype=mu.dtype)
    w = jnp.where(mask, inv_var, 0.0)
    D = mu[:, None] * A
    r = jnp.where(mask, y - mu, 0.0)
    M = D.T @ (w[:, None] * D) + jnp.diag(jnp.asarray(self.reg, dtype=mu.dtype) ** 2)
    b = D.T @ (w * r)
    d = 1.0 / jnp.sqrt(jnp.maximum(jnp.diagonal(M), jnp.finfo(mu.dtype).tiny))
    c = d * jnp.linalg.solve(d[:, None] * M * d[None, :], d * b)
    return c, 1.0 + A @ c

calibrate

calibrate(y, mu, sigma_obs, mask, params, noise_model)

mu times the profiled response (the noise model's weights at mu).

Source code in ceridwen/likelihood/poly_calibration.py
def calibrate(self, y, mu, sigma_obs, mask, params, noise_model):
    """``mu`` times the profiled response (the noise model's weights at ``mu``)."""
    out = noise_model.compute(sigma_obs, mu, mask, params, data=y)
    _c, response = self.solve(y, mu, out.inv_var, mask)
    return mu * response

The spectral GP likelihood is disabled by default. fitSED enables it when you provide log_gp_amp_spec and log_gp_length_spec, or Spectrum(noise=GaussianProcess(...)). See GP likelihood.

ceridwen.likelihood.GPGaussianLikelihood

GPGaussianLikelihood(
    noise_model=None,
    sqdist=None,
    log_amp=None,
    log_len=None,
    eps=GP_JITTER,
)

Bases: LikelihoodBase

Gaussian likelihood of one spectrum with a squared-exponential GP on the whitened residuals (:func:lnlike_gp_gaussian).

Parameters:

Name Type Description Default
noise_model DiagonalNoiseModel -- gives sigma_eff (err_scale, jitter, f_calib, f_data,

noise_floor); its outlier mixture must be off

None
sqdist (n_pix, n_pix) -- :func:`gp_sqdist` of the observed-frame pixel wavelengths
None
log_amp str or float -- ln a and ln l [ln Angstrom]: a theta key (sampled) or

a fixed value

None
log_len str or float -- ln a and ln l [ln Angstrom]: a theta key (sampled) or

a fixed value

None
eps float -- diagonal jitter (default ``GP_JITTER`` = 1e-6)
GP_JITTER
Source code in ceridwen/likelihood/gp_likelihood.py
def __init__(self, noise_model: Optional[DiagonalNoiseModel] = None, sqdist=None,
             log_amp: float | str = None, log_len: float | str = None,
             eps: float = GP_JITTER) -> None:
    noise_model = DiagonalNoiseModel() if noise_model is None else noise_model
    if getattr(noise_model, "use_outlier", False):
        raise ValueError("GPGaussianLikelihood: the outlier mixture cannot be combined "
                         "with the GP (the mixture is per pixel, the GP couples pixels)")
    if sqdist is None:
        raise ValueError("GPGaussianLikelihood needs sqdist = gp_sqdist(wavelength)")
    for what, v in (("log_amp", log_amp), ("log_len", log_len)):
        if isinstance(v, str):
            if not v:
                raise ValueError(f"GPGaussianLikelihood: {what} theta key is empty")
        elif isinstance(v, bool) or not isinstance(v, (int, float, np.floating)) \
                or not np.isfinite(v):
            raise TypeError(f"GPGaussianLikelihood: {what} must be a theta key or a "
                            f"finite float (natural log), got {v!r}")
    if not (isinstance(eps, (int, float)) and float(eps) >= 0.0):
        raise ValueError(f"GPGaussianLikelihood: eps must be a float >= 0, got {eps!r}")
    self.noise_model = noise_model
    self.sqdist = sqdist
    self.log_amp = log_amp if isinstance(log_amp, str) else float(log_amp)
    self.log_len = log_len if isinstance(log_len, str) else float(log_len)
    self.eps = float(eps)
    #: the profiled calibration is refused with a GP (see fit._gp_refusals)
    self.poly_calibration = None

gp_param_names property

gp_param_names

theta keys of the sampled GP hyperparameters (empty when both are fixed).

gp_params

gp_params(params)

(ln a, ln l): the fixed values, or looked up in params.

Source code in ceridwen/likelihood/gp_likelihood.py
def gp_params(self, params: Optional[dict[str, Array]]) -> tuple[Array, Array]:
    """``(ln a, ln l)``: the fixed values, or looked up in ``params``."""
    def get(v, what):
        if not isinstance(v, str):
            return v
        if params is None or v not in params:
            raise KeyError(f"the GP reads {what} from theta[{v!r}], which is missing: "
                           "sample it (with a prior) or give a fixed value")
        return jnp.reshape(params[v], ())
    return get(self.log_amp, "ln a"), get(self.log_len, "ln l")

__call__

__call__(y, mu, sigma_obs, mask, params=None)

Return (lnl_total, LikelihoodOutput).

Source code in ceridwen/likelihood/gp_likelihood.py
def __call__(
    self,
    y         : Array,
    mu        : Array,
    sigma_obs : Array,
    mask      : Array,
    params    : Optional[dict[str, Array]] = None,
) -> tuple[Array, LikelihoodOutput]:
    """Return ``(lnl_total, LikelihoodOutput)``."""
    noise_out: NoiseModelOutput = self.noise_model.compute(
        sigma_obs, mu, mask, params, data=y
    )
    log_amp, log_len = self.gp_params(params)
    return lnlike_gp_gaussian(y, mu, noise_out.inv_var, noise_out.log_det, mask,
                              self.sqdist, log_amp, log_len, self.eps)

conditional_mean

conditional_mean(y, mu, sigma_obs, mask, params=None)

:func:gp_conditional_mean at params (data units, every pixel).

Source code in ceridwen/likelihood/gp_likelihood.py
def conditional_mean(self, y, mu, sigma_obs, mask, params=None) -> Array:
    """:func:`gp_conditional_mean` at ``params`` (data units, every pixel)."""
    noise_out = self.noise_model.compute(sigma_obs, mu, mask, params, data=y)
    log_amp, log_len = self.gp_params(params)
    return gp_conditional_mean(y, mu, noise_out.inv_var, mask, self.sqdist,
                               log_amp, log_len, self.eps)

make_lnprobfn

make_lnprobfn(observations, model, prior)

Return a jitted log-posterior for one Spectrum (.flux, .uncertainty, .mask).

Source code in ceridwen/likelihood/gp_likelihood.py
def make_lnprobfn(
    self,
    observations : Any,
    model        : Any,
    prior        : Any,
) -> Callable[[dict[str, Array]], Array]:
    """Return a jitted log-posterior for one Spectrum (``.flux``, ``.uncertainty``,
    ``.mask``)."""
    y, sigma_obs, mask, calib, _ = single_observation_data(observations, "GPGaussianLikelihood")
    lhood = self
    rescaling = float32_rescaling(observations, self)   # None under float64

    @jax.jit
    def lnprobfn_gp(theta: dict[str, Array]) -> Array:
        lnl, _ = lhood(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                       rescaled_params(theta, rescaling))
        return lnl + prior.log_prob(theta)

    return lnprobfn_gp

config

config()

JSON-able GP settings (stored in the result file's likelihood_json).

Source code in ceridwen/likelihood/gp_likelihood.py
def config(self) -> dict:
    """JSON-able GP settings (stored in the result file's ``likelihood_json``)."""
    return {"kernel": "squared_exponential", "log_amp": self.log_amp,
            "log_len": self.log_len, "eps": self.eps, "n_pix": self.n_pix,
            "wavelength": "observed frame, Angstrom",
            "amplitude_units": "sigma_eff", "sampled_parameters": list(self.gp_param_names)}

ceridwen.likelihood.lnlike_gp_gaussian

lnlike_gp_gaussian(
    y,
    mu,
    inv_var,
    log_det,
    mask,
    sqdist,
    log_amp,
    log_len,
    eps=GP_JITTER,
)

Return (lnl_total, LikelihoodOutput) of the GP likelihood (module docstring) for the noise-model output inv_var = 1/sigma_eff^2 and log_det = ln sqrt(2 pi sigma_eff^2). residuals and chi are those of :func:lnlike_diag_gaussian; lnl_pointwise_i = -1/2 z_i^2 - ln L_ii - log_det_i with z = L^-1 r (the Cholesky-ordered decomposition, summing exactly to lnl_total); masked entries 0.

Source code in ceridwen/likelihood/gp_likelihood.py
def lnlike_gp_gaussian(
    y       : Array,
    mu      : Array,
    inv_var : Array,
    log_det : Array,
    mask    : Array,
    sqdist  : Array,
    log_amp : Array,
    log_len : Array,
    eps     : float = GP_JITTER,
) -> tuple[Array, LikelihoodOutput]:
    """Return ``(lnl_total, LikelihoodOutput)`` of the GP likelihood (module docstring) for
    the noise-model output ``inv_var`` = 1/sigma_eff^2 and ``log_det`` = ln sqrt(2 pi
    sigma_eff^2).  ``residuals`` and ``chi`` are those of :func:`lnlike_diag_gaussian`;
    ``lnl_pointwise_i = -1/2 z_i^2 - ln L_ii - log_det_i`` with ``z = L^-1 r`` (the
    Cholesky-ordered decomposition, summing exactly to ``lnl_total``); masked entries 0."""
    mask  = jnp.asarray(mask, dtype=bool)
    resid = jnp.where(mask, y - mu, 0.0)
    r     = resid * jnp.sqrt(inv_var)
    L     = _gp_cholesky(mask, sqdist, log_amp, log_len, eps)
    z     = solve_triangular(L, r, lower=True)
    lnl_i = -0.5 * z ** 2 - jnp.log(jnp.diagonal(L)) - log_det
    lnl_masked = jnp.where(mask, lnl_i, 0.0)
    lnl_total  = jnp.sum(lnl_masked)
    aux = LikelihoodOutput(
        lnl_total     = lnl_total,
        lnl_pointwise = lnl_masked,
        residuals     = resid,
        chi           = r,
        ndof          = jnp.sum(mask),
    )
    return lnl_total, aux

ceridwen.likelihood.gp_conditional_mean

gp_conditional_mean(
    y,
    mu,
    inv_var,
    mask,
    sqdist,
    log_amp,
    log_len,
    eps=GP_JITTER,
)

Posterior mean of the correlated GP component given the residuals, in DATA units (sigma_eff * a^2 E K^-1 r), on every pixel (masked ones predicted from the unmasked); mu + this is the model plus the GP's reading of the correlated residuals. A diagnostic for plots: the sampled likelihood never computes it.

Source code in ceridwen/likelihood/gp_likelihood.py
def gp_conditional_mean(
    y       : Array,
    mu      : Array,
    inv_var : Array,
    mask    : Array,
    sqdist  : Array,
    log_amp : Array,
    log_len : Array,
    eps     : float = GP_JITTER,
) -> Array:
    """Posterior mean of the correlated GP component given the residuals, in DATA units
    (``sigma_eff * a^2 E K^-1 r``), on every pixel (masked ones predicted from the unmasked);
    ``mu +`` this is the model plus the GP's reading of the correlated residuals.  A
    diagnostic for plots: the sampled likelihood never computes it."""
    mask = jnp.asarray(mask, dtype=bool)
    r    = jnp.where(mask, (y - mu) * jnp.sqrt(inv_var), 0.0)
    L    = _gp_cholesky(mask, sqdist, log_amp, log_len, eps)
    alpha = jax.scipy.linalg.cho_solve((L, True), r)
    corr = jnp.exp(2.0 * log_amp) * jnp.exp(-0.5 * sqdist * jnp.exp(-2.0 * log_len))
    corr = jnp.where(mask[None, :], corr, 0.0)
    return (corr @ alpha) / jnp.sqrt(inv_var)

ceridwen.observation.GaussianProcess

GaussianProcess(amplitude, length_scale, jitter=1e-06)

Squared-exponential GP on normalised spectral residuals, with covariance K = I + a^2 SE(l) + jitter I.

Parameters:

Name Type Description Default
amplitude float, dimensionless -- kernel amplitude in units of the per-pixel sigma.
required
length_scale float, Å -- correlation length.
required
jitter float -- diagonal added for numerical stability.
1e-06
Source code in ceridwen/observation/gp.py
def __init__(self, amplitude: float, length_scale: float,
             jitter: float = 1e-6):
    self.amplitude    = float(amplitude)
    self.length_scale = float(length_scale)
    self.jitter       = float(jitter)

log_likelihood

log_likelihood(residuals, wavelength, mask=None)

Full Gaussian log-likelihood of the normalised residuals under K, including the white-noise identity term and the -n/2 ln(2 pi) constant; do NOT add a separate -1/2 sum r^2 term.

Source code in ceridwen/observation/gp.py
def log_likelihood(self,
                   residuals: np.ndarray,
                   wavelength: np.ndarray,
                   mask: np.ndarray | None = None) -> float:
    """Full Gaussian log-likelihood of the normalised residuals under K,
    including the white-noise identity term and the -n/2 ln(2 pi) constant;
    do NOT add a separate -1/2 sum r^2 term."""
    r   = np.asarray(residuals,  dtype=np.float64)
    wav = np.asarray(wavelength, dtype=np.float64)
    if mask is not None:
        m   = np.asarray(mask, dtype=bool)
        r   = r[m]
        wav = wav[m]
    n = len(r)
    if n == 0:
        return 0.0
    L, logdet = self._factor(wav)
    if L is None:
        return -np.inf
    from scipy.linalg import cho_solve
    alpha = cho_solve((L, True), r)
    return (-0.5 * float(r @ alpha) - logdet - 0.5 * n * float(np.log(2.0 * np.pi)))

ceridwen.likelihood.poly_marginal.PolyMarginalGaussianLikelihood dataclass

PolyMarginalGaussianLikelihood(
    noise_model=DiagonalNoiseModel(), poly_marginal=None
)

Bases: LikelihoodBase

Diagonal Gaussian likelihood of a spectrum with its calibration polynomial marginalised analytically (:func:poly_marginal_loglike). No outlier mixture and no upper limits (the marginal is exact only for a Gaussian likelihood).

__call__

__call__(y, mu, sigma_obs, mask, params=None)

Return (lnl_total, LikelihoodOutput) (see :func:poly_marginal_loglike).

Source code in ceridwen/likelihood/poly_marginal.py
def __call__(self, y, mu, sigma_obs, mask, params=None):
    """Return ``(lnl_total, LikelihoodOutput)`` (see :func:`poly_marginal_loglike`)."""
    nout = self.noise_model.compute(sigma_obs, mu, mask, params, data=y)
    return poly_marginal_loglike(y, mu, nout.inv_var, nout.log_det, mask,
                                 self.poly_marginal.A, self.poly_marginal.sigma)

conditional

conditional(y, mu, sigma_obs, mask, params=None)

(mean (k,), cov (k, k), response (n,)): the conditional posterior of the coefficients at the model mu and the response 1 + A mean.

Source code in ceridwen/likelihood/poly_marginal.py
def conditional(self, y, mu, sigma_obs, mask, params=None):
    """``(mean (k,), cov (k, k), response (n,))``: the conditional posterior of the
    coefficients at the model ``mu`` and the response ``1 + A mean``."""
    nout = self.noise_model.compute(sigma_obs, mu, mask, params, data=y)
    mean, cov = poly_marginal_posterior(y, mu, nout.inv_var, mask,
                                        self.poly_marginal.A, self.poly_marginal.sigma)
    # the response in the data's float64, as the posterior it comes from (a float32 design
    # matrix would round the response, ~1, to 6e-8, and its small values far worse)
    dt = jnp.result_type(y, mu)
    return mean, cov, 1.0 + jnp.asarray(self.poly_marginal.A, dtype=dt) @ mean

make_lnprobfn

make_lnprobfn(observations, model, prior)

Return a jitted log-posterior for one observation (.flux, .uncertainty, .mask).

Source code in ceridwen/likelihood/poly_marginal.py
def make_lnprobfn(self, observations, model, prior) -> Callable[[dict[str, Array]], Array]:
    """Return a jitted log-posterior for one observation (``.flux``, ``.uncertainty``, ``.mask``)."""
    y, sigma_obs, mask, calib, _ = single_observation_data(observations, "PolyMarginalGaussianLikelihood")
    lhood = self
    rescaling = float32_rescaling(observations, self)   # None under float64

    @jax.jit
    def lnprobfn(theta):
        lnl, _ = lhood(y, calibrated_mu(model.predict(theta), calib), sigma_obs, mask,
                       rescaled_params(theta, rescaling))
        return lnl + prior.log_prob(theta)

    return lnprobfn

ceridwen.likelihood.poly_marginal.PolynomialMarginal

PolynomialMarginal(design, prior_sigma)

Static description of the marginalised polynomial of one spectrum: the design matrix A (n_pix, order+1) and the prior widths sigma (order+1,). Hashable (by value), so it can sit in a likelihood's static pytree data.

Source code in ceridwen/likelihood/poly_marginal.py
def __init__(self, design, prior_sigma):
    A = np.asarray(design, dtype=np.float64)
    if A.ndim != 2 or A.shape[1] < 2:
        raise ValueError("the calibration design matrix must be (n_pix, order + 1), order >= 1")
    sig = np.broadcast_to(np.asarray(prior_sigma, dtype=np.float64), (A.shape[1],)).copy()
    if np.any(~np.isfinite(sig)) or np.any(sig < 0.0):
        raise ValueError(f"polynomial_prior_sigma must be finite and >= 0, got {sig}")
    self.A = A
    self.sigma = sig
    self._key = hashlib.sha256(A.tobytes() + sig.tobytes()).hexdigest()

for_spectrum classmethod

for_spectrum(obs)

From Spectrum(polynomial_mode="marginalize", ...); None otherwise.

Source code in ceridwen/likelihood/poly_marginal.py
@classmethod
def for_spectrum(cls, obs):
    """From ``Spectrum(polynomial_mode="marginalize", ...)``; None otherwise."""
    order = int(getattr(obs, "polynomial_order", 0) or 0)
    if order <= 0 or getattr(obs, "polynomial_mode", "profile") != "marginalize":
        return None
    return cls(chebyshev_design_matrix(obs.wavelength, obs.mask, order),
               obs.polynomial_prior_sigma)

ceridwen.likelihood.poly_marginal.poly_marginal_loglike

poly_marginal_loglike(
    y,
    mu,
    inv_var,
    log_det,
    mask,
    A,
    prior_sigma,
    *,
    return_posterior=False
)

Marginal ln-likelihood of the spectrum over the calibration coefficients.

y, mu : (n,) data and uncalibrated model; inv_var, log_det : (n,) from the noise model (1/sigma_eff^2 and 0.5 ln(2 pi sigma_eff^2)); mask : (n,) bool, True = used; A : (n, k) design; prior_sigma : (k,) prior widths s (>= 0, finite).

Returns (lnl_total, LikelihoodOutput), whose residuals / chi / lnl_pointwise are those of the conditional-mean calibrated model mu (1 + A c_hat); lnl_total = sum(lnl_pointwise) - 1/2 c_hat^T Lambda^-1 c_hat - 1/2 ln|P| (the prior and Occam terms are global, not per pixel). With return_posterior also the conditional mean (k,) and covariance (k, k) of the coefficients.

Source code in ceridwen/likelihood/poly_marginal.py
def poly_marginal_loglike(y, mu, inv_var, log_det, mask, A, prior_sigma,
                          *, return_posterior=False):
    """Marginal ln-likelihood of the spectrum over the calibration coefficients.

    y, mu : (n,) data and uncalibrated model; inv_var, log_det : (n,) from the noise model
    (``1/sigma_eff^2`` and ``0.5 ln(2 pi sigma_eff^2)``); mask : (n,) bool, True = used;
    A : (n, k) design; prior_sigma : (k,) prior widths s (>= 0, finite).

    Returns ``(lnl_total, LikelihoodOutput)``, whose ``residuals`` / ``chi`` /
    ``lnl_pointwise`` are those of the conditional-mean calibrated model ``mu (1 + A c_hat)``;
    ``lnl_total = sum(lnl_pointwise) - 1/2 c_hat^T Lambda^-1 c_hat - 1/2 ln|P|`` (the prior and
    Occam terms are global, not per pixel).  With ``return_posterior`` also the conditional
    mean (k,) and covariance (k, k) of the coefficients.
    """
    # the factorisation in the data's float64 (the likelihood's linear algebra), whatever the
    # prediction's dtype: D^T W D spans ~1e-60 * 1e60 at cgs scale
    mu = jnp.asarray(mu, dtype=jnp.result_type(y, mu))
    A = jnp.asarray(A, dtype=mu.dtype)
    s = jnp.asarray(prior_sigma, dtype=mu.dtype)
    r, D, w, L, g, v, logdet_P = _factor(y, mu, inv_var, mask, A, s)
    lnorm = jnp.sum(jnp.where(mask, log_det, 0.0))
    lnl_total = -0.5 * jnp.sum(w * r * r) - lnorm + 0.5 * jnp.dot(v, v) - 0.5 * logdet_P

    c_hat = g * cho_solve((L, True), g * (D.T @ (w * r)))
    resid = jnp.where(mask, r - D @ c_hat, 0.0)
    chi = resid * jnp.sqrt(inv_var)
    lnl_i = jnp.where(mask, -0.5 * chi ** 2 - log_det, 0.0)
    aux = LikelihoodOutput(lnl_total=lnl_total, lnl_pointwise=lnl_i, residuals=resid,
                           chi=jnp.where(mask, chi, 0.0), ndof=jnp.sum(mask))
    if not return_posterior:
        return lnl_total, aux
    cov = g[:, None] * cho_solve((L, True), jnp.eye(g.shape[0], dtype=g.dtype)) * g[None, :]
    return lnl_total, aux, c_hat, cov

ceridwen.model.obs_params.check_names

check_names(observations, families, given, *, what='')

Validate every name of families in given against observations; return {valid name: obs}. Raises ValueError for an ambiguous plain name, both spellings for one observation, or a name that matches no observation.

Source code in ceridwen/model/obs_params.py
def check_names(observations, families, given, *, what="") -> dict:
    """Validate every name of ``families`` in ``given`` against ``observations``; return
    {valid name: obs}.  Raises ValueError for an ambiguous plain name, both spellings for one
    observation, or a name that matches no observation."""
    by_kind: dict = {}
    for o in observations:
        k = obs_kind(o)
        if k is not None:
            by_kind.setdefault(k, []).append(o)
    valid: dict = {}
    for fam in families:
        wanted = {n for n in given if fam.claims(n)}
        fam_valid = {}
        for kind in fam.kinds:
            obs = by_kind.get(kind, [])
            for o in obs:
                plain, own = names_for(o, fam)
                fam_valid[own] = o
                if len(obs) == 1:
                    fam_valid[plain] = o
                if len(obs) > 1 and plain in given:
                    raise ValueError(
                        f"{plain!r} is ambiguous: the model has {len(obs)} {kind} observations "
                        f"{[x.name for x in obs]}, and each takes its own {fam.label}; use "
                        f"{[names_for(x, fam)[1] for x in obs]}")
                if plain in given and own in given:
                    raise ValueError(f"both {plain!r} and {own!r} are set for {kind} "
                                     f"{o.name!r}; keep one")
        unknown = sorted(n for n in wanted if n not in fam_valid)
        if unknown:
            raise ValueError(
                f"{unknown} match no observation{what}, so they would be sampled without being "
                f"used; the {fam.label} names of this model are {sorted(fam_valid)}")
        valid.update(fam_valid)
    return valid

Fitting

ceridwen.fit.fitSED

fitSED(
    model,
    observations=None,
    output_dir=".",
    *,
    sampler="nested",
    rng_key=None,
    sampler_kwargs=None,
    vi=None,
    vi_kwargs=None,
    filename="ceridwen_result.h5",
    overwrite=True,
    verbose=True,
    optimize=False,
    optimize_kwargs=None,
    mfrac=None
)

Fit model to observations with sampler ("nested" or "nuts") and return the SamplingResult; writes output_dir/filename (HDF5) and a .log with the same stem.

Parameters:

Name Type Description Default
observations list[Observation] -- replaces ``model.observations`` and re-runs ``setup_for_model`` at ``model.zred``
None
sampler_kwargs dict -- forwarded to the sampler adapter constructor. fitSED's nested

defaults are num_live=500 and num_inner_steps=30 (the adapter on its own, e.g. via run_sampler, uses 5 x the number of free dimensions); pass num_inner_steps to choose

None
vi None, 'tril', 'iaf', or a VI map -- NUTS-only variational preconditioning
None
vi_kwargs dict -- forwarded to VI training / map constructor
None
optimize bool -- first find the MAP with ``ceridwen.optimize.map_fit`` (L-BFGS from prior

draws); NUTS then starts its chains there. Nested sampling draws its live points from the prior, so there the MAP is only recorded. Stored under /map in the result file.

False
optimize_kwargs dict -- forwarded to ``map_fit`` (``n_starts``, ``rng_key``, ...); the

default rng_key is fold_in(rng_key, 1), so the sampler's own key is unchanged

None
mfrac bool or None -- write ``/derived/mfrac`` (surviving / formed mass of every stored

sample, from the grid's surviving-mass table; PostProcess reads it): None writes it when the grid has the table and logs one line when it has not; True requires the table (ValueError before sampling); False skips it. The same switch as PostProcess(mfrac=).

None
Notes

Noise terms and the outlier mixture are switched on by the names the model samples (see _likelihood_for); all outlier fractions default to 0 (off).

Source code in ceridwen/fit.py
def fitSED(
    model,
    observations: Sequence | None = None,
    output_dir: str | Path = ".",
    *,
    sampler: str = "nested",
    rng_key: Array | None = None,
    sampler_kwargs: dict[str, Any] | None = None,
    vi: "str | Any | None" = None,
    vi_kwargs: dict[str, Any] | None = None,
    filename: str = "ceridwen_result.h5",
    overwrite: bool = True,
    verbose: bool = True,
    optimize: bool = False,
    optimize_kwargs: dict[str, Any] | None = None,
    mfrac: bool | None = None,
):
    """Fit ``model`` to ``observations`` with ``sampler`` ("nested" or "nuts") and return the
    ``SamplingResult``; writes ``output_dir/filename`` (HDF5) and a ``.log`` with the same stem.

    Parameters
    ----------
    observations : list[Observation] -- replaces ``model.observations`` and re-runs ``setup_for_model`` at ``model.zred``
    sampler_kwargs : dict -- forwarded to the sampler adapter constructor.  fitSED's nested
        defaults are num_live=500 and num_inner_steps=30 (the adapter on its own, e.g. via
        run_sampler, uses 5 x the number of free dimensions); pass num_inner_steps to choose
    vi : None, 'tril', 'iaf', or a VI map -- NUTS-only variational preconditioning
    vi_kwargs : dict -- forwarded to VI training / map constructor
    optimize : bool -- first find the MAP with ``ceridwen.optimize.map_fit`` (L-BFGS from prior
        draws); NUTS then starts its chains there.  Nested sampling draws its live points from
        the prior, so there the MAP is only recorded.  Stored under ``/map`` in the result file.
    optimize_kwargs : dict -- forwarded to ``map_fit`` (``n_starts``, ``rng_key``, ...); the
        default ``rng_key`` is ``fold_in(rng_key, 1)``, so the sampler's own key is unchanged
    mfrac : bool or None -- write ``/derived/mfrac`` (surviving / formed mass of every stored
        sample, from the grid's surviving-mass table; ``PostProcess`` reads it): None writes it
        when the grid has the table and logs one line when it has not; True requires the table
        (ValueError before sampling); False skips it.  The same switch as ``PostProcess(mfrac=)``.

    Notes
    -----
    Noise terms and the outlier mixture are switched on by the names the model samples (see
    ``_likelihood_for``); all outlier fractions default to 0 (off).
    """
    from .likelihood.likelihood import MultiObservationLikelihood
    from .sampler.runner import run_sampler

    if rng_key is None:
        rng_key = jax.random.PRNGKey(0)

    if sampler_kwargs is None:
        sampler_kwargs = {}

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / filename

    if output_path.exists() and not overwrite:
        raise FileExistsError(
            f"{output_path} already exists.  Pass overwrite=True to replace."
        )

    if observations is not None:
        model.observations = list(observations)
        model.setup_observations()

    if not model.observations:
        raise ValueError("No observations attached to model.")

    want_mfrac = _resolve_fit_mfrac(model, mfrac)

    _t0_likelihood = time.perf_counter()
    obs_dict = model.obs_dict
    keys = tuple(obs_dict.keys())
    likelihoods = tuple(_likelihood_for(obs_dict[k], model.param_names, model=model)
                        for k in keys)
    multi_likelihood = MultiObservationLikelihood(
        keys=keys,
        likelihoods=likelihoods,
    )
    if getattr(model, "_eline_system", None) is not None:
        from .likelihood.eline_marginal import refuse_outlier_with_elines
        refuse_outlier_with_elines(keys, likelihoods, model._eline_system.keys)
    _t_likelihood = time.perf_counter() - _t0_likelihood

    logger.setLevel(logging.INFO)
    logger.propagate = False
    if verbose and not any(
        isinstance(h, logging.StreamHandler)
        and not isinstance(h, logging.FileHandler)
        for h in logger.handlers
    ):
        _handler = logging.StreamHandler()
        _handler.setFormatter(logging.Formatter("%(message)s"))
        logger.addHandler(_handler)

    log_path = output_path.with_suffix(".log")
    _file_handler = logging.FileHandler(log_path, mode="w")
    _file_handler.setFormatter(logging.Formatter(
        "%(asctime)s  %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
    logger.addHandler(_file_handler)

    from .update_check import notify_if_outdated
    notify_if_outdated()                       # once a day at most; silent offline

    try:
        from .precision import is_x64, precision_name
        _devices = jax.devices()
        _backend = jax.default_backend().upper()
        _device_str = ", ".join(str(d) for d in _devices)
        _apple_gpu = _backend in ("MTL", "MPS")       # jax-graft (mtl) / jax-mps: float32 only
        if _apple_gpu and is_x64():
            raise ValueError(
                f"fitSED on the {_backend} backend ({_device_str}) with float64 on: an Apple GPU "
                "has no float64.  Unset CERIDWEN_X64 (float32 mode on the GPU, docs/mac_gpu.md) or "
                "keep this fit on the CPU with JAX_PLATFORMS=cpu")

        logger.info(f"ceridwen.fitSED")
        logger.info(f"  Device      : {_backend}  ({_device_str})")
        logger.info(f"  Precision   : {precision_name()}"
                    + ("" if is_x64() else
                       "  (float32 mode, docs/mac_gpu.md: ln Z and gradients are float32, not "
                       "comparable bit for bit with a float64 fit)"))
        if _backend == "CPU":
            logger.info(
                "                ^ running on CPU — for GPU check that a "
                "CUDA-enabled jaxlib is installed and JAX_PLATFORMS is unset"
            )
        elif _apple_gpu:
            logger.info("                ^ Apple GPU (float32)")
        logger.info(f"  Sampler     : {sampler}")
        logger.info(f"  Cosmology   : {model.cosmo.describe()}")
        logger.info(f"  Redshift    : {model._redshift_line()}")
        logger.info(f"  Kinematics  : {model._kinematics_line()}")
        logger.info(f"  Parameters  : {model.param_names}  ({sum(int(jnp.size(v)) for v in model.theta_init.values())} dims)")
        logger.info(f"  Observations: {list(keys)}")
        for k, lh in zip(keys, likelihoods):
            logger.info(f"    {k}: {_describe_likelihood(obs_dict[k], lh)}")
        if getattr(model, "_eline_system", None) is not None:
            logger.info(f"  Emission lines: {model._eline_system.describe()}")
        logger.info(f"  Output      : {output_path}")
        logger.info(f"  Log         : {log_path}")
        logger.info(f"  Likelihood build: {_t_likelihood:.3f} s")

        _t0_adapter = time.perf_counter()
        adapter = _build_adapter(
            sampler, model, sampler_kwargs, verbose,
            vi=vi, vi_kwargs=vi_kwargs,
        )
        _t_adapter = time.perf_counter() - _t0_adapter
        logger.info(f"  Adapter build:    {_t_adapter:.3f} s")
        logger.info(f"  Sampler settings: {_describe_adapter(adapter, model)}")

        map_result = None
        _t_map = 0.0
        if optimize:
            from .optimize import map_fit
            _okw = dict(optimize_kwargs or {})
            _okw.setdefault("rng_key", jax.random.fold_in(rng_key, 1))
            _t0_map = time.perf_counter()
            map_result = map_fit(model, **_okw)
            _t_map = time.perf_counter() - _t0_map
            logger.info(map_result.summary())
            if type(adapter).__name__ == "BlackJAXNestedSamplerAdapter":
                logger.info("  (nested sampling draws its live points from the prior: the MAP "
                            "is recorded, not used as a start)")

        _t0_sampler = time.perf_counter()
        result = run_sampler(model, multi_likelihood, adapter, rng_key,
                             theta_init=None if map_result is None
                             else map_result.free_param_init)
        _t_sampler = time.perf_counter() - _t0_sampler

        logger.info(f"\n{result.summary()}")

        derived = None
        _t_derived = 0.0
        if want_mfrac:
            from .postprocess import surviving_mass_fractions, mfrac_attrs
            _t0_derived = time.perf_counter()
            derived = {"mfrac": (surviving_mass_fractions(model, result.samples),
                                 mfrac_attrs(model.csp))}
            _t_derived = time.perf_counter() - _t0_derived
            logger.info(f"  Derived mfrac: {derived['mfrac'][0].size} samples, "
                        f"{_t_derived:.3f} s")
        elif mfrac is None:
            logger.info("  Derived mfrac: not written (the SSP grid has no surviving-mass "
                        "table; PostProcess reports mass_formed only)")

        _t0_h5 = time.perf_counter()
        write_result_h5(output_path, model, result, verbose=verbose,
                        likelihood=multi_likelihood, adapter=adapter, rng_key=rng_key,
                        map_result=map_result, derived=derived)
        _t_h5 = time.perf_counter() - _t0_h5

        _t_total = _t_likelihood + _t_adapter + _t_map + _t_sampler + _t_derived + _t_h5
        logger.info(f"\n  fitSED timing breakdown:")
        logger.info(f"    Likelihood build : {_t_likelihood:>8.3f} s")
        logger.info(f"    Adapter build    : {_t_adapter:>8.3f} s")
        if optimize:
            logger.info(f"    MAP optimisation : {_t_map:>8.1f} s")
        logger.info(f"    Sampler run      : {_t_sampler:>8.1f} s")
        if want_mfrac:
            logger.info(f"    Derived mfrac    : {_t_derived:>8.3f} s")
        logger.info(f"    HDF5 write       : {_t_h5:>8.3f} s")
        logger.info(f"    Total fitSED     : {_t_total:>8.1f} s")

        return result
    finally:
        logger.removeHandler(_file_handler)
        _file_handler.close()

ceridwen.fit.load_result_h5

load_result_h5(path)

Rebuild a SamplingResult from a result HDF5 file (the forward model itself is not restored).

Source code in ceridwen/fit.py
def load_result_h5(path: str | Path):
    """Rebuild a ``SamplingResult`` from a result HDF5 file (the forward model itself is not restored)."""
    import h5py
    from .sampler.runner import SamplingResult

    path = Path(path)
    with h5py.File(path, "r") as f:
        _require_logzsol_result(path, f)
        samp = f["samples"]
        param_names = list(f["model"]["param_names"].asstr()[()])

        samples = {p: jnp.asarray(np.array(samp[p])) for p in param_names}
        # ln L and the weights stay float64 on the host, as run_sampler returns them in float32
        # mode (runner._with_loglike_offset): float32 resolves ln L ~ 4e4 only to 4e-3
        log_likelihoods = np.asarray(samp["log_likelihoods"], dtype=np.float64)
        log_weights     = np.asarray(samp["log_weights"], dtype=np.float64)
        llb = (np.asarray(samp["log_likelihoods_birth"], dtype=np.float64)
               if "log_likelihoods_birth" in samp else None)

        raw = {}
        if "num_chains" in samp.attrs:
            raw["num_chains"] = int(samp.attrs["num_chains"])
        if "num_samples_per_chain" in samp.attrs:
            raw["num_samples"] = int(samp.attrs["num_samples_per_chain"])
        if "num_warmup" in samp.attrs:
            raw["num_warmup"] = int(samp.attrs["num_warmup"])

        return SamplingResult(
            samples               = samples,
            log_evidence          = float(samp.attrs.get("log_evidence", float("nan"))),
            log_evidence_err      = float(samp.attrs.get("log_evidence_err", float("nan"))),
            log_weights           = log_weights,
            log_likelihoods       = log_likelihoods,
            param_names           = param_names,
            n_likelihood_calls    = int(samp.attrs.get("n_likelihood_calls", -1)),
            wall_time_s           = float(samp.attrs.get("wall_time_s", float("nan"))),
            sampler_name          = str(samp.attrs.get("sampler_name", "unknown")),
            log_likelihoods_birth = llb,
            raw                   = raw or None,
        )

ceridwen.fit.read_result_h5

read_result_h5(path)

Read a result HDF5 file into a nested dict with keys 'obs', 'model', 'samples', 'provenance', 'config' (precision: float64 / float32, platform: the JAX backend the fit ran on), 'elines' (when the fit marginalised the emission lines), 'map' (when it ran with optimize=True) and 'derived' (read_derived_h5; when fitSED wrote /derived/mfrac).

Source code in ceridwen/fit.py
def read_result_h5(path: str | Path) -> dict:
    """Read a result HDF5 file into a nested dict with keys ``'obs'``, ``'model'``,
    ``'samples'``, ``'provenance'``, ``'config'`` (``precision``: float64 / float32,
    ``platform``: the JAX backend the fit ran on), ``'elines'``
    (when the fit marginalised the emission lines), ``'map'`` (when it ran with
    ``optimize=True``) and ``'derived'`` (``read_derived_h5``; when fitSED wrote
    ``/derived/mfrac``)."""
    import h5py

    out = {"obs": {}, "model": {}, "samples": {}}

    with h5py.File(path, "r") as f:
        _require_logzsol_result(path, f)
        for obs_name in f["obs"]:
            og = f["obs"][obs_name]
            obs_data = {k: np.array(og[k]) for k in og}
            for attr_name in og.attrs:
                obs_data[attr_name] = og.attrs[attr_name]
            if "likelihood_json" in og.attrs:
                obs_data["likelihood"] = json.loads(og.attrs["likelihood_json"])
            out["obs"][obs_name] = obs_data

        mod = f["model"]
        out["model"]["param_names"] = list(mod["param_names"].asstr()[()])
        out["model"]["wave"] = np.array(mod["wave"])

        out["model"]["theta_init"] = {}
        for name in mod["theta_init"]:
            out["model"]["theta_init"][name] = np.array(mod["theta_init"][name])

        out["model"]["priors"] = {}
        if "priors" in mod:
            for name in mod["priors"].attrs:
                raw = mod["priors"].attrs[name]
                try:
                    out["model"]["priors"][name] = json.loads(raw)
                except (json.JSONDecodeError, TypeError):
                    out["model"]["priors"][name] = raw

        for attr_name in mod.attrs:
            out["model"][attr_name] = mod.attrs[attr_name]
        if "cosmo_H0" in mod.attrs:
            from .cosmology import Cosmology
            out["model"]["cosmo"] = Cosmology.from_dict(dict(mod.attrs))

        samp = f["samples"]
        for dset_name in samp:
            out["samples"][dset_name] = np.array(samp[dset_name])

        for attr_name in samp.attrs:
            out["samples"][attr_name] = samp.attrs[attr_name]

        if "provenance" in f:
            out["provenance"] = _provenance_from_group(f["provenance"])
        if "config" in f:
            out["config"] = dict(f["config"].attrs)

        if "elines" in f:
            g = f["elines"]
            out["elines"] = {k: (list(g[k].asstr()[()]) if k == "names" else np.array(g[k]))
                             for k in g}
            for attr_name in g.attrs:
                out["elines"][attr_name] = g.attrs[attr_name]

        if "map" in f:
            g = f["map"]
            out["map"] = {"theta": {k: np.array(v) for k, v in g["theta"].items()},
                          "lnp_starts": np.array(g["lnp_starts"]),
                          "n_steps": np.array(g["n_steps"]), **dict(g.attrs)}

    derived = read_derived_h5(path)
    if derived:
        out["derived"] = derived
    return out

ceridwen.fit.read_provenance

read_provenance(path)

The /provenance group of a result file (JSON attrs decoded); {} for older files.

Source code in ceridwen/fit.py
def read_provenance(path) -> dict:
    """The ``/provenance`` group of a result file (JSON attrs decoded); {} for older files."""
    import h5py
    with h5py.File(Path(path), "r") as f:
        return _provenance_from_group(f["provenance"]) if "provenance" in f else {}

ceridwen.fit.convert_result

convert_result(
    path, ssp_grid, out=None, *, overwrite=False
)

Convert a result file with absolute log10 Z metallicity to the logzsol convention, writing a NEW file.

ssp_grid is the grid the fit used (SSPData/SSPDataAfe or a path); its shape is checked against the file, and every absolute metallicity (samples, theta_init, priors) is shifted by -log10 Z_sun. Returns the new path. The input file is never modified.

Source code in ceridwen/fit.py
def convert_result(path, ssp_grid, out=None, *, overwrite=False):
    """Convert a result file with absolute log10 Z metallicity to the logzsol convention, writing a NEW file.

    ``ssp_grid`` is the grid the fit used (``SSPData``/``SSPDataAfe`` or a path); its shape is
    checked against the file, and every absolute metallicity (samples, theta_init, priors) is
    shifted by -log10 Z_sun.  Returns the new path.  The input file is never modified.
    """
    import h5py
    from .ssps.ssp_data import SSPData

    path = Path(path)
    grid = ssp_grid if hasattr(ssp_grid, "log10_zsun") else SSPData.load(str(ssp_grid))
    l0 = float(grid.log10_zsun)
    n_z = int(np.asarray(grid.ssp_lgmet).size)
    n_age = int(np.asarray(grid.ssp_lg_age_gyr).size)
    out = Path(out) if out is not None else path.with_name(path.stem + "_logzsol.h5")
    if out.exists() and not overwrite:
        raise FileExistsError(f"{out} exists; pass overwrite=True or another out=")
    with h5py.File(path, "r") as f:
        mod = f["model"]
        if str(mod.attrs.get("metallicity_convention", "")) == METALLICITY_CONVENTION:
            raise ValueError(f"{path} is already in the logzsol convention")
        names = list(mod["param_names"].asstr()[()])
        legacy = _legacy_metallicity_keys(names, list(f["samples"]) + list(mod["theta_init"]))
        if not legacy:
            raise ValueError(f"{path} has no absolute-metallicity parameter to convert "
                             f"(parameters: {names})")
        if "zh" in legacy:
            raise ValueError(
                f"{path} samples 'zh', a per-NODE absolute metallicity history.  Its logzsol "
                "form, the per-node 'logzsol_hist', was removed: the model used only the bin "
                "means 0.5*(zh[k] + zh[k+1]), and a prior on nodes has no per-bin equivalent, "
                "so the file cannot be converted to 'logzsol_bins'.  The samples are still "
                "readable (ceridwen.resultfile); the per-bin metallicity of each sample is "
                "0.5*(zh[:-1] + zh[1:]) - log10 Z_sun.  Refit with theta['logzsol_bins'].")
        f_nz = int(mod.attrs.get("n_metallicities", -1))
        f_nage = int(mod.attrs.get("n_ssp_ages", -1))
        if f_nz not in (-1, n_z) or f_nage not in (-1, n_age):
            raise ValueError(
                f"{path} was fitted with a grid of {f_nz} metallicities x {f_nage} SSP ages, "
                f"but {getattr(grid, 'chash', 'the given grid')} has {n_z} x {n_age}: this is "
                "not the grid of that fit, and its Z_sun would be wrong.  Pass the grid the "
                "fit actually used.")
    shutil.copyfile(path, out)
    with h5py.File(out, "r+") as f:
        mod, samp = f["model"], f["samples"]
        rename = {"Z": "logzsol"}
        for old, new in rename.items():
            if old in samp:
                samp[new] = np.asarray(samp[old]) - l0
                del samp[old]
            if "theta_init" in mod and old in mod["theta_init"]:
                mod["theta_init"][new] = np.asarray(mod["theta_init"][old]) - l0
                del mod["theta_init"][old]
            if "priors" in mod and old in mod["priors"].attrs:
                mod["priors"].attrs[new] = json.dumps(
                    _shift_prior(json.loads(mod["priors"].attrs[old]), -l0, old))
                del mod["priors"].attrs[old]
        names = [rename.get(n, n) for n in list(mod["param_names"].asstr()[()])]
        del mod["param_names"]
        mod.create_dataset("param_names", data=np.array(names, dtype=object),
                           dtype=h5py.string_dtype())
        if "transforms" in mod.attrs:
            tx = json.loads(mod.attrs["transforms"])
            mod.attrs["transforms"] = json.dumps(
                [t.replace("Z <-", "logzsol <-") for t in tx])
        mod.attrs["metallicity_convention"] = METALLICITY_CONVENTION
        mod.attrs["log10_zsun"] = l0
        if getattr(grid, "zsun_nominal", None) is not None:
            mod.attrs["zsun_nominal"] = float(grid.zsun_nominal)
        if getattr(grid, "axis_meaning", None):
            mod.attrs["metallicity_axis_meaning"] = str(grid.axis_meaning)
        if getattr(grid, "chash", None):
            mod.attrs["grid_chash"] = str(grid.chash)
        mod.attrs["converted_from"] = str(path)
        mod.attrs["converted_note"] = (
            f"metallicity samples/priors shifted by -log10 Z_sun = {-l0!r} (logzsol conversion)")
    return out

ceridwen.fit.result_cosmology

result_cosmology(path)

The Cosmology a result file was fitted with (/model attrs cosmo_*); KeyError if absent.

Source code in ceridwen/fit.py
def result_cosmology(path: str | Path):
    """The ``Cosmology`` a result file was fitted with (``/model`` attrs ``cosmo_*``); KeyError if absent."""
    import h5py
    from .cosmology import Cosmology

    with h5py.File(Path(path), "r") as f:
        attrs = dict(f["model"].attrs)
    if "cosmo_H0" not in attrs:
        raise KeyError(f"{path} carries no cosmology attributes (written before "
                       "they were recorded); rebuild with the cosmology you used")
    return Cosmology.from_dict(attrs)

ceridwen.resultfile.rebuild_model

rebuild_model(
    path, csp, observations, transforms=None, *, check=True
)

SedModel of the fit in path, from a CSP, observations and transforms you supply.

Taken from the file: priors, the free parameters and their theta_init, zred, lumdist_mpc, kinematics and broaden_photometry. Not recorded, so supplied by you: the CSP (built as for the fit, with the same grid and cosmology), the observation objects and the transform callables (the file lists them as derived <- function name; the derived names must match). Parameters fixed with CSPBasis(fixed=...) (stored as name <- CSPBasis(fixed=[...])) come from the CSP, which must fix them to the same values. With check (default) the rebuilt model is compared with the file by :func:check_model_against_result and any difference raises a ValueError saying which.

Source code in ceridwen/resultfile.py
def rebuild_model(path, csp, observations, transforms=None, *, check: bool = True):
    """``SedModel`` of the fit in ``path``, from a CSP, observations and transforms you supply.

    Taken from the file: priors, the free parameters and their ``theta_init``, zred,
    lumdist_mpc, kinematics and ``broaden_photometry``.  Not recorded, so supplied by you: the
    CSP (built as for the fit, with the same grid and cosmology), the observation objects and
    the transform callables (the file lists them as ``derived <- function name``; the derived
    names must match).  Parameters fixed with ``CSPBasis(fixed=...)`` (stored as
    ``name <- CSPBasis(fixed=[...])``) come from the CSP, which must fix them to the same
    values.  With ``check`` (default) the rebuilt model is compared with the file by
    :func:`check_model_against_result` and any difference raises a ``ValueError`` saying which.
    """
    from .fit import read_result_h5
    from .model import SedModel

    rec = read_result_h5(path)
    mod = rec["model"]
    transforms = dict(transforms or {})
    stored = json.loads(mod["transforms"]) if "transforms" in mod else []
    from .model.model import FIXED_PREFIX
    on_csp = [t.split(" <- ")[0] for t in stored if t.split(" <- ", 1)[-1].startswith(FIXED_PREFIX)]
    missing = sorted(set(on_csp) - set(getattr(csp, "fixed", {}) or {}))
    if missing:
        raise ValueError(
            f"{path} was fitted with {missing} fixed on the CSP "
            f"({[t for t in stored if t.split(' <- ')[0] in missing]}); build the CSP with the "
            "same CSPBasis(fixed={...}) to rebuild it")
    want = [t.split(" <- ")[0] for t in stored if t.split(" <- ")[0] not in on_csp]
    if sorted(want) != sorted(transforms):
        raise ValueError(
            f"{path} was fitted with transforms {stored}; the transforms given are for "
            f"{sorted(transforms)}.  Supply one callable per derived name "
            f"{sorted(want)} (the file stores their names, not their code)")
    kwargs = dict(
        priors=priors_from_result(path),
        transforms=transforms,
        # in the fit's parameter order (h5py hands the theta_init group back sorted)
        free_param_init={k: np.asarray(mod["theta_init"][k]) for k in mod["param_names"]},
        zred=float(mod.get("zred", 0.0)),
        kinematics=kinematics_from_result(path),
    )
    if "lumdist_mpc" in mod:
        kwargs["lumdist_mpc"] = float(mod["lumdist_mpc"])
    if "broaden_photometry" in mod:
        kwargs["broaden_photometry"] = bool(mod["broaden_photometry"])
    model = SedModel(csp, observations, **kwargs)
    if check:
        check_model_against_result(model, path, raise_on_difference=True)
    return model

ceridwen.resultfile.check_model_against_result

check_model_against_result(
    model, path, *, raise_on_difference=False
)

Compare model with the model recorded in the result file path.

Every recorded attribute and dataset of /model and /obs is compared exactly (priors, parameter names and shapes, transform names, zred, kinematics, cosmology, grid provenance and metallicity axes, the model wavelength grid, and every observation's data, mask, filters and instrument, and the likelihood settings fitSED records per observation, likelihood_json). theta_init values, and a record the file predates, are reported as notes only. Returns a :class:ResultComparison; with raise_on_difference a difference raises.

Source code in ceridwen/resultfile.py
def check_model_against_result(model, path, *, raise_on_difference: bool = False
                               ) -> ResultComparison:
    """Compare ``model`` with the model recorded in the result file ``path``.

    Every recorded attribute and dataset of ``/model`` and ``/obs`` is compared exactly
    (priors, parameter names and shapes, transform names, zred, kinematics, cosmology, grid
    provenance and metallicity axes, the model wavelength grid, and every observation's data,
    mask, filters and instrument, and the likelihood settings fitSED records per observation,
    ``likelihood_json``).  ``theta_init`` values, and a record the file predates, are reported
    as notes only.
    Returns a :class:`ResultComparison`; with ``raise_on_difference`` a difference raises.
    """
    from .fit import _require_logzsol_result
    import h5py

    path = str(path)
    with h5py.File(path, "r") as f:
        _require_logzsol_result(path, f)
    in_file = _read_record(path)
    in_model = _model_record(model)
    _csp_config_old_default(in_file)
    cmp = ResultComparison(path=path)
    for key in sorted(set(in_file) | set(in_model)):
        if key.split("@")[-1] in _IGNORED_MODEL_KEYS:
            continue
        a, b = in_file.get(key), in_model.get(key)
        if a is not None and b is not None and _same(a, b):
            continue
        entry = (key, _short(a), _short(b))
        is_init = key.startswith("/model/theta_init/")
        if a is None and (key in _ADDED_LATER
                          or key.split("@")[-1] in _ADDED_LATER_ATTRS):
            cmp.notes.append((key, "(not recorded by this file)", entry[2]))
        elif is_init and a is not None and b is not None and np.shape(a) == np.shape(b):
            cmp.notes.append(entry)
        else:
            cmp.differences.append(entry)
    if raise_on_difference and not cmp.ok:
        msg = str(cmp)
        cd = [_cfg(r.get("/model@csp_config")).get("cloudy_dust") for r in (in_file, in_model)]
        if cd[0] is not None and cd[0] != cd[1]:
            msg += (f"\n  csp_config['cloudy_dust']: the fit used {cd[0]}, this CSP {cd[1]}. "
                    f"Build the CSP with init_neb_params={{'cloudy_dust': {cd[0]}}} "
                    "(True: CLOUDY grids with dust in the H II region; the default is False).")
        raise ValueError(msg)
    return cmp

ceridwen.resultfile.priors_from_result

priors_from_result(path)

The prior objects of a result file, {name: Prior}, rebuilt from their serialisation.

Source code in ceridwen/resultfile.py
def priors_from_result(path) -> dict:
    """The prior objects of a result file, ``{name: Prior}``, rebuilt from their serialisation."""
    from .sampler import priors as _priors
    from .fit import read_result_h5

    out = {}
    for name, spec in read_result_h5(path)["model"]["priors"].items():
        if not isinstance(spec, dict) or "type" not in spec:
            raise ValueError(f"{path}: the prior of {name!r} was stored as {spec!r}, not as a "
                             "serialised ceridwen prior; rebuild it by hand")
        cls = getattr(_priors, spec["type"], None)
        if not (isinstance(cls, type) and issubclass(cls, _priors.Prior)):
            raise ValueError(f"{path}: the prior of {name!r} has unknown type {spec['type']!r}")
        kwargs = {k: v for k, v in spec.items() if k not in ("type", "name")}
        out[name] = cls(name=spec.get("name", ""), **kwargs)
    return out

ceridwen.optimize.map_fit

map_fit(
    model,
    n_starts=16,
    rng_key=None,
    *,
    include_init=True,
    max_steps=3000,
    ftol=1e-12,
    bounds=None,
    lnprob=None
)

Maximise fitSED's log-posterior of model with L-BFGS from many starts.

Parameters:

Name Type Description Default
model SedModel -- every free parameter needs a prior (starts are prior draws)
required
n_starts int -- number of prior draws to start from (>= 1)
16
rng_key PRNGKey -- draws the starts; default ``PRNGKey(0)``. Same key, same result.
None
include_init bool -- also start from ``model.theta_init`` (as start 0), as Prospector's

minimizer_ball does

True
max_steps L-BFGS stopping rule (see the module docstring)
3000
ftol L-BFGS stopping rule (see the module docstring)
3000
bounds dict -- {name: (low, high)} for the logit map; default ``fit._detect_bounds(model)``
None
lnprob callable -- a prebuilt ``build_lnprob(model)``, to share its compilation
None

Returns:

Type Description
MAPResult -- ``.theta`` is usable as ``free_param_init``
Source code in ceridwen/optimize.py
def map_fit(model, n_starts: int = 16, rng_key=None, *, include_init: bool = True,
            max_steps: int = 3000, ftol: float = 1e-12, bounds: dict | None = None,
            lnprob=None) -> MAPResult:
    """Maximise ``fitSED``'s log-posterior of ``model`` with L-BFGS from many starts.

    Parameters
    ----------
    model : SedModel -- every free parameter needs a prior (starts are prior draws)
    n_starts : int -- number of prior draws to start from (>= 1)
    rng_key : PRNGKey -- draws the starts; default ``PRNGKey(0)``.  Same key, same result.
    include_init : bool -- also start from ``model.theta_init`` (as start 0), as Prospector's
        ``minimizer_ball`` does
    max_steps, ftol : L-BFGS stopping rule (see the module docstring)
    bounds : dict -- {name: (low, high)} for the logit map; default ``fit._detect_bounds(model)``
    lnprob : callable -- a prebuilt ``build_lnprob(model)``, to share its compilation

    Returns
    -------
    MAPResult -- ``.theta`` is usable as ``free_param_init``
    """
    import optax
    from .fit import _detect_bounds
    from .sampler.nuts import _build_transforms, _to_constrained, _to_unconstrained

    t0 = time.perf_counter()
    n_starts = int(n_starts)
    if n_starts < 1:
        raise ValueError(f"map_fit: n_starts must be >= 1, got {n_starts}")
    if int(max_steps) < 1:
        raise ValueError(f"map_fit: max_steps must be >= 1, got {max_steps}")
    if rng_key is None:
        rng_key = jax.random.PRNGKey(0)
    _key = rng_key
    if jnp.issubdtype(jnp.asarray(_key).dtype, jax.dtypes.prng_key):
        _key = jax.random.key_data(_key)
    settings = {"n_starts": int(n_starts), "include_init": bool(include_init),
                "max_steps": int(max_steps), "ftol": float(ftol),
                "rng_key": np.asarray(_key).tolist(), "custom_lnprob": lnprob is not None}
    lnp_offset = 0.0
    if lnprob is None:
        lnprob = build_lnprob(model)
        lnp_offset = _loglike_offset(model)       # float32 mode only; 0.0 under float64
    template = {k: jnp.asarray(v, dtype=float_dtype()) for k, v in model.theta_init.items()}
    if bounds is None:
        bounds = _detect_bounds(model)
    else:
        unknown = sorted(set(bounds) - set(template))
        if unknown:
            raise ValueError(f"map_fit: bounds given for {unknown}, which are not free "
                             f"parameters ({list(template)})")
    lo, hi, isb = _build_transforms(bounds, template)

    def unflatten(flat):
        out, i = {}, 0
        for k, v in template.items():
            out[k] = flat[i:i + v.size].reshape(v.shape)
            i += v.size
        return out

    def theta_of(x):
        return unflatten(_to_constrained(x, lo, hi, isb))

    def _loss(x):
        v = -lnprob(theta_of(x))
        return jnp.where(jnp.isfinite(v), v, jnp.inf)

    @jax.custom_jvp
    def loss(x):
        return _loss(x)

    @loss.defjvp
    def _loss_jvp(primals, tangents):
        (x,), (dx,) = primals, tangents
        v, g = jax.value_and_grad(_loss)(x)
        return v, jnp.where(jnp.isfinite(g), g, 0.0) @ dx

    opt = optax.lbfgs()
    value_and_grad = optax.value_and_grad_from_state(loss)

    @jax.jit
    def run_one(x0):
        def step(carry):
            x, state, f_now, _ = carry
            value, grad = value_and_grad(x, state=state)
            updates, state = opt.update(grad, state, x, value=value, grad=grad,
                                        value_fn=loss)
            return optax.apply_updates(x, updates), state, value, f_now

        def cont(carry):
            _, state, f_now, f_prev = carry
            it = optax.tree_utils.tree_get(state, "count")
            moving = jnp.abs(f_prev - f_now) > ftol * (1.0 + jnp.abs(f_now))
            return (it < 2) | ((it < max_steps) & moving)

        x, state, _, _ = jax.lax.while_loop(
            cont, step, (x0, opt.init(x0), jnp.inf, -jnp.inf))
        return (x, -loss(x), optax.tree_utils.tree_get(state, "count"),
                optax.tree_utils.tree_l2_norm(jax.grad(loss)(x)))

    # Starts run one after another through one compiled solver: under vmap a batched
    # while_loop runs every lane until the slowest start ends and evaluates both branches of
    # the zoom line search (the recipe measured 1018 s for 16 starts vs ~5 s per start).
    starts = _prior_starts(model, n_starts, rng_key, include_init)
    n_total = next(iter(starts.values())).shape[0]
    # flatten in template key order explicitly (never rely on a dict's order under jit/vmap)
    flat0 = jnp.concatenate([starts[k].reshape(n_total, -1) for k in template], axis=1)
    x0s = jax.vmap(lambda f: _to_unconstrained(f, lo, hi, isb))(flat0)
    out = [run_one(x0s[i]) for i in range(n_total)]
    lnps = np.array([float(o[1]) for o in out]) + lnp_offset
    good = np.isfinite(lnps)
    if not good.any():
        raise RuntimeError("map_fit: every start ended at a non-finite ln posterior")
    best = int(np.argmax(np.where(good, lnps, -np.inf)))
    theta = {k: np.asarray(v) for k, v in theta_of(out[best][0]).items()}
    return MAPResult(theta=theta, lnp=float(lnps[best]), lnp_starts=lnps,
                     theta_starts={k: np.asarray(v) for k, v in starts.items()},
                     n_steps=np.array([int(o[2]) for o in out]),
                     grad_norm=np.array([float(o[3]) for o in out]),
                     best_start=best, wall_time=time.perf_counter() - t0,
                     bounds=dict(bounds), settings=settings)

ceridwen.optimize.MAPResult dataclass

MAPResult(
    theta,
    lnp,
    lnp_starts,
    theta_starts,
    n_steps,
    grad_norm,
    best_start,
    wall_time,
    bounds=dict(),
    settings=dict(),
)

Result of :func:map_fit.

theta : dict -- best theta (constrained), shapes of model.theta_init (NumPy) lnp : float -- ln posterior at theta lnp_starts : (n,) -- final ln posterior of every start theta_starts: dict -- the starting points, {name: (n, *shape)} n_steps : (n,) -- L-BFGS iterations per start grad_norm : (n,) -- final |grad| in the unconstrained space, per start best_start : int -- index of the winning start wall_time : float -- seconds, compile included bounds : dict -- the bounds used for the logit map settings : dict -- n_starts, include_init, max_steps, ftol, rng_key (key data) and whether a custom lnprob was passed: what reproduces the run

free_param_init property

free_param_init

theta as JAX arrays of the working float dtype, for SedModel(..., free_param_init=...).

__repr__

__repr__()

Short: the best point, not every start (the per-start arrays stay attributes).

Source code in ceridwen/optimize.py
def __repr__(self) -> str:
    """Short: the best point, not every start (the per-start arrays stay attributes)."""
    return self.summary() + "\n  (per start: .lnp_starts, .theta_starts, .n_steps, .grad_norm)"

ceridwen.sampler.run_sampler

run_sampler(
    model, likelihood, adapter, rng_key, theta_init=None
)

Build JIT loglike_fn (summed over observations, no prior) and logprior_fn from model/likelihood and delegate to adapter.run. theta_init (default model.theta_init) is the start handed to the adapter, e.g. a MAP from ceridwen.optimize.map_fit; it must have the keys and shapes of model.theta_init.

Source code in ceridwen/sampler/runner.py
def run_sampler(
    model      : Any,
    likelihood : Any,
    adapter    : SamplerAdapter,
    rng_key    : Array,
    theta_init : dict[str, Array] | None = None,
) -> SamplingResult:
    """Build JIT ``loglike_fn`` (summed over observations, no prior) and
    ``logprior_fn`` from ``model``/``likelihood`` and delegate to ``adapter.run``.
    ``theta_init`` (default ``model.theta_init``) is the start handed to the adapter, e.g. a
    MAP from ``ceridwen.optimize.map_fit``; it must have the keys and shapes of
    ``model.theta_init``."""
    if theta_init is None:
        theta_init = model.theta_init
    else:
        want = {k: tuple(jnp.shape(v)) for k, v in model.theta_init.items()}
        got = {k: tuple(jnp.shape(v)) for k, v in theta_init.items()}
        if want != got:
            raise ValueError(f"run_sampler: theta_init has keys/shapes {got}, the model's "
                             f"free parameters are {want}")
        theta_init = {k: jnp.asarray(theta_init[k]) for k in model.theta_init}
    _obs_dict    = model.obs_dict
    _keys        = tuple(likelihood.keys)
    _likelihoods = tuple(likelihood.likelihoods)
    from ..likelihood.likelihood import (observation_data, float32_rescaling, rescaled_params,
                                         loglike_offset)
    for key in _keys:
        if getattr(_obs_dict[key], "flux", None) is None:
            raise ValueError(f"run_sampler: observation {key!r} has no flux; give it flux= and "
                             f"uncertainty= to fit it (without them it serves predictions only)")
    _static_data = {key: observation_data(_obs_dict[key]) for key in _keys}
    # float32 mode (docs/mac_gpu.md): the kernels run on rescaled data; ln L comes back offset
    # by a constant of the observations, added to the reported ln L / ln Z below (None in float64)
    _rescalings = {key: float32_rescaling(_obs_dict[key], lh) for key, lh in zip(_keys, _likelihoods)}
    _offset = loglike_offset(_rescalings.values())

    if getattr(model, "_eline_system", None) is not None:
        from ..likelihood.eline_marginal import joint_loglike

        @jax.jit
        def loglike_fn(theta: dict[str, Array]) -> Array:
            return joint_loglike(model, _keys, _likelihoods, _static_data, theta)

        @jax.jit
        def logprior_fn(theta: dict[str, Array]) -> Array:
            return model.ln_prior(theta)

        return adapter.run(loglike_fn, logprior_fn, theta_init, rng_key)

    @jax.jit
    def loglike_fn(theta: dict[str, Array]) -> Array:
        predictions = model.predict(theta)
        lnl = jnp.zeros(())
        for key, lhood in zip(_keys, _likelihoods):
            y_k, sig_k, mask_k, calib_k, ul_k = _static_data[key]
            th = rescaled_params(theta, _rescalings[key])
            mu_k = predictions[key]
            if calib_k is not None:
                mu_k = mu_k * calib_k
            if ul_k is not None:
                lnl_k, _ = lhood(y_k, mu_k, sig_k, mask_k, params=th, is_upper_limit=ul_k)
            else:
                lnl_k, _ = lhood(y_k, mu_k, sig_k, mask_k, params=th)
            lnl = lnl + lnl_k
        return lnl

    @jax.jit
    def logprior_fn(theta: dict[str, Array]) -> Array:
        return model.ln_prior(theta)

    result = adapter.run(loglike_fn, logprior_fn, theta_init, rng_key)
    if _offset != 0.0:
        result = _with_loglike_offset(result, _offset)
    return result

ceridwen.sampler.nested.BlackJAXNestedSamplerAdapter

BlackJAXNestedSamplerAdapter(
    priors,
    num_live=500,
    num_inner_steps=None,
    num_delete=None,
    logZ_tol=-5.0,
    verbose=True,
    checkpoint_interval_s=1200.0,
    checkpoint_dir=None,
    resume_from=None,
    slice_kernel="lanes",
)

Bases: SamplerAdapter

Nested-sampling adapter driving the NSS kernel with a Ceridwen SedModel.

Parameters:

Name Type Description Default
priors dict[str, Prior] -- every free parameter needs a proper prior
required
num_inner_steps int -- inner MCMC steps per iteration; default n_dims * 5
None
num_delete int -- live points removed per iteration; default max(1, num_live // 5), must be < num_live
None
logZ_tol float -- stop when ln(Z_live / Z) < logZ_tol; default -5
-5.0
checkpoint_interval_s float -- seconds between checkpoints; <= 0 disables
1200.0
checkpoint_dir str -- falls back to $CERIDWEN_CHECKPOINT_DIR, then $CERIDWEN_RESCUE_DIR, else off
None
resume_from str -- a periodic checkpoint (``ns_checkpoint_<pid>.pkl``) to continue from

instead of starting afresh. The run continues with the saved live points, dead points and rng key, so it reproduces the uninterrupted run at the same key. The checkpoint must come from the same model: the settings, the parameter shapes and the log-likelihood of the saved live points are checked before sampling resumes.

None
slice_kernel ('lanes', 'stock', 'carry')

"stock" is the unchanged blackjax.nss. "carry" assembles the same kernel with :func:stepping_out_carry, which evaluates each stepping-out edge once instead of twice under vmap; same random numbers and evaluations, so on CPU the samples, evidence and call counts are bitwise equal to "stock". "lanes" runs every particle's chain of slice steps as one lane of a shared loop (:func:lane_update; Dance et al. 2025): lanes do not wait for the slowest one inside each slice step, candidates below the prior slice level skip the likelihood, and idle batch slots evaluate look-ahead candidates. Equal to "stock" on CPU (bitwise on Apple silicon, to the last bits on x86, so long runs can separate there), except that a particle whose moves were all rejected is born at the contour it replaced (blackjax 1.7's rule, which "stock" follows from 1.7 on; with 1.6 the births, weights and ln Z of such chains differ); on GPU the likelihood batches differ in composition, so float rounding can make the trajectories separate after many iterations (statistically equivalent, not bitwise; GPU runs of either kernel are not bit-reproducible between processes anyway). The default since it is the fastest: 3.5-3.8x faster sampling than "stock" on an A100 for the JADES campaign model, and more on CPU.

"lanes"
Source code in ceridwen/sampler/nested.py
def __init__(
    self,
    priors          : dict,
    num_live        : int   = 500,
    num_inner_steps : Optional[int] = None,
    num_delete      : Optional[int] = None,
    logZ_tol        : float = -5.0,
    verbose         : bool  = True,
    checkpoint_interval_s : float = 1200.0,
    checkpoint_dir        : Optional[str] = None,
    resume_from           : Optional[str] = None,
    slice_kernel          : str = "lanes",
):
    if slice_kernel not in SLICE_KERNELS:
        raise ValueError(f"slice_kernel={slice_kernel!r}: choose one of {SLICE_KERNELS}")
    self.slice_kernel    = slice_kernel
    self.priors          = dict(priors)
    self.num_live        = int(num_live)
    self._num_inner_steps = num_inner_steps
    self._num_delete      = num_delete
    self.logZ_tol        = float(logZ_tol)
    self.verbose         = bool(verbose)
    self.checkpoint_interval_s = float(checkpoint_interval_s)
    self._checkpoint_dir       = checkpoint_dir
    self.resume_from           = None if resume_from is None else str(resume_from)
    if self.resume_from is not None and not os.path.isfile(self.resume_from):
        raise FileNotFoundError(f"resume_from={self.resume_from!r}: no such checkpoint")

load_checkpoint staticmethod

load_checkpoint(path)

Load a checkpoint/rescue pickle: {positions, loglikelihood, loglikelihood_birth, logZ, n_dead, partial}.

Source code in ceridwen/sampler/nested.py
@staticmethod
def load_checkpoint(path):
    """Load a checkpoint/rescue pickle: {positions, loglikelihood, loglikelihood_birth, logZ, n_dead, partial}."""
    import pickle as _pickle
    with open(path, "rb") as fh:
        return _pickle.load(fh)

run

run(loglike_fn, logprior_fn, theta_init, rng_key)

Run nested sampling and return a SamplingResult; logprior_fn must be proper.

Source code in ceridwen/sampler/nested.py
def run(
    self,
    loglike_fn  : Callable[[dict[str, Array]], Array],
    logprior_fn : Callable[[dict[str, Array]], Array],
    theta_init  : dict[str, Array],
    rng_key     : Array,
) -> SamplingResult:
    """Run nested sampling and return a ``SamplingResult``; ``logprior_fn`` must be proper."""
    import numpy as np
    # seed of the ln Z error estimate (anesthetic draws it from numpy's global RNG): derived
    # from rng_key, so the same key gives the same error, and the global RNG is restored
    _err_seed = int(np.asarray(jax.random.randint(
        jax.random.fold_in(rng_key, 0x5EED), (), 0, 2 ** 31 - 1)))
    try:
        import blackjax
        import blackjax.ns.utils as ns_utils
    except ImportError as exc:
        raise ImportError(
            "BlackJAX with nested sampling (blackjax.ns) is required.\n"
            "Install: pip install -U 'blackjax>=1.6'"
        ) from exc

    import tqdm

    # a NaN ln L (an overflow in the forward model) would make logZ_live NaN, and the
    # termination test then passes at iteration 0 with no likelihood call: treat it as -inf,
    # a point outside the support (finite values pass through unchanged)
    _loglike_raw = loglike_fn

    def loglike_fn(theta):
        lnl = _loglike_raw(theta)
        return jnp.where(jnp.isnan(lnl), -jnp.inf, lnl)

    n_dims          = self._n_dims(theta_init)
    num_inner_steps = (self._num_inner_steps
                       if self._num_inner_steps is not None
                       else n_dims * 5)
    num_delete      = (self._num_delete
                       if self._num_delete is not None
                       else max(1, self.num_live // 5))

    if self.verbose:
        print(
            f"BlackJAX NSS ({self.slice_kernel})  |  n_dims={n_dims}  "
            f"num_live={self.num_live}  "
            f"num_inner_steps={num_inner_steps}  "
            f"num_delete={num_delete}"
        )

    _config = self._run_config(theta_init, num_inner_steps, num_delete)
    _resume = (self._load_resume(_config, loglike_fn)
               if self.resume_from is not None else None)
    if _resume is None:
        rng_key, prior_key = jax.random.split(rng_key)
        particles = self._sample_prior(theta_init, prior_key)

    nested_sampler = self._build_nested_sampler(
        loglike_fn, logprior_fn, num_inner_steps, num_delete)
    init_fn = jax.jit(nested_sampler.init)
    step_fn = jax.jit(nested_sampler.step)

    if self.verbose:
        print("  [timing] Calling init_fn (JIT compile + eval) ...",
              flush=True)
        _t0 = time.perf_counter()

    if _resume is None:
        live = init_fn(particles)
    else:
        # the saved state replaces the prior draw, init and the first iterations
        live = jax.tree_util.tree_map(jnp.asarray, _resume["live"])
        rng_key = jnp.asarray(_resume["rng_key"])

    def _logz_fields(state):
        if hasattr(state, "logZ") and hasattr(state, "logZ_live"):
            return state.logZ, state.logZ_live
        ig = getattr(state, "integrator", None)
        if ig is not None and hasattr(ig, "logZ") and hasattr(ig, "logZ_live"):
            return ig.logZ, ig.logZ_live
        inner = getattr(state, "sampler_state", None)
        if inner is not None and hasattr(inner, "logZ") and hasattr(inner, "logZ_live"):
            return inner.logZ, inner.logZ_live
        raise AttributeError(
            f"Cannot locate logZ/logZ_live on {type(state).__name__} "
            f"(fields {[f for f in dir(state) if not f.startswith('_')]}); "
            "check your BlackJAX version.")

    def _logz(state):
        a, b = jax.device_get(_logz_fields(state))
        return float(a), float(b)

    _get_logZ = lambda s: _logz(s)[0]

    if self.verbose:
        _t1 = time.perf_counter()
        lz, lzl = _logz(live)
        print(f"  [timing] init_fn done    ({_t1 - _t0:.1f} s)  "
              f"logZ={lz:.4f}  logZ_live={lzl:.4f}", flush=True)

    dead_list    = [] if _resume is None else list(_resume["dead"])
    n_like_calls = 0 if _resume is None else _resume["n_like_calls"]
    _elapsed0    = 0.0 if _resume is None else _resume["elapsed_s"]
    t_start      = time.perf_counter()
    if _resume is not None and self.verbose:
        print(f"  [resume] {self.resume_from}: iteration {_resume['n_iter']}, "
              f"{len(dead_list) * num_delete} dead points", flush=True)

    _ckpt_dir   = self._resolve_ckpt_dir()
    _ckpt_on    = bool(_ckpt_dir) and self.checkpoint_interval_s > 0
    _last_ckpt  = t_start
    if _ckpt_on and self.verbose:
        print(f"  [checkpoint] every {self.checkpoint_interval_s:.0f} s "
              f"-> {_ckpt_dir}", flush=True)
    elif self.verbose:
        print("  [checkpoint] off (set checkpoint_dir= or $CERIDWEN_CHECKPOINT_DIR "
              "to write recoverable snapshots)", flush=True)

    logZ, logZ_live = _logz(live)
    with tqdm.tqdm(desc=f"NS  logZ={logZ:.1f}", unit=" dead",
                   disable=not self.verbose) as pbar:
        _iter = 0 if _resume is None else _resume["n_iter"]
        while logZ_live - logZ >= self.logZ_tol:
            rng_key, subkey = jax.random.split(rng_key)
            if _iter == (0 if _resume is None else _resume["n_iter"]) and self.verbose:
                pbar.write("  [step_fn] compiling the step kernel (one-time JIT)")
            _t_iter = time.perf_counter()
            live, dead_info = step_fn(subkey, live)
            logZ, logZ_live = _logz(live)
            _dt_iter = time.perf_counter() - _t_iter
            _iter += 1
            dead_list.append(dead_info)
            n_like_calls += num_delete * num_inner_steps
            pbar.update(num_delete)
            pbar.set_description(f"NS  logZ={logZ:.2f}  dlogZ={logZ_live - logZ:.2f}",
                                 refresh=False)
            pbar.set_postfix({"s/iter": f"{_dt_iter:.1f}"}, refresh=False)

            if _ckpt_on and (time.perf_counter() - _last_ckpt
                             >= self.checkpoint_interval_s):
                _p = self._dump_snapshot(
                    _ckpt_dir, live, dead_list, ns_utils,
                    logZ, tag="checkpoint", partial=True,
                    resume=self._resume_block(
                        live, dead_list, rng_key, _iter, n_like_calls,
                        _elapsed0 + time.perf_counter() - t_start, _config))
                _last_ckpt = time.perf_counter()
                if _p and self.verbose:
                    pbar.write(f"  [checkpoint] iter {_iter}: {_p}")

    wall_time = _elapsed0 + time.perf_counter() - t_start
    if self.verbose:
        from ..precision import float_dtype
        _units = ", in the sampler's rescaled units" if float_dtype() == jnp.float32 else ""
        print(
            f"  Converged  (live-point logZ estimate {_get_logZ(live):.3f}{_units}; the final "
            f"ln Z follows)  ({wall_time:.1f} s,  {n_like_calls:,} likelihood calls)"
        )
    if n_like_calls == 0 and _resume is None:
        import warnings
        warnings.warn("nested sampling stopped before its first iteration (0 likelihood "
                      "calls): the live points' ln L is not finite; check the model at the "
                      "prior draws", stacklevel=2)

    _dead_positions, _dead_logl, _dead_logl_birth = self._finalise_dead(
        live, dead_list, ns_utils)

    _rescue_dir = self._resolve_ckpt_dir()
    if _rescue_dir:
        self._dump_snapshot(_rescue_dir, live, dead_list, ns_utils,
                            _get_logZ(live), tag="rescue", partial=False,
                            finalised=(_dead_positions, _dead_logl, _dead_logl_birth))

    # dead set is in deletion order, NOT sorted by logL; weights follow sample order
    import numpy as np
    from .ns_weights import nested_log_weights, log_evidence_from_weights
    _logl_np    = np.asarray(_dead_logl)
    _birth_np   = np.asarray(_dead_logl_birth)
    _lw_np      = nested_log_weights(_logl_np, _birth_np)
    log_weights = jnp.asarray(_lw_np)
    log_Z       = None
    log_Z_err   = float("nan")
    try:
        from anesthetic import NestedSamples

        _raw   = _dead_positions
        _names = [n for n in _raw if n in theta_init]
        _cols  = [np.asarray(_raw[n]).reshape(_logl_np.shape[0], -1) for n in _names]
        _data  = np.hstack(_cols)
        _ns    = NestedSamples(
            _data,
            logL       = _logl_np,
            logL_birth = _birth_np,
            logzero    = float("nan"),
        )
        log_Z     = float(_ns.logZ())
        _state = np.random.get_state()
        try:
            np.random.seed(_err_seed)
            log_Z_err = float(_ns.logZ(12).std())
        finally:
            np.random.set_state(_state)
    except Exception:
        pass
    if log_Z is None:
        log_Z = log_evidence_from_weights(_lw_np)

    samples = {}
    for name in theta_init:
        arr = jnp.asarray(_dead_positions[name])
        if arr.ndim > 1 and arr.shape[-1] == 1:
            arr = jnp.squeeze(arr, axis=-1)
        samples[name] = arr

    return SamplingResult(
        samples               = samples,
        log_evidence          = log_Z,
        log_evidence_err      = log_Z_err,
        log_weights           = log_weights,
        log_likelihoods       = jnp.asarray(_dead_logl),
        log_likelihoods_birth = jnp.asarray(_dead_logl_birth),
        param_names           = list(theta_init.keys()),
        n_likelihood_calls    = n_like_calls,
        wall_time_s           = wall_time,
        sampler_name          = "blackjax.nss",
        raw                   = {
            "positions": _dead_positions,
            "loglikelihood": _dead_logl,
            "loglikelihood_birth": _dead_logl_birth,
        },
    )

ceridwen.sampler.nuts.BlackJAXNUTSAdapter

BlackJAXNUTSAdapter(
    num_warmup=None,
    num_samples=2000,
    num_chains=4,
    initial_step_size=None,
    target_acceptance=0.95,
    max_num_doublings=10,
    dense_mass=None,
    bounds=None,
    vi=None,
    vi_kwargs=None,
    verbose=True,
)

Bases: SamplerAdapter

NUTS adapter with window adaptation; bounded (uniform-prior) parameters are sampled in sigmoid/logit space, and an optional VI map (vi) whitens the target before sampling.

Parameters:

Name Type Description Default
num_warmup int -- adaptation steps per chain; default 1500 (200 with ``vi``)
None
num_samples int -- post-warmup draws per chain
2000
initial_step_size float -- leapfrog step before adaptation; default 0.01 (0.5 with ``vi``)
None
target_acceptance float -- dual-averaging target
0.95
max_num_doublings int -- max tree depth (2**n leapfrog steps)
10
dense_mass bool -- full inverse mass matrix; default True (False with ``vi``)
None
bounds dict -- name -> (low, high) for the logit map; None = no bounded parameters

(the adapter never sees the priors; fitSED passes fit._detect_bounds(model))

None
vi None | 'tril' | 'iaf' | VariationalMap | TrainedMap -- variational preconditioning
None
vi_kwargs dict -- map constructor kwargs plus ``num_steps``, ``batch_size``, ``lr0`` for training
None
Notes

One window_adaptation run is shared by all chains. Without vi every chain starts from its end state and differs only by its rng key, so the printed split R-hat measures mixing within that one run: it cannot detect a warmup that settled in one of several modes. With vi the chains start from independent N(0, 1) draws in the whitened space (no burn-in). The printed ESS is the sum of the per-chain ESS (ceridwen.plotting._ess, the estimator of the diagnostic figure).

Source code in ceridwen/sampler/nuts.py
def __init__(
    self,
    num_warmup: int | None = None,
    num_samples: int = 2000,
    num_chains: int = 4,
    initial_step_size: float | None = None,
    target_acceptance: float = 0.95,
    max_num_doublings: int = 10,
    dense_mass: bool | None = None,
    bounds: dict[str, tuple[float, float]] | None = None,
    vi: "str | Any | None" = None,
    vi_kwargs: dict | None = None,
    verbose: bool = True,
):
    _has_vi = vi is not None
    if num_warmup is None:
        num_warmup = 200 if _has_vi else 1500
    if initial_step_size is None:
        initial_step_size = 0.5 if _has_vi else 0.01
    if dense_mass is None:
        dense_mass = not _has_vi

    self.num_warmup = int(num_warmup)
    self.num_samples = int(num_samples)
    self.num_chains = int(num_chains)
    self.initial_step_size = float(initial_step_size)
    self.target_acceptance = float(target_acceptance)
    self.max_num_doublings = int(max_num_doublings)
    self.dense_mass = bool(dense_mass)
    self.bounds = dict(bounds) if bounds is not None else None
    self.vi = vi
    self.vi_kwargs = dict(vi_kwargs) if vi_kwargs is not None else {}
    self.verbose = bool(verbose)
    self.trained_map = None

run

run(loglike_fn, logprior_fn, theta_init, rng_key)

Run NUTS (one warmup, then all chains) and return a SamplingResult in constrained space.

Source code in ceridwen/sampler/nuts.py
def run(
    self,
    loglike_fn: Callable[[dict[str, Array]], Array],
    logprior_fn: Callable[[dict[str, Array]], Array],
    theta_init: dict[str, Array],
    rng_key: Array,
) -> SamplingResult:
    """Run NUTS (one warmup, then all chains) and return a ``SamplingResult`` in constrained space."""
    try:
        import blackjax
    except ImportError as exc:
        raise ImportError(
            "BlackJAX is required for NUTS sampling.\n"
            "Install: pip install -U 'blackjax>=1.6'"
        ) from exc

    if self.vi is not None:
        return self._run_whitened(
            loglike_fn, logprior_fn, theta_init, rng_key,
        )

    n_dims = self._n_dims(theta_init)
    theta_template = theta_init
    bounds = self.bounds if self.bounds is not None else {}

    if self.verbose:
        print(
            f"BlackJAX NUTS  |  n_dims={n_dims}  "
            f"num_warmup={self.num_warmup}  "
            f"num_samples={self.num_samples}  "
            f"num_chains={self.num_chains}  "
            f"dense_mass={self.dense_mass}"
        )
        if bounds:
            for k, (a, b) in bounds.items():
                print(f"  Bounded: {k} -> sigmoid({a}, {b})")
        else:
            print("  No bounded parameters (consider passing bounds=...)")

    lo, hi, is_bounded = _build_transforms(bounds, theta_template)
    n_bounded = int(jnp.sum(is_bounded))

    if self.verbose and n_bounded > 0:
        print(f"  Reparameterised {n_bounded}/{n_dims} "
              f"bounded dimensions via sigmoid/logit")

    @jax.jit
    def logposterior_flat(x):
        theta_flat = _to_constrained(x, lo, hi, is_bounded)
        theta = self._unflatten(theta_flat, theta_template)
        lnl = loglike_fn(theta)
        lnp = logprior_fn(theta)
        lnj = _log_jacobian(x, lo, hi, is_bounded)
        return lnl + lnp + lnj

    @jax.jit
    def _prior_and_jacobian(x):
        theta_flat = _to_constrained(x, lo, hi, is_bounded)
        theta = self._unflatten(theta_flat, theta_template)
        return logprior_fn(theta) + _log_jacobian(x, lo, hi, is_bounded)

    def _loglike_of(states_):
        return states_.logdensity - jax.vmap(_prior_and_jacobian)(states_.position)

    x_init_flat = self._flatten(theta_init)
    x_init = _to_unconstrained(x_init_flat, lo, hi, is_bounded)

    t_start = time.perf_counter()

    if self.verbose:
        print(f"\n  Warmup ({self.num_warmup} steps, "
              f"adapting step size + {'dense' if self.dense_mass else 'diagonal'} mass matrix)...")

    warmup = blackjax.window_adaptation(
        blackjax.nuts,
        logposterior_flat,
        target_acceptance_rate=self.target_acceptance,
        initial_step_size=self.initial_step_size,
        is_mass_matrix_diagonal=not self.dense_mass,
        max_num_doublings=self.max_num_doublings,
    )

    warmup_key, sample_key = jax.random.split(rng_key)

    _t0_warmup = time.perf_counter()
    (warmup_state, parameters), _ = warmup.run(
        warmup_key,
        x_init,
        num_steps=self.num_warmup,
    )
    jax.block_until_ready(warmup_state.position)
    _t_warmup = time.perf_counter() - _t0_warmup

    step_size = parameters['step_size']
    if self.verbose:
        print(f"    Adapted step size: {float(step_size):.4f}")
        if self.dense_mass:
            im = np.asarray(parameters['inverse_mass_matrix'])
            cond = np.linalg.cond(im)
            print(f"    Mass matrix condition number: {cond:.1f}")
        print(f"    Warmup wall time: {_t_warmup:.1f} s  "
              f"(includes XLA compilation)")

    nuts_kernel = blackjax.nuts(
        logposterior_flat,
        **parameters,
    ).step

    def _nuts_step(state, key):
        state, info = nuts_kernel(key, state)
        return state, (state, info)

    @jax.jit
    def _run_one_chain(init_state, chain_key):
        keys = jax.random.split(chain_key, self.num_samples)
        final_state, (states, infos) = jax.lax.scan(
            _nuts_step, init_state, keys
        )
        return states, infos

    chain_keys = jax.random.split(sample_key, self.num_chains)

    n_devices = len(jax.devices())
    use_pmap = (n_devices >= self.num_chains) and (self.num_chains > 1)

    if self.verbose:
        print(f"\n  Available devices: {n_devices}  |  "
              f"Chains: {self.num_chains}  |  "
              f"Strategy: {'pmap (one chain per GPU)' if use_pmap else 'sequential'}")

    all_chain_positions = []
    all_loglikelihoods = []
    all_divergences = []
    all_infos = []
    _t_sample_chains = []
    _t_postproc_chains = []

    if use_pmap:
        if self.verbose:
            print(f"\n  Running {self.num_chains} chains in parallel "
                  f"across {self.num_chains} GPUs...", flush=True)

        def _replicate_state(state, n):
            return jax.tree.map(
                lambda x: jnp.broadcast_to(x, (n,) + x.shape), state
            )

        pmap_init = _replicate_state(warmup_state, self.num_chains)

        @jax.pmap
        def _run_chains_pmap(init_state, chain_key):
            keys = jax.random.split(chain_key, self.num_samples)
            final_state, (states, infos) = jax.lax.scan(
                _nuts_step, init_state, keys
            )
            return states, infos

        _t0_sample = time.perf_counter()
        pmap_states, pmap_infos = _run_chains_pmap(
            pmap_init, chain_keys
        )
        jax.block_until_ready(pmap_states.position)
        _t_sample_total = time.perf_counter() - _t0_sample

        if self.verbose:
            print(f"    All chains wall time: {_t_sample_total:.1f} s  "
                  f"(parallel across {self.num_chains} GPUs)")

        _t0_pp = time.perf_counter()
        for ci in range(self.num_chains):
            x_chain = pmap_states.position[ci]
            theta_chain = jax.vmap(
                lambda x: _to_constrained(x, lo, hi, is_bounded)
            )(x_chain)
            all_chain_positions.append(theta_chain)
            all_loglikelihoods.append(
                _loglike_of(jax.tree.map(lambda x: x[ci], pmap_states)))

            chain_infos = jax.tree.map(lambda x: x[ci], pmap_infos)
            all_infos.append(chain_infos)
            if hasattr(chain_infos, 'is_divergent'):
                n_div = int(jnp.sum(chain_infos.is_divergent))
                all_divergences.append(n_div)
                if self.verbose and n_div > 0:
                    print(f"    Chain {ci+1}: {n_div} divergent transitions!")
            else:
                all_divergences.append(0)

        _t_pp = time.perf_counter() - _t0_pp
        _t_sample_chains = [_t_sample_total / self.num_chains] * self.num_chains
        _t_postproc_chains = [_t_pp / self.num_chains] * self.num_chains

        if self.verbose:
            print(f"    Post-processing: {_t_pp:.1f} s")

    else:
        for chain_idx in range(self.num_chains):
            if self.verbose:
                print(f"\n  Chain {chain_idx + 1}/{self.num_chains}  "
                      f"({self.num_samples} draws)...", flush=True)

            _t0_sample = time.perf_counter()
            states, infos = _run_one_chain(warmup_state, chain_keys[chain_idx])
            jax.block_until_ready(states.position)
            _t_sample = time.perf_counter() - _t0_sample
            _t_sample_chains.append(_t_sample)

            if self.verbose:
                print(f"    Sampling wall time: {_t_sample:.1f} s")

            _t0_pp = time.perf_counter()

            x_chain = states.position
            theta_chain = jax.vmap(
                lambda x: _to_constrained(x, lo, hi, is_bounded)
            )(x_chain)
            all_chain_positions.append(theta_chain)
            all_loglikelihoods.append(_loglike_of(states))

            all_infos.append(infos)
            if hasattr(infos, 'is_divergent'):
                n_div = int(jnp.sum(infos.is_divergent))
                all_divergences.append(n_div)
                if self.verbose and n_div > 0:
                    print(f"    WARNING: {n_div} divergent transitions!")
            else:
                all_divergences.append(0)

            _t_pp = time.perf_counter() - _t0_pp
            _t_postproc_chains.append(_t_pp)

            if self.verbose:
                print(f"    Post-processing wall time: {_t_pp:.1f} s")

    n_like_calls = self.num_chains * (self.num_warmup + self.num_samples)
    wall_time = time.perf_counter() - t_start

    _t_merge_start = time.perf_counter()

    if self.verbose:
        _t_sample_total = sum(_t_sample_chains)
        _t_pp_total = sum(_t_postproc_chains)
        print("\n  " + "=" * 60)
        print("  NUTS timing breakdown")
        print("  " + "=" * 60)
        print(f"  {'Phase':<40s}  {'Time':>10s}")
        print("  " + "-" * 60)
        print(f"  {'Warmup (incl. XLA compilation)':<40s}  {_t_warmup:>9.1f}s")
        if use_pmap:
            print(f"  {'Sampling (pmap, all chains parallel)':<40s}  "
                  f"{_t_sample_total:>9.1f}s")
        else:
            for ci in range(self.num_chains):
                print(f"  {'  Chain ' + str(ci+1) + ' sampling':<40s}  "
                      f"{_t_sample_chains[ci]:>9.1f}s")
            print(f"  {'Sampling total (sequential)':<40s}  {_t_sample_total:>9.1f}s")
        print(f"  {'Post-processing total':<40s}  {_t_pp_total:>9.1f}s")
        print("  " + "-" * 60)
        print(f"  {'TOTAL':<40s}  {wall_time:>9.1f}s")
        if use_pmap:
            seq_est = _t_sample_total * self.num_chains
            print(f"  {'Estimated sequential time':<40s}  {seq_est:>9.1f}s")
            print(f"  {'pmap speedup':<40s}  {seq_est / _t_sample_total:>9.1f}x")
        print("  " + "=" * 60)

    merged_flat = jnp.concatenate(all_chain_positions, axis=0)

    merged_samples = {}
    idx = 0
    for name, template in theta_template.items():
        size = int(jnp.size(template))
        arr = merged_flat[:, idx:idx + size]
        if arr.shape[-1] == 1:
            arr = jnp.squeeze(arr, axis=-1)
        merged_samples[name] = arr
        idx += size

    merged_lnl = jnp.concatenate(all_loglikelihoods, axis=0)

    total_divergences = sum(all_divergences)
    _t_merge = time.perf_counter() - _t_merge_start

    if self.verbose:
        print(
            f"\n  Done  ({wall_time:.1f} s total,  "
            f"merge {_t_merge:.1f} s,  "
            f"{n_like_calls:,} likelihood calls"
            f"{f', {total_divergences} divergences' if total_divergences else ''})"
        )

    if self.verbose and self.num_chains >= 2:
        self._print_diagnostics(
            all_chain_positions, theta_template,
            note="within-run mixing only: every chain starts from the one warmup end "
                 "state, so R-hat cannot detect a warmup stuck in one mode")

    return SamplingResult(
        samples=merged_samples,
        log_evidence=float("nan"),
        log_evidence_err=float("nan"),
        log_weights=jnp.zeros_like(merged_lnl),
        log_likelihoods=merged_lnl,
        param_names=list(theta_init.keys()),
        n_likelihood_calls=n_like_calls,
        wall_time_s=wall_time,
        sampler_name="blackjax.nuts",
        raw={
            "num_chains": self.num_chains,
            "num_warmup": self.num_warmup,
            "num_samples": self.num_samples,
            "total_divergences": total_divergences,
            "dense_mass": self.dense_mass,
            "per_chain_constrained": all_chain_positions,
            "per_chain_infos": all_infos,
            "used_pmap": use_pmap,
            "n_devices": n_devices,
        },
    )

Post-processing

ceridwen.postprocess.PostProcess

PostProcess(
    model,
    result,
    *,
    n_samples=None,
    seed=0,
    windows_myr=DEFAULT_WINDOWS_MYR,
    sfr=True,
    ssfr=True,
    uv=True,
    ionizing=True,
    predictions=True,
    derived=None,
    batch_size=256,
    mfrac=None
)

Posterior post-processing of a fit.

Parameters:

Name Type Description Default
model SedModel -- the model the samples were drawn with; parameter names must match the result's
required
result SamplingResult or path -- sampler output or the HDF5 file it was written to
required
n_samples int, optional -- equal-weight draws (default 2000 for weighted results, all for uniform)
None
windows_myr sequence of float, Myr -- averaging windows W for ``sfrW`` / ``ssfrW``
DEFAULT_WINDOWS_MYR
derived dict[str, callable] -- ``name -> f(SpectrumSample) -> float or 1-D array``, evaluated per draw
None
batch_size int -- draws per compiled batch through the forward model
256
mfrac bool or None -- surviving-mass block (``mfrac``, ``mass_surviving``,

ssfrW_surviving): None reports it when it is available and warns when it is not; True requires it (ValueError otherwise); False skips it. It is read from the result file's /derived/mfrac (written by fitSED) when there is one, which is refused when its grid_chash or sfh_interp differ from the model's; otherwise it is computed from the grid's surviving-mass table

None
Source code in ceridwen/postprocess.py
def __init__(self, model, result, *, n_samples: Optional[int] = None,
             seed: int = 0, windows_myr: Sequence[float] = DEFAULT_WINDOWS_MYR,
             sfr: bool = True, ssfr: bool = True, uv: bool = True,
             ionizing: bool = True, predictions: bool = True,
             derived: Optional[dict] = None, batch_size: int = 256,
             mfrac: Optional[bool] = None):
    self.model = model
    self.csp = model.csp
    self.result = self._load_result(result)
    self.seed = int(seed)
    self.windows_myr = tuple(float(w) for w in windows_myr)
    if any(w <= 0 for w in self.windows_myr):
        raise ValueError("windows_myr must be positive")
    self.want = dict(sfr=bool(sfr), ssfr=bool(ssfr), uv=bool(uv),
                     ionizing=bool(ionizing), predictions=bool(predictions))
    if self.want["ssfr"] and not self.want["sfr"]:
        raise ValueError("ssfr=True needs sfr=True")
    self.want["mfrac"] = self._resolve_mfrac(mfrac)
    self.derived = dict(derived or {})
    for k, f in self.derived.items():
        if not callable(f):
            raise TypeError(f"derived[{k!r}] is not callable")
        if k in ("sfh", "uv", "ionizing"):
            raise ValueError(f"derived name {k!r} collides with a built-in block")
    self.batch_size = int(batch_size)
    if self.batch_size < 1:
        raise ValueError("batch_size must be >= 1")
    self._samples_np = {k: np.asarray(v, dtype=float) for k, v in self.result.samples.items()}
    self._logl_np = np.asarray(self.result.log_likelihoods, dtype=float)
    self._check_names()
    self.log_weights = self._log_weights()
    self.n_samples = n_samples
    self.output: Optional[dict] = None

run

run()

Compute and return (and store in self.output) the nested dict of the module docstring.

Source code in ceridwen/postprocess.py
def run(self) -> dict:
    """Compute and return (and store in ``self.output``) the nested dict of the module docstring."""
    self._compile()
    idx = self._draw_indices()
    theta_batch = self._theta_batch(idx)
    raw = self._with_stored_mfrac(self._run_batches(theta_batch), idx)
    out = self._derive(theta_batch, raw)
    out["theta"] = {k: np.asarray(v).reshape((v.shape[0], -1)).squeeze(axis=-1)
                    if np.asarray(v).shape[1:] == (1,) else np.asarray(v)
                    for k, v in theta_batch.items()}
    out["draw_index"] = idx
    out["log_likelihood"] = np.asarray(self.result.log_likelihoods, dtype=float)[idx]

    ll = np.asarray(self.result.log_likelihoods, dtype=float)
    ibest = int(np.nanargmax(ll))
    tb = self._theta_batch(np.array([ibest]))
    rb = self._with_stored_mfrac(self._run_batches(tb), [ibest])
    best = self._derive(tb, rb)
    best["theta"] = {k: np.asarray(v)[0] for k, v in tb.items()}
    best["index"] = ibest
    best["log_likelihood"] = float(ll[ibest])
    best = _squeeze_leading(best)
    out["bestfit"] = best

    out["meta"] = {
        "n_samples": int(idx.size), "n_raw": int(self.n_raw), "seed": self.seed,
        "resampled": not self._uniform_weights(),
        "windows_myr": list(self.windows_myr), "param_names": list(self.model.param_names),
        "zred_fixed": float(self.model.zred), "cosmology": self.csp.cosmo.to_dict(),
        "sampler": getattr(self.result, "sampler_name", ""),
        "weights": self._weights_source,
        "log_evidence": float(getattr(self.result, "log_evidence", float("nan"))),
        "log_evidence_err": float(getattr(self.result, "log_evidence_err", float("nan"))),
        "observations": [(o.name, getattr(o, "_kind", "")) for o in self.model.observations],
        "sfh_interp": self.csp.sfh_interp, "sfh_per_bin": bool(getattr(self.csp, "sfh_per_bin", False)),
        "metallicity": self._metallicity_meta(),
        "mfrac": ("not computed" if not self.want["mfrac"]
                  else "read from the result file's /derived/mfrac"
                  if self._mfrac_stored is not None
                  else "computed from the SSP grid's surviving-mass table"),
    }
    self.output = out
    return out

figures

figures(
    outdir, *, prefix="", title=None, truths=None, fmt="pdf"
)

Write the summary, corner and sampling-diagnostic figures (:mod:ceridwen.plotting) to outdir; returns their paths. truths ({name: value}) marks injected values in mock tests.

Source code in ceridwen/postprocess.py
def figures(self, outdir, *, prefix="", title=None, truths=None, fmt="pdf"):
    """Write the summary, corner and sampling-diagnostic figures
    (:mod:`ceridwen.plotting`) to ``outdir``; returns their paths.
    ``truths`` ({name: value}) marks injected values in mock tests."""
    from .plotting import make_figures
    if self.output is None:
        self.run()
    return make_figures(self.output, self.model, self.result, outdir,
                        prefix=prefix, title=title, truths=truths, fmt=fmt)

save

save(path)

Write self.output (running first if needed) as a flat .npz with '/'-joined keys.

Source code in ceridwen/postprocess.py
def save(self, path) -> Path:
    """Write ``self.output`` (running first if needed) as a flat ``.npz`` with '/'-joined keys."""
    if self.output is None:
        self.run()
    path = Path(path)
    if path.suffix != ".npz":
        path = path.with_suffix(".npz")
    flat = {}
    _flatten(self.output, "", flat)
    np.savez(path, **flat)
    return path

ceridwen.postprocess.SpectrumSample dataclass

SpectrumSample(
    wave_rest,
    full,
    intrinsic,
    dustfree,
    theta,
    zred,
    logmass,
    sfr,
    lookback_gyr,
    cosmo,
)

One posterior draw as handed to a derived function: rest-frame L_nu [L_sun/Hz] x 10**logmass on wave_rest [A]; theta after the model transforms.

index_of

index_of(wave_aa)

Index of the model pixel closest to wave_aa (rest frame).

Source code in ceridwen/postprocess.py
def index_of(self, wave_aa: float) -> int:
    """Index of the model pixel closest to ``wave_aa`` (rest frame)."""
    return int(np.argmin(np.abs(self.wave_rest - float(wave_aa))))

mean_lnu

mean_lnu(spectrum, lo_aa, hi_aa)

Wavelength-averaged L_nu of spectrum over [lo, hi] A (trapezoid).

Source code in ceridwen/postprocess.py
def mean_lnu(self, spectrum: np.ndarray, lo_aa: float, hi_aa: float) -> float:
    """Wavelength-averaged L_nu of ``spectrum`` over [lo, hi] A (trapezoid)."""
    m = (self.wave_rest >= lo_aa) & (self.wave_rest <= hi_aa)
    if m.sum() < 2:
        raise ValueError(f"fewer than two model pixels in [{lo_aa}, {hi_aa}] A")
    w = self.wave_rest[m]
    return float(_trapz(spectrum[m], w) / (w[-1] - w[0]))

luminosity

luminosity(spectrum, lo_aa, hi_aa)

int L_nu dnu over [lo, hi] A of spectrum [erg/s].

Source code in ceridwen/postprocess.py
def luminosity(self, spectrum: np.ndarray, lo_aa: float, hi_aa: float) -> float:
    """int L_nu dnu over [lo, hi] A of ``spectrum`` [erg/s]."""
    m = (self.wave_rest >= lo_aa) & (self.wave_rest <= hi_aa)
    if m.sum() < 2:
        raise ValueError(f"fewer than two model pixels in [{lo_aa}, {hi_aa}] A")
    nu = 2.99792458e18 / self.wave_rest[m]
    return float(-_trapz(spectrum[m], nu) * _LSUN_ERG_S)

ceridwen.postprocess.load_postprocess

load_postprocess(path)

Rebuild the nested dict written by :meth:PostProcess.save.

Source code in ceridwen/postprocess.py
def load_postprocess(path) -> dict:
    """Rebuild the nested dict written by :meth:`PostProcess.save`."""
    out: dict = {}
    with np.load(path, allow_pickle=False) as f:
        for key in f.files:
            parts = key.split("/")
            d = out
            for p in parts[:-1]:
                d = d.setdefault(p, {})
            v = f[key]
            if v.dtype.kind in ("U", "S"):
                try:
                    v = json.loads(str(v))
                except json.JSONDecodeError:
                    v = str(v)
            d[parts[-1]] = v
    return out

Figures

ceridwen.plotting.summary_figure

summary_figure(
    out,
    model,
    *,
    title=None,
    prior_draws=500,
    params=None,
    truths=None,
    savepath=None,
    figsize=(15, 11)
)

Summary page: SED with residuals (photometry and model in the same units, limited to the observed wavelengths; the full width when there are no emission lines), emission lines, the SFH (per-bin log10 SFR vs lookback time, posterior 16-84 % and median, prior 16-84 % at the median mass; a linear time axis for a uniform node grid, else log), and 1-D marginals of the fitted parameters (median, 16-84 %, best fit, prior 16-84 %). out is PostProcess.run()'s dict; model the fitted SedModel; truths ({name: value or array}) marks injected values in green, and draws the injected SFH when it gives the SFH parameters (e.g. logsfr_ratios).

Source code in ceridwen/plotting.py
def summary_figure(out, model, *, title=None, prior_draws=500, params=None, truths=None,
                   savepath=None, figsize=(15, 11)):
    """Summary page: SED with residuals (photometry and model in the same units, limited to
    the observed wavelengths; the full width when there are no emission lines), emission
    lines, the SFH (per-bin log10 SFR vs lookback time, posterior 16-84 % and median, prior
    16-84 % at the median mass; a linear time axis for a uniform node grid, else log), and
    1-D marginals of the fitted parameters (median,
    16-84 %, best fit, prior 16-84 %).  ``out`` is ``PostProcess.run()``'s dict; ``model``
    the fitted ``SedModel``; ``truths`` ({name: value or array}) marks injected values in
    green, and draws the injected SFH when it gives the SFH parameters (e.g. logsfr_ratios)."""
    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec

    C = COLORS
    theta = out["theta"]
    feh = _feh_axis(out)
    cols = _flat_params(theta, params)
    best = _flat_point(out["bestfit"]["theta"], (params or list(theta.keys())))
    prior = None
    pd = None
    if prior_draws:
        pd = _prior_draws(model, int(prior_draws))
        if pd is not None:
            prior = {"theta": _flat_params(pd)}

    obs_by_kind = {"photometry": [], "spectrum": [], "lines": []}
    for o in model.observations:
        obs_by_kind.get(getattr(o, "_kind", ""), []).append(o)
    has_lines = bool(obs_by_kind["lines"])
    n_par = len(cols)
    n_marg_cols = 4
    n_marg_rows = int(np.ceil(n_par / n_marg_cols))

    fig = plt.figure(figsize=figsize)
    gs = GridSpec(2, 2, figure=fig, height_ratios=[1.0, 1.0], width_ratios=[1.35, 1.0],
                  left=0.06, right=0.98, top=0.90, bottom=0.07, hspace=0.32, wspace=0.22)
    gs_top = (gs[0, 0] if has_lines else gs[0, :]).subgridspec(2, 1, height_ratios=[3, 1],
                                                                hspace=0.05)
    ax_sed = fig.add_subplot(gs_top[0]); ax_chi = fig.add_subplot(gs_top[1], sharex=ax_sed)
    ax_lines = fig.add_subplot(gs[0, 1]) if has_lines else None
    ax_sfh = fig.add_subplot(gs[1, 0])
    gs_marg = gs[1, 1].subgridspec(n_marg_rows, n_marg_cols, hspace=0.9, wspace=0.35)

    chi2, ndata = 0.0, 0
    pred = out["prediction"]
    best_pred = out["bestfit"]["prediction"]
    truth_pt = _flat_point(truths, list(truths)) if truths else {}
    observed = "spectra_observed" in pred
    unit = _MAGGIE_TO_NJY if observed else _MAGGIE_TO_CGS     # photometry -> spectrum's units

    wave_rest = np.asarray(pred["wave_rest"])
    if observed:
        z = np.asarray(pred["zred"])
        wobs = (1.0 + np.median(z)) * wave_rest
        spec = np.asarray(pred["spectra_observed"], dtype=float) * _CGS_FNU_TO_NJY
    else:
        wobs = wave_rest
        spec = np.asarray(pred["spectra_model"], dtype=float)
    lo, med, hi = _quantiles(spec)
    xr = _data_wave_range(obs_by_kind)                 # [um], observed frame; None: no data
    m = (med > 0) & np.isfinite(med)
    if xr is not None:
        m &= (wobs / 1e4 >= xr[0]) & (wobs / 1e4 <= xr[1])
    ax_sed.fill_between(wobs[m] / 1e4, lo[m], hi[m], color=C["band"], alpha=0.6, lw=0,
                        label="model (16$-$84%)")
    ax_sed.plot(wobs[m] / 1e4, med[m], color=C["posterior"], lw=0.9)
    y_seen = [lo[m], hi[m]]
    agn_key = "spectra_agn_observed" if observed else "spectra_agn"
    if agn_key in pred:                                  # CSPBasis(agn=...): the AGN alone
        agn = np.asarray(pred[agn_key], dtype=float) * (_CGS_FNU_TO_NJY if observed else 1.0)
        a_med = _quantiles(agn)[1]
        ma = m & (a_med > 0) & np.isfinite(a_med)
        ax_sed.plot(wobs[ma] / 1e4, a_med[ma], color=C["posterior"], lw=0.8, ls="--",
                    label="AGN (median)")
    unit_spec = _CGS_FNU_TO_NJY if observed else 1.0     # spectra are cgs f_nu, photometry maggies
    for o in obs_by_kind["spectrum"]:
        w = np.asarray(o.wavelength, dtype=float) / 1e4
        y = np.asarray(o.flux, dtype=float) * unit_spec
        s = np.asarray(o.uncertainty, dtype=float) * unit_spec
        mk = np.asarray(o.mask, dtype=bool)
        ax_sed.fill_between(w[mk], (y - s)[mk], (y + s)[mk], color=C["data"], alpha=0.15, lw=0)
        ax_sed.plot(w[mk], y[mk], color=C["data"], lw=0.6, label=f"observed spectrum ({o.name})")
        y_seen.append(y[mk])
        if o.name in pred["spectra"]:
            p = np.asarray(pred["spectra"][o.name], dtype=float) * unit_spec
            plo, pmed, phi = _quantiles(p)
            ax_sed.plot(w[mk], pmed[mk], color=C["bestfit"], lw=0.6, alpha=0.8, label="posterior spectrum")
            r = ((pmed - y) / s)[mk]
            ax_chi.plot(w[mk], r, color=C["posterior"], lw=0.5)
            pb = np.asarray(best_pred["spectra"][o.name], dtype=float) * unit_spec
            chi2 += float(np.sum(((pb - y) / s)[mk] ** 2)); ndata += int(mk.sum())
    for o in obs_by_kind["photometry"]:
        w = np.asarray(o.wavelength, dtype=float) / 1e4
        y = np.asarray(o.flux, dtype=float) * unit
        s = np.asarray(o.uncertainty, dtype=float) * unit
        mk = np.asarray(o.mask, dtype=bool)
        ul = np.asarray(o.upper_limit, dtype=bool) if getattr(o, "upper_limit", None) is not None else np.zeros_like(mk)
        det = mk & ~ul
        ax_sed.errorbar(w[det], y[det], yerr=s[det], fmt="o", color=C["data"], ms=5, capsize=2,
                        label="observed", zorder=5)
        y_seen.append(y[det])
        if ul.any():
            ax_sed.errorbar(w[ul], y[ul], yerr=0.3 * y[ul], uplims=True, fmt="v", color=C["grid"],
                            ms=5, label="upper limit", zorder=5)
        if o.name in pred["photometry"]:
            p = np.asarray(pred["photometry"][o.name], dtype=float) * unit
            plo, pmed, phi = _quantiles(p)
            ax_sed.errorbar(w, pmed, yerr=[pmed - plo, phi - pmed], fmt="s", mfc="none",
                            color=C["bestfit"], ms=6, capsize=0, label="posterior photometry", zorder=6)
            r = (pmed - y) / s
            rlo, rhi = (plo - y) / s, (phi - y) / s
            ax_chi.errorbar(w[det], r[det], yerr=[(r - rlo)[det], (rhi - r)[det]], fmt="o",
                            color=C["bestfit"], ms=4, capsize=0)
            pb = np.asarray(best_pred["photometry"][o.name], dtype=float) * unit
            rb = (pb - y) / s
            chi2 += float(np.sum(np.where(ul, np.maximum(rb, 0.0), rb)[mk] ** 2)); ndata += int(mk.sum())
    ax_sed.set_xscale("log"); ax_sed.set_yscale("log")
    if xr is not None:
        ax_sed.set_xlim(*xr)
    ys = np.concatenate([np.ravel(v) for v in y_seen]) if y_seen else np.array([])
    ys = ys[np.isfinite(ys) & (ys > 0)]
    if ys.size:
        ax_sed.set_ylim(ys.min() / 3.0, ys.max() * 3.0)
    ax_sed.set_ylabel(r"$F_\nu$ [nJy]" if observed
                      else r"$L_\nu$ [$\mathrm{L}_\odot\,\mathrm{Hz}^{-1}$] ($z = 0$: no distance)")
    ax_sed.legend(fontsize=7, loc="lower right", frameon=False)
    ax_sed.tick_params(labelbottom=False)
    ax_chi.axhline(0, color=C["data"], lw=0.8)
    ax_chi.axhspan(-1, 1, color=C["prior"], alpha=0.6, lw=0)
    ax_chi.set_ylim(-4, 4); ax_chi.set_ylabel(r"$\chi$")
    ax_chi.set_xlabel(r"observed wavelength [$\mu$m]")
    if xr is not None:
        _nice_log_ticks(ax_chi.xaxis, *xr)
    for ax in (ax_sed, ax_chi):
        ax.grid(False)

    # emission lines: (model - observed) / sigma per line
    if has_lines:
        yy = 0
        for o in obs_by_kind["lines"]:
            names = list(o.line_names) if getattr(o, "line_names", None) else [f"{float(l):.0f}" for l in np.asarray(o.wavelength)]
            y = np.asarray(o.flux, dtype=float); s = np.asarray(o.uncertainty, dtype=float)
            mk = np.asarray(o.mask, dtype=bool)
            ul = np.asarray(o.upper_limit, dtype=bool) if getattr(o, "upper_limit", None) is not None else np.zeros_like(mk)
            p = np.asarray(pred["lines"][o.name], dtype=float) if o.name in pred["lines"] else None
            pb = np.asarray(best_pred["lines"][o.name], dtype=float) if o.name in best_pred["lines"] else None
            for i, nm in enumerate(names):
                if not mk[i]:
                    continue
                snr = y[i] / s[i]
                if p is not None:
                    lo, med, hi = _quantiles((p[:, i] - y[i]) / s[i])
                    ax_lines.errorbar(med, yy, xerr=[[med - lo], [hi - med]], fmt="o",
                                      color=C["bestfit"] if snr >= 3 else C["band"],
                                      mfc=C["bestfit"] if snr >= 3 else "white", ms=5, capsize=0)
                    if pb is not None:
                        rb = (pb[i] - y[i]) / s[i]
                        ax_lines.plot(rb, yy, marker="|", color=C["data"], ms=8, lw=0)
                        chi2 += float(max(rb, 0.0) ** 2 if ul[i] else rb ** 2); ndata += 1
                ax_lines.text(4.9, yy, f"{snr:.0f}", ha="right", va="center", fontsize=7, color=C["grid"])
                ax_lines.text(-5.2, yy, nm, ha="right", va="center", fontsize=8)
                yy += 1
        ax_lines.axvline(0, color=C["data"], lw=0.8)
        ax_lines.axvspan(-1, 1, color=C["prior"], alpha=0.6, lw=0)
        ax_lines.set_xlim(-5.4, 5.2); ax_lines.set_ylim(-0.7, yy - 0.3); ax_lines.invert_yaxis()
        ax_lines.set_yticks([]); ax_lines.set_xlabel(r"(model $-$ observed) / $\sigma$")
        ax_lines.text(5.05, -0.55, "S/N", ha="right", va="center", fontsize=7, color=C["grid"])
        ax_lines.plot([], [], "o", color=C["bestfit"], label=r"S/N $\geq$ 3")
        ax_lines.plot([], [], "o", color=C["band"], mfc="white", label="S/N < 3")
        ax_lines.plot([], [], "|", color=C["data"], label="best fit")
        ax_lines.legend(fontsize=7, loc="upper right", frameon=False, ncol=3, bbox_to_anchor=(1.0, 1.08))

    # SFH (as the paper's figures): per-bin log10 SFR against lookback time [Gyr];
    # posterior 16-84 % per bin, posterior median, prior 16-84 %, and the injected SFH when
    # given.  A uniform node grid (linspace) gets a linear axis, so the youngest bin
    # [0, t1] is drawn whole; any other grid a log axis, whose first bin starts at t1 / 2
    sfh = out["extras"]["sfh"]
    T = np.median(np.asarray(sfh["lookback_gyr"], dtype=float), axis=0)
    edges = T.copy()
    dT = np.diff(T)
    log_axis = not (T[0] <= 0.0 and np.allclose(dT, dT.mean(), rtol=0.02))
    if log_axis and edges[0] <= 0.0:
        edges[0] = 0.5 * edges[1]              # a log axis has no 0: first bin from t1 / 2
    if "sfr_per_bin" in sfh:
        per_bin = np.asarray(sfh["sfr_per_bin"], dtype=float)
    else:
        from .postprocess import _per_bin_and_nodes
        per_bin = np.array([_per_bin_and_nodes(r, T.size)[0]
                            for r in np.asarray(sfh["sfr"], dtype=float)])
    with np.errstate(divide="ignore"):
        lsfr = np.log10(per_bin)
    lsfr = np.where(np.isfinite(lsfr), lsfr, np.nan)
    lo, med, hi = _quantiles(lsfr)
    p_sfr = _prior_sfr_per_bin(model, out, pd) if pd is not None else None
    if p_sfr is not None:
        with np.errstate(divide="ignore"):
            lp = np.log10(p_sfr)
        plo, _, phi = _quantiles(np.where(np.isfinite(lp), lp, np.nan))
        ax_sfh.stairs(phi, edges, baseline=plo, fill=True, color=C["prior"], alpha=0.8, lw=0,
                      label=r"prior 16$-$84%" + (" (at the median mass)"
                                                 if "logmass" in theta else ""))
    ax_sfh.stairs(hi, edges, baseline=lo, fill=True, color=C["band"], alpha=0.6, lw=0,
                  label=r"posterior 16$-$84%")
    ax_sfh.stairs(med, edges, baseline=None, color=C["posterior"], lw=1.6,
                  label="posterior median")          # baseline=None: no drop to (and y-limit at) 0
    t_sfr = _truth_sfr_per_bin(model, out, truths)
    if t_sfr is not None:
        with np.errstate(divide="ignore"):
            lt = np.log10(t_sfr)
        ax_sfh.stairs(np.where(np.isfinite(lt), lt, np.nan), edges, baseline=None,
                      color=C["truth"], lw=1.4, ls="--", label="truth")
    ax_sfh.set_xlim(edges[0], edges[-1])
    if log_axis:
        ax_sfh.set_xscale("log")
        _nice_log_ticks(ax_sfh.xaxis, edges[0], edges[-1])
    ax_sfh.set_xlabel("lookback time [Gyr]")
    ax_sfh.set_ylabel(r"$\log_{10}$ SFR [M$_\odot$ yr$^{-1}$]")
    ax_sfh.legend(fontsize=8, loc="best", frameon=False)

    # marginals
    for i, (name, x) in enumerate(cols.items()):
        ax = fig.add_subplot(gs_marg[i // n_marg_cols, i % n_marg_cols])
        x = x[np.isfinite(x)]
        q = _quantiles(x)
        if prior is not None and name in prior["theta"]:
            plo, _, phi = _quantiles(prior["theta"][name])
            ax.axvspan(plo, phi, color=C["prior"], alpha=0.8, lw=0)
        ax.hist(x, bins=30, color=C["band"], histtype="stepfilled", alpha=0.9)
        ax.hist(x, bins=30, color=C["posterior"], histtype="step", lw=1.0)
        ax.axvline(q[1], color=C["posterior"], lw=1.2)
        if name in best:
            ax.axvline(best[name], color=C["bestfit"], lw=1.0)
        if name in truth_pt:
            ax.axvline(truth_pt[name], color=C["truth"], lw=1.2, ls="--")
        ax.set_yticks([]); ax.tick_params(axis="x", labelsize=7)
        ax.set_title(_label(name, feh), fontsize=9, pad=3)
        ax.set_xlabel(_fmt_q(*q), fontsize=8, labelpad=1)
        for s_ in ("top", "right", "left"):
            ax.spines[s_].set_visible(False)

    # header
    meta = out["meta"]
    bits = []
    if "zred" in theta:
        q = _quantiles(theta["zred"]); bits.append(r"$z$ = " + _fmt_q(*q, nd=3))
    else:
        bits.append(rf"$z$ = {meta.get('zred_fixed', 0.0):.3f} (fixed)")
    if "logmass" in theta:
        bits.append(r"$\log M_\mathrm{formed}/\mathrm{M}_\odot$ = " + _fmt_q(*_quantiles(theta["logmass"])))
    if "sfr10" in sfh:
        with np.errstate(divide="ignore"):
            s10 = np.log10(np.asarray(sfh["sfr10"]))
        s10 = s10[np.isfinite(s10)]
        if s10.size:
            bits.append(r"$\log\,\mathrm{SFR}_{10}$ = " + _fmt_q(*_quantiles(s10)))
    nfree = sum(int(np.size(v)) for v in model.theta_init.values())
    if ndata:
        # diagonal chi^2 with the quoted uncertainties; a spectrum fitted with a GP likelihood
        # is scored by the full covariance in the fit, which this number does not include
        diag = " diagonal, no GP;" if _has_gp(model) else ""
        bits.append(rf"$\chi^2/\nu$ = {chi2 / max(ndata - nfree, 1):.2f} (best fit, quoted uncertainties;{diag} $N_\mathrm{{data}}$ = {ndata})")
    if "log_evidence" in meta and np.isfinite(meta["log_evidence"]):
        bits.append(rf"$\ln Z$ = {meta['log_evidence']:.1f}")
    fig.text(0.06, 0.965, title or "CERIDWEN fit", fontsize=14, weight="bold", va="top")
    fig.text(0.06, 0.93, "    ".join(bits) + f"    sampler: {meta.get('sampler', '')}", fontsize=9.5, va="top")
    if savepath:
        fig.savefig(savepath, bbox_inches="tight")
    return fig

ceridwen.plotting.corner_figure

corner_figure(
    out,
    *,
    params=None,
    truths=None,
    savepath=None,
    bins=30,
    panel=1.6
)

Corner plot of all fitted parameters: 1-D marginals on the diagonal, 2-D histograms with 1 and 2 sigma contours below; posterior median (blue, dashed), maximum-likelihood sample (red) and, when given, truths (green) marked.

Source code in ceridwen/plotting.py
def corner_figure(out, *, params=None, truths=None, savepath=None, bins=30, panel=1.6):
    """Corner plot of all fitted parameters: 1-D marginals on the diagonal, 2-D
    histograms with 1 and 2 sigma contours below; posterior median (blue, dashed),
    maximum-likelihood sample (red) and, when given, ``truths`` (green) marked."""
    import matplotlib.pyplot as plt
    C = COLORS
    feh = _feh_axis(out)
    cols = dict(_flat_params(out["theta"], params))
    best = _flat_point(out["bestfit"]["theta"], (params or list(out["theta"].keys())))
    tot = out.get("extras", {}).get("metallicity", {}).get("logzsol_total")
    best_tot = out.get("bestfit", {}).get("extras", {}).get("metallicity", {}).get("logzsol_total")
    if params is None and tot is not None and best_tot is not None:
        cols["logzsol_total"] = np.asarray(tot).reshape(-1)
        best["logzsol_total"] = float(np.asarray(best_tot).reshape(-1)[0])
    truth_pt = _flat_point(truths, list(truths)) if truths else {}
    names = list(cols)
    K = len(names)
    X = np.column_stack([cols[n] for n in names])
    ok = np.all(np.isfinite(X), axis=1)
    X = X[ok]
    fig, axes = plt.subplots(K, K, figsize=(panel * K, panel * K))
    axes = np.atleast_2d(axes)
    lims = [(np.quantile(X[:, i], 0.001), np.quantile(X[:, i], 0.999)) for i in range(K)]
    lims = [(a - 0.05 * (b - a), b + 0.05 * (b - a)) if b > a else (a - 1, a + 1) for a, b in lims]
    for i in range(K):                   # a supplied truth is always inside its panel
        t = truth_pt.get(names[i])
        if t is not None and np.isfinite(t):
            a, b = lims[i]
            pad = 0.05 * (b - a)
            lims[i] = (min(a, float(t) - pad), max(b, float(t) + pad))
    for i in range(K):
        for j in range(K):
            ax = axes[i, j]
            if j > i:
                ax.set_visible(False); continue
            if i == j:
                x = X[:, i]
                q = _quantiles(x)
                ax.hist(x, bins=bins, range=lims[i], color=C["band"], histtype="stepfilled", alpha=0.9)
                ax.hist(x, bins=bins, range=lims[i], color=C["posterior"], histtype="step", lw=1.0)
                ax.axvline(q[1], color=C["posterior"], ls="--", lw=1.0)
                ax.axvline(q[0], color=C["posterior"], ls=":", lw=0.7); ax.axvline(q[2], color=C["posterior"], ls=":", lw=0.7)
                ax.axvline(best[names[i]], color=C["bestfit"], lw=1.2)
                if names[i] in truth_pt:
                    ax.axvline(truth_pt[names[i]], color=C["truth"], lw=1.2, ls="--")
                ax.set_title(_label(names[i], feh) + "\n" + _fmt_q(*q), fontsize=8)
                ax.set_yticks([]); ax.set_xlim(lims[i])
            else:
                x, y = X[:, j], X[:, i]
                H, xe, ye = np.histogram2d(x, y, bins=bins, range=[lims[j], lims[i]])
                Hs = _smooth(H.T)
                flat = np.sort(Hs.ravel())[::-1]
                csum = np.cumsum(flat) / flat.sum()
                levels = [flat[np.searchsorted(csum, f)] for f in (0.865, 0.393)]
                levels = sorted(set([max(l, 1e-12) for l in levels]))
                xc = 0.5 * (xe[1:] + xe[:-1]); yc = 0.5 * (ye[1:] + ye[:-1])
                ax.pcolormesh(xe, ye, np.ma.masked_where(Hs == 0, Hs), cmap="Blues", shading="flat", rasterized=True)
                if len(levels) >= 1:
                    ax.contour(xc, yc, Hs, levels=levels + [Hs.max() + 1], colors=C["posterior"], linewidths=0.8)
                ax.axvline(np.median(x), color=C["posterior"], ls="--", lw=0.7)
                ax.axhline(np.median(y), color=C["posterior"], ls="--", lw=0.7)
                ax.plot(best[names[j]], best[names[i]], "o", color=C["bestfit"], ms=4)
                if names[j] in truth_pt and names[i] in truth_pt:
                    ax.plot(truth_pt[names[j]], truth_pt[names[i]], "s", color=C["truth"], ms=4)
                ax.set_xlim(lims[j]); ax.set_ylim(lims[i])
            if i < K - 1:
                ax.tick_params(labelbottom=False)
            else:
                ax.set_xlabel(_label(names[j], feh), fontsize=8)
            if j > 0 or i == 0:
                ax.tick_params(labelleft=False)
            else:
                ax.set_ylabel(_label(names[i], feh), fontsize=8)
            ax.tick_params(labelsize=6)
    fig.text(0.62, 0.95, "dashed: posterior median (dotted: 16 / 84 %)\nred: maximum-likelihood sample"
             + ("\ngreen: injected truth" if truth_pt else ""), fontsize=9, color=C["data"], va="top")
    fig.subplots_adjust(left=0.07, right=0.98, bottom=0.07, top=0.95, hspace=0.08, wspace=0.08)
    if savepath:
        fig.savefig(savepath, bbox_inches="tight")
    return fig

ceridwen.plotting.diagnostic_figure

diagnostic_figure(
    result,
    out=None,
    *,
    params=None,
    savepath=None,
    max_points=4000
)

Sampling diagnostics. Nested sampling: every parameter's dead points in deletion order coloured by posterior weight, the log-likelihood run and the cumulative evidence. MCMC: per-chain traces with split-R-hat and ESS (summed over chains; without vi the NUTS chains share one warmup end state, so the R-hat is within-run mixing only).

Source code in ceridwen/plotting.py
def diagnostic_figure(result, out=None, *, params=None, savepath=None, max_points=4000):
    """Sampling diagnostics.  Nested sampling: every parameter's dead points in
    deletion order coloured by posterior weight, the log-likelihood run and the
    cumulative evidence.  MCMC: per-chain traces with split-R-hat and ESS (summed over chains;
    without ``vi`` the NUTS chains share one warmup end state, so the R-hat is within-run
    mixing only)."""
    import matplotlib.pyplot as plt
    C = COLORS
    feh = _feh_axis(out) if out is not None else False     # label logzsol as the others do
    theta = {k: np.asarray(v) for k, v in result.samples.items()}
    if params:
        theta = {k: theta[k] for k in params}
    cols = _flat_params(theta)
    names = list(cols); K = len(names)
    raw = getattr(result, "raw", None) or {}
    n_chains = int(raw.get("num_chains", 0) or 0)
    is_mcmc = n_chains > 0 and getattr(result, "log_likelihoods_birth", None) is None
    ncol = 2
    nrow = int(np.ceil(K / ncol)) + 1
    fig, axes = plt.subplots(nrow, ncol, figsize=(12, 2.0 * nrow))
    axes = np.atleast_2d(axes)
    ll = np.asarray(result.log_likelihoods, dtype=float)
    n = ll.size
    if is_mcmc:
        S = n // n_chains
        for i, name in enumerate(names):
            ax = axes[i // ncol, i % ncol]
            ch = cols[name][: n_chains * S].reshape(n_chains, S)
            for c in range(n_chains):
                ax.plot(ch[c], color=C["chains"][c % len(C["chains"])], lw=0.4, alpha=0.8)
            rhat = _split_rhat(ch); ess = sum(_ess(ch[c]) for c in range(n_chains))
            ax.set_title(f"{_label(name, feh)}    $\\hat R$ = {rhat:.3f}    ESS = {ess:.0f}", fontsize=8)
            ax.tick_params(labelsize=7)
        ax = axes[-1, 0]
        for c in range(n_chains):
            ax.plot(ll[c * S:(c + 1) * S], color=C["chains"][c % len(C["chains"])], lw=0.4, alpha=0.8)
        ax.set_title("log-likelihood per chain", fontsize=8)
        ax2 = axes[-1, 1]
        div = raw.get("total_divergences", None)
        ax2.axis("off")
        ax2.text(0.0, 0.8, f"{n_chains} chains x {S} draws" + (f", {div} divergences" if div is not None else ""),
                 fontsize=9, transform=ax2.transAxes)
        fig.suptitle("MCMC traces", fontsize=11)
    else:
        from .sampler.ns_weights import nested_log_weights
        births = getattr(result, "log_likelihoods_birth", None)
        lw = (nested_log_weights(ll, np.asarray(births)) if births is not None
              else np.asarray(result.log_weights, dtype=float))
        fin = np.isfinite(lw)
        w = np.zeros(n); w[fin] = np.exp(lw[fin] - lw[fin].max()); w /= w.sum()
        order = np.arange(n)
        step = max(1, n // max_points)
        sel = order[::step]
        for i, name in enumerate(names):
            ax = axes[i // ncol, i % ncol]
            ax.scatter(sel, cols[name][sel], c=np.clip(lw[sel] - lw[fin].max(), -12, 0), cmap=_LazyCmap()(),
                       s=3, vmin=-12, vmax=0, rasterized=True)
            qs = _weighted_quantiles(cols[name], w, (0.16, 0.5, 0.84))
            ax.set_title(f"{_label(name, feh)}    posterior " + _fmt_q(*qs), fontsize=8)
            ax.tick_params(labelsize=7)
        ax = axes[-1, 0]
        ax.plot(order, ll, color=C["posterior"], lw=0.6)
        ax.set_ylabel(r"$\ln L$", fontsize=8); ax.set_xlabel("dead point (deletion order)", fontsize=8)
        fl = ll[fin]
        if fl.size:
            ax.set_ylim(np.quantile(fl, 0.02), fl.max() + 0.05 * (fl.max() - np.quantile(fl, 0.02)))
        ax.set_title("log-likelihood run", fontsize=8)
        ax2 = axes[-1, 1]
        ax2.plot(order, np.cumsum(w), color=C["posterior"], lw=1.0)
        ax2.set_ylim(0, 1.02); ax2.set_xlabel("dead point (deletion order)", fontsize=8)
        ax2.set_ylabel("cumulative posterior weight", fontsize=8)
        ess = 1.0 / np.sum(w ** 2)
        lz = getattr(result, "log_evidence", np.nan); lze = getattr(result, "log_evidence_err", np.nan)
        ax2.set_title(rf"$\ln Z$ = {lz:.2f} $\pm$ {lze:.2f}    ESS = {ess:.0f} of {n}", fontsize=8)
        fig.suptitle("nested-sampling run: dead points coloured by posterior weight", fontsize=11)
    for k in range(K, (nrow - 1) * ncol):
        axes[k // ncol, k % ncol].axis("off")
    fig.tight_layout()
    if savepath:
        fig.savefig(savepath, bbox_inches="tight")
    return fig

ceridwen.plotting.make_figures

make_figures(
    out,
    model,
    result,
    outdir,
    *,
    prefix="",
    title=None,
    truths=None,
    fmt="pdf"
)

Write summary, corner and diagnostic figures to outdir; returns their paths.

Source code in ceridwen/plotting.py
def make_figures(out, model, result, outdir, *, prefix="", title=None, truths=None, fmt="pdf"):
    """Write summary, corner and diagnostic figures to ``outdir``; returns their paths."""
    import matplotlib.pyplot as plt
    outdir = Path(outdir); outdir.mkdir(parents=True, exist_ok=True)
    paths = {}
    for name, fn, args, kw in (("summary", summary_figure, (out, model), {"title": title, "truths": truths}),
                               ("corner", corner_figure, (out,), {"truths": truths}),
                               ("diagnostics", diagnostic_figure, (result, out), {})):
        p = outdir / f"{prefix}{name}.{fmt}"
        plt.close(fn(*args, savepath=p, **kw))
        paths[name] = p
    return paths

Dust, nebular, IGM, cosmology

ceridwen.dust.Dust

Dust(bin_edges=[(-jnp.inf, -1.97)], laws=['powerlaw'])

Modular dust attenuation model: one attenuation law per age bin, parameters read from a plain theta dict.

Parameters:

Name Type Description Default
bin_edges list of (lo, hi), log10(Gyr) -- age range of each bin
[(-inf, -1.97)]
laws list of str -- attenuation-law name per bin (see ``describe_attenuation_laws``)
['powerlaw']
Source code in ceridwen/dust/DustModel.py
def __init__(self, bin_edges=[(-jnp.inf, -1.97)], laws=['powerlaw']):
    assert len(bin_edges) == len(laws), "Must have one dust law per bin"
    self.bin_edges = jnp.array(bin_edges)
    self.num_bins = len(bin_edges)
    self.laws = laws

    self.law_names_resolved = []
    law_name_counter = defaultdict(int)
    law_occurrences = {name: laws.count(name) for name in set(laws)}

    self.law_funcs = []
    self.law_params = []

    for name in laws:
        count = law_name_counter[name]
        law_name_counter[name] += 1

        law_entry = ATTENUATION_LAWS[name]
        base_func = law_entry["func"]
        defaults = law_entry.get("defaults", {})
        params = law_entry.get("params", {})
        doc = law_entry.get("doc", "")

        if law_occurrences[name] == 1:
            resolved_name = name
            func = base_func
            param_dict = self._get_law_params(name)
        else:
            number = count + 1
            resolved_name = f"{name}{number}"
            func = modify_function(base_func, number, defaults)

            ATTENUATION_LAWS[resolved_name] = {
                "func": func,
                "defaults": {f"{k}{number}": v for k, v in defaults.items()},
                "params": {f"{k}{number}": d for k, d in params.items()},
                "doc": doc
            }

            renamed_keys = [f"{k}{number}" for k in defaults.keys()]
            ignored_keys = list(defaults.keys())
            print(f"[dust setup] Law '{name}' used multiple times → registered as '{resolved_name}'.")
            print(f"             Use parameters: {', '.join(renamed_keys)}")
            print(f"             Parameters like {', '.join(ignored_keys)} will be ignored.")

            param_dict = self._get_law_params(name)
            param_dict = {f"{k}{number}": v for k, v in param_dict.items()}

        sig = inspect.signature(func)
        ordered_param_names = [
            p.name for p in sig.parameters.values()
            if p.name != "wave"
            and p.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
        ]
        ordered_param_names = [n for n in ordered_param_names if n in param_dict]

        if not ordered_param_names:
            ordered_param_names = sorted(param_dict.keys())

        missing = [n for n in ordered_param_names if n not in param_dict]
        if missing:
            raise ValueError(
                f"Parameters {missing} expected for '{resolved_name}' but not found in param_dict"
            )

        law_defaults = ATTENUATION_LAWS.get(resolved_name, {}).get("defaults", {})
        wrapped_func = make_law_wrapper(func, ordered_param_names, law_defaults)

        self.law_names_resolved.append(resolved_name)
        self.law_funcs.append(wrapped_func)
        self.law_params.append(param_dict)

compute_attenuation

compute_attenuation(wave, fit_params)

Per-bin attenuation curves, shape (num_bins, len(wave)); wave in Angstroms.

Source code in ceridwen/dust/DustModel.py
def compute_attenuation(self, wave, fit_params):
    """Per-bin attenuation curves, shape ``(num_bins, len(wave))``; ``wave`` in Angstroms."""
    return jnp.stack([f(wave, fit_params) for f in self.law_funcs])

get_default_fit_params

get_default_fit_params()

Dict of default fit parameters (JAX scalars) for the active laws.

Source code in ceridwen/dust/DustModel.py
def get_default_fit_params(self):
    """Dict of default fit parameters (JAX scalars) for the active laws."""
    defaults = {}
    for law in self.law_names_resolved:
        for k, v in ATTENUATION_LAWS[law].get("defaults", {}).items():
            defaults[k] = jnp.asarray(v)
    return defaults

ceridwen.dust.DiffuseDust

DiffuseDust(law='kriek_conroy')

Bases: Dust

Single-bin dust model covering all ages, with diffuse_-prefixed parameter names.

Source code in ceridwen/dust/DustModel.py
def __init__(self, law="kriek_conroy"):
    super().__init__(bin_edges=[(-jnp.inf, jnp.inf)], laws=[law])

    old_name = self.law_names_resolved[0]
    param_dict = self.law_params[0]

    self.diffuse_param_map = {}
    renamed_param_dict = {}
    for k, v in param_dict.items():
        new_k = f"diffuse_{k}"
        renamed_param_dict[new_k] = v
        self.diffuse_param_map[new_k] = k

    self.law_params[0] = renamed_param_dict

    func = ATTENUATION_LAWS[old_name]["func"]
    sig = inspect.signature(func)
    param_names = [
        f"diffuse_{p.name}" for p in sig.parameters.values()
        if p.name != "wave"
        and p.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
    ]
    wrapped_func = make_law_wrapper(func, param_names)
    self.law_funcs[0] = wrapped_func
    self.dust_param_names = param_names

get_default_params

get_default_params()

Dict of default diffuse-dust parameters (diffuse_* keys).

Source code in ceridwen/dust/DustModel.py
def get_default_params(self):
    """Dict of default diffuse-dust parameters (``diffuse_*`` keys)."""
    defaults = {}
    law = self.law_names_resolved[0]
    for k, v in ATTENUATION_LAWS[law].get("defaults", {}).items():
        defaults[f"diffuse_{k}"] = jnp.asarray(v)
    return defaults

compute_attenuation

compute_attenuation(wave, fit_params)

Diffuse attenuation curve, shape (len(wave),).

Source code in ceridwen/dust/DustModel.py
def compute_attenuation(self, wave, fit_params):
    """Diffuse attenuation curve, shape ``(len(wave),)``."""
    return self.law_funcs[0](wave, fit_params)

ceridwen.dust.DustEmission.DustEmission

DustEmission(
    duste_model="DL07",
    dust_file=None,
    spec_lambda=None,
    **kwargs
)

Dust emission templates ('DL07' or 'THEMIS') interpolated onto spec_lambda [Angstrom].

Parameters:

Name Type Description Default
dust_file str -- data root containing dust/dustem/
None
kwargs duste_qpah, duste_umin, duste_gamma defaults
{}
Source code in ceridwen/dust/DustEmission.py
def __init__(self, duste_model="DL07",
             dust_file=None, spec_lambda=None, **kwargs):
    """Dust emission templates ('DL07' or 'THEMIS') interpolated onto spec_lambda [Angstrom].

    Parameters
    ----------
    dust_file : str -- data root containing dust/dustem/
    kwargs : duste_qpah, duste_umin, duste_gamma defaults
    """
    self.duste_model = duste_model

    self.duste_qpah = None
    self.duste_umin = None
    self.duste_gamma = None

    self.qpaharr = None
    self.uminarr = None

    self.dustem2_dustem = None

    self.dust_file = None
    self.spec_lambda = None

    self.dwargs = kwargs

    self.duste_qpah = kwargs.pop("duste_qpah", 3.5)
    self.duste_umin = kwargs.pop("duste_umin", 1.0)
    self.duste_gamma = kwargs.pop("duste_gamma", 0.01)

    if self.duste_model == "DL07":
        self.qpaharr = jnp.array([0.47,1.12,1.77,2.50,3.19,3.90,4.58])
        self.uminarr = jnp.array([0.1,0.15,0.2,0.3,0.4,0.5,0.7,0.8,1.0,1.2,1.5,
                                  2.0,2.5,3.0,4.0,5.0,7.0,8.0,12.0,15.0,20.0,25.0])
        self.nqpah_dustem = self.qpaharr.size
        self.numin_dustem = self.uminarr.size
    elif self.duste_model == "THEMIS":
        self.qpaharr = jnp.array([0.02, 0.06, 0.10, 0.14, 0.17, 0.20, 0.24,
                                  0.28, 0.32, 0.36, 0.40]) / 2.2 * 100
        self.uminarr = jnp.array([
            0.1, 0.12, 0.15, 0.17, 0.2, 0.25, 0.3, 0.35, 0.4, 0.5, 0.6,
            0.7, 0.8, 1.0, 1.2, 1.5, 1.7, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0,
            6.0, 7.0, 8.0, 10.0, 12.0, 15.0, 17.0, 20.0, 25.0, 30.0,
            35.0, 40.0, 50.0, 80.0
        ])
        self.nqpah_dustem = self.qpaharr.size
        self.numin_dustem = self.uminarr.size
    else:
        raise ValueError("Invalid duste_model. Choose 'DL07' or 'THEMIS'.")

    if dust_file is None or spec_lambda is None:
        raise ValueError("If `duste=True`, both `dust_file` and `spec_lambda` must be provided.")

    self.dust_file = dust_file
    self.spec_lambda = spec_lambda

    self.load_dust_emission(dust_file, spec_lambda)

    nu = CLIGHT_AA_S / jnp.asarray(spec_lambda)
    dnu = jnp.diff(nu)
    self._trap_w = jnp.concatenate([
        jnp.array([0.5 * dnu[0]]),
        0.5 * (dnu[:-1] + dnu[1:]),
        jnp.array([0.5 * dnu[-1]]),
    ])

get_default_params

get_default_params()

Return dict of default dust-emission fit parameters.

Source code in ceridwen/dust/DustEmission.py
def get_default_params(self):
    """Return dict of default dust-emission fit parameters."""
    return {
        "duste_qpah": jnp.asarray(self.duste_qpah),
        "duste_umin": jnp.asarray(self.duste_umin),
        "duste_gamma": jnp.asarray(self.duste_gamma),
    }

update_dust_params

update_dust_params(
    duste_qpah=3.5, duste_umin=1.0, duste_gamma=0.01
)

Set the default dust-emission parameters.

Source code in ceridwen/dust/DustEmission.py
def update_dust_params(self, duste_qpah = 3.5, duste_umin = 1.0, duste_gamma = 0.01):
    """Set the default dust-emission parameters."""
    self.duste_qpah = duste_qpah
    self.duste_umin = duste_umin
    self.duste_gamma = duste_gamma

compute_dust_emission

compute_dust_emission(
    spec_attn,
    spec_dustfree,
    spec_lambda,
    diffuse_curve,
    duste_qpah,
    duste_umin,
    duste_gamma,
)

Return (spec_attn + dust emission, dust mass, dust emission); diffuse_curve is exp(-tau_diffuse).

Source code in ceridwen/dust/DustEmission.py
def compute_dust_emission(self, spec_attn, spec_dustfree, spec_lambda, diffuse_curve,
                                    duste_qpah, duste_umin, duste_gamma):
    """Return (spec_attn + dust emission, dust mass, dust emission); diffuse_curve is exp(-tau_diffuse)."""
    tiny = safe_tiny(1e-70)                       # float32 mode: 1.2e-38
    w = self._trap_w
    dc = diffuse_curve.ravel()
    f_attn = spec_attn.ravel()
    f_free = spec_dustfree.ravel()

    # float64 on purpose (catastrophic cancellation): the trapezoid weights w are float64, so
    # these dots accumulate in float64, and labs0 = lboln - lbold below is a difference of two
    # nearly equal numbers (the absorbed luminosity), which float32 would leave with few
    # correct digits when little light is absorbed
    lbold = jnp.dot(f_attn, w)
    lboln = jnp.dot(f_free, w)

    qlo = jnp.clip(jnp.searchsorted(self.qpaharr, duste_qpah) - 1, 0, self.nqpah_dustem - 2)
    dq  = jnp.clip((duste_qpah - self.qpaharr[qlo]) / (self.qpaharr[qlo + 1] - self.qpaharr[qlo]), 0, 1)

    ulo = jnp.clip(jnp.searchsorted(self.uminarr, duste_umin) - 1, 0, self.numin_dustem - 2)
    du  = jnp.clip((duste_umin - self.uminarr[ulo]) / (self.uminarr[ulo + 1] - self.uminarr[ulo]), 0, 1)

    gamma = jnp.clip(duste_gamma, 0.0, 1.0)

    w00 = (1 - dq) * (1 - du)
    w10 = dq * (1 - du)
    w01 = (1 - dq) * du
    w11 = dq * du

    i_lo = 2 * ulo
    i_hi = 2 * (ulo + 1)

    D = self.dustem2_dustem  # (n_wave, n_qpah, 2*n_umin): Umin/Umax pairs interleaved

    dumin = (w00 * D[:, qlo, i_lo]     + w10 * D[:, qlo + 1, i_lo] +
             w11 * D[:, qlo + 1, i_hi] + w01 * D[:, qlo, i_hi])

    dumax = (w00 * D[:, qlo, i_lo + 1]     + w10 * D[:, qlo + 1, i_lo + 1] +
             w11 * D[:, qlo + 1, i_hi + 1] + w01 * D[:, qlo, i_hi + 1])

    mduste = jnp.maximum((1 - gamma) * dumin + gamma * dumax, tiny).ravel()
    norm   = jnp.dot(mduste, w)
    mduste_norm = mduste / norm

    labs0  = lboln - lbold
    duste0 = jnp.maximum(mduste_norm * labs0, tiny)

    duste0_atten = duste0 * dc
    absorbed_1 = jnp.dot(duste0 * (1.0 - dc), w)
    duste1 = jnp.maximum(mduste_norm * absorbed_1, tiny)

    duste1_atten = duste1 * dc

    tduste = duste0_atten + duste1_atten
    specdust = f_attn + tduste
    mdust = MDUST_PREFACTOR * labs0 / norm

    return specdust, mdust, tduste

ceridwen.neb.NebularModel

NebularModel(
    cloudy_dust=False,
    sps_home=None,
    csp_lambda=None,
    ssp_flux=None,
    ssp_ages_lgyr=None,
    isoc_type="mist",
    nebnz=11,
    nebnage=10,
    nebnip=7,
    smooth_velocity=True,
    sigma_smooth=0.0,
    res_floor_fwhm_px=2.0,
    nebular_smooth_init=None,
    **removed
)

Nebular continuum and lines from the CLOUDY cubes under <sps_home>/nebular.

Parameters:

Name Type Description Default
cloudy_dust bool -- CLOUDY grids with dust inside the H II region, ``ZAU_WD`` (True), or

without, ZAU_ND (False, the default, as in FSPS / python-fsps / Prospector).

False
csp_lambda (nspec,) -- model wavelength grid [A].
None
ssp_flux (n_z, n_age, n_wave) -- SSP L_nu [L_sun/Hz]; gives ``log_qq`` (n_z, n_age).
None
ssp_ages_lgyr (n_age,) -- log10(age/yr) of the SSPs; ages inside both cubes are "young".
None
isoc_type str -- ZAU file suffix.
'mist'
nebnz int -- cube dimensions.
11
nebnage int -- cube dimensions.
11
nebnip int -- cube dimensions.
11
smooth_velocity bool -- ``sigma_smooth`` in km/s (True) or A.
True
sigma_smooth float -- intrinsic width of the painted lines (0: pixel floor only).
0.0
res_floor_fwhm_px float -- minimum painted FWHM in local pixels (FSPS: 2 pixels per FWHM,

sigma = pixel x 2 / 2.355, sps_setup.f90:999-1002).

2.0

Attributes:

Name Type Description
nebem_cont (nspec, nz, nage, nu) - -log10(L_nu / Q)
nebem_line (nemline, nz, nage, nu) - -log10(L / Q)
nebem_line_pos (nemline,) -- rest wavelengths [A]
gaussnebarr (nspec, nemline) -- painted profiles including lambda^2/c
young_mask, young_idx the young ages over ``ssp_ages_lgyr``
Source code in ceridwen/neb/NebularGridModel.py
def __init__(self,
             cloudy_dust=False,
             sps_home=None,
             csp_lambda=None,
             ssp_flux=None,
             ssp_ages_lgyr=None,
             isoc_type='mist',
             nebnz=11, nebnage=10, nebnip=7,
             smooth_velocity=True,
             sigma_smooth=0.0,
             res_floor_fwhm_px=2.0,
             nebular_smooth_init=None,
             **removed):
    if nebular_smooth_init is not None:
        sigma_smooth = float(nebular_smooth_init)

    self.csp_lambda = jnp.asarray(csp_lambda)
    self.nspec      = int(self.csp_lambda.size)

    self.smooth_velocity = bool(smooth_velocity)
    self.sigma_smooth    = float(sigma_smooth)
    if "res_floor_factor" in removed:
        old = float(removed.pop("res_floor_factor"))
        raise TypeError(
            "NebularModel(res_floor_factor=) was removed in 1.0.14: it was the minimum line "
            "SIGMA in model-grid pixels. The floor is now res_floor_fwhm_px, the minimum "
            "FWHM in pixels (sigma = res_floor_fwhm_px / 2.355, as in FSPS; default 2). "
            f"The old width is res_floor_fwhm_px={old * FWHM_PER_SIGMA:g} "
            f"(res_floor_factor x 2.355).")
    if removed:
        raise TypeError(f"NebularModel() got unexpected keyword argument(s) {sorted(removed)}")
    self.res_floor_fwhm_px = float(res_floor_fwhm_px)

    self.nebnz   = int(nebnz)
    self.nebnage = int(nebnage)
    self.nebnip  = int(nebnip)

    if sps_home is None or csp_lambda is None:
        raise TypeError("NebularModel needs sps_home= and csp_lambda=")
    self.cloudy_dust = bool(cloudy_dust)
    suffix = 'WD' if self.cloudy_dust else 'ND'
    base = Path(sps_home) / 'nebular' / f'ZAU_{suffix}_{isoc_type}'
    self.cont_file = base.with_suffix('.cont')
    self.line_file = base.with_suffix('.lines')

    self._load_continuum()
    self._load_lines()
    self._compute_resolution_elements()
    self._build_gaussians()

    if ssp_flux is not None:
        self.log_qq = self.compute_log_qq(jnp.asarray(ssp_flux))
    else:
        self.log_qq = None

    if ssp_ages_lgyr is not None:
        ages = jnp.asarray(ssp_ages_lgyr)
        max_age = min(float(self.nebem_cont_age[-1]),
                      float(self.nebem_line_age[-1]))
        young = ages <= max_age
        self.young_mask = young
        self.young_idx  = jnp.where(young)[0]
        n_young = int(np.asarray(young).sum())
        oldest_young_yr = (10.0 ** float(np.asarray(ages)[
            np.asarray(young)].max()) if n_young else 0.0)
        if n_young == 0 or oldest_young_yr > 3.2e8:
            raise RuntimeError(
                "Nebular young-SSP mask is inconsistent with the CLOUDY "
                f"grid: {n_young} SSPs flagged young, oldest "
                f"{oldest_young_yr/1e6:.1f} Myr (grid max_age "
                f"{max_age:.3f} log10 yr). Check the cube age-axis "
                "units.")
    else:
        self.young_mask = None
        self.young_idx  = None

    self.emline_index_consistent = None
    self.nebem_line_names = None
    try:
        _info_path = str(Path(sps_home) / "data" / "emlines_info.dat")
        _info_wave = []
        _info_name = []
        with open(_info_path) as _f:
            for _row in _f:
                _parts = _row.split(",")
                if len(_parts) >= 2:
                    _info_wave.append(float(_parts[0]))
                    _info_name.append(_parts[1].strip())
        _info_wave = np.asarray(_info_wave)
        _pos = np.asarray(self.nebem_line_pos)
        # names per cube row, matched by wavelength (1 A) like CSPBasis matches Lines
        if _info_wave.size:
            _j = np.argmin(np.abs(_pos[:, None] - _info_wave[None, :]), axis=1)
            self.nebem_line_names = [
                _info_name[j] if abs(_pos[i] - _info_wave[j]) <= 1.0 else None
                for i, j in enumerate(_j)]
        if _info_wave.size != _pos.size:
            self.emline_index_consistent = False
            warnings.warn(
                f"emlines_info.dat lists {_info_wave.size} lines but the "
                f"nebular cube {getattr(self, 'line_file', '?')} has "
                f"{_pos.size} -- the two files are from different FSPS "
                "vintages. Raw line_ind indices into this cube are "
                "UNRELIABLE; ceridwen's own predictions match lines by "
                "wavelength and are unaffected.", stacklevel=2)
        else:
            _n = min(_info_wave.size, _pos.size)
            _bad = int(np.sum(np.abs(_info_wave[:_n] - _pos[:_n]) > 1.0))
            self.emline_index_consistent = (_bad == 0)
            if _bad:
                warnings.warn(
                    f"{_bad}/{_n} rows of emlines_info.dat disagree with "
                    "the nebular cube wavelengths by >1 A -- mixed FSPS "
                    "vintages in $SPS_HOME. Raw line_ind indices into "
                    "this cube are UNRELIABLE; ceridwen's own predictions "
                    "match lines by wavelength and are unaffected.",
                    stacklevel=2)
    except OSError:
        pass                              # no emlines_info.dat: nothing to check

compute_log_qq

compute_log_qq(ssp_flux)

log10 Q [photons/s] for every SSP: (L_sun/h) * int_{lambda<912} L_nu / lambda dlambda (the working float dtype, float64 by default).

Source code in ceridwen/neb/NebularGridModel.py
def compute_log_qq(self, ssp_flux):
    """log10 Q [photons/s] for every SSP: (L_sun/h) * int_{lambda<912} L_nu / lambda dlambda (the working float dtype, float64 by default)."""
    mask = self.csp_lambda < LYMAN_LIMIT_AA
    scale = LSUN_ERG_S / HPLANK_ERG_S
    if not is_x64():
        # float32 mode (docs/mac_gpu.md): scale (5.8e59) and TINY (1e-95) are outside float32
        # (qq * scale overflowed to inf and made every prediction NaN).  The table is a
        # construction-time constant, so it is computed on the host in float64, as the
        # float64 path does on the device, and stored in the working dtype.
        m = np.asarray(mask)
        wave_ion = np.asarray(self.csp_lambda, dtype=np.float64)[m]
        flux_ion = np.asarray(ssp_flux, dtype=np.float64)[..., m]
        qq = np.trapezoid(flux_ion / wave_ion, x=wave_ion)
        return jnp.asarray(np.log10(np.maximum(qq * scale, TINY)), dtype=float_dtype())
    wave_ion = self.csp_lambda[mask].astype(float_dtype())
    flux_ion = ssp_flux[..., mask].astype(float_dtype())
    qq = jnp.trapezoid(flux_ion / wave_ion, x=wave_ion)
    return jnp.log10(jnp.maximum(qq * scale, TINY))

line_profiles

line_profiles(sigma_kms=0.0)

(nspec, nemline) NumPy profiles like gaussnebarr with width sqrt(floor^2 + (lambda sigma_kms / c)^2): a line painted at the floor and then broadened.

Source code in ceridwen/neb/NebularGridModel.py
def line_profiles(self, sigma_kms=0.0):
    """(nspec, nemline) NumPy profiles like ``gaussnebarr`` with width
    sqrt(floor^2 + (lambda sigma_kms / c)^2): a line painted at the floor and then broadened.
    """
    pos = np.asarray(self.nebem_line_pos, dtype=np.float64)
    lam = np.asarray(self.csp_lambda, dtype=np.float64)
    floor = np.asarray(self.neb_res_min, dtype=np.float64) * self.res_floor_fwhm_px / FWHM_PER_SIGMA
    if self.smooth_velocity:
        base = pos * self.sigma_smooth / CLIGHT_AA_S * 1.0e13
    else:
        base = np.full_like(pos, self.sigma_smooth)
    dl0 = np.maximum(base, floor)
    dl = np.sqrt(dl0 ** 2 + (pos * float(sigma_kms) / CLIGHT_AA_S * 1.0e13) ** 2)
    prof = np.exp(-0.5 * ((lam[:, None] - pos[None, :]) / dl[None, :]) ** 2)
    return prof / (SQRT_2PI * dl[None, :]) * (pos[None, :] ** 2 / CLIGHT_AA_S)

evaluate

evaluate(logZ, logU, logage, logQ)

(cont (nspec,), lines (nspec,)) [L_sun/Hz] at one (logZ, logU, logage, logQ).

Source code in ceridwen/neb/NebularGridModel.py
def evaluate(self, logZ, logU, logage, logQ):
    """``(cont (nspec,), lines (nspec,))`` [L_sun/Hz] at one (logZ, logU, logage, logQ)."""
    zc  = _locate(logZ,   self.nebem_cont_logz)
    dzc = _frac(logZ,     self.nebem_cont_logz, zc)
    uc  = _locate(logU,   self.nebem_cont_logu)
    duc = _frac(logU,     self.nebem_cont_logu, uc)
    ac  = _locate(logage, self.nebem_cont_age)
    dac = _frac(logage,   self.nebem_cont_age,  ac)
    log_cont = _trilinear(self.nebem_cont, zc, dzc, ac, dac, uc, duc)

    zl  = _locate(logZ,   self.nebem_line_logz)
    dzl = _frac(logZ,     self.nebem_line_logz, zl)
    ul  = _locate(logU,   self.nebem_line_logu)
    dul = _frac(logU,     self.nebem_line_logu, ul)
    al  = _locate(logage, self.nebem_line_age)
    dal = _frac(logage,   self.nebem_line_age,  al)
    log_line = _trilinear(self.nebem_line, zl, dzl, al, dal, ul, dul)

    cont_flux = jnp.power(10.0, log_cont + logQ)
    line_lum  = jnp.power(10.0, log_line + logQ)
    line_spec = self.gaussnebarr @ line_lum
    return cont_flux, line_spec

evaluate_batch

evaluate_batch(
    logZ_gas,
    logU,
    ssp_ages_young,
    logqq_young,
    return_components=False,
)

(n_z, n_young, nspec) nebular spectra at one (logZ_gas, logU) for the young SSP ages, or (cont, lines) in that layout with return_components. The metallicity dependence enters only through logqq_young; the per-age reference ref keeps 10**(...) in float32 range.

Source code in ceridwen/neb/NebularGridModel.py
def evaluate_batch(self, logZ_gas, logU, ssp_ages_young, logqq_young,
                    return_components=False):
    """(n_z, n_young, nspec) nebular spectra at one (logZ_gas, logU) for the young SSP ages,
    or ``(cont, lines)`` in that layout with ``return_components``.  The metallicity dependence
    enters only through ``logqq_young``; the per-age reference ``ref`` keeps 10**(...) in float32 range.
    """
    logZ_gas = jnp.squeeze(logZ_gas)
    logU     = jnp.squeeze(logU)

    def _interp_cube(cube, logz_grid, age_grid, logu_grid):
        z1 = _locate(logZ_gas, logz_grid)
        dz = _frac(logZ_gas,   logz_grid, z1)
        u1 = _locate(logU,     logu_grid)
        du = _frac(logU,       logu_grid, u1)

        w00 = (1.0 - dz) * (1.0 - du)
        w01 = (1.0 - dz) *       du
        w10 =       dz   * (1.0 - du)
        w11 =       dz   *       du
        zu = (w00 * cube[..., z1,     :, u1    ]
            + w01 * cube[..., z1,     :, u1 + 1]
            + w10 * cube[..., z1 + 1, :, u1    ]
            + w11 * cube[..., z1 + 1, :, u1 + 1])

        a1 = jnp.clip(jnp.searchsorted(age_grid, ssp_ages_young) - 1,
                      0, age_grid.shape[0] - 2)
        da = jnp.clip(
            (ssp_ages_young - age_grid[a1])
            / (age_grid[a1 + 1] - age_grid[a1]),
            0.0, 1.0,
        )
        return (1.0 - da)[None, :] * zu[..., a1] + da[None, :] * zu[..., a1 + 1]

    log_cont = _interp_cube(self.nebem_cont,
                            self.nebem_cont_logz,
                            self.nebem_cont_age,
                            self.nebem_cont_logu)                     # (nspec , n_young)
    log_line = _interp_cube(self.nebem_line,
                            self.nebem_line_logz,
                            self.nebem_line_age,
                            self.nebem_line_logu)                     # (nlines, n_young)

    ref   = jnp.max(logqq_young, axis=0)                          # (n_young,)
    ref   = jnp.where(jnp.isfinite(ref), ref, 0.0)
    scale = jnp.power(10.0, logqq_young - ref[None, :])            # (n_z, n_young)

    cont_base = jnp.power(10.0, log_cont + ref[None, :])           # (nspec , n_young)
    line_base = jnp.einsum('wl,ly->wy', self.gaussnebarr,
                           jnp.power(10.0, log_line + ref[None, :]))
    cont_flux = cont_base[None, :, :] * scale[:, None, :]          # (n_z, nspec, n_young)
    line_spec = line_base[None, :, :] * scale[:, None, :]          # (n_z, nspec, n_young)
    if return_components:
        return (cont_flux.transpose(0, 2, 1),
                line_spec.transpose(0, 2, 1))
    return (cont_flux + line_spec).transpose(0, 2, 1)

evaluate_batch_factored

evaluate_batch_factored(
    logZ_gas,
    logU,
    ssp_ages_young,
    logqq_young,
    include_lines=True,
)

(base (n_young, n_wave), scale (n_z, n_young)) with neb[z, y, w] == scale[z, y] * base[y, w] (same arithmetic as evaluate_batch, not expanded). include_lines="both" returns (base_continuum, base_with_lines, scale) from one evaluation.

Source code in ceridwen/neb/NebularGridModel.py
def evaluate_batch_factored(self, logZ_gas, logU, ssp_ages_young,
                            logqq_young, include_lines=True):
    """``(base (n_young, n_wave), scale (n_z, n_young))`` with neb[z, y, w] == scale[z, y] * base[y, w]
    (same arithmetic as ``evaluate_batch``, not expanded).  ``include_lines="both"`` returns
    ``(base_continuum, base_with_lines, scale)`` from one evaluation.
    """
    logZ_gas = jnp.squeeze(logZ_gas)
    logU     = jnp.squeeze(logU)

    def _interp_cube(cube, logz_grid, age_grid, logu_grid):
        z1 = _locate(logZ_gas, logz_grid)
        dz = _frac(logZ_gas,   logz_grid, z1)
        u1 = _locate(logU,     logu_grid)
        du = _frac(logU,       logu_grid, u1)
        w00 = (1.0 - dz) * (1.0 - du)
        w01 = (1.0 - dz) *       du
        w10 =       dz   * (1.0 - du)
        w11 =       dz   *       du
        zu = (w00 * cube[..., z1,     :, u1    ]
            + w01 * cube[..., z1,     :, u1 + 1]
            + w10 * cube[..., z1 + 1, :, u1    ]
            + w11 * cube[..., z1 + 1, :, u1 + 1])
        a1 = jnp.clip(jnp.searchsorted(age_grid, ssp_ages_young) - 1,
                      0, age_grid.shape[0] - 2)
        da = jnp.clip(
            (ssp_ages_young - age_grid[a1])
            / (age_grid[a1 + 1] - age_grid[a1]),
            0.0, 1.0,
        )
        return (1.0 - da)[None, :] * zu[..., a1] + da[None, :] * zu[..., a1 + 1]

    log_cont = _interp_cube(self.nebem_cont, self.nebem_cont_logz,
                            self.nebem_cont_age, self.nebem_cont_logu)
    ref   = jnp.max(logqq_young, axis=0)
    ref   = jnp.where(jnp.isfinite(ref), ref, 0.0)
    scale = jnp.power(10.0, logqq_young - ref[None, :])            # (n_z, n_young)

    # the interpolation and 10**(...) in float64 (log values near 50: float32 would overflow
    # or cost ~1e-5 in 10**x); the profiles and their (n_wave, n_lines) contraction in
    # float32, the precision csp.py keeps of this result anyway (it casts it to float32
    # before its own contraction)
    base = jnp.power(10.0, log_cont + ref[None, :]).astype(jnp.float32)   # (nspec, n_young)
    if include_lines:
        log_line = _interp_cube(self.nebem_line, self.nebem_line_logz,
                                self.nebem_line_age, self.nebem_line_logu)
        base_full = base + jnp.einsum(
            'wl,ly->wy', self.gaussnebarr.astype(jnp.float32),
            jnp.power(10.0, log_line + ref[None, :]).astype(jnp.float32))
        if include_lines == "both":
            return base.T, base_full.T, scale
        base = base_full
    return base.T, scale                                           # (n_young, n_wave), (n_z, n_young)

evaluate_batch_line_lum

evaluate_batch_line_lum(
    logZ_gas, logU, ssp_ages_young, logqq_young
)

Line luminosities (n_z, n_young, nlines) [L_sun] at one (logZ_gas, logU), no painting.

Source code in ceridwen/neb/NebularGridModel.py
def evaluate_batch_line_lum(self, logZ_gas, logU, ssp_ages_young,
                            logqq_young):
    """Line luminosities (n_z, n_young, nlines) [L_sun] at one (logZ_gas, logU), no painting."""
    logZ_gas = jnp.squeeze(logZ_gas)
    logU     = jnp.squeeze(logU)
    cube      = self.nebem_line
    logz_grid = self.nebem_line_logz
    age_grid  = self.nebem_line_age
    logu_grid = self.nebem_line_logu

    z1 = _locate(logZ_gas, logz_grid)
    dz = _frac(logZ_gas,   logz_grid, z1)
    u1 = _locate(logU,     logu_grid)
    du = _frac(logU,       logu_grid, u1)
    w00 = (1.0 - dz) * (1.0 - du)
    w01 = (1.0 - dz) *       du
    w10 =       dz   * (1.0 - du)
    w11 =       dz   *       du
    zu = (w00 * cube[..., z1,     :, u1    ]
        + w01 * cube[..., z1,     :, u1 + 1]
        + w10 * cube[..., z1 + 1, :, u1    ]
        + w11 * cube[..., z1 + 1, :, u1 + 1])          # (nlines, nage)

    a1 = jnp.clip(jnp.searchsorted(age_grid, ssp_ages_young) - 1,
                  0, age_grid.shape[0] - 2)
    da = jnp.clip(
        (ssp_ages_young - age_grid[a1])
        / (age_grid[a1 + 1] - age_grid[a1]),
        0.0, 1.0,
    )
    log_line = ((1.0 - da)[None, :] * zu[..., a1]
                +       da[None, :] * zu[..., a1 + 1])   # (nlines, n_young)

    line_lum = jnp.power(10.0, log_line[None, :, :]
                         + logqq_young[:, None, :])
    return line_lum.transpose(0, 2, 1)

get_default_params

get_default_params()

Default nebular parameters (gas_logz = 0, gas_logu = -2).

Source code in ceridwen/neb/NebularGridModel.py
def get_default_params(self):
    """Default nebular parameters (gas_logz = 0, gas_logu = -2)."""
    return {'gas_logz': jnp.asarray(0.0),
            'gas_logu': jnp.asarray(-2.0)}

ceridwen.igm

Intergalactic-medium absorption models: transmission curves exp(-tau * factor) on the rest-frame wavelength grid at a given source redshift.

IGMModel

Bases: ABC

Abstract IGM attenuation model; subclasses implement tau(lam_rest, zred).

A model that reads theta keys of its own lists them in param_names; the CSP then passes attenuation(..., params={key: scalar}) with those of the keys present in theta (and only then, so a subclass with the three-argument attenuation keeps working).

tau abstractmethod

tau(lam_rest, zred)

Optical depth on the rest-frame wavelength grid [Å] at source redshift zred.

Source code in ceridwen/igm.py
@abc.abstractmethod
def tau(self, lam_rest: Array, zred: Array) -> Array:
    """Optical depth on the rest-frame wavelength grid [Å] at source redshift ``zred``."""

attenuation

attenuation(lam_rest, zred, factor=1.0)

Transmission curve exp(-tau * factor).

Source code in ceridwen/igm.py
def attenuation(self, lam_rest: Array, zred: Array,
                factor: Union[Array, float] = 1.0) -> Array:
    """Transmission curve ``exp(-tau * factor)``."""
    return jnp.exp(-self.tau(lam_rest, zred) * factor)

NoIGM

Bases: IGMModel

Identity IGM: zero optical depth at every wavelength.

Madau1995

Bases: IGMModel

Madau (1995) IGM attenuation: 17 Lyman-series lines, Ly-α metal blanketing and Lyman-continuum absorption; tau is capped at its short-wavelength peak and is zero at zred = 0.

MadauDampingDLA

MadauDampingDLA(
    Ob0=None,
    cosmo=None,
    x_HI=0.0,
    zmin=5.0,
    Y=0.25,
    logN_HI=None,
    z_dla=None,
    b_kms=40.0,
)

Bases: Madau1995

Madau (1995) x IGM damping wing x damped Ly-alpha absorber (DLA).

attenuation = exp(-(igm_factor * tau_Madau + tau_damp(x_HI) + tau_DLA(logN_HI, z_dla)))

igm_factor scales the Madau forest only; the neutral fraction is its own parameter (Prospector instead reads x_HI from igm_factor, sedmodel.py:824).

x_HI, logN_HI and z_dla are theta keys like igm_factor: the constructor values are the defaults, and a theta entry (fixed or sampled) overrides them. A component is evaluated when its constructor value switches it on or its key is in theta; otherwise it is skipped, so MadauDampingDLA() is Madau1995 bit for bit, and so are x_HI = 0 and logN_HI = -inf.

Parameters:

Name Type Description Default
Ob0 float -- baryon density today; required for the damping wing (CERIDWEN's Cosmology

carries no Ob0, so it is not guessed). Planck18: 0.04897; WMAP9: 0.04628.

None
cosmo Cosmology or None -- supplies ``h`` and ``Om0``; ``None`` = the CSP's cosmology,

bound at CSPBasis construction (a different one given here raises there).

None
x_HI float -- IGM neutral fraction (> 1 mimics a local overdensity); 0 = no damping wing.
0.0
zmin float -- lower redshift of the neutral IGM; no wing for ``zred <= zmin``.
5.0
Y float -- helium mass fraction.
0.25
logN_HI float or None -- DLA column [log10 cm^-2]; ``None`` = no DLA.
None
z_dla float or None -- absorber redshift; ``None`` = the source redshift. No DLA for

z_dla > zred. A foreground absorber is placed at rest wavelength 1215.67 (1 + z_dla) / (1 + zred) (Prospector's add_dla, sedmodel.py:816, divides the other way and puts it redward of Ly-alpha; they agree at z_dla = zred).

None
b_kms float -- Doppler parameter of the DLA [km/s].
40.0
Source code in ceridwen/igm.py
def __init__(self, Ob0=None, cosmo=None, x_HI=0.0, zmin=5.0, Y=0.25,
             logN_HI=None, z_dla=None, b_kms=40.0):
    x_HI = float(x_HI)
    if not x_HI >= 0.0:
        raise ValueError(f"x_HI must be >= 0, got {x_HI}")
    if Ob0 is not None and not float(Ob0) > 0.0:
        raise ValueError(f"Ob0 must be > 0, got {Ob0}")
    if logN_HI is not None and np.isnan(float(logN_HI)):
        raise ValueError("logN_HI is NaN; pass None for no DLA")
    self.x_HI = x_HI
    self.zmin = float(zmin)
    self.Y = float(Y)
    self.Ob0 = None if Ob0 is None else float(Ob0)
    self.cosmo = None
    self.h = self.Om0 = None
    if cosmo is not None:
        self.bind_cosmology(cosmo)
    self.logN_HI = None if logN_HI is None else float(logN_HI)
    self.z_dla = None if z_dla is None else float(z_dla)
    self.b_kms = float(b_kms)
    if self.x_HI > 0.0 and self.Ob0 is None:
        raise ValueError(
            f"x_HI = {self.x_HI} > 0 switches on the damping wing, which needs Ob0= "
            "(baryon density; Planck18 0.04897, WMAP9 0.04628): CERIDWEN's Cosmology "
            "has no Ob0, so it is not guessed")

bind_cosmology

bind_cosmology(cosmo)

Take h and Om0 from cosmo; a model already bound to a different cosmology raises (the damping wing and the flux factor would disagree).

Source code in ceridwen/igm.py
def bind_cosmology(self, cosmo):
    """Take ``h`` and ``Om0`` from ``cosmo``; a model already bound to a different
    cosmology raises (the damping wing and the flux factor would disagree)."""
    h, Om0 = float(cosmo.h), float(cosmo.Om0)
    if self.cosmo is not None and (h, Om0) != (self.h, self.Om0):
        raise ValueError(
            f"{type(self).__name__} was built with cosmology h={self.h}, Om0={self.Om0} "
            f"but the CSP uses h={h}, Om0={Om0}; pass the same Cosmology, or cosmo=None "
            "to take the CSP's")
    self.cosmo, self.h, self.Om0 = cosmo, h, Om0

tau_damp

tau_damp(lam_rest, zred, params=None)

Damping-wing optical depth; params['x_HI'] overrides the constructor value.

Source code in ceridwen/igm.py
def tau_damp(self, lam_rest, zred, params=None):
    """Damping-wing optical depth; ``params['x_HI']`` overrides the constructor value."""
    sampled = params is not None and "x_HI" in params
    if not sampled and self.x_HI == 0.0:
        return jnp.zeros_like(lam_rest)
    if self.Ob0 is None:
        raise ValueError(
            "theta['x_HI'] switches on the damping wing, which needs the baryon density: "
            "build the model as MadauDampingDLA(Ob0=...) and pass it as CSPBasis(igm_model=...)")
    if self.h is None:
        raise ValueError(
            "MadauDampingDLA has no cosmology: pass cosmo= or use it through "
            "CSPBasis(igm_model=...), which binds the CSP's")
    x_HI = self._get(params, "x_HI", self.x_HI)
    return tau_damping(lam_rest, zred, x_HI, self.h, self.Om0, self.Ob0,
                       zmin=self.zmin, Y=self.Y)

tau_dla

tau_dla(lam_rest, zred, params=None)

DLA Voigt optical depth; params['logN_HI'] / params['z_dla'] override.

Source code in ceridwen/igm.py
def tau_dla(self, lam_rest, zred, params=None):
    """DLA Voigt optical depth; ``params['logN_HI']`` / ``params['z_dla']`` override."""
    sampled = params is not None and "logN_HI" in params
    if not sampled and self.logN_HI is None:
        return jnp.zeros_like(lam_rest)
    N = 10.0 ** self._get(params, "logN_HI", self.logN_HI)
    z_abs = self._get(params, "z_dla", zred if self.z_dla is None else self.z_dla)
    wave_abs = lam_rest * (1 + zred) / (1 + z_abs)
    tau = voigt_tau(wave_abs, N, bkms=self.b_kms)
    return jnp.where(z_abs > zred, 0.0, tau)

attenuation

attenuation(lam_rest, zred, factor=1.0, params=None)

exp(-(factor * tau_Madau + tau_damp + tau_DLA)): igm_factor scales the forest only.

Source code in ceridwen/igm.py
def attenuation(self, lam_rest, zred, factor=1.0, params=None):
    """``exp(-(factor * tau_Madau + tau_damp + tau_DLA))``: ``igm_factor`` scales the forest only."""
    return jnp.exp(-(self.tau_madau(lam_rest, zred) * factor
                     + self.tau_damp(lam_rest, zred, params)
                     + self.tau_dla(lam_rest, zred, params)))

voigt_tau

voigt_tau(
    wave_abs,
    N,
    bkms=40.0,
    l0=_LYA,
    f=_F_LYA,
    gamma=_GAMMA_LYA,
)

Optical depth of a Voigt line (Krogager 2018 normalisation) on wave_abs [A, absorber rest frame] for a column density N [cm^-2]; Ly-alpha by default.

Source code in ceridwen/igm.py
def voigt_tau(wave_abs, N, bkms=40.0, l0=_LYA, f=_F_LYA, gamma=_GAMMA_LYA):
    """Optical depth of a Voigt line (Krogager 2018 normalisation) on ``wave_abs`` [A, absorber
    rest frame] for a column density ``N`` [cm^-2]; Ly-alpha by default."""
    l0_cm = l0 * 1.e-8
    b = bkms * 1e5
    C_a = _VOIGT_CONST * f * l0_cm / b
    a = l0_cm * gamma / (4. * jnp.pi * b)
    x = (_C_CMS / b) * (1. - l0 / wave_abs)
    return C_a * N * _voigt_H(a, x)

tau_gp

tau_gp(zred, h, Om0, Ob0, Y=0.25)

Gunn-Peterson optical depth, Miralda-Escude (1998) normalisation.

Source code in ceridwen/igm.py
def tau_gp(zred, h, Om0, Ob0, Y=0.25):
    """Gunn-Peterson optical depth, Miralda-Escude (1998) normalisation."""
    scale = (1 - Y) * h * Om0 ** (-0.5) * (Ob0 / 0.03)
    return 2.6e5 * scale * ((1 + zred) / 7) ** (3 / 2)

tau_damping

tau_damping(
    wave_rest,
    zred,
    x_HI,
    h,
    Om0,
    Ob0,
    zmin=5.0,
    Y=0.25,
    l0=_LYA,
)

Damping-wing optical depth of a uniformly neutral IGM (neutral fraction x_HI) between zmin and zred (Miralda-Escude 1998; Totani et al. 2006), on the rest-frame grid. Zero blueward of Ly-alpha and for zred <= zmin; masked with safe arguments so jit and gradients stay finite.

Source code in ceridwen/igm.py
def tau_damping(wave_rest, zred, x_HI, h, Om0, Ob0, zmin=5.0, Y=0.25, l0=_LYA):
    """Damping-wing optical depth of a uniformly neutral IGM (neutral fraction ``x_HI``) between
    ``zmin`` and ``zred`` (Miralda-Escude 1998; Totani et al. 2006), on the rest-frame grid.
    Zero blueward of Ly-alpha and for ``zred <= zmin``; masked with safe arguments so ``jit``
    and gradients stay finite."""
    wave_obs = wave_rest * (1 + zred)
    zobs = wave_obs / l0 - 1
    red = ((zobs - zred) / (1 + zobs) > (100 * _R_ALPHA)) & (zred > zmin)
    x1 = jnp.where(red, (1 + zred) / (1 + zobs), 0.5)
    x2 = jnp.where(red, (1 + zmin) / (1 + zobs), 0.25)
    xx = _Ix(x1) - _Ix(x2)
    zobs_s = jnp.where(red, zobs, zred)
    tau = _R_ALPHA / jnp.pi * x_HI * tau_gp(zred, h, Om0, Ob0, Y=Y)
    tau = tau * ((1 + zobs_s) / (1 + zred)) ** (3 / 2) * xx
    return jnp.where(red, tau, 0.0)

make_igm_model

make_igm_model(name_or_model)

Return an :class:IGMModel from a registry name, an instance (as-is), or None (NoIGM).

Source code in ceridwen/igm.py
def make_igm_model(name_or_model):
    """Return an :class:`IGMModel` from a registry name, an instance (as-is), or ``None`` (NoIGM)."""
    if name_or_model is None:
        return NoIGM()
    if isinstance(name_or_model, IGMModel):
        return name_or_model
    name = str(name_or_model).lower().strip()
    if name not in _MODEL_REGISTRY:
        raise ValueError(
            f"Unknown IGM model {name!r}.  "
            f"Available: {sorted(_MODEL_REGISTRY)}"
        )
    return _MODEL_REGISTRY[name]()

ceridwen.cosmology

Flat LambdaCDM redshift helpers: :class:Cosmology presets, D_L(z), age(z) and the maggies flux factor, JAX-native (differentiable in z) with an optional scalar-only astropy backend.

Cosmology dataclass

Cosmology(
    H0=67.66,
    Om0=0.30966,
    Tcmb0=2.7255,
    Neff=3.046,
    m_nu_ev_sum=0.06,
    name=None,
)

Flat LambdaCDM cosmology with photons and effective neutrinos; the massive neutrino is folded into Om0 as cold matter. Defaults to Planck 2018.

Parameters:

Name Type Description Default
H0 (float, km / s / Mpc)
67.66
Om0 float -- cold matter today, EXCLUDING massive neutrinos.
0.30966
Tcmb0 (float, K)
2.7255
Neff float -- effective number of neutrino species.
3.046
m_nu_ev_sum float, eV -- sum of neutrino masses.
0.06
name str -- label only; ignored in equality.
None

Ogamma0 property

Ogamma0

Photon density today.

Onu0_massive_as_matter property

Onu0_massive_as_matter

Massive-neutrino density today, treated as cold matter.

Onu0_relativistic property

Onu0_relativistic

Relativistic neutrino density today (Neff - 1 species).

Om0_eff property

Om0_eff

Matter density today including massive neutrinos.

Or0 property

Or0

Radiation + relativistic-neutrino density today.

Ode0 property

Ode0

Dark-energy density today (flat: 1 - Om0_eff - Or0).

is_planck18 property

is_planck18

True when the parameters equal the Planck-2018 preset (name ignored).

wmap9 classmethod

wmap9()

WMAP9 preset.

Source code in ceridwen/cosmology.py
@classmethod
def wmap9(cls) -> "Cosmology":
    """WMAP9 preset."""
    return cls(**_PRESETS["WMAP9"], name="WMAP9")

flat classmethod

flat(
    H0,
    Om0,
    *,
    Tcmb0=2.7255,
    Neff=3.046,
    m_nu_ev_sum=0.06,
    name=None
)

Flat LCDM from H0 and Om0; radiation and neutrinos default to Planck 2018.

Source code in ceridwen/cosmology.py
@classmethod
def flat(cls, H0: float, Om0: float, *, Tcmb0: float = 2.7255,
         Neff: float = 3.046, m_nu_ev_sum: float = 0.06,
         name: Optional[str] = None) -> "Cosmology":
    """Flat LCDM from H0 and Om0; radiation and neutrinos default to Planck 2018."""
    return cls(H0=H0, Om0=Om0, Tcmb0=Tcmb0, Neff=Neff,
               m_nu_ev_sum=m_nu_ev_sum, name=name)

from_name classmethod

from_name(name)

Preset by name, case-insensitive (see available_cosmologies()).

Source code in ceridwen/cosmology.py
@classmethod
def from_name(cls, name: str) -> "Cosmology":
    """Preset by name, case-insensitive (see ``available_cosmologies()``)."""
    key = {k.lower(): k for k in _PRESETS}.get(str(name).strip().lower())
    if key is None:
        raise KeyError(
            f"unknown cosmology preset {name!r}; known: {', '.join(_PRESETS)}")
    return cls(**_PRESETS[key], name=key)

from_dict classmethod

from_dict(d)

Inverse of :meth:to_dict; also accepts cosmo_*-prefixed HDF5 attrs.

Source code in ceridwen/cosmology.py
@classmethod
def from_dict(cls, d) -> "Cosmology":
    """Inverse of :meth:`to_dict`; also accepts ``cosmo_*``-prefixed HDF5 attrs."""
    d = dict(d)
    if "H0" not in d and "cosmo_H0" in d:
        d = {k[len("cosmo_"):]: v for k, v in d.items() if k.startswith("cosmo_")}
    missing = [k for k in _FIELDS if k not in d]
    if missing:
        raise KeyError(f"Cosmology.from_dict: missing {missing} (have {sorted(d)})")
    name = d.get("name", None)
    if isinstance(name, bytes):
        name = name.decode()
    if name is not None:
        name = str(name).strip() or None
    return cls(**{k: float(d[k]) for k in _FIELDS}, name=name)

to_dict

to_dict()

Plain floats plus name ("" when unnamed).

Source code in ceridwen/cosmology.py
def to_dict(self) -> dict:
    """Plain floats plus ``name`` ("" when unnamed)."""
    d = {k: float(getattr(self, k)) for k in _FIELDS}
    d["name"] = self.name or ""
    return d

age

age(z)

Age of the Universe at z [Gyr].

Source code in ceridwen/cosmology.py
def age(self, z) -> Array:
    """Age of the Universe at ``z`` [Gyr]."""
    return age_gyr(z, self)

luminosity_distance

luminosity_distance(z)

D_L(z) [Mpc].

Source code in ceridwen/cosmology.py
def luminosity_distance(self, z) -> Array:
    """D_L(z) [Mpc]."""
    return luminosity_distance_mpc(z, self)

from_astropy classmethod

from_astropy(cosmo)

Build from a flat astropy cosmology; a non-flat input raises.

Source code in ceridwen/cosmology.py
@classmethod
def from_astropy(cls, cosmo) -> "Cosmology":
    """Build from a flat astropy cosmology; a non-flat input raises."""
    Ok0 = float(getattr(cosmo, "Ok0", 0.0))
    if abs(Ok0) > 1e-8:
        raise ValueError(
            f"ceridwen's cosmology integrator assumes flatness, but the "
            f"supplied cosmology has Ok0 = {Ok0:.3e}."
        )
    m_nu = getattr(cosmo, "m_nu", None)
    if m_nu is None:
        m_nu_sum = 0.0
    else:
        try:
            m_nu_sum = float(m_nu.to("eV").value.sum())
        except AttributeError:
            m_nu_sum = float(m_nu.to("eV").value)
    return cls(
        H0=float(cosmo.H0.to("km/(s Mpc)").value),
        Om0=float(cosmo.Om0),
        Tcmb0=float(cosmo.Tcmb0.to("K").value),
        Neff=float(cosmo.Neff),
        m_nu_ev_sum=m_nu_sum,
        name=(str(cosmo.name) if getattr(cosmo, "name", None) else None),
    )

to_astropy

to_astropy()

Return the matching astropy.cosmology.FlatLambdaCDM (requires astropy).

Source code in ceridwen/cosmology.py
def to_astropy(self):
    """Return the matching ``astropy.cosmology.FlatLambdaCDM`` (requires astropy)."""
    import math

    import astropy.units as u
    from astropy.cosmology import FlatLambdaCDM

    kwargs = dict(
        H0=self.H0 * u.km / u.s / u.Mpc,
        Om0=self.Om0,
        Tcmb0=self.Tcmb0 * u.K,
        Neff=self.Neff,
    )
    # astropy needs len(m_nu) == floor(Neff); total mass on the last species
    n_species = math.floor(self.Neff)
    if n_species > 0 and self.Tcmb0 > 0.0:
        masses = [0.0] * n_species
        masses[-1] = self.m_nu_ev_sum
        kwargs["m_nu"] = u.Quantity(masses, u.eV)
    return FlatLambdaCDM(**kwargs)

available_cosmologies

available_cosmologies()

Names accepted by :meth:Cosmology.from_name.

Source code in ceridwen/cosmology.py
def available_cosmologies() -> tuple:
    """Names accepted by :meth:`Cosmology.from_name`."""
    return tuple(_PRESETS)

resolve_cosmology

resolve_cosmology(cosmo=None)

Return cosmo, or Planck 2018 when None.

Source code in ceridwen/cosmology.py
def resolve_cosmology(cosmo: "Cosmology | None" = None) -> Cosmology:
    """Return ``cosmo``, or Planck 2018 when ``None``."""
    return DEFAULT_COSMO if cosmo is None else cosmo

E_of_z

E_of_z(z, cosmo=None)

Dimensionless expansion rate E(z) = H(z)/H0; z is clamped to >= 0 so transient negative proposals cannot produce NaN.

Source code in ceridwen/cosmology.py
def E_of_z(z: Array, cosmo: Cosmology | None = None) -> Array:
    r"""Dimensionless expansion rate E(z) = H(z)/H0; ``z`` is clamped to >= 0
    so transient negative proposals cannot produce NaN."""
    cosmo = resolve_cosmology(cosmo)
    z = jnp.maximum(z, 0.0)
    opz = 1.0 + z
    return jnp.sqrt(
        opz * opz * opz * (cosmo.Or0 * opz + cosmo.Om0_eff)
        + cosmo.Ode0
    )

comoving_distance_mpc

comoving_distance_mpc(z, cosmo=None, n_nodes=128)

Line-of-sight comoving distance D_C(z) [Mpc].

Source code in ceridwen/cosmology.py
def comoving_distance_mpc(z: Array, cosmo: Cosmology | None = None,
                          n_nodes: int = 128) -> Array:
    r"""Line-of-sight comoving distance D_C(z) [Mpc]."""
    cosmo = resolve_cosmology(cosmo)
    return cosmo.hubble_distance_mpc * _integrate_dz_over_E(z, cosmo, n_nodes)

age_gyr

age_gyr(z, cosmo=None, n_nodes=257)

Age of the Universe at z [Gyr], JAX-native and differentiable in z.

Source code in ceridwen/cosmology.py
def age_gyr(z: Array, cosmo: Cosmology | None = None,
            n_nodes: int = 257) -> Array:
    r"""Age of the Universe at ``z`` [Gyr], JAX-native and differentiable in z."""
    cosmo = resolve_cosmology(cosmo)
    if n_nodes % 2 == 0:
        n_nodes += 1
    z = jnp.asarray(z, dtype=float)
    a = 1.0 / (1.0 + jnp.maximum(z, 0.0))
    u = jnp.linspace(0.0, 1.0, n_nodes)
    x = a[..., None] * u                           # (..., n_nodes): a' from 0..a
    pos = x > 0.0
    x_safe = jnp.where(pos, x, 1.0)
    zp = 1.0 / x_safe - 1.0
    g = jnp.where(pos, 1.0 / (x_safe * E_of_z(zp, cosmo)), 0.0)
    w = jnp.ones(n_nodes).at[1::2].set(4.0).at[2:-1:2].set(2.0)
    h = a / (n_nodes - 1)
    integral = (h / 3.0) * jnp.sum(w * g, axis=-1)
    return (_INV_H0_GYR_NUM / cosmo.H0) * integral

luminosity_distance_mpc

luminosity_distance_mpc(
    z, cosmo=None, n_nodes=128, backend="native"
)

Luminosity distance D_L(z) [Mpc].

Parameters:

Name Type Description Default
backend ('native', 'astropy')

'astropy' is scalar-z only.

'native'
Source code in ceridwen/cosmology.py
def luminosity_distance_mpc(z, cosmo: Cosmology | None = None,
                            n_nodes: int = 128,
                            backend: str = "native") -> Array:
    r"""Luminosity distance D_L(z) [Mpc].

    Parameters
    ----------
    backend : {'native', 'astropy'} -- 'native' is JAX and differentiable;
        'astropy' is scalar-z only.
    """
    cosmo = resolve_cosmology(cosmo)
    if backend == "astropy":
        return _astropy_luminosity_distance_mpc(z, cosmo)
    if backend != "native":
        raise ValueError(f"Unknown cosmology backend {backend!r}")
    return (1.0 + z) * comoving_distance_mpc(z, cosmo, n_nodes)

flux_factor

flux_factor(z, cosmo=None, n_nodes=128)

(1+z) / (4 pi D_L^2) with D_L in cm: converts rest-frame L_nu [erg/s/Hz] to observed F_nu [erg/s/cm^2/Hz].

Source code in ceridwen/cosmology.py
def flux_factor(z: Array, cosmo: Cosmology | None = None,
                n_nodes: int = 128) -> Array:
    r"""(1+z) / (4 pi D_L^2) with D_L in cm: converts rest-frame L_nu
    [erg/s/Hz] to observed F_nu [erg/s/cm^2/Hz]."""
    cosmo = resolve_cosmology(cosmo)
    dL_mpc = luminosity_distance_mpc(z, cosmo, n_nodes)
    dL_cm = dL_mpc * MPC_TO_CM
    return (1.0 + z) / (4.0 * jnp.pi * dL_cm * dL_cm)

flux_factor_cgs

flux_factor_cgs(
    z,
    cosmo=None,
    n_nodes=128,
    backend="native",
    lumdist_mpc=None,
)

Factor turning a CSP spectrum [L_sun/Hz/M_sun] into observed-frame F_nu [erg/s/cm^2/Hz] (cgs): (1+z) (10 pc / D_L)^2 times the 10 pc unit constant. z <= 0 is pinned to D_L = 10 pc. The AB-maggies photometry is obtained downstream by projecting this cgs spectrum through the filters (dividing by the 3631 Jy AB zero point); this factor itself is NOT maggies.

Parameters:

Name Type Description Default
backend ('native', 'astropy')
'native'
lumdist_mpc float or Array, Mpc -- explicit D_L replacing D_L(z); the

(1+z) term still comes from z and the z <= 0 pin does not apply.

None
Source code in ceridwen/cosmology.py
def flux_factor_cgs(z, cosmo: Cosmology | None = None,
                    n_nodes: int = 128,
                    backend: str = "native",
                    lumdist_mpc=None) -> Array:
    r"""Factor turning a CSP spectrum [L_sun/Hz/M_sun] into observed-frame
    F_nu [erg/s/cm^2/Hz] (cgs): (1+z) (10 pc / D_L)^2 times the 10 pc unit
    constant. z <= 0 is pinned to D_L = 10 pc.  The AB-maggies photometry is
    obtained downstream by projecting this cgs spectrum through the filters
    (dividing by the 3631 Jy AB zero point); this factor itself is NOT maggies.

    Parameters
    ----------
    backend : {'native', 'astropy'} -- see :func:`luminosity_distance_mpc`.
    lumdist_mpc : float or Array, Mpc -- explicit D_L replacing D_L(z); the
        (1+z) term still comes from z and the z <= 0 pin does not apply.
    """
    cosmo = resolve_cosmology(cosmo)
    if lumdist_mpc is not None:
        dL_pc = 1e6 * jnp.asarray(lumdist_mpc, dtype=float)
        return ((1.0 + z) * (_D_FID_10PC / dL_pc) ** 2
                * _LSUN_HZ_TO_FNU_CGS_AT_10PC)
    dL_pc = 1e6 * luminosity_distance_mpc(z, cosmo, n_nodes, backend=backend)
    positive_z = z > 0
    safe_dL = jnp.where(positive_z, dL_pc, float(_D_FID_10PC))
    ff_distance = jnp.where(
        positive_z,
        (1.0 + z) * (_D_FID_10PC / safe_dL) ** 2,
        1.0,
    )
    return ff_distance * _LSUN_HZ_TO_FNU_CGS_AT_10PC

have_astropy

have_astropy()

True if astropy is importable.

Source code in ceridwen/cosmology.py
def have_astropy() -> bool:
    """True if astropy is importable."""
    try:
        import astropy.cosmology  # noqa: F401
        return True
    except Exception:
        return False

Spectrophotometric calibration

ceridwen.csp.spectrum_calibration.spectrum_calibration_factor

spectrum_calibration_factor(obs, theta, dtype=None)

Factor spectrum_scaling * (1 + spectrum_calib . P(x)) multiplying the MODEL spectrum of obs (keys from :func:calibration_keys): a scalar (level only), an (n_pix,) vector (shape term), or None if the spectrum has neither.

Source code in ceridwen/csp/spectrum_calibration.py
def spectrum_calibration_factor(obs, theta, dtype=None):
    """Factor ``spectrum_scaling * (1 + spectrum_calib . P(x))`` multiplying the MODEL spectrum
    of ``obs`` (keys from :func:`calibration_keys`): a scalar (level only), an ``(n_pix,)``
    vector (shape term), or ``None`` if the spectrum has neither.
    """
    level_key, shape_key = calibration_keys(obs, theta)
    if level_key is None and shape_key is None:
        return None
    factor = None
    if level_key is not None:
        factor = jnp.ravel(theta[level_key])[0]
    if shape_key is not None:
        coeff = jnp.ravel(theta[shape_key])
        order = int(coeff.shape[0])
        if order < 1:
            raise ValueError(
                "spectrum_calib must have at least one coefficient "
                "(shape (order,), order >= 1); the level term is "
                "spectrum_scaling."
            )
        design = _design(obs, order)
        shape_term = 1.0 + design @ coeff
        factor = shape_term if factor is None else factor * shape_term
    if dtype is not None:
        factor = factor.astype(dtype)
    return factor

ceridwen.csp.spectrum_calibration.legendre_design_matrix

legendre_design_matrix(wavelength, order)

(n_pix, order) float64 matrix of Legendre P_1..P_order on the pixel wavelengths mapped affinely onto [-1, 1] (range over ALL pixels, masked or not; no P_0 term).

Source code in ceridwen/csp/spectrum_calibration.py
def legendre_design_matrix(wavelength, order: int) -> np.ndarray:
    """``(n_pix, order)`` float64 matrix of Legendre P_1..P_order on the pixel wavelengths
    mapped affinely onto [-1, 1] (range over ALL pixels, masked or not; no P_0 term)."""
    lam = np.asarray(wavelength, dtype=np.float64)
    if lam.ndim != 1 or lam.size < 2:
        raise ValueError(
            "spectrum_calib needs a 1-D observed wavelength array with at "
            f"least 2 pixels; got shape {lam.shape}."
        )
    fin = np.isfinite(lam)
    lo, hi = float(lam[fin].min()), float(lam[fin].max())
    if not hi > lo:
        raise ValueError(
            "spectrum_calib: observed wavelength range is degenerate "
            f"(min = max = {lo})."
        )
    x = 2.0 * (lam - lo) / (hi - lo) - 1.0
    x = np.where(fin, x, 0.0)
    return np.polynomial.legendre.legvander(x, int(order))[:, 1:]