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 toFalse.constrain_age (bool, optional) – If
True, exclude templates older than the age of the universe at the object’s redshift. Defaults toFalse.
- ztemplatewave
Redshifted template wavelength array in Angstroms.
- Type:
- zfactors
Combined flux scaling factors including IGM attenuation, luminosity distance, and flux normalization.
- Type:
- agekeep
Index selection for templates younger than the age of the universe.
- Type:
slice or
numpy.ndarray
- vdisp_grid
Velocity dispersion grid used in the chi2 scan.
- Type:
- spec_pre
Preprocessing cache for spectroscopic resampling (set only when
fastphot=False).- Type:
- _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=Falsecases (photometry-only, spectroscopy-only, or combined). For fixedtauv, 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 overtauvsolved with Brent’s method (~10-15 function evaluations), replacing the TRF optimizer that otherwise finite-differences over allntemplates + 1parameters.Spectroscopic and photometric residuals are stacked in that order, matching the
splitconvention used bystellar_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 (
tupleor 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:
lums (
numpy.ndarray) – Rest-frame luminosities at the wavelengths defined bylums_keys().cfluxes (
numpy.ndarray) – Observed-frame continuum fluxes at the wavelengths defined bycfluxes_keys().
- 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 (
listorspeclite.filters.FilterSequence[nfilt]) – Optionally override the filter curves stored in the filters attribute of the global Photometry object.phottable (
bool) – Return anastropy.table.Tablewith 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.ndarrayorastropy.table.Table[nfilt]
- continuum_to_photometry_batch(phi)[source]
Apply
continuum_to_photometry()to all rows ofphi.- 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 ofphi.- 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 (
tupleof 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:
- 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 towave.ivar (
numpy.ndarray) – Inverse variance spectrum corresponding toflux.linemask (
numpy.ndarrayof bool) – Boolean mask whereTruemarks 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
fluxto produce a pure emission-line spectrum.- Return type:
- 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) –
Trueif 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 ofMASSNORMsolar 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.fluxis used without any convolution. To match the default production behavior, passvdisp=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 toTrue.
- 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²/Å perMASSNORMsolar 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) –
Trueif 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 ofobjflam.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:
- 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 ofobjflam.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 toFalse.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:
- 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 byfastspecfit.io.DESISpectra.read().- Returns:
Table with all the continuum-fitting results with columns documented in
init_output().- Return type:
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 ofspecflux.fitmask (
numpy.ndarrayof 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 toFalse.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).
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.Namespaceor list of str or None, optional) – Pre-parsed arguments or raw argument list. IfNone, reads fromsys.argv.comm (
mpi4py.MPI.Commor None, optional) – MPI intracommunicator for parallel execution, orNonefor single-process mode.verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to
False.mp_pool (
fastspecfit.util.MPPoolor None, optional) – Pre-created worker pool to reuse; a new pool is created and closed whenNone.
- Returns:
Exit code (0 on success).
- Return type:
- 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.Namespaceor list of str or None, optional) – Pre-parsed arguments or raw argument list. IfNone, reads fromsys.argv.comm (
mpi4py.MPI.Commor None, optional) – MPI intracommunicator for parallel execution, orNonefor single-process mode.verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to
False.
- Returns:
Exit code (0 on success).
- Return type:
- 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:
meta (
astropy.table.Row) – Updated metadata row with observed photometry filled in.specphot (
numpy.ndarray) – Spectrophotometric output row.fastfit (
numpy.ndarray) – Emission-line fitting output row.emmodel (
astropy.table.Tableor None) – Coadded model spectra table, orNoneiffastphot=True.
- fastspecfit.fastspecfit.make_init_sc_args(args, fastphot=False, fitstack=False)[source]
Build the sc_data.initialize() kwargs from a parsed args Namespace.
- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments (fromparse()or frommpi-fastspecfit).fastphot (bool, optional) – Passed through to
initialize().fitstack (bool, optional) – Passed through to
initialize().
- Returns:
Keyword arguments suitable for
sc_data.initialize(**...).- Return type:
- fastspecfit.fastspecfit.parse(options=None, rank=0)[source]
Parse input arguments to fastspec and fastphot scripts.
- Parameters:
- Returns:
args – Parsed command-line arguments.
- Return type:
- fastspecfit.fastspecfit.stackfit(args=None, comm=None, verbose=False)[source]
Entry point to fit generic stacked DESI spectra.
- Parameters:
args (
argparse.Namespaceor list of str or None, optional) – Pre-parsed arguments or raw argument list. IfNone, reads fromsys.argv.comm (
mpi4py.MPI.Commor None, optional) – MPI intracommunicator for parallel execution, orNonefor single-process mode.verbose (bool, optional) – Enable verbose (debug-level) logging. Defaults to
False.
- Returns:
Exit code (0 on success).
- Return type:
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.
- 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:
- 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.
Noneimposes no upper limit.zwarnmax (int or None, optional) – Maximum Redrock
ZWARNvalue for selected targets.Noneimposes 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. IfNone, 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, andspecprod. Thespecprodis 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 toFalse.constrain_age (bool, optional) – If
True, pass age-constraint information to the per-object processor. Defaults toFalse.
- 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:
- 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 fromread().phot (
fastspecfit.photometry.Photometry) – Photometry object providing band and column information.fastphot (bool, optional) – If
True, omit spectroscopy-specific columns. Defaults toFalse.fitstack (bool, optional) – If
True, format for stacked-spectra output. Defaults toFalse.
- Returns:
meta – Output metadata table with columns in the standard data model order.
- Return type:
- fastspecfit.io.create_output_table(records, meta, units, fitstack=False)[source]
Generate the output FASTSPEC/FASTPHOT or SPECPHOT table.
- Parameters:
records (list of
numpy.ndarray) – Per-object output records.meta (
astropy.table.Table) – Output metadata table fromcreate_output_meta().units (dict) – Mapping from column name to astropy unit.
fitstack (bool, optional) – If
True, format for stacked-spectra output. Defaults toFalse.
- Returns:
output_table – Table with identification columns from
metaprepended to the fitted-quantity columns.- Return type:
- 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 toFalse.fastphot (bool, optional) – If
True, omit spectroscopy-only fields. Defaults toFalse.fitstack (bool, optional) – If
True, omit per-object spectroscopic fields. Defaults toFalse.
- 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, ornumpy.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 toFalse.
- Returns:
pngfile – QA filename(s) for the given object(s).
- Return type:
- 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
specdatain-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 toFalse.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:
- 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. Modifiesspecdatain-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:
- 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 toFalse.
- Returns:
meta (
astropy.table.Tableor None) – Metadata table, orNoneif the file is not found.specphot (
astropy.table.Tableor None) – Spectrophotometric results table.fastfit (
astropy.table.Tableor None) – Emission-line fitting results, orNonein fastphot mode.coadd_type (str or None) – Coadd type string from the file header.
fastphot (bool or None) –
Trueif the file was produced in fastphot (photometry-only) mode.models (
numpy.ndarrayor None) – Model spectra array (only included in the return tuple whenread_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 toEMFitToolsfor 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 offastspecfit.resolution.Resolutionobjects, 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 (
floator None, optional) – Initial broad-line width in km/s. Default is 3000.initsigma_narrow (
floator None, optional) – Initial narrow/forbidden-line width in km/s. Default is 150.initsigma_balmer_broad (
floator None, optional) – Initial broad Balmer-line width in km/s. Default is 1000.initvshift_broad (
floator None, optional) – Initial broad-line velocity shift in km/s. Default is 0.initvshift_narrow (
floator None, optional) – Initial narrow-line velocity shift in km/s. Default is 0.initvshift_balmer_broad (
floator 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) – IfTrue, write per-patch and per-line diagnostic PNG files. Default isFalse.
- Returns:
out – Dictionary with fitted line-width and velocity-shift scalars for broad, narrow, and broad-Balmer populations, a
balmerbroadboolean flag, andcoadd_linepixmapping each line name to its pixel indices in the coadded spectrum.- Return type:
- 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 withrestwaveandnamecolumns.linesigmas (
numpy.ndarray) – Line widths in km/s for each entry inlinetable.residuals (
numpy.ndarrayor None, optional) – Residual spectrum used for S/N estimation whenget_snr=True.flux (
numpy.ndarrayor None, optional) – Observed flux array used for amplitude estimation whenget_snr=True.linevshifts (
numpy.ndarrayor None, optional) – Velocity shifts in km/s for each line; defaults to zero.patchMap (
dictor 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) – IfTrue, also compute continuum pixel indices. Default isTrue.get_snr (
bool, optional) – IfTrue, estimate the amplitude and S/N for each line. Default isFalse.
- Returns:
pix – Dictionary with keys
linepixandcontpix(each mapping line name to pixel index arrays). Ifget_snr=True, also containsclocal,cnoise,amp, andsnrper line. IfpatchMapis provided, also containspatch_contpix,dropped,merged, andmerged_from.- Return type:
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.
- table
Emission-line parameters.
- Type:
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:
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.Tableor None, optional) – Optional target sample table with columns{SURVEY, PROGRAM, HEALPIX, TARGETID}.fastphot (
bool, optional) – IfTrue, build arguments forfastphotinstead offastspec.input_redshifts (
bool, optional) – IfTrue, include input redshifts fromsample['Z'].
- Returns:
- 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 (
stror None, optional) – Coadd type:'healpix','cumulative','pernight', or'perexp'.survey (
stror array-like of str, optional) – DESI survey name(s), e.g.'main'.program (
stror 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) – IfTrue, look for.fits.gzfiles. Default isFalse.sample (
astropy.table.Tableor None, optional) – Input sample catalog; when provided, file paths are built directly fromSURVEY,PROGRAM, andHEALPIXcolumns.
- Returns:
thesefiles – Sorted array of matching file paths.
- Return type:
numpy.ndarrayof 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 (
stror None, optional) – DESI spectroscopic production name.coadd_type (
stror None, optional) – Coadd type:'healpix','cumulative','pernight', etc.survey (
stror array-like of str, optional) – DESI survey name(s).program (
stror 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.Tableor None, optional) – Input sample catalog; overrides file-system discovery.outsuffix (
stror None, optional) – Suffix for the merged output filename; defaults tospecprod.fastphot (
bool, optional) – IfTrue, mergefastphotoutput files. Default isFalse.specprod_dir (
stror None, optional) – Override the standard specprod directory path.outdir_data (
str, optional) – Root output directory. Default is'.'.split_hdu (
bool, optional) – IfTrue, write main-survey outputs as separate HDUs by HEALPix nside. Default isFalse.fastfiles_to_merge (
listor None, optional) – Explicit list of files to merge whensupermerge=True.merge_suffix (
stror None, optional) – Filename suffix for sample-based merges. Default is'sample'.mergedir (
stror None, optional) – Directory for merged output files; defaults to<outdir_data>/<specprod>/catalogs.supermerge (
bool, optional) – IfTrue, merge previously merged per-survey/program catalogs into one master file. Default isFalse.overwrite (
bool, optional) – IfTrue, overwrite existing merged output files. Default isFalse.nside_main (
intor 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 (
stror None, optional) – DESI spectroscopic production name (e.g.'iron').specprod_dir (
stror None, optional) – Override the standard specprod directory path.coadd_type (
str, optional) – Coadd type:'healpix','cumulative','pernight', or'perexp'. Default is'healpix'.survey (
stror array-like of str, optional) – DESI survey name(s).program (
stror 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.Tableor 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) – IfTrue, plan for catalog merging rather than fitting. Default isFalse.makeqa (
bool, optional) – IfTrue, plan for QA generation rather than fitting. Default isFalse.fastphot (
bool, optional) – IfTrue, usefastphotoutput filenames. Default isFalse.overwrite (
bool, optional) – IfTrue, include files that already have output. Default isFalse.
- Returns:
outdir (
str) – Root output directory.redrockfiles (
listornumpy.ndarray) – Input redrock files to process (orNone/[]when merging/QA).outfiles (
listornumpy.ndarray) – Corresponding output file paths.ntargets (
numpy.ndarrayor None) – Number of targets per file;Nonewhen 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 (
stror None, optional) – Path to the YAML file defining filter names, bands, and column mappings. Defaults to the bundled DR9 configuration.fitstack (
bool, optional) – IfTrue, load the stacked-spectra photometry configuration instead of the default DR9 one. Default isFalse.ignore_photometry (
bool, optional) – IfTrue, set all photometric bands to not be fit. Default isFalse.
- 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:
- 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 withinwave.wave (
numpy.ndarray) – Wavelength array in Angstroms.
- Returns:
pre – Tuple of
(lo, hi, resp, idenom)per filter, whereloandhiare the slice indices intowave,respis the interpolated response times wavelength, andidenomis the reciprocal of the AB-reference normalization integral.- Return type:
- 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. Useget_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 (
tupleor None, optional) – Precomputed interpolation data fromget_ab_maggies_pre(); computed on the fly ifNone.
- Returns:
maggies – Synthesized flux in maggies, one value per filter.
- Return type:
- 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.ndarrayor None, optional) – Inverse variance offlam; uniform weights assumed ifNone.redshift (
floator None, optional) – Object redshift; required whenrest=False.rest (
bool, optional) – IfTrue,waveis already in the rest frame. Default isTrue.
- Returns:
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 tonanomaggies.redshift (
float) – Galaxy or QSO redshift.dmod (
float) – Distance modulus corresponding toredshift.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.FilterSequenceor None, optional) – Observed-frame filter set. Defaults toself.filters[photsys].filters_out (
speclite.filters.FilterSequenceor None, optional) – Rest-frame output filter set. Defaults toself.filters_out.bands_to_fit (
numpy.ndarrayor None, optional) – Boolean or integer mask selecting which photometric bands are used in the fit. Defaults toself.bands_to_fit.
- Returns:
kcorr (
numpy.ndarray) – K-corrections for each bandpass inabsmag_filters.absmag (
numpy.ndarray) – Band-shifted absolute magnitudes for each bandpass inabsmag_filters.ivarabsmag (
numpy.ndarray) – Inverse variance corresponding toabsmag; 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
snrminthreshold), minimizing the K-correction. When no qualifying bandpass is available,ivarabsmagis set to zero andabsmagfalls back tosynth_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.ndarrayof str) – Photometric band names.maggies (
numpy.ndarray) – Photometric fluxes; interpreted as nanomaggies whennanomaggies=True.lambda_eff (
numpy.ndarray) – Effective wavelengths of each band in Angstroms.ivarmaggies (
numpy.ndarrayor None, optional) – Inverse variance; zeros assumed ifNone.nanomaggies (
bool, optional) – IfTrue, treatmaggiesas nanomaggies. Default isTrue.nsigma (
float, optional) – S/N threshold for computing magnitude upper limits. Default is 2.min_uncertainty (
numpy.ndarrayor None, optional) – Minimum magnitude uncertainty per band, added in quadrature toivarmaggiesbefore computingflam_ivar.get_abmag (
bool, optional) – IfTrue, also compute AB-magnitude columns needed byfastqa. Default isFalse.
- Returns:
phot – Table with columns
band,lambda_eff,nanomaggies,nanomaggies_ivar,flam, andflam_ivar. Whenget_abmag=True, also includesabmag,abmag_ivar,abmag_brighterr,abmag_fainterr, andabmag_limit.- Return type:
- 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 toredshift.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.FilterSequenceor None, optional) – Rest-frame output filter set used to synthesize absolute magnitudes. Defaults toself.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.
- 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_OBJIDwhen available; falls back to positional matching withinradius_matcharcseconds.- Parameters:
input_cat (
astropy.table.Table) – Input catalog with required columnsTARGETID,TARGET_RA, andTARGET_DEC. Optional columnsBRICKNAME,RELEASE,PHOTSYS,BRICKID, andBRICK_OBJIDimprove 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 (
stror None, optional) – Path to the Legacy Surveys Tractor catalog directory tree.dr9dir (
stror None, optional) – Deprecated alias forlegacysurveydir.radius_match (
float, optional) – Positional matching radius in arcseconds. Default is 1.0.restrict_region (
stror 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:
- fastspecfit.photometry.tractorphot_datamodel(from_file=False, datarelease='dr9')[source]
Return a zero-filled table matching the Tractor catalog data model.
- Parameters:
- Returns:
datamodel – Single-row table with the Tractor catalog column names and dtypes, all values set to zero.
- Return type:
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:
metadata (
astropy.table.Row) – Object metadata.specphot (
astropy.table.Row) – Spectrophotometric measurements.fastspec (
astropy.table.Rowor None) – Emission-line fit results;Noneforfastphotmode.phot (
fastspecfit.photometry.Photometry) – Photometry object with absolute magnitude filter definitions.fastphot (
bool) – IfTrue, photometry-only mode.fitstack (
bool) – IfTrue, stacked spectrum mode.redshift (
float) – Object redshift.line_stats (
astropy.table.Tableor None, optional) – Line kinematics returned by_compute_line_stats().snrcut (
float, optional) – Minimum line S/N for emission-line legend entries. Default is 1.5.
- Returns:
- 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:
CTools (
fastspecfit.continuum.ContinuumTools) – Continuum fitting tools with data already loaded.templates (
fastspecfit.templates.Templates) – SPS templates.specphot (
astropy.table.Row) – Spectrophotometric fit results.metadata (
astropy.table.Row) – Object metadata containing flux columns.phot (
fastspecfit.photometry.Photometry) – Photometry object with band definitions.redshift (
float) – Object redshift.phot_wavelims (tuple of float) –
(min, max)photometric wavelength range in microns.allfilters (filter object) – All photometric filters (
phot.filters[photsys]).
- Returns:
sedwave (
numpy.ndarray) – Observed-frame wavelengths (Angstroms), trimmed tophot_wavelims.sedmodel (
numpy.ndarray) – Best-fit SED flux trimmed tophot_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) – IfTrue, apply stacked-spectrum flux normalization.no_smooth_continuum (
bool) – IfTrue, 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:
- 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 abovesnrcut.- 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 awavekey.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.
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; ifNonetight_layoutis 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 withRA,DEC, andTARGETIDcolumns.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) – IfTrue, use the photometry-only layout.fitstack (
bool) – IfTrue, use the stacked-spectrum layout.wcs (
astropy.wcs.WCSor None) – WCS projection for the cutout axes;NonewhenfitstackisTrue.
- Returns:
fig (
matplotlib.figure.Figure)cutax (axis or None) – Cutout image axes;
Noneforfitstack.sedax (axis or None) – SED axes;
Noneforfitstack.specax (axis or None) – Full-spectrum axes;
Noneforfastphot.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:
- Raises:
ValueError – If
coadd_typeis 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.Rowor None, optional) – Emission-line fit results;Noneforfastphotmode.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) – IfTrue, generate photometry-only QA. Default isFalse.fitstack (
bool, optional) – IfTrue, process a stacked spectrum. Default isFalse.inputz (
bool, optional) – IfTrue, use the input redshift. Default isFalse.no_smooth_continuum (
bool, optional) – IfTrue, do not smooth the continuum model. Default isFalse.outdir (
stror None, optional) – Output directory for the PNG figure.outprefix (
stror None, optional) – Optional filename prefix.
- fastspecfit.qa.fastqa(args=None, comm=None)[source]
Entry point for the
fastqaCLI: read fitting results and generate QA figures.- Parameters:
args (
listor None, optional) – Command-line argument list; parsed fromsys.argvwhenNone.comm (MPI communicator or None, optional) – MPI communicator for parallel execution.
- 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.Rowor None, optional) – Emission-line and continuum fit results;Noneforfastphotmode.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) – IfTrue, generate photometry-only QA. Default isFalse.fitstack (
bool, optional) – IfTrue, this is a stacked spectrum. Default isFalse.outprefix (
stror None, optional) – Optional prefix for the output filename.no_smooth_continuum (
bool, optional) – IfTrue, do not smooth the continuum model. Default isFalse.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 (
stror None, optional) – Output directory; defaults to the current directory.inputz (
boolor None, optional) – IfTrue, 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 (
stror None, optional) – Path to the emission-line parameter file; uses the bundled default whenNone.constraints_file (
stror None, optional) – Path to the emission-line kinematic constraint YAML file; uses the bundled default whenNone. A consistency check againstemlines_fileis run at startup.fphotofile (
stror None, optional) – Path to the photometric configuration YAML file; uses the bundled DR9 default whenNone.fastphot (
bool, optional) – IfTrue, load templates in photometry-only mode. Default isFalse.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) – IfTrue, use the stacked-spectra photometry configuration. Default isFalse.ignore_photometry (
bool, optional) – IfTrue, disable photometric fitting. Default isFalse.template_file (
stror None, optional) – Full path to the SPS template FITS file; auto-detected whenNone.template_version (
stror None, optional) – Template version string; used whentemplate_fileisNone.template_imf (
stror None, optional) – Initial mass function name for template selection.log_verbose (
bool, optional) – IfTrue, set the logger level toDEBUG. Default isFalse.
- 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.initializewould be pickled together with the parent’s fully initializedsc_dataobject and then called on that pickled copy in the worker, leaving the worker’s own module-levelsc_datauninitialized.
- fastspecfit.singlecopy._initialize_sc_data_worker(**kwargs)[source]
Pool initializer for MPI production workers.
Like
_initialize_sc_data()but suppresses INFO logging in workers unlesslog_verbose=Truewas 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. Interactivefastspec/fastphotruns 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_VDISPkm/s.- Parameters:
template_file (
stror None, optional) – Full path to the SPS template FITS file. Auto-detected fromFTEMPLATES_DIRwhenNone.template_version (
stror None, optional) – Template version string used to build the filename whentemplate_fileisNone. Defaults toDEFAULT_TEMPLATEVERSION.imf (
stror None, optional) – Initial mass function used to build the filename whentemplate_fileisNone. Defaults toDEFAULT_IMF.mintemplatewave (
floator None, optional) – Minimum wavelength to load into memory (Angstroms). Uses the minimum available wavelength whenNone.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 isVDISP_NOMINAL.vdisp_bounds (tuple of float, optional) –
(min, max)velocity dispersion bounds in km/s. Default isVDISP_BOUNDS.fastphot (
bool, optional) – IfTrue, load in photometry-only mode. Default isFalse.read_linefluxes (
bool, optional) – IfTrue, also read the model emission-line flux arrays. Default isFalse.
- 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 (
tupleor None) – Preprocessing structure fromconvolve_vdisp_pre(), orNone.rows (array-like of int) – Indices of the templates to keep.
- Returns:
conv_pre_subset – Preprocessing data restricted to the selected rows, or
Noneifconv_preisNone.- Return type:
tupleor None
- convolve_vdisp(templateflux, vdisp)[source]
Convolve one or more template spectra with a velocity dispersion.
Only the wavelength range defined by
PIXKMS_BOUNDSis 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:
- 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 outsidePIXKMS_BOUNDS.ft_flux_mid (
numpy.ndarrayof complex) – FFT of the central wavelength range.flux_len (
int) – Total length of the output flux array.fft_len (
int) – Padded FFT length used forft_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)whereflux_lohicontains the raw fluxes outsidePIXKMS_BOUNDS,ft_flux_midis the FFT of the central wavelength range, andfft_lenis the padded FFT length.- Return type:
- static get_templates_filename(template_version, imf)[source]
Build the SPS template filename from
FTEMPLATES_DIR, version, and IMF.
- 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:
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
.valueto 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:
- class fastspecfit.util.ZWarningMask[source]
Redrock
ZWARNbitmask 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 ofY(ntemplates × npix).- Parameters:
x (
numpy.ndarray, shape (npix,))Y (
numpy.ndarray, shape (ntemplates, npix))edges (precomputed bin edges and inverse widths from
trapz_rebin_pre())ibw (precomputed bin edges and inverse widths from
trapz_rebin_pre())out (
numpy.ndarray, shape (ntemplates, nbins))
- 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:
- fastspecfit.util.find_minima(x)[source]
Return indices of local minima of
x, including edges.Indices are sorted in ascending order of
xvalue. 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
xvalue (smallest first).- Return type:
numpy.ndarrayof 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 (
stror 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:
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) – Minimumivarvalue treated as valid. Default is 1e-8.sigma (
bool, optional) – IfTrue, return the square root (i.e. standard deviation). Default isFalse.allmasked_ok (
bool, optional) – IfTrue, return zeros rather than raising when all pixels are masked. Default isFalse.
- Returns:
var (
numpy.ndarray) – Variance (or sigma) array; zero whereivar <= clip.goodmask (
numpy.ndarrayof bool) –Truewhereivar > 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) – IfTrue, also return the raw polynomial coefficients(a, b, c). Default isFalse.
- 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_MINFITon failure.coeff (
tuple, optional) – Raw(a, b, c)polynomial coefficients; only present whenreturn_coeff=True.
- fastspecfit.util.mwdust_transmission(ebv, filtername)[source]
Convert SFD E(B-V) to Milky Way dust transmission in a given bandpass.
- Parameters:
- Returns:
transmission – Milky Way dust transmission (0–1), same shape as
ebv.- Return type:
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().
- fastspecfit.util.quantile(A, q)
Compute quantile(s)
qof arrayA(Numba-accelerated).
- fastspecfit.util.radec2pix(nside, ra, dec)[source]
Convert RA/Dec to HEALPix nested pixel numbers.
- Parameters:
- Returns:
pix – HEALPix pixel numbers in the nested scheme.
- Return type:
numpy.ndarrayof 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
yoverx(Numba-accelerated).
- fastspecfit.util.trapz_rebin(src_x, src_y, bin_centers, out=None, pre=None)[source]
Resample
src_yinto bins centered atbin_centers(area-conserving).- Parameters:
src_x (
numpy.ndarray) – x coordinates of the input signal.src_y (
numpy.ndarray) – Input signal sampled atsrc_x.bin_centers (
numpy.ndarray) – Center x coordinates of the output bins.out (
numpy.ndarrayor None, optional) – Pre-allocated output array; allocated ifNone.pre (
tupleor None, optional) – Preprocessing data fromtrapz_rebin_pre(); computed frombin_centerswhenNone.
- Returns:
out – Resampled signal at the center of each output bin.
- Return type:
- 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)whereedgesare the bin edges andibwis the array of inverse bin widths. Pass as thepreargument totrapz_rebin()to avoid recomputation.- Return type: