WavelengthSolution1D#

class specreduce.wavesol1d.WavelengthSolution1D(p2w: None | CompoundModel, bounds_pix: tuple[int, int], unit: Unit, wave_air: bool = False)[source]#

Bases: object

Class defining a one-dimensional wavelength solution.

This class manages the mapping between pixel positions and wavelength values in a 1D spectrum, supporting both forward and reverse transformations. It provides methods for resampling spectra in the pixel-to-wavelength space while conserving flux, and integrates with GWCS for coordinate transformations.

Initializes an object with pixel-to-wavelength transformation, pixel bounds, and measurement unit. Also, converts the unit to its LaTeX string representation.

Parameters:
p2w

The pixel-to-wavelength transformation model. If None, no transformation will be set.

bounds_pix

The lower and upper pixel bounds defining the range of the spectrum.

unit

The wavelength unit.

wave_air

Whether the solution maps pixels to air rather than vacuum wavelengths; by default False, meaning vacuum wavelengths.

Attributes Summary

gwcs

GWCS object defining the mapping between pixel and spectral coordinate frames.

p2w

Pixel-to-wavelength transformation.

p2w_dldx

Partial derivative of the pixel-to-wavelength transformation, (d lambda) / (d pix).

w2p

Wavelength-to-pixel transformation.

Methods Summary

attach_wcs(spectrum[, wave_air, max_residual])

Attach the fitted FITS WCS to a copy of a pixel-space spectrum.

from_asdf(path)

Create a wavelength solution from an ASDF file written by to_asdf().

pix_to_wav(pix)

Map pixel values into wavelength values.

resample(spectrum[, nbins, wlbounds, bin_edges])

Bin the given pixel-space 1D spectrum to a wavelength space conserving the flux.

to_asdf(path, **kwargs)

Serialize the wavelength solution into an ASDF file.

wav_to_pix(wav)

Map wavelength values into pixel values.

wcs([wave_air, max_residual])

Fit and return a FITS WCS approximating the wavelength solution.

Attributes Documentation

gwcs[source]#

GWCS object defining the mapping between pixel and spectral coordinate frames.

p2w#

Pixel-to-wavelength transformation.

p2w_dldx[source]#

Partial derivative of the pixel-to-wavelength transformation, (d lambda) / (d pix).

w2p[source]#

Wavelength-to-pixel transformation.

Methods Documentation

attach_wcs(spectrum: Spectrum, wave_air: bool | None = None, max_residual: float = 1.0) → Spectrum[source]#

Attach the fitted FITS WCS to a copy of a pixel-space spectrum.

Returns a new Spectrum holding the flux, uncertainty, mask, and metadata of the given spectrum with the FITS WCS returned by wcs() as its world coordinate system. The samples are left where they are and only their spectral coordinates change, so the result can be written with the specutils ‘wcs1d-fits’ format, which stores the flux as an image and the wavelength solution as WCS header keywords. Use resample() instead to rebin the flux onto a wavelength grid.

The fitted WCS is cached per air/vacuum axis type and reused, so applying one solution to many spectra runs the grism fit only once. The cache is cleared whenever the pixel-to-wavelength transformation changes.

Parameters:
spectrum

A pixel-space spectrum sampled on the pixel grid the solution was fitted on.

wave_air

Whether the spectral axis represents air rather than vacuum wavelengths. If None, the value given in the initialization is used.

max_residual

Maximum allowed absolute deviation between the fitted dispersion function and the exact solution in pixels. A fit exceeding this limit emits an AstropyUserWarning.

Returns:
A spectrum with the same flux as the input and a FITS WCS spectral axis.
Raises:
ValueError

If the spectrum is not one-dimensional, or if its length does not match the pixel range the solution was fitted over.

Notes

The spectrum is assumed to be sampled one flux value per pixel over the solution’s pixel bounds, which is what the calibration produces: the WCS maps array index i to the solution’s pixel i, and a length mismatch means the spectrum does not share the pixel grid the solution was derived on.

Because wcslib normalizes spectral axes to SI units, the spectral axis of the returned spectrum is in metres regardless of the solution unit.

classmethod from_asdf(path: str | Path) → WavelengthSolution1D[source]#

Create a wavelength solution from an ASDF file written by to_asdf().

Parameters:
path

File to read from, given either as a path or as a readable file object.

Returns:
The wavelength solution stored in the file.
Raises:
ValueError

If the file holds no wavelength solution written by to_asdf(), if the stored GWCS carries no bounding box giving the pixel bounds, or if its transformation is not a shift followed by a polynomial.

pix_to_wav(pix: float | ArrayLike) → float | NDArray | MaskedArray[source]#

Map pixel values into wavelength values.

Parameters:
pix

The pixel value(s) to be transformed into wavelength value(s).

Returns:
Transformed wavelength value(s) corresponding to the input pixel value(s).
resample(spectrum: Spectrum, nbins: int | None = None, wlbounds: tuple[float, float] | None = None, bin_edges: ArrayLike | None = None) → Spectrum[source]#

Bin the given pixel-space 1D spectrum to a wavelength space conserving the flux.

This method bins a pixel-space spectrum to a wavelength space using the computed pixel-to-wavelength and wavelength-to-pixel transformations and their derivatives with respect to the spectral axis. The binning is exact and conserves the integrated flux.

Parameters:
spectrum

A Spectrum instance containing the flux to be resampled over the wavelength space.

nbins

The number of bins for resampling. If not provided, it defaults to the size of the input spectrum.

wlbounds

A tuple specifying the starting and ending wavelengths for resampling. If not provided, the wavelength bounds are inferred from the object’s methods and the entire flux array is used.

bin_edges

Explicit bin edges in the wavelength space. Should be an 1D array-like [e_0, e_1, …, e_n] with n = nbins + 1. The bins are created as [[e_0, e_1], [e_1, e_2], …, [e_n-1, n]]. If provided, nbins and wlbounds are ignored.

Returns:
1D spectrum binned to the specified wavelength bins.
to_asdf(path: str | Path, **kwargs) → None[source]#

Serialize the wavelength solution into an ASDF file.

Stores the pixel-to-wavelength transformation as a GWCS object under the ‘wavelength_solution’ key of the ASDF tree. The transformation is written as an analytic model rather than as a tabulated array, so the solution read back is identical to the one written, and the file can be opened by any ASDF-aware tool without specreduce.

Only the coordinate transformation is stored: the line lists, matched-line tables, and fit diagnostics held by the calibration that produced the solution are not included.

Parameters:
path

File to write to, given either as a path or as a writable file object.

**kwargs

Additional keyword arguments passed to asdf.AsdfFile.write_to.

Raises:
ValueError

If the wavelength solution is not set.

Notes

The pixel bounds travel as the bounding box of the exported GWCS, which is the idiomatic way to declare the domain over which a GWCS is valid. The bounding box is set on the exported object only: the gwcs property is deliberately left unbounded, because a bounded GWCS returns NaN outside its box instead of extrapolating.

The air-wavelength flag is stored as a separate ‘wave_air’ entry because it states what the wavelengths mean rather than how they are computed, and neither GWCS spectral frames nor their physical types can express it.

wav_to_pix(wav: float | ArrayLike) → float | NDArray | MaskedArray[source]#

Map wavelength values into pixel values.

Parameters:
wav

The wavelength value(s) to be converted into pixel value(s).

Returns:
The corresponding pixel value(s) for the input wavelength(s).
wcs(wave_air: bool | None = None, max_residual: float = 1.0) → WCS[source]#

Fit and return a FITS WCS approximating the wavelength solution.

Fits the FITS WCS Paper III grism dispersion function (Greisen et al. 2006, A&A 446, 747, Sect. 5.1) to the exact pixel-to-wavelength model and returns the result as a standard WCS object that can be serialized into a FITS header and evaluated by any FITS-compliant reader. The spectral axis type is ‘AWAV-GRA’ for air wavelengths or ‘WAVE-GRI’ for vacuum wavelengths.

Note on the naming: despite appearances, neither algorithm code refers to a grating versus a grism. Both ‘GRA’ and ‘GRI’ denote the same Paper III grism dispersion algorithm, and the trailing letter only identifies the medium the wavelengths are measured in: ‘GRA’ is the grism dispersion relation for air wavelengths and ‘GRI’ the one for vacuum wavelengths. The algorithm code is therefore always paired with the matching coordinate type: ‘AWAV’ (air wavelength) with ‘GRA’, and ‘WAVE’ (vacuum wavelength) with ‘GRI’.

The fit is cached per air/vacuum axis type and invalidated whenever the pixel-to-wavelength transformation changes. Each call returns an independent copy of the cached WCS, so the caller is free to modify the result.

Parameters:
wave_air

Whether the spectral axis represents air rather than vacuum wavelengths, selecting between the ‘AWAV-GRA’ and ‘WAVE-GRI’ axis types. If None, the value given in the initialization is used. The flag only declares what the solution’s wavelengths mean: no air-vacuum conversion is applied to the wavelength values, so overriding it relabels the axis without changing the numbers.

max_residual

Maximum allowed absolute deviation between the fitted dispersion function and the exact solution in pixels. A fit exceeding this limit emits an AstropyUserWarning.

Returns:
A 1D WCS using the Paper III grism dispersion function.
Raises:
ValueError

If the wavelength solution is not set, its unit is not a length unit, or it produces non-finite values within the pixel bounds.

TypeError

If the wavelength solution does not use a power-series Polynomial1D model.

RuntimeError

If the grism dispersion function cannot be evaluated anywhere along the spectral axis, meaning the solution is outside the parameter space reachable by the dispersion model.

Notes

The reference pixel keywords are exact statements about the wavelength solution rather than fit parameters: CRPIX is the solution’s reference pixel, and CRVAL and CDELT are the value and derivative of the solution polynomial at that pixel. Only four grism terms (the grating ruling density PV1_0, the incidence angle PV1_2, the refractive index derivative PV1_4, and the camera angle PV1_6; see Greisen et al. 2006, Table 6) are fitted, so all approximation error lives in the PV terms, and the residual is zero in both value and slope at the reference pixel and grows towards the chip edges.

The grism dispersion function cannot represent an arbitrary polynomial exactly, so the returned WCS is a numerical approximation of the wavelength solution and the fitted PV values are effective rather than physical. The remaining Table 6 parameters are fixed at values that make them redundant with the fitted ones: the interference order PV1_1 and the grating tilt PV1_5 enter the grism equation only through the combination G*m/cos(eps), so they are absorbed by the fitted ruling density, and the prism refractive index PV1_3 is fixed at 1 (the paper’s plain grating case) because it enters only through the product n_r*sin(alpha) and is absorbed by the fitted incidence angle; PV1_4 acts as a curvature absorber rather than a measure of glass dispersion. No spectrograph physics should be read from the fitted PV values. If the fit fails to reach max_residual, the solution is far from any grism dispersion curve, and the lossless gwcs property should be used instead.

Vacuum solutions use ‘WAVE-GRI’ (the grism-in-vacuum form of the algorithm, Sect. 5.1.2 of the paper) rather than ‘WAVE-GRA’ because the ‘GRA’ form (Sect. 5.1.4) is native to air wavelengths: pairing it with a vacuum axis would route every evaluation through wcslib’s air-refraction model, which is not valid below ~200 nm.

Note also that wcslib normalizes spectral axes to SI units, so evaluating the returned WCS yields wavelengths in metres regardless of the CUNIT, and serializing it with to_header() likewise writes CRVAL and CDELT in metres with CUNIT ‘m’.