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

_fit_stellar_continuum_varpro(templateflux, tauv_bounds, dust_emission, synthphot, synthspec, objflam, objflamistd, specflux, specistd)[source]

Fit stellar continuum via variable projection (VARPRO).

Handles all fit_vdisp=False cases (photometry-only, spectroscopy-only, or combined). For fixed tauv, the full model (including energy-balance dust emission) is linear in the template coefficients, so the inner problem reduces to non-negative least squares. The outer problem is a scalar bounded minimization over tauv solved with Brent’s method (~10-15 function evaluations), replacing the TRF optimizer that otherwise finite-differences over all ntemplates + 1 parameters.

Spectroscopic and photometric residuals are stacked in that order, matching the split convention used by stellar_continuum_chi2().

_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_photometry_batch(phi)[source]

Apply continuum_to_photometry() to all rows of phi.

Parameters:

phi (numpy.ndarray, shape (ntemplates, npix))

Returns:

out

Return type:

numpy.ndarray, shape (ntemplates, nphot)

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]

continuum_to_spectroscopy_batch(phi)[source]

Apply continuum_to_spectroscopy() to all rows of phi.

Parameters:

phi (numpy.ndarray, shape (ntemplates, npix))

Returns:

out

Return type:

numpy.ndarray, shape (ntemplates, nspec)

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, ftol=1e-06, xtol=1e-10)[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.

  • ftol (float, optional) – Relative tolerance on the cost function for convergence. Defaults to 1e-6; pass a looser value (e.g. 1e-3) when only a relative chi2 ranking is needed (e.g. the vdisp scan).

  • xtol (float, optional) – Relative tolerance on the parameter step for convergence. Defaults to 1e-10; pass a looser value (e.g. 1e-5) when only a relative chi2 ranking is needed.

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.build_stellar_continuum(coeff, tauv, redshift, templates, cosmo, igm, vdisp=None, fluxnorm=1e+17, massnorm=10000000000.0, dust_emission=True)[source]

Build a stellar continuum model from template coefficients.

This is a standalone version of ContinuumTools.build_stellar_continuum() intended for use outside of the main fitting pipeline (e.g., in notebooks). It constructs the redshift, IGM, and luminosity-distance scaling factors internally from the supplied cosmology and IGM objects.

Parameters:
  • coeff (numpy.ndarray [ntemplates]) – Non-negative template coefficients in units of MASSNORM solar masses.

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

  • redshift (float) – Object redshift.

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

  • cosmo (fastspecfit.cosmo.TabulatedDESI) – Tabulated DESI fiducial cosmology, used to compute the luminosity distance.

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

  • vdisp (float or None, optional) – Velocity dispersion in km/s. If None, the raw (unbroadened) templates.flux is used without any convolution. To match the default production behavior, pass vdisp=templates.vdisp_nominal (250 km/s).

  • fluxnorm (float, optional) – Flux normalization factor in erg/s/cm²/Å. Defaults to FLUXNORM (1017).

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

  • dust_emission (bool, optional) – If True, add the energy-balance infrared dust emission spectrum. Defaults to True.

Returns:

  • ztemplatewave (numpy.ndarray [npix]) – Observed-frame (redshifted) wavelength array in Angstroms.

  • contmodel (numpy.ndarray [npix]) – Observed-frame continuum model in units of 10-17 erg/s/cm²/Å per MASSNORM solar masses.

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=50, 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.

  • 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=50, 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.

  • 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=50, 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.fastspecfit

See sandbox/running-fastspecfit for examples.

fastspecfit.fastspecfit.fastphot(args=None, comm=None, verbose=False, mp_pool=None)[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.

  • mp_pool (fastspecfit.util.MPPool or None, optional) – Pre-created worker pool to reuse; a new pool is created and closed when None.

Returns:

Exit code (0 on success).

Return type:

int

fastspecfit.fastspecfit.fastspec(fastphot=False, fitstack=False, args=None, comm=None, verbose=False, mp_pool=None)[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=50, 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.

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

Returns:

fastspecfit.fastspecfit.make_init_sc_args(args, fastphot=False, fitstack=False)[source]

Build the sc_data.initialize() kwargs from a parsed args Namespace.

Parameters:
Returns:

Keyword arguments suitable for sc_data.initialize(**...).

Return type:

dict

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, constraintsfile=None, fastphot=False, inputz=False, inputseeds=None, nmonte=50, 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, constraints)[source]

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

Parameters:
  • emline_table (astropy.table.Table) – Emission line table.

  • constraints (fastspecfit.emlines.EmlineConstraints) – Parsed kinematic constraint file; passed to EMFitTools for the preliminary patch-fitting step.

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.

class fastspecfit.logger._DynamicStdoutHandler(stream=None)[source]

StreamHandler that always writes to the current sys.stdout.

Rebinds self.stream on every emit() so that OS-level stdout redirections (e.g. desispec.io.util.stdouterr_redirected) are followed correctly.

emit(record)[source]

Emit a record.

If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ‘encoding’ attribute, it is used to determine how to do the output to the stream.

fastspecfit.logger.getFastspecLogger()[source]

Create a fastspecfit-specific logger that writes to stdout.

Returns the same logger object on every call without resetting its level, so external code (e.g. sc_data.initialize) can safely call setLevel() and have that setting persist.

Returns:

log – Logger named fastspec.

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._perfile_init(init_sc_args, sample, rank, fastphot, input_redshifts)[source]

Pool initializer for –mp-per-file mode.

Loads sc_data once per worker process and stores per-run state in module-level globals so that _perfile_run() can access them without per-task pickling overhead.

fastspecfit.mpi._perfile_run(redrockfile, outfile, ntarget, args)[source]

Per-file worker task for –mp-per-file mode.

Reads worker state from module-level globals set by _perfile_init(), builds per-file command args (forcing –mp=1 so no inner pool is created), and calls fastspec/fastphot for this file.

fastspecfit.mpi.build_cmdargs(args, redrockfile, outfile, sample=None, fastphot=False, input_redshifts=False)[source]

Build the command-line argument string for fastspec, fastphot, or fastqa.

Parameters:
  • args (argparse.Namespace) – Parsed command-line arguments.

  • redrockfile (str) – Path to the input redrock file (or QA output directory for --makeqa).

  • outfile (str) – Path to the output FITS file (or input file for --makeqa).

  • sample (astropy.table.Table or None, optional) – Optional target sample table with columns {SURVEY, PROGRAM, HEALPIX, TARGETID}.

  • fastphot (bool, optional) – If True, build arguments for fastphot instead of fastspec.

  • input_redshifts (bool, optional) – If True, include input redshifts from sample['Z'].

Returns:

  • cmd (str) – Executable name ('fastspec', 'fastphot', or 'fastqa').

  • cmdargs (str) – Command-line argument string.

  • logfile (str) – Path to the log file.

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, uniqueid='')[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, filters_obs=None, filters_out=None, bands_to_fit=None)[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.

  • filters_obs (speclite.filters.FilterSequence or None, optional) – Observed-frame filter set. Defaults to self.filters[photsys].

  • filters_out (speclite.filters.FilterSequence or None, optional) – Rest-frame output filter set. Defaults to self.filters_out.

  • bands_to_fit (numpy.ndarray or None, optional) – Boolean or integer mask selecting which photometric bands are used in the fit. Defaults to self.bands_to_fit.

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, filters_out=None)[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.

  • filters_out (speclite.filters.FilterSequence or None, optional) – Rest-frame output filter set used to synthesize absolute magnitudes. Defaults to self.filters_out.

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._build_legend(metadata, specphot, fastspec, phot, fastphot, fitstack, redshift, line_stats=None, snrcut=1.5)[source]

Build legend dictionaries for the QA figure.

Parameters:
Returns:

  • leg (dict) – Main legend entries (stellar params, abs mags, kinematics).

  • leg_broad (dict) – Broad Balmer line entries.

  • leg_narrow (dict) – Narrow line entries.

  • leg_uv (dict) – UV line entries.

fastspecfit.qa._build_sed_model(CTools, templates, specphot, metadata, phot, redshift, phot_wavelims, allfilters)[source]

Construct the best-fit broadband SED model and observed photometry.

Parameters:
Returns:

  • sedwave (numpy.ndarray) – Observed-frame wavelengths (Angstroms), trimmed to phot_wavelims.

  • sedmodel (numpy.ndarray) – Best-fit SED flux trimmed to phot_wavelims.

  • sedphot (astropy.table.Table) – Synthesized photometry from the SED model.

  • phot_tbl (astropy.table.Table) – Observed photometry with AB magnitudes and errors.

fastspecfit.qa._build_spectral_models(CTools, EMFit, data, fastspec, specphot, templates, fitstack, no_smooth_continuum, emline_snrmin, redshift)[source]

Reconstruct per-camera continuum and emission-line spectral models.

Parameters:
  • CTools (fastspecfit.continuum.ContinuumTools) – Continuum fitting tools.

  • EMFit (fastspecfit.emlines.EMFitTools) – Emission-line fitting tools.

  • data (dict) – Per-camera spectral data.

  • fastspec (astropy.table.Row) – Best-fit parameters.

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

  • templates (fastspecfit.templates.Templates) – SPS templates.

  • fitstack (bool) – If True, apply stacked-spectrum flux normalization.

  • no_smooth_continuum (bool) – If True, skip the smooth continuum component.

  • emline_snrmin (float) – Minimum line S/N for the emission-line model.

  • redshift (float) – Object redshift.

Returns:

Keys: fullwave, apercorr, desicontinuum, fullcontinuum, desiresiduals, fullsmoothcontinuum, desismoothcontinuum, desiemlines.

Return type:

dict

fastspecfit.qa._compute_line_stats(EMFit, fastspec, data, redshift, snrcut=1.5)[source]

Compute per-group kinematics for in-range emission lines.

Calls EMFit.compute_inrange_lines() and collects sigma and redshift statistics for narrow, broad Balmer, and UV lines detected above snrcut.

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

  • fastspec (astropy.table.Row) – Best-fit emission-line parameters.

  • data (dict) – Spectral data dictionary containing a wave key.

  • redshift (float) – Object redshift.

  • snrcut (float, optional) – Minimum amplitude S/N to include a line. Default is 1.5.

Returns:

  • linetable (astropy.table.Table) – Emission lines falling within the observed wavelength range.

  • line_stats (astropy.table.Table) – Mean sigma and redshift for NARROW, BROAD, and UV line groups.

fastspecfit.qa._corner_plot(plotdata, bins, ranges, labels, titles, truths, sigmas, suptitle, pngfile, subplots_adjust=None)[source]

Minimal corner-style N×N plot: histograms on the diagonal, scatter on the lower triangle.

Parameters:
  • plotdata (array_like, shape (nsamples, ndim)) – Monte Carlo samples, one column per parameter.

  • bins (int) – Number of histogram bins.

  • ranges (list of (lo, hi) tuples) – Axis limits for each parameter.

  • labels (list of str) – Axis labels, one per parameter.

  • titles (list of str) – Titles shown above each diagonal histogram (typically best-fit ± sigma).

  • truths (list of float) – Best-fit values; drawn as solid vertical/horizontal lines.

  • sigmas (list of float) – 1σ uncertainties; drawn as dashed lines on diagonal histograms.

  • suptitle (str) – Figure suptitle.

  • pngfile (str) – Output PNG filename.

  • subplots_adjust (dict or None, optional) – Keyword arguments forwarded to fig.subplots_adjust; if None tight_layout is called instead.

fastspecfit.qa._fetch_cutout(metadata, outdir, pngfile, layer, pixscale)[source]

Download and load a Legacy Survey viewer cutout image.

Parameters:
  • metadata (astropy.table.Row) – Object metadata with RA, DEC, and TARGETID columns.

  • outdir (str) – Output directory for the temporary JPEG file.

  • pngfile (str) – Output PNG path (used to name the temp JPEG).

  • layer (str) – Legacy Survey viewer layer (e.g. 'ls-dr9').

  • pixscale (float) – Pixel scale in arcsec per pixel.

Returns:

  • img (numpy.ndarray) – RGB image array of shape (height, width, 3).

  • wcs (astropy.wcs.WCS) – WCS object for the cutout image geometry.

  • width (int) – Cutout width in pixels.

  • height (int) – Cutout height in pixels.

fastspecfit.qa._setup_figure(fastphot, fitstack, wcs)[source]

Create the QA figure and gridspec layout.

Parameters:
  • fastphot (bool) – If True, use the photometry-only layout.

  • fitstack (bool) – If True, use the stacked-spectrum layout.

  • wcs (astropy.wcs.WCS or None) – WCS projection for the cutout axes; None when fitstack is True.

Returns:

  • fig (matplotlib.figure.Figure)

  • gs (matplotlib.gridspec.GridSpec)

  • cutax (axis or None) – Cutout image axes; None for fitstack.

  • sedax (axis or None) – SED axes; None for fitstack.

  • specax (axis or None) – Full-spectrum axes; None for fastphot.

  • nlinecols (int) – Number of emission-line panel columns in the gridspec.

fastspecfit.qa._target_label(metadata, coadd_type)[source]

Build target identification strings for the QA figure legend.

Parameters:
  • metadata (astropy.table.Row) – Object metadata.

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

Returns:

Two or three strings identifying the target for display.

Return type:

list of str

Raises:

ValueError – If coadd_type is not recognized.

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, constraints_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.

  • constraints_file (str or None, optional) – Path to the emission-line kinematic constraint YAML file; uses the bundled default when None. A consistency check against emlines_file is run at startup.

  • 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.singlecopy._initialize_sc_data(**kwargs)[source]

Pool initializer: initialize the per-process sc_data singleton.

This must be a module-level function so that multiprocessing (spawn mode) pickles it by reference rather than by value. A bound method such as sc_data.initialize would be pickled together with the parent’s fully initialized sc_data object and then called on that pickled copy in the worker, leaving the worker’s own module-level sc_data uninitialized.

fastspecfit.singlecopy._initialize_sc_data_worker(**kwargs)[source]

Pool initializer for MPI production workers.

Like _initialize_sc_data() but suppresses INFO logging in workers unless log_verbose=True was requested. This keeps per-object progress messages out of the Slurm log (where output from all MPI ranks is interleaved) while still routing them to the per-healpix log file via the parent process. Interactive fastspec/fastphot runs use _initialize_sc_data() instead and therefore keep full INFO logging regardless of --mp.

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._trapz_rebin_batch(x, Y, edges, ibw, out)

Apply _trapz_rebin() to each row of Y (ntemplates × npix).

Parameters:
fastspecfit.util._uid(data)[source]

Return a log-friendly uniqueid that includes the output basename when set.

Use in warning/error messages so SLURM logs can be linked back to a specific healpix output file without changing plot filenames.

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.fsftime(operation, duration, context=None)[source]

Return a standardized, parseable timing message string.

Durations under 60 seconds are reported in seconds; longer durations are reported in minutes. Use parse_fsftime() to parse these messages back out of log files.

Parameters:
  • operation (str) – Short name of the pipeline stage being timed, e.g. 'continuum_specfit' or 'write_fastspecfit'.

  • duration (float) – Elapsed wall time in seconds.

  • context (str or None, optional) – Optional comma-separated key=value context string appended in square brackets, e.g. 'targetid=39627739988231708'.

Returns:

Formatted timing string ready to pass to a logger.

Return type:

str

Examples

>>> log.info(fsftime('continuum_specfit', 3.45, context='targetid=12345'))
fsftime 3.45 sec for continuum_specfit [targetid=12345] at 2026-...
>>> log.info(fsftime('fit_all', 125.3, context='nobj=500'))
fsftime 2.09 min for fit_all [nobj=500] at 2026-...
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.parse_fsftime(line)[source]

Parse a line for an fsftime timing message produced by fsftime().

Parameters:

line (str) – Log line to parse.

Returns:

Dict with keys operation (str), duration_sec (float), context (str or None), and timestamp (str); or None if the line does not contain an fsftime message.

Return type:

dict or None

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