Skip to content

torchsky.spectral

Stability: core. Names on this page follow the deprecation policy in contributing.

Spectral and data cube support for torchsky.

Guides: spectral-axes


This reference is generated from the package source. Names are grouped by the module that defines them; import every name from the public namespace torchsky.spectral unless the group text says otherwise.

Top-level namespace

Spectral and data cube support for torchsky.

Implements 1D spectra with inverse variance/mask arrays and 3D data cubes for IFU instruments and radio astronomy.

Note: This is a core torchsky module. FITS file I/O is owned by torchfits; spectra and cubes here operate on in-memory tensors and header mappings.

DataCube dataclass

DataCube(
    data: Tensor,
    spectral_axis: SpectralAxis,
    spatial_wcs: Optional[WCS] = None,
    ivar: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
    header: Optional[Dict[str, Any]] = None,
    spectral_axis_index: int = 0,
)

3D data cube for IFU instruments and radio astronomy.

data instance-attribute

data: Tensor

header class-attribute instance-attribute

header: Optional[Dict[str, Any]] = None

ivar class-attribute instance-attribute

ivar: Optional[Tensor] = None

mask class-attribute instance-attribute

mask: Optional[Tensor] = None

n_spectral property

n_spectral: int

Number of spectral channels.

shape property

shape: Tuple[int, ...]

Get cube shape.

spatial_shape property

spatial_shape: Tuple[int, int]

Get spatial dimensions (y, x).

spatial_wcs class-attribute instance-attribute

spatial_wcs: Optional[WCS] = None

spectral_axis instance-attribute

spectral_axis: SpectralAxis

spectral_axis_index class-attribute instance-attribute

spectral_axis_index: int = 0

__post_init__

__post_init__()

Validate cube data.

collapse_spectral

collapse_spectral(
    method: str = "mean",
    wavelength_range: Optional[Tuple[float, float]] = None,
) -> Tensor

Collapse cube along spectral axis.

extract_slice

extract_slice(
    wavelength: float, width: Optional[float] = None
) -> Tensor

Extract 2D slice at specific wavelength.

extract_spectrum

extract_spectrum(y: int, x: int) -> 'Spectrum1D'

Extract 1D spectrum at spatial position (y, x).

to

to(device: device) -> 'DataCube'

Move cube to device.

SpectralAxis dataclass

SpectralAxis(
    values: Tensor,
    unit: str,
    type: str,
    rest_frequency: Optional[float] = None,
    redshift: Optional[float] = None,
    bin_edges: Optional[Tensor] = None,
)

Represent sampled wavelength, frequency, energy, or velocity coordinates.

Parameters:

Name Type Description Default
values Tensor

One-dimensional coordinate samples.

required
unit str

Physical unit label such as "Angstrom" or "Hz".

required
type str

FITS-style spectral coordinate type.

required
rest_frequency Optional[float]

Optional rest frequency required by velocity conversions.

None
redshift Optional[float]

Optional reference redshift.

None
bin_edges Optional[Tensor]

Optional coordinate-bin edges with one more element than values.

None

Examples:

>>> import torch
>>> from torchsky.spectral import SpectralAxis
>>> SpectralAxis(torch.tensor([5000.0]), "Angstrom", "WAVE").quantity
'wavelength'

bin_edges class-attribute instance-attribute

bin_edges: Optional[Tensor] = None

direction property

direction: int

Return 1 for ascending and -1 for descending coordinates.

quantity property

quantity: str

Return a normalized physical quantity name.

redshift class-attribute instance-attribute

redshift: Optional[float] = None

rest_frequency class-attribute instance-attribute

rest_frequency: Optional[float] = None

type instance-attribute

type: str

unit instance-attribute

unit: str

values instance-attribute

values: Tensor

_validated_values

_validated_values() -> Tensor

channel_widths

channel_widths() -> Tensor

Return positive channel widths in the declared axis unit.

edges

edges() -> Tensor

Return explicit or midpoint-derived channel edges in axis units.

is_regular

is_regular(
    *, rtol: float = 1e-06, atol: float = 0.0
) -> bool

Return whether adjacent coordinate steps are equal within tolerance.

quadrature_weights

quadrature_weights() -> Tensor

Return positive trapezoid weights for samples on this axis.

select_interval

select_interval(
    lower: float, upper: float
) -> tuple["SpectralAxis", Tensor]

Select a closed physical interval and return the axis plus source mask.

to

to(
    *,
    device: device | str | None = None,
    dtype: dtype | None = None,
) -> "SpectralAxis"

Transfer coordinate tensors without changing physical metadata.

to_energy

to_energy(unit: str = 'eV') -> Tensor

Convert to photon energy in joules or electron-volt units.

to_frequency

to_frequency() -> Tensor

Convert to frequency in Hz via FITS spectral conventions.

to_wavelength

to_wavelength() -> Tensor

Convert to vacuum wavelength in Angstroms.

Air wavelengths (AWAV) are refracted to vacuum first. Length axes use FITS unit scales; other types go through frequency.

to_wavenumber

to_wavenumber(unit: str = '1/m') -> Tensor

Convert to reciprocal wavelength (cycles per metre or centimetre).

SpectralReader

Reader for spectral data from FITS files.

read_data_cube staticmethod

read_data_cube(filepath: str, hdu: int = 0) -> 'DataCube'

Read 3D data cube from FITS image.

read_spectrum_1d staticmethod

read_spectrum_1d(
    filepath: str,
    hdu: int = 0,
    flux_col: str = "FLUX",
    wave_col: str = "WAVELENGTH",
    ivar_col: Optional[str] = "IVAR",
    mask_col: Optional[str] = "MASK",
) -> "Spectrum1D"

Read 1D spectrum from FITS table.

SpectralRebinResult dataclass

SpectralRebinResult(
    flux: Tensor,
    spectral_edges: Tensor,
    ivar: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
)

Flux-density samples and validity metadata on a spectral edge grid.

flux instance-attribute

flux: Tensor

ivar class-attribute instance-attribute

ivar: Optional[Tensor] = None

mask class-attribute instance-attribute

mask: Optional[Tensor] = None

spectral_edges instance-attribute

spectral_edges: Tensor

Spectrum1D dataclass

Spectrum1D(
    flux: Tensor,
    spectral_axis: SpectralAxis,
    ivar: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
    header: Optional[Dict[str, Any]] = None,
)

1D spectrum with optional inverse variance and mask arrays.

error property

error: Optional[Tensor]

Get error from inverse variance.

flux instance-attribute

flux: Tensor

frequency property

frequency: Tensor

Get frequency values in Hz.

header class-attribute instance-attribute

header: Optional[Dict[str, Any]] = None

ivar class-attribute instance-attribute

ivar: Optional[Tensor] = None

mask class-attribute instance-attribute

mask: Optional[Tensor] = None

spectral_axis instance-attribute

spectral_axis: SpectralAxis

wavelength property

wavelength: Tensor

Get wavelength values in Angstroms.

__post_init__

__post_init__()

Validate spectrum data.

apply_mask

apply_mask() -> 'Spectrum1D'

Return spectrum with mask applied.

resample

resample(new_wavelength: Tensor) -> 'Spectrum1D'

Linearly resample onto new_wavelength (Angstrom).

Inverse variance is propagated through the interpolation weights; masking is dropped because interpolated channels mix masked samples.

flux_conserving_rebin

flux_conserving_rebin(
    flux: Tensor,
    input_edges: Tensor,
    output_edges: Tensor,
    *,
    ivar: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
) -> SpectralRebinResult

Rebin piecewise-constant flux density while preserving integrated flux.

Spectral samples occupy bins described by input_edges. Leading flux dimensions are batches; all tensors remain on the input device. Output bins that extend beyond the input range or overlap invalid input samples are marked false without renormalising away missing flux.

Parameters:

Name Type Description Default
flux Tensor

Flux density with spectral bins on the trailing axis.

required
input_edges Tensor

Monotonic edges of the input bins.

required
output_edges Tensor

Monotonic edges of the requested output bins.

required
ivar Optional[Tensor]

Optional inverse variance matching flux.

None
mask Optional[Tensor]

Optional valid-sample mask matching flux.

None

Returns:

Type Description
SpectralRebinResult

Rebinned flux, optional inverse variance, and output validity mask.

Examples:

>>> import torch
>>> from torchsky.spectral import flux_conserving_rebin
>>> result = flux_conserving_rebin(torch.tensor([1.0]), torch.tensor([0.0, 1.0]), torch.tensor([0.0, 1.0]))
>>> result.flux.tolist()
[1.0]

relativistic_doppler_shift

relativistic_doppler_shift(
    flux: Tensor,
    input_edges: Tensor,
    radial_velocity: Union[float, Tensor],
    *,
    output_edges: Optional[Tensor] = None,
    ivar: Optional[Tensor] = None,
    mask: Optional[Tensor] = None,
) -> SpectralRebinResult

