API

fastspecfit

Tools for fast stellar continuum, emission-line, and broadband photometric modeling.

fastspecfit.continuum

Methods and tools for continuum-fitting.

class fastspecfit.continuum.ContinuumTools(data, templates, phot, igm, tauv_guess=0.1, vdisp_guess=250.0, tauv_bounds=(0.0, 2.0), vdisp_bounds=(75.0, 500.0), vdisp_nbin=5, fluxnorm=1e+17, massnorm=10000000000.0, fastphot=False, constrain_age=False)[source]

Tools for fitting and manipulating stellar continua.

Parameters:
  • data (dict) – Per-object spectral and photometric data dictionary.

  • templates (fastspecfit.templates.Templates) – Stellar population synthesis templates.

  • phot (fastspecfit.photometry.Photometry) – Photometric filter and band information.

  • igm (fastspecfit.igm.Inoue14) – IGM attenuation model.

  • tauv_guess (float, optional) – Initial guess for the V-band optical depth. Defaults to 0.1.

  • vdisp_guess (float, optional) – Initial guess for the velocity dispersion in km/s.

  • tauv_bounds (tuple, optional) – Lower and upper bounds on tau(V). Defaults to (0., 2.).

  • vdisp_bounds (tuple, optional) – Lower and upper bounds on the velocity dispersion in km/s.

  • vdisp_nbin (int, optional) – Number of grid points for the velocity dispersion chi2 scan. Defaults to 5.

  • fluxnorm (float, optional) – Flux normalization factor in erg/s/cm2/A. Defaults to 1e17.

  • massnorm (float, optional) – Stellar mass normalization in solar masses. Defaults to 1e10.

  • fastphot (bool, optional) – If True, skip spectroscopic preprocessing. Defaults to False.

  • constrain_age (bool, optional) – If True, exclude templates older than the age of the universe at the object’s redshift. Defaults to False.

ztemplatewave

Redshifted template wavelength array in Angstroms.

Type:

numpy.ndarray

zfactors

Combined flux scaling factors including IGM attenuation, luminosity distance, and flux normalization.

Type:

numpy.ndarray

agekeep

Index selection for templates younger than the age of the universe.

Type:

slice or numpy.ndarray

nage

Number of age templates in use.

Type:

int

vdisp_grid

Velocity dispersion grid used in the chi2 scan.

Type:

numpy.ndarray

phot_pre

Preprocessing cache for photometry synthesis.

Type:

tuple

wavelen

Total spectroscopic pixel count (set only when fastphot=False).

Type:

int

spec_pre

Preprocessing cache for spectroscopic resampling (set only when fastphot=False).

Type:

tuple

_stellar_objective(params, templateflux, dust_emission, fit_vdisp, conv_pre, objflam, objflamistd, specflux, specistd, synthphot, synthspec)[source]

Objective function for fitting a stellar continuum.

static _younger_than_universe(age, tuniv, agepad=0.5)[source]

Return the indices of the templates younger than the age of the universe (plus an agepadding amount) at the given redshift. age in yr, agepad and tuniv in Gyr

static attenuate(M, A, zfactors, wave, dustflux)

Compute attenuated version of a model spectrum, including contribution of dust emission.

static attenuate_nodust(M, A, zfactors)

Compute attenuated version of a model spectrum M, without dust emission.

build_stellar_continuum(templateflux, templatecoeff, tauv, vdisp=None, conv_pre=None, dust_emission=True)[source]

Build a stellar continuum model.

Parameters:
  • templateflux (numpy.ndarray [ntemplates, npix]) – Rest-frame, native-resolution template spectra corresponding to templatewave.

  • templatecoeff (numpy.ndarray [ntemplates]) – Column vector of positive coefficients corresponding to each template.

  • tauv (float) – V-band optical depth, tau(V).

  • vdisp (float) – Velocity dispersion in km/s. If None, do not convolve to the specified velocity dispersion (usually because templateflux has already been smoothed to some nominal value).

  • conv_pre (tuple or None) – Optional preprocessing data to accelerate template convolution with vdisp (may be present only if vdisp is not None).

  • dust_emission (bool) – Model impact of infrared dust emission spectrum. Energy-balance is used to compute the normalization of this spectrum.

Returns:

contmodel – Full-wavelength, native-resolution, observed-frame model spectrum.

Return type:

numpy.ndarray [npix]

static cfluxes_keys()[source]

Return observed-frame continuum flux output keys and reference wavelengths.

Returns:

  • keys (tuple of str) – Output column names for continuum fluxes.

  • waves (tuple of float) – Corresponding rest-frame reference wavelengths in Angstroms.

continuum_fluxes(continuum, uniqueid=0, width1=50.0, width2=100.0, debug_plots=False)[source]

Compute rest-frame luminosities and observed-frame continuum fluxes.

Parameters:
  • continuum (numpy.ndarray) – Best-fit stellar continuum model at the native template wavelengths.

  • uniqueid (int or str, optional) – Object identifier used in debug plot filenames.

  • width1 (float, optional) – Inner half-width in Angstroms for continuum measurement. Defaults to 50.

  • width2 (float, optional) – Outer half-width in Angstroms for continuum measurement. Defaults to 100.

  • debug_plots (bool, optional) – If True, write a QA plot to the current directory.

Returns:

continuum_to_photometry(contmodel, filters=None, phottable=False, get_abmag=False)[source]

Synthesize photometry from a continuum model.

