API

fastspecfit

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

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