Apply a signed relativistic radial-velocity shift to flux density.

Positive velocity is receding. The Doppler factor is sqrt((1 + v/c) / (1 - v/c)). When output_edges is omitted, each batch receives its shifted edge grid. Supplying a common output grid rebins the shifted spectra onto that grid without losing integrated flux.

spectral_axis_from_header

spectral_axis_from_header(
    header: Dict[str, Any],
    *,
    data_shape: Optional[Tuple[int, ...]] = None,
    tables: Optional[Any] = None,
) -> Tuple["SpectralAxis", int]

Build a linear or tabular SpectralAxis from FITS WCS header metadata.

spectral_bin_edges_from_header

spectral_bin_edges_from_header(
    header: Dict[str, Any],
    *,
    data_shape: Optional[Tuple[int, ...]] = None,
    tables: Optional[Any] = None,
) -> Tuple[Tensor, int]

Build linear or non-linear spectral bin edges from FITS WCS header metadata.

Interior edges sit at channel midpoints; the outer edges extend by half the adjacent spacing, so uniform and non-uniform grids share one rule.

write_cube_fits

write_cube_fits(
    path: str,
    cube: Tensor,
    *,
    spatial_header: Dict[str, Any],
    spectral_axis: SpectralAxis,
    spectral_axis_index: int = 0,
    overwrite: bool = False,
    compress: Union[bool, str] = False,
    allow_nonuniform: bool = False,
    nonuniform_fallback: str = "custom_cards",
) -> Dict[str, Any]

Write a 3D spectral cube to a FITS primary image HDU (with potential coordinate tables).

The cube is written with FITS axis 3 = spectral (CTYPE3 / CRVAL3 / CDELT3), matching :meth:SpectralReader.read_data_cube when the spectral axis is the slowest-varying FITS axis (tensor index 0).

Parameters:

Name Type Description Default
path str

Output .fits path.

required
cube Tensor

Three-dimensional tensor. Default layout is (L, H, W) with L == len(spectral_axis.values) when spectral_axis_index=0.

required
spatial_header Dict[str, Any]

Header-like dict for the spatial plane (axes 1 and 2): e.g. CTYPE1/2, CRPIX1/2, CRVAL1/2, CD* or CDELT*. NAXIS / NAXIS1 / NAXIS2 are replaced using cube shape.

required
spectral_axis SpectralAxis

Spectral coordinates for axis 3; values length must match the spectral dimension of cube.

required
spectral_axis_index int

Which dimension of cube is spectral (default 0).

0
overwrite bool

Passed to :func:torchfits.write.

False
compress Union[bool, str]

Passed to :func:torchfits.write.

False
allow_nonuniform bool

If True, allows non-uniform spacing of spectral axis coordinates.

False
nonuniform_fallback str

Method to handle non-uniform coordinates: "custom_cards" (writes each wavelength into custom WAVE0, WAVE1... cards) or "table" (writes a standards-compliant -TAB coordinate table binary extension).

'custom_cards'

Returns:

Type Description
Dict[str, Any]

The merged FITS header dictionary written with the array.

Raises:

Type Description
ValueError

If cube is not 3D, shapes disagree, or the spectral grid is not linear and allow_nonuniform is False.

Spectral axes

Spectral and data cube support for torchsky.

Implements 1D spectra with inverse variance/mask arrays and 3D data cubes for IFU instruments and radio astronomy.

Note: This is a core torchsky module. FITS file I/O is owned by torchfits; spectra and cubes here operate on in-memory tensors and header mappings.

air_wavelength_to_vacuum

air_wavelength_to_vacuum(
    wavelength_air: Any, unit: str | None = None
) -> Tensor

Convert standard-air wavelength to vacuum wavelength.

Uses the WCSLIB awavwave refractive index (FITS-WCS Paper III / Edlén form), matching astropy.wcs. Inputs and outputs use unit when provided; FITS default is meters.

canonical_spectral_type

canonical_spectral_type(spectral_type: str) -> str

Return the canonical FITS spectral coordinate type.

frequency_to_spectral

frequency_to_spectral(
    frequency: Any,
    spectral_type: str,
    *,
    unit: str | None = None,
    rest_frequency: float | Tensor | None = None,
    rest_wavelength: float | Tensor | None = None,
) -> Tensor

Convert frequency in Hz to a requested spectral coordinate.

spectral_unit_scale

spectral_unit_scale(
    spectral_type: str, unit: str | None = None
) -> float

Return the multiplicative scale from unit to the SI unit for a type.