Spectrum¶
Spectrum¶
The Spectrum class — a single observed spectrum.
- class unite.spectrum.spectrum.Spectrum(low, high, flux, error, disperser, *, name='')[source]¶
Bases:
objectA single observed spectrum.
A spectrum is defined by pixel bin edges (low, high), flux and error arrays, and a
Disperser. Calibration parameters live on the disperser asCalibParamtokens (disperser.r_scale,disperser.flux_scale,disperser.pix_offset).Use
from_arrays(),from_DJA(), orfrom_sdss_fits()to construct spectra from arrays or instrument-native file formats.- Parameters:
- lowastropy.units.Quantity
Lower wavelength edges of each pixel. Must be 1-D with wavelength (length) dimensions.
- highastropy.units.Quantity
Upper wavelength edges of each pixel. Same shape and compatible units as low.
- fluxastropy.units.Quantity
Flux density values per pixel. Must be 1-D with the same length as low and carry spectral flux density per wavelength units (f_lambda, e.g.
erg / s / cm^2 / Angstrom).- errorastropy.units.Quantity
Flux density uncertainty per pixel. Must be 1-D with the same length as low and carry units compatible with flux.
- disperserDisperser
Instrumental disperser associated with this spectrum. Carries any calibration tokens (
r_scale,flux_scale,pix_offset).- namestr, optional
Human-readable label (e.g.
'G235H'). Used in repr and for constructing numpyro site names. Defaults todisperser.name.
- Raises:
- TypeError
If low / high are not Quantities with wavelength dimensions, if flux / error are not Quantities with f_lambda dimensions, or if disperser is not a
Disperserinstance.- ValueError
If array shapes are inconsistent or low ≥ high for any pixel.
- Parameters:
- property error_scale: Array | float¶
Multiplicative scale factor applied to errors.
Can be a scalar (applied uniformly) or a per-pixel array.
- property scaled_error: Array¶
Flux uncertainty scaled by
error_scale.
- property scale_diagnostic¶
Continuum-fit diagnostics from the most recent
compute_scales()call.Returns a
SpectrumScaleDiagnosticholding the line mask, the fitted continuum model array, and per-region fit details.Noneifcompute_scales()has not been called yet.The spectrum’s own
wavelength,flux,error, and unit attributes provide the full picture alongside this diagnostic.Examples
>>> diag = spectrum.scale_diagnostic >>> if diag is not None: ... cont = diag.continuum_model # NaN outside fitted regions ... mask = diag.line_mask # True where a pixel was excluded
Spectra Collection¶
Spectrum collection and scale diagnostics.
- class unite.spectrum.collection.RegionDiagnostic(obs_low, obs_high, in_region, good_mask, model_on_region, chi2_red, fit_params=<factory>)[source]¶
Bases:
objectDiagnostics for a single continuum region fit.
- Attributes:
- obs_lowfloat
Observed-frame lower bound of the region (disperser’s unit).
- obs_highfloat
Observed-frame upper bound of the region (disperser’s unit).
- in_regionjnp.ndarray
Boolean mask of shape
(npix,)selecting all pixels inside the region bounds.- good_maskjnp.ndarray
Boolean mask of shape
(npix,)selecting pixels used for fitting (in_region & ~line_mask).- model_on_regionjnp.ndarray or None
Best-fit continuum model evaluated at the
in_regionpixels.Noneif the fit failed (too few unmasked pixels).- chi2_redfloat or None
Reduced chi-squared of the fit, or
Noneif the fit failed.- fit_paramsdict of str to float
Best-fit parameter dict returned by
fit_continuum_form(). Empty if the fit failed.
- Parameters:
- class unite.spectrum.collection.ScaleDiagnosticList(iterable=(), /)[source]¶
Bases:
listA list of
SpectrumScaleDiagnosticobjects that also supports lookup by spectrum name.Inherits all standard
listbehaviour. Additionally,diags["my_spectrum"]returns the first diagnostic whosenamematches the given string, raisingKeyErrorif no match is found.
- class unite.spectrum.collection.SpectrumScaleDiagnostic(name, line_mask, continuum_model, regions)[source]¶
Bases:
objectDiagnostics for one spectrum produced by
Spectra.compute_scales().Stored directly on the spectrum via
scale_diagnosticso callers always have the spectrum’s ownwavelength,flux, anderrorto hand — those fields are not duplicated here.- Attributes:
- namestr
Spectrum name (from
name).- line_maskjnp.ndarray
Boolean mask of shape
(npix,);Truewhere a pixel was excluded because it lies near an emission line.- continuum_modeljnp.ndarray
Full-spectrum continuum model array of shape
(npix,). Pixels not covered by any continuum region areNaN.- regionslist of RegionDiagnostic
Per-region fit diagnostics (one entry per region that overlaps this spectrum).
- Parameters:
- class unite.spectrum.collection.Spectra(spectra, redshift=0.0, canonical_unit=None)[source]¶
Bases:
objectCollection of spectra with coverage filtering.
Wraps one or more
Spectrumobjects together with a systemic redshift estimate. The main role of this class isfilter_config(), which drops lines and continuum regions not covered by any spectrum.- Parameters:
- spectrasequence of Spectrum
Individual spectrum objects. Must not be empty.
- redshiftfloat
Systemic redshift estimate used for rest-frame → observed-frame conversion during coverage checks. Default
0.0.- canonical_unitastropy.units.UnitBase, optional
Wavelength unit used for all internal model computations (line centers, continuum bounds, pixel edges). Defaults to the first spectrum’s disperser unit. Override this if you want a specific unit regardless of spectrum order.
- Raises:
- ValueError
If spectra is empty or contains non-Spectrum objects.
- Parameters:
- property canonical_unit: UnitBase¶
Canonical wavelength unit used for all internal model computations.
Defaults to the first spectrum’s wavelength unit. Can be overridden via the canonical_unit constructor parameter.
- property scale_diagnostics: ScaleDiagnosticList | None¶
Per-spectrum diagnostics from the most recent
compute_scales()call.Returns a
ScaleDiagnosticListofSpectrumScaleDiagnosticobjects (one per spectrum). Supports both integer indexing and lookup by spectrum name (e.g.diags["my_spectrum"]).Noneifcompute_scales()has not been called yet.The diagnostic for an individual spectrum is also available via
scale_diagnostic, which is the preferred access pattern when iterating over spectra:for s in spectra: diag = s.scale_diagnostic # s.wavelength / s.flux / s.error available directly
- compute_scales(line_config, continuum_config=None, *, line_mask_width=<Quantity 1000. km / s>, box_width=<Quantity 1000. km / s>, error_scale=False)[source]¶
Estimate characteristic flux scales for lines and continuum.
The algorithm:
Mask pixels near emission lines (using line_mask_fwhm, a full FWHM convolved in quadrature with the local LSF).
Fit a low-order polynomial to the unmasked pixels in each continuum region.
Estimate the line scale as
peak_above_continuum * line_widthwhere the peak is measured relative to the fitted continuum.Estimate the continuum scale as the maximum median
|flux|across continuum regions (after masking lines).Optionally compute per-region error scale factors (
sqrt(chi2_red)) and store them as per-pixel arrays on eachSpectrum.
Both flux scales are stored as
Quantityobjects: integrated flux forline_scaleand flux density forcontinuum_scale.- Parameters:
- line_configLineConfiguration
Line configuration.
- continuum_configContinuumConfiguration, optional
Continuum configuration. If
None, only line scale is computed (without continuum subtraction).- max_fwhmastropy.units.Quantity
Maximum expected intrinsic line FWHM (full width). Must have velocity units. Default
1000 km/s.- line_mask_fwhmastropy.units.Quantity
Full FWHM used for masking lines when fitting continuum. Must have velocity units. Default
1000 km/s.- error_scalebool
If
True, compute per-region error scale factors from the reduced chi-squared of the continuum fit residuals and store them as per-pixel arrays on each spectrum viaerror_scale. DefaultFalse.- :rtype: :sphinx_autodoc_typehints_type:`:py:obj:`None``
- Parameters:
line_config (LineConfiguration)
continuum_config (ContinuumConfiguration | None)
line_mask_width (Quantity)
box_width (Quantity)
error_scale (bool)
- Return type:
None
- prepare(line_config, continuum_config=None, *, linedet_width=<Quantity 1000. km / s>, drop_empty_regions=True)[source]¶
Filter configs for coverage and optionally drop empty continuum regions.
Calls
filter_config()to remove lines and continuum regions not covered by any spectrum, then optionally drops continuum regions that contain no emission lines. Stores the filtered configs on this object.- Return type:
- Parameters:
- line_configLineConfiguration
Line configuration.
- continuum_configContinuumConfiguration, optional
Continuum configuration.
- linedet_widthastropy.units.Quantity
Detection width. Must have velocity units. Default
1000 km/s.- drop_empty_regionsbool
If
True(default), drop continuum regions that do not contain any filtered line (in rest frame).
- Returns:
- filtered_linesLineConfiguration
- filtered_continuumContinuumConfiguration or None
- Parameters:
line_config (LineConfiguration)
continuum_config (ContinuumConfiguration | None)
linedet_width (Quantity)
drop_empty_regions (bool)
- property prepared_line_config: LineConfiguration | None¶
Filtered line configuration from
prepare(), orNone.
- property prepared_cont_config: ContinuumConfiguration | None¶
Filtered continuum configuration from
prepare(), orNone.
- filter_config(line_config, continuum_config=None, *, linedet_width=<Quantity 1000. km / s>)[source]¶
Drop lines and continuum regions not covered by any spectrum.
Each line’s rest-frame wavelength is shifted to the observed frame using
redshift, then padded by linedet_width to form a detection window. A line is kept if any spectrum partially overlaps that window. Continuum regions are checked the same way.- Return type:
- Parameters:
- line_configLineConfiguration
Line configuration to filter.
- continuum_configContinuumConfiguration, optional
Continuum configuration to filter.
Noneis passed through.- linedet_widthastropy.units.Quantity
Detection width. Must have velocity units. Default
1000 km/s.
- Returns:
- filtered_linesLineConfiguration
- filtered_continuumContinuumConfiguration or None
- Parameters:
line_config (LineConfiguration)
continuum_config (ContinuumConfiguration | None)
linedet_width (Quantity)
Loaders¶
Spectrum loader functions.
Convenience functions for constructing Spectrum
objects from pre-loaded arrays or instrument-native file formats.
All loaders are re-exported from unite.spectrum:
from unite.spectrum import from_arrays, from_DJA, from_sdss_fits
- unite.spectrum.loaders.from_arrays(low, high, flux, error, disperser, *, name='')[source]¶
Construct a
Spectrumfrom pre-loaded arrays.- Return type:
- Parameters:
- lowastropy.units.Quantity
Lower wavelength edges of each pixel. Must be 1-D with wavelength (length) dimensions.
- highastropy.units.Quantity
Upper wavelength edges of each pixel. Same shape and compatible units as low.
- fluxastropy.units.Quantity
Flux density values per pixel (f_lambda). Must be 1-D with the same length as low.
- errorastropy.units.Quantity
Flux density uncertainty per pixel. Must be 1-D with the same length as low and compatible units as flux.
- disperserDisperser
The disperser associated with this spectrum. Carries any calibration tokens (
r_scale,flux_scale,pix_offset).- namestr, optional
Human-readable label. Defaults to
disperser.name.
- Returns:
- Spectrum
- Parameters:
- unite.spectrum.loaders.from_DJA(path, disperser, *, name='', cache=False)[source]¶
Construct a
Spectrumfrom a DJA FITS file.Reads a NIRSpec x1d spectrum from the Dawn JWST Archive (DJA) format. Any
Disperseris accepted; a built-in NIRSpec disperser or aGenericDisperserare both valid.- Return type:
- Parameters:
- pathstr or Path
Local path or URL to a NIRSpec x1d FITS file.
- disperserDisperser
The disperser associated with this spectrum.
- namestr, optional
Human-readable label. Defaults to
disperser.name.- cachebool, optional
Whether to use astropy’s caching when fetching a remote file. Defaults to
False.
- Returns:
- Spectrum
- Raises:
- FileNotFoundError
If path does not exist.
- KeyError
If the expected FITS extensions or columns are not found.
- Parameters:
- unite.spectrum.loaders.from_sdss_fits(path, disperser, *, name='', cache=False)[source]¶
Construct a
Spectrumfrom an SDSS FITS file.Reads a standard SDSS
spec-*.fitsfile (DR7-DR17 format). The coadded spectrum is read from theCOADDHDU. The disperser’s internal wavelength and resolving-power grids are updated from theloglamandwdispcolumns in the file.- Return type:
- Parameters:
- pathstr or Path
Path to an SDSS spec FITS file.
- disperserSDSSDisperser
The SDSS disperser for this spectrum. Its internal wavelength grid and R(λ) curve will be updated from the FITS data. Must be an
SDSSDisperserinstance.- namestr, optional
Human-readable label. Defaults to
disperser.name.- cachebool, optional
Whether to use astropy’s caching when reading the file. Defaults to
False.
- Returns:
- Spectrum
- Raises:
- TypeError
If disperser is not an
SDSSDisperser.- FileNotFoundError
If path does not exist.
- KeyError
If the expected columns are not found.
- Parameters:
disperser (SDSSDisperser)
name (str)
cache (bool)