Parameters:
  • contmodel (numpy.ndarray [npix]) – Full-wavelength, native-resolution, observed-frame model spectrum.

  • filters (list or speclite.filters.FilterSequence [nfilt]) – Optionally override the filter curves stored in the filters attribute of the global Photometry object.

  • phottable (bool) – Return an astropy.table.Table with additional bandpass information. Otherwise, return synthesized photometry in f_lambda (10^17 erg/s/cm2/A) units, which are used in fitting Only true for QA.

  • get_abmag (bool) – Add AB magnitudes to the synthesized photometry table (only applies if phottable=True. Only used for QA.

Returns:

modelphot – Synthesized model photometry as an array or a table, depending on phottable.

Return type:

numpy.ndarray or astropy.table.Table [nfilt]

continuum_to_spectroscopy(contmodel, interp=False)[source]

Synthesize spectroscopy from a continuum model.

Parameters:
  • contmodel (numpy.ndarray [npix]) – Full-wavelength, native-resolution, observed-frame model spectrum.

  • interp (bool) – For cosmetic (plotting) purposes, interpolate over masked pixels.

Returns:

modelflux – Observed-frame model spectrum at the instrumental resolution and wavelength sampling given by specres and specwave.

Return type:

numpy.ndarray [nwave]

fit_stellar_continuum(templateflux, fit_vdisp=False, conv_pre=None, vdisp_guess=None, tauv_guess=None, vdisp_bounds=None, tauv_bounds=None, coeff_guess=None, dust_emission=True, objflam=None, objflamistd=None, specflux=None, specistd=None, synthphot=False, synthspec=False)[source]

Fit a stellar continuum using bounded non-linear least-squares.

Parameters:
  • templateflux (numpy.ndarray [ntemplate, npix]) – Grid of input (model) spectra.

  • fit_vdisp (bool) – If True, solve for the velocity dispersion; if False, use a nominal dispersion.

  • conv_pre (tuple of None) – If not None, preprocessing data for convolving templateflux with vdisp values. (Occurs only if fit_vdisp is True.)

  • vdisp_guess (float) – Guess for scalar value of the velocity dispersion if fitting.

  • tauv_guess (float) – Guess scalar value of the dust optical depth.

  • coeff_guess (numpy.ndarray [ntemplates]) – Guess of the template coefficients.

  • vdisp_bounds (tuple) – Two-element list of minimum and maximum allowable values of the velocity dispersion; only used if fit_vdisp=True.

  • tauv_bounds (tuple) – Two-element list of minimum and maximum allowable values of the V-band optical depth, tau(V).

  • dust_emission (bool) – Model impact of infrared dust emission spectrum. Energy-balance is used to compute the normalization of this spectrum.

  • objflam – Measured object photometry (used if fitting photometry).

  • objflamistd – Sqrt of inverse variance of objflam (used if fitting photometry).

  • specflux (numpy.ndarray [nwave]) – Observed-frame spectrum in 10**-17 erg/s/cm2/A corresponding to specwave (used if fitting spectroscopy).

  • specfluxistd (numpy.ndarray [nwave]) – Sqrt of inverse variance of the observed-frame spectrum (used if fitting spectroscopy).

  • synthphot (bool) – True iff fitting objective includes object photometry.

  • synthspec (bool) – True iff fitting objective includes observed spectrum.

Returns:

  • tauv (float) – Maximum-likelihood V-band optical depth.

  • vdisp (float) – Maximum-likelihood velocity dispersion in km/s, or nominal velocity if it was not fitted.

  • templatecoeff (numpy.ndarray [ntemplate]) – Column vector of maximum-likelihood template coefficients.

  • resid (numpy.ndarray) – Vector of residuals at final parameter values.

Notes

This method supports several different fitting ‘modes’, depending on the whether vdisp is fitted or left nominal, and whether the caller requests fitting a model against spectroscopy, photometry, or both.

In all cases, we solve for dust attenuation via the tau(V) parameter and we also include IGM attenuation.

get_zfactors(igm, ztemplatewave, redshift, dluminosity)[source]

Cache the redshift-dependent flux scaling factors including IGM attenuation.

Parameters:
  • igm (fastspecfit.igm.Inoue14) – IGM attenuation model.

  • ztemplatewave (numpy.ndarray) – Redshifted template wavelength array in Angstroms.

  • redshift (float) – Object redshift.

  • dluminosity (float) – Luminosity distance in Mpc.

Returns:

Combined flux scaling factors.

Return type:

numpy.ndarray

static lums_keys()[source]

Return rest-frame luminosity output keys and reference wavelengths.

Returns:

  • keys (tuple of str) – Output column names for rest-frame luminosities.

  • waves (tuple of float) – Corresponding rest-frame reference wavelengths in Angstroms.

static smooth_continuum(wave, flux, ivar, linemask, camerapix, uniqueid=0, smooth_window=75, smooth_step=125, clip_sigma=2.0, nminpix=15, nmaskpix=9, debug_plots=False)[source]

Build a smooth, nonparametric continuum spectrum.

Parameters:
  • wave (numpy.ndarray) – Observed-frame wavelength array in Angstroms.

  • flux (numpy.ndarray) – Spectrum corresponding to wave.

  • ivar (numpy.ndarray) – Inverse variance spectrum corresponding to flux.

  • linemask (numpy.ndarray of bool) – Boolean mask where True marks pixels possibly affected by emission lines.

  • camerapix (array-like) – Per-camera start/end pixel index pairs.

  • uniqueid (int or str, optional) – Object identifier used in debug plot filenames.

  • smooth_window (int, optional) – Width of the sliding window in pixels. Defaults to 75.

  • smooth_step (int, optional) – Step size of the sliding window in pixels. Defaults to 125.

  • clip_sigma (float, optional) – Sigma threshold for iterative clipping. Defaults to 2.

  • nminpix (int, optional) – Minimum number of unmasked pixels required per window. Defaults to 15.

  • nmaskpix (int, optional) – Number of pixels to mask at each camera edge. Defaults to 9.

  • debug_plots (bool, optional) – If True, write a QA plot to the current directory.

Returns:

Smooth continuum spectrum that can be subtracted from flux to produce a pure emission-line spectrum.

Return type:

numpy.ndarray

stellar_continuum_chi2(resid, ncoeff, vdisp_fitted, split=0, ndof_spec=0, ndof_phot=0)[source]

Compute the reduced spectroscopic and/or photometric chi2.

Parameters:
  • resid (numpy.ndarray) – Residual vector from least-squares fitting.

  • ncoeff (int) – Number of template coefficients fitted.

  • vdisp_fitted (bool) – True if the velocity dispersion was a free parameter.

  • split (int, optional) – Index separating spectroscopic and photometric residuals. Defaults to 0.

  • ndof_spec (int, optional) – Number of spectroscopic degrees of freedom. Defaults to 0.

  • ndof_phot (int, optional) – Number of photometric degrees of freedom. Defaults to 0.

Returns:

  • rchi2_spec (float) – Reduced chi2 for the spectroscopy.

  • rchi2_phot (float) – Reduced chi2 for the photometry.

  • rchi2_tot (float) – Reduced chi2 for the combined fit.

fastspecfit.continuum._continuum_nominal_vdisp(CTools, templates, specflux, specwave, specistd, agekeep, compute_chi2=False)[source]

Support routine to fit a spectrum at the nominal velocity dispersion.

fastspecfit.continuum.can_compute_vdisp(redshift, specwave, min_restrange=(3800.0, 4800.0), fit_restrange=(3800.0, 6000.0))[source]

Determine whether the spectrum has sufficient coverage to fit velocity dispersion.

Parameters:
  • redshift (float) – Object redshift.

  • specwave (numpy.ndarray) – Observed-frame wavelength array in Angstroms.

  • min_restrange (tuple, optional) – Minimum required rest-frame wavelength range (lo, hi) in Angstroms. Defaults to (3800., 4800.).

  • fit_restrange (tuple, optional) – Rest-frame wavelength range used when fitting velocity dispersion. Defaults to (3800., 6000.).

Returns:

  • compute_vdisp (bool) – True if the spectrum covers the minimum required rest-frame range.

  • pixel_range (tuple of int) – Start and end pixel indices of the fitting wavelength range.

fastspecfit.continuum.continuum_fastphot(redshift, objflam, objflamivar, CTools, uniqueid=0, nmonte=10, rng=None, debug_plots=False)[source]

Fit the stellar continuum to broadband photometry only.

Parameters:
  • redshift (float) – Object redshift.

  • objflam (numpy.ndarray) – Observed photometry in units of 10**-17 erg/s/cm2/A.

  • objflamivar (numpy.ndarray) – Inverse variance of objflam.

  • CTools (ContinuumTools) – Initialized continuum-fitting tools for this object.

  • uniqueid (int or str, optional) – Object identifier used in log messages and debug plot filenames.

  • nmonte (int, optional) – Number of Monte Carlo realizations for uncertainty estimation. Defaults to 10.

  • rng (numpy.random.Generator, optional) – Random number generator for Monte Carlo draws.

  • debug_plots (bool, optional) – If True, write QA plots to the current directory.

Returns:

Fitted continuum parameters, model spectra, and uncertainty estimates. See source for the full unpacking order.

Return type:

tuple

fastspecfit.continuum.continuum_fastspec(redshift, objflam, objflamivar, CTools, nmonte=10, rng=None, uniqueid=0, no_smooth_continuum=False, debug_plots=False)[source]

Jointly fit the stellar continuum to spectroscopy and broadband photometry.

Parameters:
  • redshift (float) – Object redshift.

  • objflam (numpy.ndarray) – Observed photometry in units of 10**-17 erg/s/cm2/A.

  • objflamivar (numpy.ndarray) – Inverse variance of objflam.

  • CTools (ContinuumTools) – Initialized continuum-fitting tools for this object.

  • nmonte (int, optional) – Number of Monte Carlo realizations for uncertainty estimation. Defaults to 10.

  • rng (numpy.random.Generator, optional) – Random number generator for Monte Carlo draws.

  • uniqueid (int or str, optional) – Object identifier used in log messages and debug plot filenames.

  • no_smooth_continuum (bool, optional) – If True, skip the nonparametric smooth continuum step. Defaults to False.

  • debug_plots (bool, optional) – If True, write QA plots to the current directory.

Returns:

Fitted continuum parameters, model spectra, and uncertainty estimates. See source for the full unpacking order.

Return type:

tuple

fastspecfit.continuum.continuum_specfit(data, fastfit, specphot, templates, igm, phot, nmonte=10, seed=1, constrain_age=False, no_smooth_continuum=False, fitstack=False, fastphot=False, debug_plots=False)[source]

Fit the non-negative stellar continuum of a single spectrum.

Parameters:

data (dict) – Dictionary of input spectroscopy (plus ancillary data) populated by fastspecfit.io.DESISpectra.read().

Returns:

Table with all the continuum-fitting results with columns documented in init_output().

Return type:

astropy.table.Table

Notes

  • Consider using cross-correlation to update the redrock redshift.

  • We solve for velocity dispersion if …

fastspecfit.continuum.vdisp_by_chi2scan(CTools, templates, uniqueid, specflux, specwave, specistd, fitmask, agekeep, deltachi2min=25.0, fit_for_min=False, debug_plots=False)[source]

Determine the stellar velocity dispersion via a chi2 grid scan.

Parameters:
  • CTools (ContinuumTools) – Initialized continuum-fitting tools for this object.

  • templates (fastspecfit.templates.Templates) – Stellar population synthesis templates.

  • uniqueid (int or str) – Object identifier used in log messages and debug plot filenames.

  • specflux (numpy.ndarray) – Observed-frame spectrum in 10**-17 erg/s/cm2/A.

  • specwave (numpy.ndarray) – Observed-frame wavelength array in Angstroms.

  • specistd (numpy.ndarray) – Square root of the inverse variance of specflux.

  • fitmask (numpy.ndarray of bool) – Boolean mask selecting the wavelength range used for the vdisp fit.

  • agekeep (slice or numpy.ndarray) – Index selection for age templates to use.

  • deltachi2min (float, optional) – Minimum peak-to-peak delta-chi2 required to accept a fit. Defaults to 25.

  • fit_for_min (bool, optional) – If True, fit a parabola to refine the chi2 minimum. Defaults to False.

  • debug_plots (bool, optional) – If True, write a QA plot to the current directory.

Returns:

  • vdisp (float) – Best-fit velocity dispersion in km/s, or the nominal value if the fit failed.

  • vdisp_ivar (float) – Inverse variance of vdisp; zero if the fit failed.

fastspecfit.cosmo

Cosmology utilities.

class fastspecfit.cosmo.TabulatedDESI[source]

Tabulated DESI fiducial cosmology for fast redshift interpolation.

Loads tabulated \(E(z)\) and comoving radial distance as a function of redshift and performs linear interpolation. The cosmology parameters are defined by the AbacusSummit baseline (Planck 2018 ΛCDM).

file

Path to the tabulated cosmology file.

Type:

str

H0

Hubble constant in km/s/Mpc.

Type:

float

h

Dimensionless Hubble parameter.

Type:

float

hubble_time

Hubble time in Gyr.

Type:

float

Notes

Redshift interpolation range is [0, 100]. Cosmology defined at https://github.com/abacusorg/AbacusSummit; tabulated file generated with https://github.com/adematti/cosmoprimo.

Examples

>>> cosmo = TabulatedDESI()
>>> distance = cosmo.comoving_radial_distance([0.1, 0.2])
>>> efunc = cosmo.efunc(0.3)
comoving_radial_distance(z)[source]

Return comoving radial distance.

Parameters:

z (float or array-like) – Redshift.

Returns:

Comoving radial distance in \(\mathrm{Mpc}/h\).

Return type:

float or numpy.ndarray

distance_modulus(z)[source]

Return the distance modulus.

Parameters:

z (float or array-like) – Redshift.

Returns:

Distance modulus in magnitudes (Hogg 1999, Eq. 24).

Return type:

float or numpy.ndarray

efunc(z)[source]

Return \(E(z) = H(z) / H_0\).

Parameters:

z (float or array-like) – Redshift.

Returns:

Dimensionless Hubble parameter at the given redshift(s).

Return type:

float or numpy.ndarray

luminosity_distance(z)[source]

Return luminosity distance.

Parameters:

z (float or array-like) – Redshift.

Returns:

Luminosity distance in \(\mathrm{Mpc}/h\).

Return type:

float or numpy.ndarray

universe_age(z)[source]

Return the age of the universe at the given redshift.

Parameters:

z (float or array-like) – Redshift.

Returns:

Age of the universe in Gyr.

Return type:

float or numpy.ndarray

fastspecfit.emlines

Methods and tools for fitting emission lines.

class fastspecfit.emlines.EMFitTools(emline_table, uniqueid=None, stronglines=False)[source]

Tools for fitting emission-line spectra from DESI spectroscopy.

Builds and manages line models, parameter tables, tying relationships, doublet constraints, and fitting infrastructure for a set of spectral emission lines.

Parameters:
  • emline_table (astropy.table.Table) – Table of emission lines to fit.

  • uniqueid (str or None, optional) – Unique identifier for the current object, used in log messages.

  • stronglines (bool, optional) – If True, restrict to strong lines only. Defaults to False.

_initial_guesses_and_bounds(linepix, coadd_flux, contpix=None, initial_linesigma_broad=3000.0, initial_linesigma_narrow=150.0, initial_linesigma_balmer_broad=1000.0, initial_linevshift_broad=0.0, initial_linevshift_narrow=0.0, initial_linevshift_balmer_broad=0.0, subtract_local_continuum=False)[source]

Build data-informed initial parameter guesses and bounds for all in-range lines.

bestfit(linemodel, redshift, emlinewave, resolution_matrix, camerapix, continuum_patches=None)[source]

Construct the best-fitting emission-line spectrum from a linemodel.

build_linemodels(separate_oiii_fit=True)[source]

Build broad and narrow emission-line model tables.

Establishes fixed parameters, tying relationships, and doublet constraints for each model. compute_inrange_lines() must be called first to populate in-range information.

Parameters:

separate_oiii_fit (bool, optional) – If True, fit [OIII] 4959,5007 separately from the other narrow forbidden lines. Defaults to True.

Returns:

static chi2(linemodel, emlinewave, emlineflux, emlineivar, emlineflux_model, continuum_model=None, nfree_patches=0, return_dof=False)[source]

Compute the reduced chi-squared of the emission-line fit.

compute_inrange_lines(redshift, wavelims=(3600.0, 9900.0), wavepad=4.0)[source]

Record which lines fall within the observed wavelength range.

emlinemodel_bestfit(fastfit, redshift, emlinewave, resolution_matrix, camerapix, snrcut=None)[source]

Construct the best-fitting emission-line model from a fitted result structure (used below and in QA)

optimize(linemodel, initials, param_bounds, obs_bin_centers, obs_bin_fluxes, obs_weights, redshift, resolution_matrices, camerapix, continuum_patches=None, debug=False)[source]

Run the least-squares optimizer to fit emission-line parameters.

Parameters:
  • linemodel (astropy.table.Table) – Line model table (modified in-place with fitted values).

  • initials (numpy.ndarray) – Initial parameter values for all parameters.

  • param_bounds (numpy.ndarray, shape (nparams, 2)) – Lower and upper bounds for all parameters.

  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • obs_bin_fluxes (numpy.ndarray) – Observed flux in each wavelength bin.

  • obs_weights (numpy.ndarray) – Per-bin weights (square root of inverse variance).

  • redshift (float) – Redshift of the observed spectrum.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

  • continuum_patches (dict or None, optional) – Patch pedestal parameters, or None if not used.

  • debug (bool, optional) – Passed to the optimizer for verbose output. Defaults to False.

Returns:

  • linemodel (astropy.table.Table) – The input linemodel with a 'value' column added or updated, and metadata 'obsamps', 'line_fluxes', and 'nfev' set.

  • continuum_patches (dict) – Updated patch parameters (only returned if continuum_patches was provided).

populate_emtable(fastfit, linemodel, emlineflux_model, emlinewave, emlineflux, emlineivar, oemlineivar, specflux_nolines, redshift, resolution_matrices, camerapix, results_monte=None, nminpix=7, nsigma=3.0, moment_nsigma=5.0, limitsigma_narrow_default=75.0, limitsigma_broad_default=1200.0)[source]

Populate the output table with per-line flux measurements and uncertainties.

summarize_linemodel(linemodel)[source]

Simple function to summarize an input linemodel.

class fastspecfit.emlines.ParamType(value)[source]

An enumeration.

fastspecfit.emlines.build_coadded_models(data, emlinewave, emlineflux_model, continuum_flux, smooth_continuum_flux)[source]

Interpolate per-camera model spectra onto a uniform wavelength grid.

Assumes constant dispersion in wavelength.

fastspecfit.emlines.emline_specfit(data, fastfit, specphot, continuummodel, smooth_continuum, phot, emline_table, minsnr_balmer_broad=2.5, minsigma_balmer_broad=250.0, continuummodel_monte=None, specflux_monte=None, synthphot=True, broadlinefit=True, debug_plots=False)[source]

Fit emission lines in a continuum-subtracted DESI spectrum.

Parameters:
  • data (dict) – Per-spectrum data dictionary from the pipeline, including wavelength, flux, inverse variance, resolution matrices, and coadd arrays.

  • fastfit (astropy.table.Row) – Output row to populate with fitted emission-line parameters.

  • specphot (astropy.table.Row) – Output row to populate with spectrophotometric quantities.

  • continuummodel (numpy.ndarray) – Stellar continuum model flux for each observed wavelength bin.

  • smooth_continuum (numpy.ndarray) – Smooth (residual) continuum model flux for each observed wavelength bin.

  • phot (fastspecfit.photometry.Photometry) – Photometry object providing filter curves for synthetic photometry.

  • emline_table (astropy.table.Table) – Table of emission lines to fit.

  • minsnr_balmer_broad (float, optional) – Minimum S/N required to adopt the broad Balmer component. Defaults to 2.5.

  • minsigma_balmer_broad (float, optional) – Minimum velocity width [km/s] required for a broad Balmer component. Defaults to 250.

  • continuummodel_monte (numpy.ndarray or None, optional) – Monte Carlo realizations of the continuum model, shape (nmonte, nbins). Defaults to None.

  • specflux_monte (numpy.ndarray or None, optional) – Monte Carlo realizations of the observed flux, shape (nmonte, nbins). Defaults to None.

  • synthphot (bool, optional) – If True, synthesize broadband photometry from the best-fit model. Defaults to True.

  • broadlinefit (bool, optional) – If True, attempt to fit broad Balmer components. Defaults to True.

  • debug_plots (bool, optional) – If True, write diagnostic QA plots. Defaults to False.

Returns:

spectra_out – Coadded model spectra (continuum, smooth continuum, emission-line model) on a uniform wavelength grid.

Return type:

astropy.table.Table

fastspecfit.emlines.linefit(EMFit, linemodel, initial_guesses, param_bounds, emlinewave, emlineflux, emlineivar, weights, redshift, resolution_matrix, camerapix, debug=False)[source]

Fit emission-line parameters and return the model flux and fit statistics.

Thin wrapper around EMFitTools.optimize() and EMFitTools.bestfit() that also computes chi-squared.

Returns:

  • emlineflux_model (numpy.ndarray) – Best-fit model flux for each wavelength bin.

  • nfree (int) – Number of free parameters in the fit.

  • chi2 (float) – Reduced chi-squared of the fit.

fastspecfit.emlines.synthphot_spectrum(phot, data, specphot, modelwave, modelflux)[source]

Synthesize broadband photometry from the best-fitting continuum + emission-line model.

fastspecfit.emlines.test_broad_model(EMFit, linemodel_nobroad, emlineflux_model_nobroad, linemodel_broad, emlineflux_model_broad, emlinewave, emlineflux, emlineivar, redshift, minsnr_balmer_broad, minsigma_balmer_broad)[source]

Test whether the broad Balmer-line model is preferred over the narrow-only model.

Parameters:
  • EMFit (EMFitTools) – Emission-line fitting tools instance.

  • linemodel_nobroad (astropy.table.Table) – Fitted narrow-only line model.

  • emlineflux_model_nobroad (numpy.ndarray) – Best-fit model fluxes from the narrow-only fit.

  • linemodel_broad (astropy.table.Table) – Fitted broad + narrow line model.

  • emlineflux_model_broad (numpy.ndarray) – Best-fit model fluxes from the broad fit.

  • emlinewave (numpy.ndarray) – Observed wavelength array in Angstroms.

  • emlineflux (numpy.ndarray) – Observed emission-line flux array.

  • emlineivar (numpy.ndarray) – Inverse variance of the emission-line flux.

  • redshift (float) – Redshift of the observed spectrum.

  • minsnr_balmer_broad (float) – Minimum S/N required for a broad Balmer detection.

  • minsigma_balmer_broad (float) – Minimum velocity width [km/s] required for a broad Balmer component.

Returns:

  • adopt_broad (bool) – True if the broad-line model is preferred.

  • delta_linechi2_balmer (float) – Improvement in chi-squared at the Balmer lines.

  • delta_linendof_balmer (int) – Change in degrees of freedom at the Balmer lines.

fastspecfit.fastspecfit

See sandbox/running-fastspecfit for examples.

fastspecfit.fastspecfit.fastphot(args=None, comm=None, verbose=False)[source]

Main fastphot entry point: fit broadband photometry for DESI objects.

Parameters:
  • args (argparse.Namespace or list of str or None, optional) – Pre-parsed arguments or raw argument list. If None, reads from sys.argv.

  • comm (mpi4py.MPI.Comm or None, optional) – MPI intracommunicator for parallel execution, or None for single-process mode.

  • verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to False.

Returns:

Exit code (0 on success).

Return type:

int

fastspecfit.fastspecfit.fastspec(fastphot=False, fitstack=False, args=None, comm=None, verbose=False)[source]

Main fastspec engine: read, fit, and write results for one or more DESI spectra.

Parameters:
  • fastphot (bool, optional) – Fit broadband photometry only (no spectra). Defaults to False.

  • fitstack (bool, optional) – Treat input as stacked spectra. Defaults to False.

  • args (argparse.Namespace or list of str or None, optional) – Pre-parsed arguments or raw argument list. If None, reads from sys.argv.

  • comm (mpi4py.MPI.Comm or None, optional) – MPI intracommunicator for parallel execution, or None for single-process mode.

  • verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to False.

Returns:

Exit code (0 on success).

Return type:

int

fastspecfit.fastspecfit.fastspec_one(iobj, data, meta, fastfit_dtype, specphot_dtype, broadlinefit=True, fastphot=False, fitstack=False, constrain_age=False, no_smooth_continuum=False, debug_plots=False, uncertainty_floor=0.01, minsnr_balmer_broad=2.5, nmonte=10, seed=1)[source]

Fit the continuum and emission lines for a single DESI object.

Parameters:
  • iobj (int) – Index of the object in the input list, used for log messages.

  • data (dict) – Per-object data dictionary from fastspecfit.io.DESISpectra.

  • meta (astropy.table.Row) – Metadata row for this object.

  • fastfit_dtype (numpy.dtype) – NumPy dtype for the emission-line fitting output table.

  • specphot_dtype (numpy.dtype) – NumPy dtype for the spectrophotometric output table.

  • broadlinefit (bool, optional) – Attempt to fit broad Balmer components. Defaults to True.

  • fastphot (bool, optional) – Fit broadband photometry only (no spectra). Defaults to False.

  • fitstack (bool, optional) – Treat input as stacked spectra. Defaults to False.

  • constrain_age (bool, optional) – Constrain the stellar population age during fitting. Defaults to False.

  • no_smooth_continuum (bool, optional) – Skip smooth continuum fitting. Defaults to False.

  • debug_plots (bool, optional) – Write diagnostic QA plots to the working directory. Defaults to False.

  • uncertainty_floor (float, optional) – Minimum fractional uncertainty added in quadrature to the formal inverse variance spectrum. Defaults to 0.01.

  • minsnr_balmer_broad (float, optional) – Minimum S/N required to adopt the broad Balmer component. Defaults to 2.5.

  • nmonte (int, optional) – Number of Monte Carlo realizations for uncertainty estimation. Defaults to 10.

  • seed (int, optional) – Random seed for Monte Carlo reproducibility. Defaults to 1.

Returns:

fastspecfit.fastspecfit.parse(options=None, rank=0)[source]

Parse input arguments to fastspec and fastphot scripts.

Parameters:
  • options (list of str or None, optional) – Command-line argument strings. If None, reads from sys.argv.

  • rank (int, optional) – MPI rank of the calling process, used to suppress log output on non-zero ranks. Defaults to 0.

Returns:

args – Parsed command-line arguments.

Return type:

argparse.Namespace

fastspecfit.fastspecfit.stackfit(args=None, comm=None, verbose=False)[source]

Entry point to fit generic stacked DESI spectra.

Parameters:
  • args (argparse.Namespace or list of str or None, optional) – Pre-parsed arguments or raw argument list. If None, reads from sys.argv.

  • comm (mpi4py.MPI.Comm or None, optional) – MPI intracommunicator for parallel execution, or None for single-process mode.

  • verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to False.

Returns:

Exit code (0 on success).

Return type:

int

fastspecfit.igm

Tools for handling intergalactic medium (IGM) attenuation.

The Inoue14 implementation is adapted from Gabriel Brammer’s eazy-py package and is used here under the MIT License. Copyright (c) 2016-2022 Gabriel Brammer.

class fastspecfit.igm.Inoue14(scale_tau=1.0)[source]

IGM absorption model from Inoue et al. (2014).

Parameters:

scale_tau (float, optional) – Scaling factor applied to the IGM optical depth \(\tau\). The transmission is \(f_\mathrm{igm} = e^{-\mathrm{scale\_tau}\,\tau}\). Defaults to 1.

scale_tau

Optical depth scaling factor.

Type:

float

igm_params

Pre-computed LAF and DLA absorption coefficients.

Type:

tuple

reference

Citation string for the IGM model.

Type:

str

full_IGM(z, lobs)[source]

Compute the full IGM transmission at observed wavelengths.

Parameters:
  • z (float) – Source redshift.

  • lobs (numpy.ndarray) – Observed-frame wavelengths in Angstroms.

Returns:

IGM transmission \(e^{-\tau}\) at each wavelength.

Return type:

numpy.ndarray

fastspecfit.igm._tLCDLA(zS, lobs)

Lyman continuum, DLA

fastspecfit.igm._tLCLAF(zS, lobs)

Lyman continuum, LAF

fastspecfit.igm._tLSDLA(zS, lobs, lam, cADLA1, cADLA2)

Lyman Series, DLA

fastspecfit.igm._tLSLAF(zS, lobs, lam, cALAF1, cALAF2, cALAF3)

Lyman series, Lyman-alpha forest

fastspecfit.io

Tools for reading DESI spectra and reading and writing fastspecfit files.

class fastspecfit.io.DESISpectra(phot, cosmo, redux_dir=None, fphotodir=None, mapdir=None)[source]

Reader for DESI spectra and associated metadata.

Parameters:
  • phot (fastspecfit.photometry.Photometry) – Photometry configuration object.

  • cosmo (fastspecfit.cosmo.TabulatedDESI) – Tabulated cosmology object.

  • redux_dir (str or None, optional) – Full path to the DESI spectroscopic reduction outputs. Defaults to $DESI_SPECTRO_REDUX.

  • fphotodir (str or None, optional) – Top-level directory of the source photometry (Legacy Survey). Defaults to $FPHOTO_DIR.

  • mapdir (str or None, optional) – Directory containing the Milky Way dust maps. Defaults to $DUST_DIR/maps.

_gather_photometry(specprod=None, alltiles=None)[source]

Gather Tractor photometry from disk and merge into the metadata tables.

gather_metadata(redrockfiles, zmin=None, zmax=None, zwarnmax=None, targetids=None, firsttarget=0, ntargets=None, input_redshifts=None, specprod_dir=None, use_quasarnet=True, redrockfile_prefix='redrock-', specfile_prefix='coadd-', qnfile_prefix='qso_qn-', mgiifile_prefix='qso_mgii-')[source]

Select targets for fitting and gather spectroscopic metadata.

Parameters:
  • redrockfiles (str or array-like) – Full path to one or more input Redrock file(s).

  • zmin (float or None, optional) – Minimum redshift of targets to select. Defaults to 0.001.

  • zmax (float or None, optional) – Maximum redshift of targets to select. None imposes no upper limit.

  • zwarnmax (int or None, optional) – Maximum Redrock ZWARN value for selected targets. None imposes no cut.

  • targetids (int or array-like or None, optional) – Restrict to these TARGETIDs. If None, select all targets satisfying the other criteria.

  • firsttarget (int, optional) – Index of the first object to consider in each file. Defaults to 0.

  • ntargets (int or None, optional) – Number of objects to analyze per file. If None, select all passing targets.

  • input_redshifts (float or array-like or None, optional) – Override redshifts for each entry in targetids. If None, use Redrock (or QuasarNet) redshifts.

  • specprod_dir (str or None, optional) – Override the spectroscopic production directory.

  • use_quasarnet (bool, optional) – Use QuasarNet afterburner redshifts for QSOs when available. Defaults to True.

  • redrockfile_prefix (str, optional) – Filename prefix of the Redrock files. Defaults to 'redrock-'.

  • specfile_prefix (str, optional) – Filename prefix of the spectroscopic coadds. Defaults to 'coadd-'.

  • qnfile_prefix (str, optional) – Filename prefix of the QuasarNet afterburner file. Defaults to 'qso_qn-'.

  • mgiifile_prefix (str, optional) – Filename prefix of the MgII afterburner file. Defaults to 'qso_mgii-'.

Notes

Sets the following instance attributes: coadd_type, meta, redrockfiles, specfiles, and specprod. The specprod is read from the header of the first Redrock file only.

read(photometry, fastphot=False, constrain_age=False)[source]

Read selected spectra and photometry for all gathered targets.

Reads DESI coadded spectra from disk, gathers Tractor photometry, and calls one_spectrum() for each object to produce the per-object data dictionaries used by the fitting routines.

Parameters:
  • photometry (fastspecfit.photometry.Photometry) – Photometry configuration object.

  • fastphot (bool, optional) – If True, read photometry only (no spectra). Defaults to False.

  • constrain_age (bool, optional) – If True, pass age-constraint information to the per-object processor. Defaults to False.

Returns:

  • data (list of dict) – Per-object data dictionaries (one per target), each containing wavelength, flux, inverse variance, resolution matrices, emission-line masks, photometry, and coadded spectra.

  • meta (list of astropy.table.Table) – Updated metadata tables with photometry and dust-transmission columns populated.

read_stacked(stackfiles, firsttarget=0, ntargets=None, stackids=None, synthphot=True, constrain_age=False)[source]

Read one or more stacked DESI spectra.

Parameters:
  • stackfiles (str or array-like) – Full path to one or more stacked-spectra FITS file(s).

  • firsttarget (int, optional) – Index of the first object to consider in each file. Defaults to 0.

  • ntargets (int or None, optional) – Number of objects to read per file. If None, read all.

  • stackids (int or array-like or None, optional) – Restrict to these stack IDs. If None, read all.

  • synthphot (bool, optional) – Synthesize photometry from the coadded spectrum. Defaults to True.

  • constrain_age (bool, optional) – Pass age-constraint information to the per-object processor. Defaults to False.

Returns:

  • data (list of dict) – Per-object data dictionaries.

  • meta (list of astropy.table.Table) – Metadata tables.

static resolve(targets)[source]

Resolve which targets are primary in imaging overlap regions.

Parameters:

targets (ndarray) – Rec array of targets. Must have columns “RA” and “DEC” and either “RELEASE” or “PHOTSYS” or “TARGETID”.

Returns:

The original target list trimmed to only objects from the “northern” photometry in the northern imaging area and objects from “southern” photometry in the southern imaging area.

Return type:

ndarray

static update_qso_redshifts(zb, meta, qnfile, mgiifile, fitindx, specprod)[source]

Update QSO redshifts using the afterburners.

fastspecfit.io.create_output_meta(input_meta, phot, fastphot=False, fitstack=False)[source]

Create the fastspecfit output metadata table.

Parameters:
  • input_meta (astropy.table.Table) – Input metadata table from read().

  • phot (fastspecfit.photometry.Photometry) – Photometry object providing band and column information.

  • fastphot (bool, optional) – If True, omit spectroscopy-specific columns. Defaults to False.

  • fitstack (bool, optional) – If True, format for stacked-spectra output. Defaults to False.

Returns:

meta – Output metadata table with columns in the standard data model order.

Return type:

astropy.table.Table

fastspecfit.io.create_output_table(records, meta, units, fitstack=False)[source]

Generate the output FASTSPEC/FASTPHOT or SPECPHOT table.

Parameters:
Returns:

output_table – Table with identification columns from meta prepended to the fitted-quantity columns.

Return type:

astropy.table.Table

fastspecfit.io.get_output_dtype(specprod, phot, linetable, ncoeff, cameras=['B', 'R', 'Z'], specphot=False, fastphot=False, fitstack=False)[source]

Build the NumPy dtype for one fastspecfit output data record.

Parameters:
  • specprod (str) – Spectroscopic production name.

  • phot (fastspecfit.photometry.Photometry) – Photometry object providing band and column information.

  • linetable (astropy.table.Table) – Emission-line table.

  • ncoeff (int) – Number of stellar template coefficients.

  • cameras (list of str, optional) – Camera names. Defaults to ['B', 'R', 'Z'].

  • specphot (bool, optional) – If True, build the SPECPHOT extension dtype. Defaults to False.

  • fastphot (bool, optional) – If True, omit spectroscopy-only fields. Defaults to False.

  • fitstack (bool, optional) – If True, omit per-object spectroscopic fields. Defaults to False.

Returns:

  • out_dtype (list) – NumPy dtype specification as a list of (name, dtype[, shape]) tuples.

  • out_units (dict) – Mapping from column name to astropy unit.

fastspecfit.io.get_qa_filename(metadata, coadd_type, outprefix=None, outdir=None, fastphot=False)[source]

Build the QA PNG filename for one or more objects.

Parameters:
  • metadata (astropy.table.Table, astropy.table.Row, or numpy.void) – Metadata for one or more objects.

  • coadd_type (str) – Coadd type: 'healpix', 'cumulative', 'pernight', 'perexp', 'custom', or 'stacked'.

  • outprefix (str or None, optional) – Filename prefix. Defaults to 'fastspec' or 'fastphot'.

  • outdir (str or None, optional) – Output directory. Defaults to the current directory.

  • fastphot (bool, optional) – If True, use 'fastphot' as the default prefix. Defaults to False.

Returns:

pngfile – QA filename(s) for the given object(s).

Return type:

str or list of str

fastspecfit.io.one_desi_spectrum(survey, program, healpix, targetid, specprod='fuji', outdir='.', overwrite=False)[source]

Extract and fit a single DESI spectrum from the full production.

Utility function for generating paper figures or unit tests: reads a single target from the full production, writes minimal coadd and redrock files, runs fastspec, and generates QA.

Parameters:
  • survey (str) – Survey name (e.g., 'main', 'sv3').

  • program (str) – Program name (e.g., 'dark', 'bright').

  • healpix (int) – HEALPix pixel number.

  • targetid (int) – DESI TARGETID.

  • specprod (str, optional) – Spectroscopic production name. Defaults to 'fuji'.

  • outdir (str, optional) – Output directory. Defaults to the current directory.

  • overwrite (bool, optional) – Overwrite existing output files. Defaults to False.

fastspecfit.io.one_spectrum(specdata, meta, uncertainty_floor=0.01, RV=3.1, init_sigma_uv=None, init_sigma_narrow=None, init_sigma_balmer=None, init_vshift_uv=None, init_vshift_narrow=None, init_vshift_balmer=None, fastphot=False, synthphot=True, debug_plots=False)[source]

Pre-process a single DESI spectrum for fitting.

Applies MW dust corrections to photometry, processes per-camera spectra (masking, uncertainty floor, dust correction), and builds the emission-line mask. Modifies specdata in-place.

Parameters:
  • specdata (dict) – Per-object data dictionary. Modified in-place with processed arrays.

  • meta (astropy.table.Row) – Metadata row for this object.

  • uncertainty_floor (float, optional) – Minimum fractional uncertainty added in quadrature to the formal inverse variance. Defaults to 0.01.

  • RV (float, optional) – Total-to-selective extinction ratio. Defaults to 3.1.

  • init_sigma_uv (float or None, optional) – Initial UV line-width guess in km/s for emission-line masking.

  • init_sigma_narrow (float or None, optional) – Initial narrow line-width guess in km/s for emission-line masking.

  • init_sigma_balmer (float or None, optional) – Initial broad Balmer line-width guess in km/s for emission-line masking.

  • init_vshift_uv (float or None, optional) – Initial UV velocity shift in km/s for emission-line masking.

  • init_vshift_narrow (float or None, optional) – Initial narrow-line velocity shift in km/s for emission-line masking.

  • init_vshift_balmer (float or None, optional) – Initial broad Balmer velocity shift in km/s for emission-line masking.

  • fastphot (bool, optional) – If True, skip spectroscopic processing. Defaults to False.

  • synthphot (bool, optional) – Synthesize photometry from the coadded spectrum. Defaults to True.

  • debug_plots (bool, optional) – Write diagnostic plots to the working directory. Defaults to False.

Returns:

specdata – The input dictionary updated with processed spectroscopic and photometric data.

Return type:

dict

fastspecfit.io.one_stacked_spectrum(specdata, meta, synthphot=True, debug_plots=False)[source]

Pre-process a single stacked DESI spectrum for fitting.

Similar to one_spectrum() but for stacked spectra: uses dummy photometry and skips MW dust correction. Modifies specdata in-place.

Parameters:
  • specdata (dict) – Per-object data dictionary. Modified in-place with processed arrays.

  • meta (astropy.table.Row) – Metadata row for this object.

  • synthphot (bool, optional) – Synthesize photometry from the coadded spectrum. Defaults to True.

  • debug_plots (bool, optional) – Write diagnostic plots to the working directory. Defaults to False.

Returns:

specdata – The input dictionary updated with processed spectroscopic data.

Return type:

dict

fastspecfit.io.read_fastspecfit(fastfitfile, rows=None, metadata_columns=None, specphot_columns=None, fastspec_columns=None, read_models=False)[source]

Read fastspecfit fitting results from a FITS file.

Parameters:
  • fastfitfile (str) – Full path to the fastspecfit output FITS file.

  • rows (array-like or None, optional) – Row indices to read. If None, read all rows.

  • metadata_columns (list of str or None, optional) – Column names to read from the METADATA extension. If None, read all.

  • specphot_columns (list of str or None, optional) – Column names to read from the SPECPHOT extension. If None, read all.

  • fastspec_columns (list of str or None, optional) – Column names to read from the FASTSPEC extension. If None, read all.

  • read_models (bool, optional) – If True, also read the MODELS extension. Defaults to False.

Returns:

  • meta (astropy.table.Table or None) – Metadata table, or None if the file is not found.

  • specphot (astropy.table.Table or None) – Spectrophotometric results table.

  • fastfit (astropy.table.Table or None) – Emission-line fitting results, or None in fastphot mode.

  • coadd_type (str or None) – Coadd type string from the file header.

  • fastphot (bool or None) – True if the file was produced in fastphot (photometry-only) mode.

  • models (numpy.ndarray or None) – Model spectra array (only included in the return tuple when read_models=True).

fastspecfit.io.select(metadata, specphot, fastfit=None, coadd_type='healpix', healpixels=None, tiles=None, nights=None, return_index=False)[source]

Optionally trim to a particular healpix or tile and/or night.

fastspecfit.io.write_fastspecfit(meta, specphot, fastfit, modelspectra=None, outfile=None, specprod=None, coadd_type=None, fphotofile=None, template_file=None, emlinesfile=None, fastphot=False, inputz=False, inputseeds=None, nmonte=10, vdisp_nominal=250.0, vdisp_bounds=(75.0, 500.0), seed=1, uncertainty_floor=0.01, minsnr_balmer_broad=2.5, nside=None, no_smooth_continuum=False, ignore_photometry=False, broadlinefit=True, use_quasarnet=True, constrain_age=False, split_hdu=False, verbose=True)[source]

Write fastspecfit results to a multi-extension FITS file.

fastspecfit.linemasker

Tools for pre-fitting and masking emission lines.

class fastspecfit.linemasker.LineMasker(emline_table)[source]

Compute spectral line mask for continuum estimation and line parameter initialization.

Parameters:

emline_table (astropy.table.Table) – Emission line table.

build_linemask(wave, flux, ivar, resolution_matrix, redshift=0.0, uniqueid=0, minsnr_balmer_broad=1.5, minsnr_linemask=3.5, initsigma_broad=None, initsigma_narrow=None, initsigma_balmer_broad=None, initvshift_broad=None, initvshift_narrow=None, initvshift_balmer_broad=None, niter=2, nsigma_mask=5.0, debug_plots=False)[source]

Generate a mask which identifies pixels impacted by emission lines.

Parameters:
  • wave (numpy.ndarray [npix]) – Observed-frame wavelength array.

  • flux (numpy.ndarray [npix]) – Spectrum corresponding to wave.

  • ivar (numpy.ndarray [npix]) – Inverse variance spectrum corresponding to flux.

  • resolution_matrix (list) – List of fastspecfit.resolution.Resolution objects, one per camera.

  • redshift (float, optional) – Object redshift. Default is 0.

  • uniqueid (int, optional) – Unique identification number used in debug plot filenames.

  • minsnr_balmer_broad (float, optional) – Minimum S/N to accept a broad Balmer line detection. Default is 1.5.

  • minsnr_linemask (float, optional) – Minimum S/N to include a non-strong line in the final pixel mask. Default is 3.5.

  • initsigma_broad (float or None, optional) – Initial broad-line width in km/s. Default is 3000.

  • initsigma_narrow (float or None, optional) – Initial narrow/forbidden-line width in km/s. Default is 150.

  • initsigma_balmer_broad (float or None, optional) – Initial broad Balmer-line width in km/s. Default is 1000.

  • initvshift_broad (float or None, optional) – Initial broad-line velocity shift in km/s. Default is 0.

  • initvshift_narrow (float or None, optional) – Initial narrow-line velocity shift in km/s. Default is 0.

  • initvshift_balmer_broad (float or None, optional) – Initial broad Balmer-line velocity shift in km/s. Default is 0.

  • niter (int, optional) – Number of fit-in-patches iterations. Default is 2.

  • nsigma_mask (float, optional) – Half-width of the final line mask in units of the line sigma. Default is 5.

  • debug_plots (bool, optional) – If True, write per-patch and per-line diagnostic PNG files. Default is False.

Returns:

out – Dictionary with fitted line-width and velocity-shift scalars for broad, narrow, and broad-Balmer populations, a balmerbroad boolean flag, and coadd_linepix mapping each line name to its pixel indices in the coadded spectrum.

Return type:

dict

static linepix_and_contpix(wave, ivar, linetable, linesigmas, residuals=None, flux=None, linevshifts=None, patchMap=None, redshift=0.0, nsigma=2.5, minlinesigma=50.0, mincontpix=11, get_contpix=True, get_snr=False)[source]

Identify pixels containing emission lines and adjacent continuum.

Parameters:
  • wave (numpy.ndarray) – Observed-frame wavelength array in Angstroms.

  • ivar (numpy.ndarray) – Inverse variance array.

  • linetable (astropy.table.Table) – Emission line table with restwave and name columns.

  • linesigmas (numpy.ndarray) – Line widths in km/s for each entry in linetable.

  • residuals (numpy.ndarray or None, optional) – Residual spectrum used for S/N estimation when get_snr=True.

  • flux (numpy.ndarray or None, optional) – Observed flux array used for amplitude estimation when get_snr=True.

  • linevshifts (numpy.ndarray or None, optional) – Velocity shifts in km/s for each line; defaults to zero.

  • patchMap (dict or None, optional) – Mapping from patch ID to (linenames, line_indices, full_indices) tuples. When provided, continuum pixels are grouped into patches.

  • redshift (float, optional) – Object redshift. Default is 0.

  • nsigma (float, optional) – Half-width of the line mask in units of the line sigma. Default is 2.5.

  • minlinesigma (float, optional) – Minimum line sigma in km/s used for masking. Default is 50.

  • mincontpix (int, optional) – Minimum number of continuum pixels per line or patch. Default is 11.

  • get_contpix (bool, optional) – If True, also compute continuum pixel indices. Default is True.

  • get_snr (bool, optional) – If True, estimate the amplitude and S/N for each line. Default is False.

Returns:

pix – Dictionary with keys linepix and contpix (each mapping line name to pixel index arrays). If get_snr=True, also contains clocal, cnoise, amp, and snr per line. If patchMap is provided, also contains patch_contpix, dropped, merged, and merged_from.

Return type:

dict

fastspecfit.linetable

Emission line table, read from a file.

class fastspecfit.linetable.LineTable(emlines_file=None)[source]

Emission line table used for spectral fitting.

Parameters:

emlines_file (str, optional) – Path to an ECSV emission-line parameter file. Defaults to the bundled data/emlines.ecsv.

file

Path to the emission-line file that was read.

Type:

str

table

Emission-line parameters.

Type:

astropy.table.Table

fastspecfit.logger

Unique logger object, distinct from the one used by the DESI libraries, allocated at startup and used throughout code base. We need to create our own logger to avoid the DESI libraries accidentally changing the log level out from under us.

Having just one logger allows us to initialize its level on startup and have those changes propagate everywhere.

This needs to be in its own file to prevent circular imports with other code.

fastspecfit.logger.getFastspecLogger()[source]

Create a fastspecfit-specific logger that writes to stdout.

Formats messages identically to DESIUtil defaults. Every call returns the same log object and resets its level to INFO, so this should only be called once at program startup.

Returns:

log – Logger named fastspec with level INFO.

Return type:

logging.Logger

fastspecfit.mpi

MPI tools.

fastspecfit.mpi._domerge(outfiles, outprefix=None, specprod=None, coadd_type=None, mergefile=None, fastphot=False, split_hdu=False, nside_main=None, mp=1)[source]

Read and concatenate a set of per-healpix/tile output files into one catalog.

fastspecfit.mpi.findfiles(filedir, prefix='redrock', coadd_type=None, survey=None, program=None, healpix=None, tile=None, night=None, gzip=False, sample=None)[source]

Find all DESI spectral files matching the given selection criteria.

Parameters:
  • filedir (str) – Root directory to search for files.

  • prefix (str, optional) – Filename prefix. Default is 'redrock'.

  • coadd_type (str or None, optional) – Coadd type: 'healpix', 'cumulative', 'pernight', or 'perexp'.

  • survey (str or array-like of str, optional) – DESI survey name(s), e.g. 'main'.

  • program (str or array-like of str, optional) – DESI program name(s), e.g. 'dark'.

  • healpix (array-like or None, optional) – Specific HEALPix pixel(s) to include.

  • tile (array-like or None, optional) – Specific tile ID(s) to include.

  • night (array-like or None, optional) – Specific observing night(s) to include.

  • gzip (bool, optional) – If True, look for .fits.gz files. Default is False.

  • sample (astropy.table.Table or None, optional) – Input sample catalog; when provided, file paths are built directly from SURVEY, PROGRAM, and HEALPIX columns.

Returns:

thesefiles – Sorted array of matching file paths.

Return type:

numpy.ndarray of str

fastspecfit.mpi.get_ntargets_one(specfile, htmldir_root, outdir_root, coadd_type='healpix', makeqa=False, overwrite=False, fastphot=False)[source]

Count the number of targets to process in a single output file.

fastspecfit.mpi.merge_fastspecfit(specprod=None, coadd_type=None, survey=None, program=None, healpix=None, tile=None, night=None, sample=None, outsuffix=None, fastphot=False, specprod_dir=None, outdir_data='.', split_hdu=False, fastfiles_to_merge=None, merge_suffix=None, mergedir=None, supermerge=False, overwrite=False, nside_main=None, mp=1)[source]

Merge per-healpix or per-tile output catalogs into a single catalog.

Runs only on MPI rank 0. When supermerge=True, merges previously merged per-survey/program catalogs into one master file instead.

Parameters:
  • specprod (str or None, optional) – DESI spectroscopic production name.

  • coadd_type (str or None, optional) – Coadd type: 'healpix', 'cumulative', 'pernight', etc.

  • survey (str or array-like of str, optional) – DESI survey name(s).

  • program (str or array-like of str, optional) – DESI program name(s).

  • healpix (array-like or None, optional) – Specific HEALPix pixel(s) to merge.

  • tile (array-like or None, optional) – Specific tile ID(s) to merge.

  • night (array-like or None, optional) – Specific observing night(s) to merge.

  • sample (astropy.table.Table or None, optional) – Input sample catalog; overrides file-system discovery.

  • outsuffix (str or None, optional) – Suffix for the merged output filename; defaults to specprod.

  • fastphot (bool, optional) – If True, merge fastphot output files. Default is False.

  • specprod_dir (str or None, optional) – Override the standard specprod directory path.

  • outdir_data (str, optional) – Root output directory. Default is '.'.

  • split_hdu (bool, optional) – If True, write main-survey outputs as separate HDUs by HEALPix nside. Default is False.

  • fastfiles_to_merge (list or None, optional) – Explicit list of files to merge when supermerge=True.

  • merge_suffix (str or None, optional) – Filename suffix for sample-based merges. Default is 'sample'.

  • mergedir (str or None, optional) – Directory for merged output files; defaults to <outdir_data>/<specprod>/catalogs.

  • supermerge (bool, optional) – If True, merge previously merged per-survey/program catalogs into one master file. Default is False.

  • overwrite (bool, optional) – If True, overwrite existing merged output files. Default is False.

  • nside_main (int or None, optional) – HEALPix nside for splitting main-survey output by healpixel.

  • mp (int, optional) – Number of multiprocessing workers. Default is 1.

fastspecfit.mpi.plan(comm=None, specprod=None, specprod_dir=None, coadd_type='healpix', survey=None, program=None, healpix=None, tile=None, night=None, sample=None, outdir_data='.', mp=1, merge=False, makeqa=False, fastphot=False, overwrite=False)[source]

Determine which files still need to be processed.

Parameters:
  • comm (MPI communicator or None, optional) – MPI communicator for distributed execution. When None, runs single-process.

  • specprod (str or None, optional) – DESI spectroscopic production name (e.g. 'iron').

  • specprod_dir (str or None, optional) – Override the standard specprod directory path.

  • coadd_type (str, optional) – Coadd type: 'healpix', 'cumulative', 'pernight', or 'perexp'. Default is 'healpix'.

  • survey (str or array-like of str, optional) – DESI survey name(s).

  • program (str or array-like of str, optional) – DESI program name(s).

  • healpix (array-like or None, optional) – Specific HEALPix pixel(s) to process.

  • tile (array-like or None, optional) – Specific tile ID(s) to process.

  • night (array-like or None, optional) – Specific observing night(s) to process.

  • sample (astropy.table.Table or None, optional) – Input sample catalog; overrides file-system discovery.

  • outdir_data (str, optional) – Root output directory. Default is '.'.

  • mp (int, optional) – Number of multiprocessing workers. Default is 1.

  • merge (bool, optional) – If True, plan for catalog merging rather than fitting. Default is False.

  • makeqa (bool, optional) – If True, plan for QA generation rather than fitting. Default is False.

  • fastphot (bool, optional) – If True, use fastphot output filenames. Default is False.

  • overwrite (bool, optional) – If True, include files that already have output. Default is False.

Returns:

  • outdir (str) – Root output directory.

  • redrockfiles (list or numpy.ndarray) – Input redrock files to process (or None/[] when merging/QA).

  • outfiles (list or numpy.ndarray) – Corresponding output file paths.

  • ntargets (numpy.ndarray or None) – Number of targets per file; None when merging.

fastspecfit.mpi.plan_makeqa(outdir, htmldir, outprefix, coadd_type, survey, program, healpix, tile, night, sample=None, gzip=False)[source]

Build the list of output files and HTML directories for QA generation.

fastspecfit.mpi.plan_merge(outdir, outprefix, coadd_type, survey, program, healpix, tile, night, sample=None, gzip=False)[source]

Build the list of output files to be merged.

fastspecfit.mpi.read_to_merge_one(filename, fastphot)[source]

Read metadata, specphot, and fastfit tables from one output file.

fastspecfit.photometry

Tools for handling filters and photometry calculations.

class fastspecfit.photometry.Photometry(fphotofile=None, fitstack=False, ignore_photometry=False)[source]

Load filter curves and provide photometric synthesis methods.

Parameters:
  • fphotofile (str or None, optional) – Path to the YAML file defining filter names, bands, and column mappings. Defaults to the bundled DR9 configuration.

  • fitstack (bool, optional) – If True, load the stacked-spectra photometry configuration instead of the default DR9 one. Default is False.

  • ignore_photometry (bool, optional) – If True, set all photometric bands to not be fit. Default is False.

static get_ab_maggies(filters, flux, wave)[source]

Synthesize AB maggies, padding the spectrum when wavelength coverage is insufficient.

Parameters:
  • filters (speclite.filters.FilterSequence) – Filter sequence.

  • flux (numpy.ndarray) – Spectrum (or array of spectra) in erg/s/cm2/A.

  • wave (numpy.ndarray) – Wavelength array in Angstroms.

Returns:

maggies – Synthesized flux in maggies, shape (nfilters,) or (nspectra, nfilters).

Return type:

numpy.ndarray

static get_ab_maggies_pre(filters, wave)[source]

Precompute filter-interpolation data for get_ab_maggies_unchecked().

Parameters:
  • filters (speclite.filters.FilterSequence) – Filter sequence whose response functions lie strictly within wave.

  • wave (numpy.ndarray) – Wavelength array in Angstroms.

Returns:

pre – Tuple of (lo, hi, resp, idenom) per filter, where lo and hi are the slice indices into wave, resp is the interpolated response times wavelength, and idenom is the reciprocal of the AB-reference normalization integral.

Return type:

tuple

static get_ab_maggies_unchecked(filters, flux, wave, pre=None)[source]

Synthesize AB maggies without speclite’s padding or interpolation.

Assumes all filter response functions lie strictly within wave. Use get_ab_maggies() when wavelength coverage may be insufficient.

Parameters:
  • filters (speclite.filters.FilterSequence) – Filter sequence.

  • flux (numpy.ndarray) – Spectrum in erg/s/cm2/A.

  • wave (numpy.ndarray) – Wavelength array in Angstroms.

  • pre (tuple or None, optional) – Precomputed interpolation data from get_ab_maggies_pre(); computed on the fly if None.

Returns:

maggies – Synthesized flux in maggies, one value per filter.

Return type:

numpy.ndarray

static get_dn4000(wave, flam, flam_ivar=None, redshift=None, rest=True)[source]

Compute the Dn(4000) spectral break index and its inverse variance.

Parameters:
  • wave (numpy.ndarray) – Wavelength array in Angstroms.

  • flam (numpy.ndarray) – Flux density in erg/s/cm2/A.

  • flam_ivar (numpy.ndarray or None, optional) – Inverse variance of flam; uniform weights assumed if None.

  • redshift (float or None, optional) – Object redshift; required when rest=False.

  • rest (bool, optional) – If True, wave is already in the rest frame. Default is True.

Returns:

  • dn4000 (float) – Dn(4000) index (0 if coverage is insufficient or computation fails).

  • dn4000_ivar (float) – Inverse variance of dn4000; 0 when flam_ivar is None.

Notes

Uses the narrow-band definition of Balogh et al. (1999): the ratio of mean flux density in 4000–4100 Å to that in 3850–3950 Å (rest frame), following eq. 11 of Bruzual (1983). Returns zeros when wavelength coverage is insufficient or integration fails.

static get_photflam(maggies, lambda_eff)[source]

Convert maggies to erg/s/cm2/A at the given effective wavelength.

kcorr_and_absmag(nanomaggies, ivar_nanomaggies, redshift, dmod, photsys, zmodelwave, zmodelflux, synth_absmag, synth_maggies_rest, snrmin=2.0)[source]

Compute K-corrected rest-frame photometry.

Parameters:
  • nanomaggies (numpy.ndarray) – Input photometric fluxes in the observed-frame bandpasses, in nanomaggies.

  • ivar_nanomaggies (numpy.ndarray) – Inverse variance photometry corresponding to nanomaggies.

  • redshift (float) – Galaxy or QSO redshift.

  • dmod (float) – Distance modulus corresponding to redshift.

  • photsys (str) – Photometric system (e.g. 'N' or 'S') selecting the appropriate observed-frame filter set.

  • zmodelwave (numpy.ndarray) – Observed-frame (redshifted) model wavelength array in Angstroms.

  • zmodelflux (numpy.ndarray) – Observed-frame (redshifted) model spectrum in erg/s/cm2/A.

  • synth_absmag (numpy.ndarray) – Absolute magnitudes synthesized from the model SED.

  • synth_maggies_rest (numpy.ndarray) – Synthesized rest-frame photometry in maggies.

  • snrmin (float, optional) – Minimum S/N in an observed bandpass for it to contribute to the K-correction. Default is 2.

Returns:

  • kcorr (numpy.ndarray) – K-corrections for each bandpass in absmag_filters.

  • absmag (numpy.ndarray) – Band-shifted absolute magnitudes for each bandpass in absmag_filters.

  • ivarabsmag (numpy.ndarray) – Inverse variance corresponding to absmag; zero when derived from synthesized photometry.

  • synth_maggies_obs (numpy.ndarray) – Synthesized observed-frame photometry in maggies.

Notes

The K-correction uses the observed-frame bandpass whose rest-frame effective wavelength most closely matches the desired band-shifted absolute-magnitude band (and which meets the snrmin threshold), minimizing the K-correction. When no qualifying bandpass is available, ivarabsmag is set to zero and absmag falls back to synth_absmag.

static parse_photometry(bands, maggies, lambda_eff, ivarmaggies=None, nanomaggies=True, nsigma=2.0, min_uncertainty=None, get_abmag=False)[source]

Parse (nano)maggies into a photometric table with flux-density and magnitude columns.

Parameters:
  • bands (numpy.ndarray of str) – Photometric band names.

  • maggies (numpy.ndarray) – Photometric fluxes; interpreted as nanomaggies when nanomaggies=True.

  • lambda_eff (numpy.ndarray) – Effective wavelengths of each band in Angstroms.

  • ivarmaggies (numpy.ndarray or None, optional) – Inverse variance; zeros assumed if None.

  • nanomaggies (bool, optional) – If True, treat maggies as nanomaggies. Default is True.

  • nsigma (float, optional) – S/N threshold for computing magnitude upper limits. Default is 2.

  • min_uncertainty (numpy.ndarray or None, optional) – Minimum magnitude uncertainty per band, added in quadrature to ivarmaggies before computing flam_ivar.

  • get_abmag (bool, optional) – If True, also compute AB-magnitude columns needed by fastqa. Default is False.

Returns:

phot – Table with columns band, lambda_eff, nanomaggies, nanomaggies_ivar, flam, and flam_ivar. When get_abmag=True, also includes abmag, abmag_ivar, abmag_brighterr, abmag_fainterr, and abmag_limit.

Return type:

astropy.table.Table

synth_absmag(redshift, dmod, zmodelwave, zmodelflux)[source]

Synthesize absolute magnitudes from the best-fitting SED.

Parameters:
  • redshift (float) – Galaxy or QSO redshift.

  • dmod (float) – Distance modulus corresponding to redshift.

  • zmodelwave (numpy.ndarray) – Observed-frame (redshifted) model wavelength array in Angstroms.

  • zmodelflux (numpy.ndarray) – Observed-frame (redshifted) model spectrum in erg/s/cm2/A.

Returns:

  • synth_absmag (numpy.ndarray) – Absolute magnitudes synthesized from the model SED.

  • synth_maggies_rest (numpy.ndarray) – Synthesized rest-frame photometry in maggies.

static to_nanomaggies(maggies)[source]

Convert maggies to nanomaggies (multiply by 1e9).

fastspecfit.photometry._gather_tractorphot_onebrick(input_cat, legacysurveydir, radius_match, racolumn, deccolumn, datamodel, restrict_region)[source]

Retrieve Tractor photometry for targets sharing a single brick.

fastspecfit.photometry.gather_tractorphot(input_cat, racolumn='TARGET_RA', deccolumn='TARGET_DEC', legacysurveydir=None, dr9dir=None, radius_match=1.0, restrict_region=None, columns=None)[source]

Retrieve Tractor photometry for all objects in an input catalog.

Matches using BRICKID/BRICK_OBJID when available; falls back to positional matching within radius_match arcseconds.

Parameters:
  • input_cat (astropy.table.Table) – Input catalog with required columns TARGETID, TARGET_RA, and TARGET_DEC. Optional columns BRICKNAME, RELEASE, PHOTSYS, BRICKID, and BRICK_OBJID improve matching.

  • racolumn (str, optional) – Name of the RA column. Default is 'TARGET_RA'.

  • deccolumn (str, optional) – Name of the Dec column. Default is 'TARGET_DEC'.

  • legacysurveydir (str or None, optional) – Path to the Legacy Surveys Tractor catalog directory tree.

  • dr9dir (str or None, optional) – Deprecated alias for legacysurveydir.

  • radius_match (float, optional) – Positional matching radius in arcseconds. Default is 1.0.

  • restrict_region (str or None, optional) – Restrict positional matching to 'north' or 'south'; both are checked by default.

  • columns (array-like or None, optional) – If provided, return only this subset of columns.

Returns:

out – Tractor photometry matched to input_cat, in the same row order.

Return type:

astropy.table.Table

fastspecfit.photometry.tractorphot_datamodel(from_file=False, datarelease='dr9')[source]

Return a zero-filled table matching the Tractor catalog data model.

Parameters:
  • from_file (bool, optional) – If True, read the data model from an actual Tractor catalog on disk. Default is False.

  • datarelease (str, optional) – Legacy Surveys data release; 'dr9' and 'dr10' are supported. Default is 'dr9'.

Returns:

datamodel – Single-row table with the Tractor catalog column names and dtypes, all values set to zero.

Return type:

astropy.table.Table

fastspecfit.qa

fastspecfit.qa.desiqa_one(data, metadata, specphot, coadd_type, fastfit=None, minspecwave=3500.0, maxspecwave=9900.0, minphotwave=0.1, maxphotwave=35.0, emline_snrmin=0.0, nsmoothspec=1, init_sigma_uv=None, init_sigma_narrow=None, init_sigma_balmer=None, init_vshift_uv=None, init_vshift_narrow=None, init_vshift_balmer=None, fastphot=False, fitstack=False, inputz=False, no_smooth_continuum=False, outdir=None, outprefix=None)[source]

Generate a QA figure for a single object.

Prepares the spectrum data and then calls qa_fastspec() to produce the figure.

Parameters:
  • data (dict) – Spectral data dictionary for one object.

  • metadata (astropy.table.Row) – Metadata row for the object.

  • specphot (astropy.table.Row) – Spectrophotometric measurements row.

  • coadd_type (str) – Coadd type (e.g. 'healpix').

  • fastfit (astropy.table.Row or None, optional) – Emission-line fit results; None for fastphot mode.

  • minspecwave (float, optional) – Minimum wavelength displayed in the spectral panel (Angstroms).

  • maxspecwave (float, optional) – Maximum wavelength displayed in the spectral panel (Angstroms).

  • minphotwave (float, optional) – Minimum wavelength displayed in the photometric panel (microns).

  • maxphotwave (float, optional) – Maximum wavelength displayed in the photometric panel (microns).

  • emline_snrmin (float, optional) – Minimum emission-line S/N for display. Default is 0.

  • nsmoothspec (int, optional) – Boxcar smoothing width for the displayed spectrum. Default is 1.

  • fastphot (bool, optional) – If True, generate photometry-only QA. Default is False.

  • fitstack (bool, optional) – If True, process a stacked spectrum. Default is False.

  • inputz (bool, optional) – If True, use the input redshift. Default is False.

  • no_smooth_continuum (bool, optional) – If True, do not smooth the continuum model. Default is False.

  • outdir (str or None, optional) – Output directory for the PNG figure.

  • outprefix (str or None, optional) – Optional filename prefix.

fastspecfit.qa.fastqa(args=None, comm=None)[source]

Entry point for the fastqa CLI: read fitting results and generate QA figures.

Parameters:
  • args (list or None, optional) – Command-line argument list; parsed from sys.argv when None.

  • comm (MPI communicator or None, optional) – MPI communicator for parallel execution.

fastspecfit.qa.format_niceline(line)[source]

Simple function to nicely format the name of a line.

fastspecfit.qa.parse(options=None)[source]

Parse input arguments for the fastqa command.

fastspecfit.qa.qa_fastspec(data, templates, metadata, specphot, fastspec=None, coadd_type='healpix', spec_wavelims=(3550, 9900), phot_wavelims=(0.1, 35), fastphot=False, fitstack=False, outprefix=None, no_smooth_continuum=False, emline_snrmin=0.0, nsmoothspec=1, outdir=None, inputz=None)[source]

Generate and write a QA figure for one fitted object.

Produces a multi-panel PNG showing the observed spectrum, best-fit continuum and emission-line model, broadband photometry, and key derived quantities.

Parameters:
  • data (dict) – Spectral data dictionary for one object.

  • templates (fastspecfit.templates.Templates) – Stellar population synthesis templates.

  • metadata (astropy.table.Row) – Targeting and redshift metadata for the object.

  • specphot (astropy.table.Row) – Spectrophotometric measurements row.

  • fastspec (astropy.table.Row or None, optional) – Emission-line and continuum fit results; None for fastphot mode.

  • coadd_type (str, optional) – Coadd type (e.g. 'healpix'). Default is 'healpix'.

  • spec_wavelims (tuple of float, optional) – (min, max) spectral wavelength range in Angstroms. Default is (3550, 9900).

  • phot_wavelims (tuple of float, optional) – (min, max) photometric wavelength range in microns. Default is (0.1, 35).

  • fastphot (bool, optional) – If True, generate photometry-only QA. Default is False.

  • fitstack (bool, optional) – If True, this is a stacked spectrum. Default is False.

  • outprefix (str or None, optional) – Optional prefix for the output filename.

  • no_smooth_continuum (bool, optional) – If True, do not smooth the continuum model. Default is False.

  • emline_snrmin (float, optional) – Minimum emission-line S/N ratio for display. Default is 0.

  • nsmoothspec (int, optional) – Boxcar smoothing width applied to the displayed spectrum. Default is 1.

  • outdir (str or None, optional) – Output directory; defaults to the current directory.

  • inputz (bool or None, optional) – If True, use the input redshift rather than the fitted one.

fastspecfit.singlecopy

Single-copy (per process) data structures read from files.

class fastspecfit.singlecopy.Singletons[source]

Container for per-process singleton data structures.

Holds global shared objects (templates, emission lines, photometry, cosmology, IGM model) that are read from disk once at startup and shared across all worker threads/processes within a single MPI rank.

initialize(emlines_file=None, fphotofile=None, fastphot=False, vdisp_nominal=250.0, vdisp_bounds=(75.0, 500.0), fitstack=False, ignore_photometry=False, template_file=None, template_version=None, template_imf=None, log_verbose=False)[source]

Load all singleton data structures from disk.

Parameters:
  • emlines_file (str or None, optional) – Path to the emission-line parameter file; uses the bundled default when None.

  • fphotofile (str or None, optional) – Path to the photometric configuration YAML file; uses the bundled DR9 default when None.

  • fastphot (bool, optional) – If True, load templates in photometry-only mode. Default is False.

  • vdisp_nominal (float, optional) – Nominal velocity dispersion in km/s used to pre-cache FFTs.

  • vdisp_bounds (tuple of float, optional) – (min, max) velocity dispersion bounds in km/s.

  • fitstack (bool, optional) – If True, use the stacked-spectra photometry configuration. Default is False.

  • ignore_photometry (bool, optional) – If True, disable photometric fitting. Default is False.

  • template_file (str or None, optional) – Full path to the SPS template FITS file; auto-detected when None.

  • template_version (str or None, optional) – Template version string; used when template_file is None.

  • template_imf (str or None, optional) – Initial mass function name for template selection.

  • log_verbose (bool, optional) – If True, set the logger level to DEBUG. Default is False.

fastspecfit.templates

Tools for handling templates.

class fastspecfit.templates.Templates(template_file=None, template_version=None, imf=None, mintemplatewave=None, maxtemplatewave=400000.0, vdisp_nominal=250.0, vdisp_bounds=(75.0, 500.0), fastphot=False, read_linefluxes=False)[source]

Stellar population synthesis templates for continuum fitting.

Reads SPS template spectra from a FITS file and pre-caches FFTs for velocity-dispersion convolution up to MAX_PRE_VDISP km/s.

Parameters:
  • template_file (str or None, optional) – Full path to the SPS template FITS file. Auto-detected from FTEMPLATES_DIR when None.

  • template_version (str or None, optional) – Template version string used to build the filename when template_file is None. Defaults to DEFAULT_TEMPLATEVERSION.

  • imf (str or None, optional) – Initial mass function used to build the filename when template_file is None. Defaults to DEFAULT_IMF.

  • mintemplatewave (float or None, optional) – Minimum wavelength to load into memory (Angstroms). Uses the minimum available wavelength when None.

  • maxtemplatewave (float, optional) – Maximum wavelength to load into memory (Angstroms). Default is 400 000 Å.

  • vdisp_nominal (float, optional) – Nominal velocity dispersion in km/s used to pre-broaden the templates. Default is VDISP_NOMINAL.

  • vdisp_bounds (tuple of float, optional) – (min, max) velocity dispersion bounds in km/s. Default is VDISP_BOUNDS.

  • fastphot (bool, optional) – If True, load in photometry-only mode. Default is False.

  • read_linefluxes (bool, optional) – If True, also read the model emission-line flux arrays. Default is False.

static _gaussian_kernel1d(sigma, radius, order=0)[source]

Compute a 1-D Gaussian convolution kernel of width 2*radius + 1.

static _gaussian_radius(sigma)[source]

Return the truncated radius (in pixels) of a Gaussian kernel with stddev sigma.

static conv_pre_select(conv_pre, rows)[source]

Select a subset of templates from a convolve_vdisp_pre() result.

Parameters:
  • conv_pre (tuple or None) – Preprocessing structure from convolve_vdisp_pre(), or None.

  • rows (array-like of int) – Indices of the templates to keep.

Returns:

conv_pre_subset – Preprocessing data restricted to the selected rows, or None if conv_pre is None.

Return type:

tuple or None

convolve_vdisp(templateflux, vdisp)[source]

Convolve one or more template spectra with a velocity dispersion.

Only the wavelength range defined by PIXKMS_BOUNDS is convolved; pixels outside that range are copied unchanged.

Parameters:
  • templateflux (numpy.ndarray) – Either a 1D spectrum or a 2D array of shape (ntemplates, nwavelengths).

  • vdisp (float) – Velocity dispersion in km/s.

Returns:

output – Convolved spectrum or array of spectra, same shape as templateflux.

Return type:

numpy.ndarray

convolve_vdisp_from_pre(flux_lohi, ft_flux_mid, flux_len, fft_len, vdisp)[source]

Convolve a pre-decomposed spectrum with a velocity dispersion.

Uses precomputed FFT data for the central wavelength range (from convolve_vdisp_pre()) and raw fluxes for the peripheral ranges.

Parameters:
  • flux_lohi (numpy.ndarray, shape (2*lo,)) – Concatenated raw fluxes for wavelengths outside PIXKMS_BOUNDS.

  • ft_flux_mid (numpy.ndarray of complex) – FFT of the central wavelength range.

  • flux_len (int) – Total length of the output flux array.

  • fft_len (int) – Padded FFT length used for ft_flux_mid.

  • vdisp (float) – Velocity dispersion in km/s; must be ≤ MAX_PRE_VDISP.

Returns:

output – Convolved flux spectrum.

Return type:

numpy.ndarray, shape (flux_len,)

convolve_vdisp_pre(templateflux)[source]

Precompute FFT data to accelerate repeated velocity-dispersion convolutions.

Parameters:

templateflux (numpy.ndarray, shape (ntemplates, nwavelengths)) – Array of template flux spectra.

Returns:

conv_pre(flux_lohi, ft_flux_mid, fft_len) where flux_lohi contains the raw fluxes outside PIXKMS_BOUNDS, ft_flux_mid is the FFT of the central wavelength range, and fft_len is the padded FFT length.

Return type:

tuple

static get_templates_filename(template_version, imf)[source]

Build the SPS template filename from FTEMPLATES_DIR, version, and IMF.

init_ffts()[source]

Configure the FFT backend and set the convolution function.

static klambda(wave)[source]

Construct the total-to-selective dust attenuation curve k(lambda).

Parameters:

wave (numpy.ndarray) – Rest-frame wavelength array in Angstroms.

Returns:

klambda – Total-to-selective attenuation curve, same shape as wave.

Return type:

numpy.ndarray

fastspecfit.util

General utilities.

class fastspecfit.util.BoxedScalar(dtype)[source]

A zero-initialized NumPy structured scalar that can be passed by reference.

Parameters:

dtype (dtype-like) – NumPy dtype of the scalar value.

value

The boxed value; access via .value to unbox.

Type:

numpy scalar

class fastspecfit.util.MPPool(nworkers, initializer=None, init_argdict=None)[source]

Parallel execution pool that falls back to sequential for a single worker.

Unlike multiprocessing.Pool, starmap() accepts a list of keyword-argument dictionaries rather than positional arguments.

Parameters:
  • nworkers (int) – Number of worker processes. When 1, work runs in the current process.

  • initializer (callable or None, optional) – Function to call in each worker subprocess at startup.

  • init_argdict (dict or None, optional) – Keyword arguments passed to initializer at startup.

close()[source]

Close the multiprocessing pool if one was created.

starmap(func, argdicts)[source]

Apply func to each keyword-argument dict in argdicts.

class fastspecfit.util.ZWarningMask[source]

Redrock ZWARN bitmask definitions (from Redrock 0.15.4).

Not all flags are currently used by fastspecfit.

fastspecfit.util._trapz_rebin(x, y, edges, ibw, out)

Numba-accelerated trapezoidal rebinning core.

fastspecfit.util.air2vac(airwave)[source]

Convert an air wavelength in Angstroms to vacuum wavelength.

fastspecfit.util.centers2edges(centers)

Convert bin centers to bin edges by linear extrapolation at the boundaries.

Parameters:

centers (numpy.ndarray) – Bin center coordinates.

Returns:

edges – Bin edge coordinates, length len(centers) + 1.

Return type:

numpy.ndarray

fastspecfit.util.find_minima(x)[source]

Return indices of local minima of x, including edges.

Indices are sorted in ascending order of x value. Conservative with repeated values: find_minima([1,1,1,2,2,2]) returns [0,1,2,4,5].

Parameters:

x (array-like) – Input data array.

Returns:

ii – Indices of local minima, sorted by x value (smallest first).

Return type:

numpy.ndarray of int

fastspecfit.util.ivar2var(ivar, clip=1e-08, sigma=False, allmasked_ok=False)[source]

Safely convert an inverse variance array to variance (or sigma).

Parameters:
  • ivar (numpy.ndarray) – Inverse variance array.

  • clip (float, optional) – Minimum ivar value treated as valid. Default is 1e-8.

  • sigma (bool, optional) – If True, return the square root (i.e. standard deviation). Default is False.

  • allmasked_ok (bool, optional) – If True, return zeros rather than raising when all pixels are masked. Default is False.

Returns:

  • var (numpy.ndarray) – Variance (or sigma) array; zero where ivar <= clip.

  • goodmask (numpy.ndarray of bool) – True where ivar > clip.

fastspecfit.util.median(A)

Compute the median of array A (Numba-accelerated).

fastspecfit.util.minfit(x, y, return_coeff=False)[source]

Fit a parabola y = y0 + ((x - x0) / xerr)^2 to find the minimum.

Parameters:
  • x (array-like) – x values.

  • y (array-like) – y values.

  • return_coeff (bool, optional) – If True, also return the raw polynomial coefficients (a, b, c). Default is False.

Returns:

  • x0 (float) – x position of the parabola minimum (-1 on failure).

  • xerr (float) – Half-width of the parabola at unit height (-1 on failure).

  • y0 (float) – Minimum y value (-1 on failure).

  • zwarn (int) – Zero on success; ZWarningMask.BAD_MINFIT on failure.

  • coeff (tuple, optional) – Raw (a, b, c) polynomial coefficients; only present when return_coeff=True.

fastspecfit.util.mwdust_transmission(ebv, filtername)[source]

Convert SFD E(B-V) to Milky Way dust transmission in a given bandpass.

Parameters:
  • ebv (float or array-like) – SFD E(B-V) reddening value(s).

  • filtername (str) – Filter name, e.g. 'decam2014-r'.

Returns:

transmission – Milky Way dust transmission (0–1), same shape as ebv.

Return type:

float or numpy.ndarray

Notes

Uses tabulated k_X = A(X)/E(B-V) values where transmission = 10^{-0.4 * k_X * ebv}. Based on desiutil.dust.mwdust_transmission.

fastspecfit.util.quantile(A, q)

Compute quantile(s) q of array A (Numba-accelerated).

fastspecfit.util.radec2pix(nside, ra, dec)[source]

Convert RA/Dec to HEALPix nested pixel numbers.

Parameters:
  • nside (int) – HEALPix nside parameter, must be 2**k for 0 < k < 30.

  • ra (float or array-like) – Right ascension in degrees.

  • dec (float or array-like) – Declination in degrees.

Returns:

pix – HEALPix pixel numbers in the nested scheme.

Return type:

numpy.ndarray of int

fastspecfit.util.sigmaclip(c, low=3.0, high=3.0)

Iterative sigma-clipping; returns the clipped array and a boolean mask.

fastspecfit.util.trapz(y, x)

Trapezoidal integration of y over x (Numba-accelerated).

fastspecfit.util.trapz_rebin(src_x, src_y, bin_centers, out=None, pre=None)[source]

Resample src_y into bins centered at bin_centers (area-conserving).

Parameters:
  • src_x (numpy.ndarray) – x coordinates of the input signal.

  • src_y (numpy.ndarray) – Input signal sampled at src_x.

  • bin_centers (numpy.ndarray) – Center x coordinates of the output bins.

  • out (numpy.ndarray or None, optional) – Pre-allocated output array; allocated if None.

  • pre (tuple or None, optional) – Preprocessing data from trapz_rebin_pre(); computed from bin_centers when None.

Returns:

out – Resampled signal at the center of each output bin.

Return type:

numpy.ndarray

fastspecfit.util.trapz_rebin_pre(bin_centers)[source]

Precompute bin edges and inverse widths for trapz_rebin().

Parameters:

bin_centers (numpy.ndarray) – Center x coordinates of the output bins.

Returns:

pre(edges, ibw) where edges are the bin edges and ibw is the array of inverse bin widths. Pass as the pre argument to trapz_rebin() to avoid recomputation.

Return type:

tuple

fastspecfit.util.var2ivar(var, sigma=False)[source]

Safely convert a scalar variance (or standard deviation) to an inverse variance.

Parameters:
  • var (float) – Variance, or standard deviation when sigma=True.

  • sigma (bool, optional) – If True, treat var as a standard deviation. Default is False.

Returns:

ivar – Inverse variance; 0 when var is too small to invert safely.

Return type:

float

class fastspecfit.emline_fit.interface.EMLine_Objective(obs_bin_centers, obs_fluxes, obs_weights, redshift, line_wavelengths, resolution_matrices, camerapix, params_mapping, continuum_patches=None)[source]

Objective function for emission-line least-squares fitting.

Parameters:
  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • obs_fluxes (numpy.ndarray) – Observed flux in each wavelength bin.

  • obs_weights (numpy.ndarray) – Weighting factors for each wavelength bin in the residual.

  • redshift (float) – Redshift of the observed spectrum.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

  • params_mapping (ParamsMapping) – Mapping from free to full line parameters.

  • continuum_patches (dict or None, optional) – Patch pedestal parameters, or None if not used.

jacobian(free_parameters)[source]

Compute the sparse Jacobian of the objective function.

Parameters:

free_parameters (numpy.ndarray) – Values of all free parameters.

Returns:

J – Sparse Jacobian at the given parameter values.

Return type:

EMLineJacobian

objective(free_parameters)[source]

Compute the weighted residuals between the emission-line model and observations.

Parameters:

free_parameters (numpy.ndarray) – Values of all free parameters.

Returns:

residuals – Weighted residuals for each wavelength bin.

Return type:

numpy.ndarray

class fastspecfit.emline_fit.interface.MultiLines(line_parameters, obs_bin_centers, redshift, line_wavelengths, resolution_matrices, camerapix)[source]

Per-line emission-line flux models across one or more cameras.

Builds and stores individual resolution-convolved line profiles so that the caller can retrieve a sparse model for any single line.

Parameters:
  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • redshift (float) – Redshift of the observed spectrum.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

getLine(line)[source]

Return the model for one emission line as a sparse array.

Parameters:

line (int) – Index of the line to return.

Returns:

  • range (tuple of int) – (s, e) giving the half-open bin range [s, e) in the combined observed wavelength array with nonzero flux.

  • data (numpy.ndarray) – Flux values for bins obs_bin_centers[s:e].

fastspecfit.emline_fit.interface._add_patches(obs_bin_centers, model_fluxes, patch_endpts, patch_pivotwaves, slopes, intercepts)

Add affine patch pedestals to model_fluxes in-place.

fastspecfit.emline_fit.interface._build_model_core(line_parameters, line_wavelengths, redshift, log_obs_bin_edges, ibin_widths, resolution_matrices, camerapix, model_fluxes)[source]

Compute resolution-convolved combined model fluxes, writing into model_fluxes.

fastspecfit.emline_fit.interface._build_multimodel_core(line_parameters, obs_bin_centers, redshift, line_wavelengths, resolution_matrices, camerapix, consumer_fun)[source]

Compute sparse per-line models for each camera and pass each to consumer_fun.

fastspecfit.emline_fit.interface._prepare_bins(centers, camerapix)

Convert observed bin centers to log bin edges and inverse bin widths.

Parameters:
  • centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

Returns:

  • log_obs_bin_edges (numpy.ndarray) – Natural log of each bin edge wavelength. Edges are placed halfway between adjacent centers, with extrapolation at the ends. One extra edge per camera gap is included.

  • ibin_widths (numpy.ndarray) – Inverse bin widths, zero-padded by one entry on each end.

fastspecfit.emline_fit.interface.build_model(redshift, line_parameters, line_wavelengths, obs_bin_centers, resolution_matrices, camerapix, continuum_patches=None)[source]

Compute the resolution-convolved emission-line model fluxes.

Parameters:
  • redshift (float) – Redshift of the observed spectrum.

  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

  • continuum_patches (dict or None, optional) – Patch pedestal parameters, or None if not used.

Returns:

model_fluxes – Modeled flux in each observed wavelength bin.

Return type:

numpy.ndarray

fastspecfit.emline_fit.interface.find_peak_amplitudes(line_parameters, obs_bin_centers, redshift, line_wavelengths, resolution_matrices, camerapix)[source]

Return the maximum flux contributed by each line to any observed bin.

Parameters:
  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • redshift (float) – Redshift of the observed spectrum.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

Returns:

max_amps – Maximum flux in any observed bin for each line.

Return type:

numpy.ndarray

fastspecfit.emline_fit.interface.find_peak_amplitudes_and_fluxes(line_parameters, obs_bin_centers, redshift, line_wavelengths, resolution_matrices, camerapix)[source]

Return the peak amplitude and integrated flux for each emission line.

Parameters:
  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • obs_bin_centers (numpy.ndarray) – Center wavelength of each observed wavelength bin.

  • redshift (float) – Redshift of the observed spectrum.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • resolution_matrices (tuple of fastspecfit.resolution.Resolution) – Resolution matrices for each camera.

  • camerapix (numpy.ndarray of int) – Start and end wavelength bin indices for each camera.

Returns:

  • max_amps (numpy.ndarray) – Maximum flux in any observed bin for each line.

  • line_fluxes (numpy.ndarray) – Wavelength-integrated flux of the convolved line profile for each line.

fastspecfit.emline_fit.interface.mulWMJ(w, M, Jsp)

Compute the sparse matrix product P = W @ M @ J.

W is a diagonal weight matrix, M is a resolution matrix, and J is a column-sparse matrix with one contiguous nonzero range per column. The result is written back into Jsp in-place.

Parameters:
  • w (numpy.ndarray) – Diagonal of the weight matrix W.

  • M (numpy.ndarray, shape (nbins, ndiag)) – Resolution matrix in sparse row form.

  • Jsp (tuple) – Column-sparse matrix (endpts, J), where endpts[j] = (s, e) gives the half-open nonzero range for column j and J[j, :e-s] holds the values.

Returns:

result – Product W @ M @ J in the same column-sparse form as Jsp.

Return type:

tuple

Notes

The input Jsp must have sufficient padding so that each column of J can be overwritten with the corresponding column of P.

fastspecfit.emline_fit.jacobian.emline_model_jacobian(line_parameters, log_obs_bin_edges, ibin_widths, redshift, line_wavelengths, padding)

Compute the sparse Jacobian of emline_model().

Parameters:
  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • log_obs_bin_edges (numpy.ndarray) – Natural logs of observed wavelength bin edges.

  • ibin_widths (numpy.ndarray) – Inverse widths of each observed wavelength bin.

  • redshift (float) – Redshift of the observed spectrum.

  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • padding (int) – Extra entries to pad each sparse row for later use.

Returns:

  • endpts (numpy.ndarray of int, shape (3*nlines, 2)) – Start and end bin indices of the nonzero range for each parameter.

  • dd (numpy.ndarray, shape (3*nlines, max_width)) – Partial derivative values within each parameter’s nonzero bin range.

fastspecfit.emline_fit.model.emline_model(line_wavelengths, line_parameters, log_obs_bin_edges, redshift, ibin_widths)

Compute average emission-line flux in each observed wavelength bin.

Parameters:
  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • log_obs_bin_edges (numpy.ndarray) – Natural logs of observed wavelength bin edges.

  • redshift (float) – Redshift of the observed spectrum.

  • ibin_widths (numpy.ndarray) – Inverse widths of each observed wavelength bin.

Returns:

Average flux in each observed wavelength bin.

Return type:

numpy.ndarray

fastspecfit.emline_fit.model.emline_model_core(line_wavelength, line_amplitude, line_vshift, line_sigma, log_obs_bin_edges, redshift, ibin_widths, vals)

Compute the flux contribution of one spectral line to a model spectrum.

Determines the range of bins where the line contributes flux, writes those contributions to vals, and returns the half-open bin range [s, e).

Parameters:
  • line_wavelength (float) – Nominal rest-frame wavelength of the line in Angstroms.

  • line_amplitude (float) – Amplitude of the line.

  • line_vshift (float) – Velocity shift of the line in km/s.

  • line_sigma (float) – Gaussian width of the line in km/s.

  • log_obs_bin_edges (numpy.ndarray) – Natural logs of observed wavelength bin edges.

  • redshift (float) – Redshift of the observed spectrum.

  • ibin_widths (numpy.ndarray) – Inverse widths of each observed wavelength bin.

  • vals (numpy.ndarray) – Output array in which nonzero bin fluxes are written.

Returns:

  • s (int) – Index of the first bin with nonzero flux.

  • e (int) – One past the index of the last bin with nonzero flux. vals[0:e-s] contains the fluxes. If s == e, no nonzero fluxes were found.

Notes

vals must have length at least two more than the maximum possible number of nonzero bins. Entries beyond the returned range may be set to arbitrary values.

fastspecfit.emline_fit.model.emline_perline_models(line_wavelengths, line_parameters, log_obs_bin_edges, redshift, ibin_widths, padding)

Compute the per-line emission-line flux profiles sparsely.

Shares the core computation of emline_model() but returns individual line profiles rather than a collapsed composite.

Parameters:
  • line_wavelengths (numpy.ndarray) – Nominal rest-frame wavelengths of all fitted lines in Angstroms.

  • line_parameters (numpy.ndarray) – Concatenated array of amplitudes, velocity shifts, and sigmas for all lines.

  • log_obs_bin_edges (numpy.ndarray) – Natural logs of observed wavelength bin edges.

  • redshift (float) – Redshift of the observed spectrum.

  • ibin_widths (numpy.ndarray) – Inverse widths of each observed wavelength bin.

  • padding (int) – Extra entries to pad each sparse row for later use.

Returns:

  • endpts (numpy.ndarray of int, shape (nlines, 2)) – Start and end bin indices of the nonzero range for each line.

  • profiles (numpy.ndarray, shape (nlines, max_width)) – Flux values within each line’s nonzero bin range.

class fastspecfit.emline_fit.params_mapping.ParamsMapping(nParms, isFree, tiedSources, tiedFactors, doubletTargets, doubletSources)[source]

Map free line parameters to the full EMLine model parameter set.

Precomputes and caches the mapping from free (unconstrained) parameters to the full parameter vector, including fixed, tied, and doublet relationships, as well as the Jacobian of that mapping.

Parameters:
  • nParms (int) – Total number of parameters (free + fixed/tied).

  • isFree (numpy.ndarray of bool) – Boolean mask indicating which parameters are free.

  • tiedSources (numpy.ndarray of int) – Index of the source parameter for each tied parameter (-1 if not tied).

  • tiedFactors (numpy.ndarray of float) – Multiplicative factor from source to target for each tied parameter.

  • doubletTargets (numpy.ndarray of int) – Indices of parameters that are doublet ratio targets.

  • doubletSources (numpy.ndarray of int) – Source parameter indices for each doublet ratio.

static _add_rmatvec(J_S, v, w)

Multiply v by the transpose of sparse Jacobian J_S, adding the result to w.

Parameters:
static _matvec(J_S, v, w)

Multiply sparse parameter Jacobian J_S by v, writing the result to w.

Parameters:
_precomputeJacobian()[source]

Precompute sparse Jacobian structure and doublet patches for getJacobian().

_precomputeMapping(isFree, pFree, tiedSources, tiedFactors, doubletTargets, doubletSources)[source]

Precompute source/factor arrays and doublet patches for mapFreeToFull().

fixedMask()[source]

Return a Boolean mask with True for each fixed parameter.

Returns:

maskTrue where parameters are fixed (not free or tied).

Return type:

numpy.ndarray of bool

getJacobian(freeParms)[source]

Return the Jacobian of the free-to-full parameter mapping.

Parameters:

freeParms (numpy.ndarray) – Current values of the free parameters.

Returns:

J_S – Sparse Jacobian as (shape, elts, factors), where shape is (nParms, nFreeParms), elts contains the row and column indices of each nonzero element, and factors contains their values.

Return type:

tuple

mapFreeToFull(freeParms, out=None, patchDoublets=True)[source]

Map a vector of free parameters to the full parameter set.

Parameters:
  • freeParms (numpy.ndarray) – Values of the free parameters.

  • out (numpy.ndarray or None, optional) – Pre-allocated output array; if None, one is allocated.

  • patchDoublets (bool, optional) – If True, replace doublet ratio parameters with their actual values. Defaults to True.

Returns:

fullParms – Values of all parameters (free, fixed, tied, and doublet).

Return type:

numpy.ndarray

class fastspecfit.emline_fit.sparse_rep.EMLineJacobian(*args: Any, **kwargs: Any)[source]

Sparse Jacobian of the emission-line fitting objective function.

For each camera’s pixel range, the Jacobian is a matrix product W * M * J_I * J_S, where J_S is the Jacobian of the parameter expansion, J_I is the ideal Jacobian for the Gaussian mixture, M is the camera’s resolution matrix, and W is a diagonal matrix of per-observation weights.

The product W * M * J_I is precomputed for each camera. When patch pedestals are used, the Jacobian is extended with additional columns for the slope and intercept of each patch.

Parameters:
  • shape (tuple) – Shape (nrows, ncols) of the Jacobian matrix.

  • nLineFreeParms (int) – Number of free line parameters.

  • camerapix (numpy.ndarray) – Start and end wavelength bin indices for each camera.

  • jacs (tuple) – Precomputed partial Jacobians (W * M * J_I) for each camera.

  • J_S (numpy.ndarray) – Parameter expansion Jacobian mapping free to full line parameters.

  • J_P (numpy.ndarray or None, optional) – Sparse Jacobian of patch pedestals, or None if not used.

_matmat(M)[source]

Compute the left matrix-matrix product J @ M.

Parameters:

M (numpy.ndarray, shape (nfreeparms, N)) – Matrix whose columns are free-parameter vectors.

Returns:

result – Product of the Jacobian with each column of M.

Return type:

numpy.ndarray, shape (nbins, N)

_matvec(v)[source]

Compute the left matrix-vector product J @ v.

Parameters:

v (numpy.ndarray) – Vector of free parameters.

Returns:

w – Result vector over all wavelength bins.

Return type:

numpy.ndarray

static _matvec_J(J, v, w)

Multiply sparse Jacobian J by v, writing the result to w.

Parameters:
  • J (tuple) – Sparse Jacobian in (endpts, values) form.

  • v (numpy.ndarray) – Input vector of line parameters.

  • w (numpy.ndarray) – Output vector of wavelength bins (overwritten).

_rmatvec(v)[source]

Compute the right matrix-vector product J.T @ v.

Parameters:

v (numpy.ndarray) – Vector over all wavelength bins.

Returns:

w – Result vector of free parameters.

Return type:

numpy.ndarray

static _rmatvec_J(J, v, w)

Multiply v by the transpose of sparse Jacobian J, writing the result to w.

Parameters:
  • J (tuple) – Sparse Jacobian in (endpts, values) form.

  • v (numpy.ndarray) – Input vector of wavelength bins.

  • w (numpy.ndarray) – Output vector of line parameters (overwritten).

fastspecfit.emline_fit.sparse_rep._matvec_J_add(J, v, w)

Multiply sparse Jacobian J by v, adding the result to w.

Parameters:
  • J (tuple) – Sparse Jacobian in (endpts, values) form.

  • v (numpy.ndarray) – Input vector of line parameters.

  • w (numpy.ndarray) – Output vector of wavelength bins (accumulated in-place).

Notes

This function is module-level rather than a static method of EMLineJacobian because Numba cannot call a static class method from JIT-compiled code.

fastspecfit.emline_fit.utils.max_buffer_width(log_obs_bin_edges, line_sigmas, padding=0)

Estimate the maximum number of nonzero bins possible for any spectral line.

Parameters:
  • log_obs_bin_edges (np.ndarray) – Log wavelengths of all observed bin edges.

  • line_sigmas (np.ndarray) – Gaussian widths of all spectral lines in km/s.

  • padding (int, optional) – Extra bins to add on each side for future expansion. Defaults to 0.

Returns:

Safe upper bound on the number of bins with nonzero flux for any line.

Return type:

int

fastspecfit.emline_fit.utils.norm_cdf(a)

Approximate the CDF of the standard normal distribution.

Parameters:

a (float) – Upper integration limit.

Returns:

Integral of the standard normal PDF from \(-\infty\) to a.

Return type:

float

fastspecfit.emline_fit.utils.norm_pdf(a)

PDF of the standard normal distribution.

Parameters:

a (float) – Evaluation point.

Returns:

Probability density at a.

Return type:

float