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.
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).
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 |
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'
channel_widths ¶
channel_widths() -> Tensor
Return positive channel widths in the declared axis unit.
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_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.
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.
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 |
None
|
mask
|
Optional[Tensor]
|
Optional valid-sample mask matching |
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 |
required |
cube
|
Tensor
|
Three-dimensional tensor. Default layout is |
required |
spatial_header
|
Dict[str, Any]
|
Header-like dict for the spatial plane (axes 1 and 2):
e.g. |
required |
spectral_axis
|
SpectralAxis
|
Spectral coordinates for axis 3; |
required |
spectral_axis_index
|
int
|
Which dimension of |
0
|
overwrite
|
bool
|
Passed to :func: |
False
|
compress
|
Union[bool, str]
|
Passed to :func: |
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 |
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.