hispecdrp.primitives.utils.spectral_utils

Spectral utilities: template I/O and wavelength / velocity / pixel conversions.

Includes BT-Settl template loading for stellar CCF, plus helpers that convert between wavelength, velocity, and pixel deltas.

Loads BT-Settl-style HDF5 spectra (lte*.h5), resolves paths, converts air ↔ vacuum wavelengths (see air_wavelength_nm_to_vacuum_nm() and vacuum_wavelength_nm_to_air_nm()), normalizes to 2MASS AB magnitudes using profiles from the SVO Filter Profile Service, and builds \((\ln\lambda, \mathrm{flux})\) grids for StellarRVPrimitive.

Submodules and data

Bundled templates and format notes live under hispecdrp/data/templates/ (see that directory’s README.md for BT-Settl CIFIST, air wavelengths, and HDF5 layout).

Notes

  • BT-Settl model grids: cite Allard et al. / BT-Settl papers for the atmosphere data, not HISPEC DRP.

  • 2MASS filter curves prefer bundled Cohen/IPAC RSR files under hispecdrp/data/filters/; SVO (SVO_FILTER_URL) is only tried if those are missing.

  • Air–vacuum conversions use a dry-air refractivity polynomial in _edlen_refractivity_ppm_nm() (SPIROU / Morton-style Cauchy form); refractivity is evaluated at the air wavelength, so the inverse uses fixed-point iteration.

  • Wavelength convention for loaded templates matches vacuum L2 axes when wavelengths_are_air=True in load_btsettl_spectrum().

References

See also

air_wavelength_nm_to_vacuum_nm()

Air → vacuum (nm).

vacuum_wavelength_nm_to_air_nm()

Vacuum → air (nm), inverse pairing.

Functions

_ab_mag_through_filter(wavelength_um, ...)

Bandpass AB magnitude from \(f_\nu\)-weighted integration.

_coalesce_existing_spectrum_path(resolved)

Prefer resolved if it exists; else a Dropbox conflicted-copy sibling.

_edlen_refractivity_ppm_nm(wavelength_nm, *)

Dry-air refractivity \((n - 1)\) in parts per million (ppm).

_load_2mass_filter_table(path)

Load a 2-column wavelength_Angstrom, transmission table from path.

air_wavelength_nm_to_vacuum_nm(...[, ...])

Convert air wavelength to vacuum wavelength (nanometers).

delta_pix_to_delta_wave(delta_pix, x[, ...])

Convert a change in pixels to a change in wavelength.

delta_vel_to_delta_wave(delta_vel, wave)

Convert a change in velocity to a change in wavelength.

delta_wave_to_delta_vel(delta_wave, wave)

Convert a change in wavelength to a change in velocity.

fetch_svo_2mass_filter(band)

Return a 2MASS filter bandpass (wavelength Å, transmission).

get_spectrum_path(path[, base_dir])

Resolve a spectrum file path, optionally relative to a package data directory.

load_btsettl_spectrum(filepath[, wl_min_um, ...])

Load wavelength and flux from a BT-Settl spectrum HDF5 file.

load_template_from_path(filepath[, ...])

Load wavelength and flux as plain numpy arrays from a stellar template file.

normalize_2mass_band(band)

Return canonical 2MASS band 'J', 'H', or 'K' ('Ks' → 'K').

resolve_stellar_template_to_log_micron(...)

Resolve a stellar template to (ln λ, flux) with λ in microns, for CCF.

resolve_twomass_mag_ab(*[, mag_ab, ...])

Resolve optional AB/Vega magnitudes to (mag_ab, band) for template scaling.

twomass_ab_to_vega(mag_ab, band)

Convert a 2MASS AB magnitude to Vega using a fixed per-band offset.

twomass_vega_to_ab(mag_vega, band)

Convert a 2MASS Vega magnitude to AB using a fixed per-band offset.

vacuum_wavelength_nm_to_air_nm(...[, ...])

Convert vacuum wavelength to air wavelength (nanometers).

air_wavelength_nm_to_vacuum_nm(air_wavelength_nm, *, air_density=1.0)[source]

Convert air wavelength to vacuum wavelength (nanometers).

Uses the standard mapping

\[\lambda_\mathrm{vac} = \lambda_\mathrm{air}\, \bigl(1 + 10^{-6} N(\lambda_\mathrm{air})\bigr),\]

where \(N\) is _edlen_refractivity_ppm_nm() evaluated at \(\lambda_\mathrm{air}\).

Parameters:
  • air_wavelength_nm (array_like) – Wavelength(s) in nanometers (air).

  • air_density (float, optional) – Passed to _edlen_refractivity_ppm_nm().

Returns:

np.ndarray – Vacuum wavelength(s) in nanometers (same shape as broadcast input).

See also

vacuum_wavelength_nm_to_air_nm

Inverse conversion (fixed-point iteration).

delta_pix_to_delta_wave(delta_pix, x, wavesol=None, dispersion=None)[source]

Convert a change in pixels to a change in wavelength.

The sign follows dλ/dpix. On a decreasing WAVE row the result is negative; callers that need a width (FWHM, uncertainty) should take abs(...).

Parameters:
  • delta_pix (float) – Change in pixels.

  • x (float) – Pixel position.

  • wavesol (np.ndarray | None) – Wavelength solution used to calculate the dispersion. If None, the dispersion must be provided.

  • dispersion (np.ndarray | float) – Dispersion in wavelength per pixel. If None, it will be calculated from the wavelength solution.

Returns:

np.ndarray | float – Change in wavelength in the same units as the wavelength solution.

delta_vel_to_delta_wave(delta_vel, wave)[source]

Convert a change in velocity to a change in wavelength.

Parameters:
  • delta_vel (np.ndarray | float) – Change in velocity in m/s.

  • wave (np.ndarray | float) – Wavelength (any units).

Returns:

np.ndarray | float – Change in wavelength in the same units as wave.

delta_wave_to_delta_vel(delta_wave, wave)[source]

Convert a change in wavelength to a change in velocity.

Parameters:
  • delta_wave (np.ndarray | float) – Change in wavelength (any units).

  • wave (np.ndarray | float) – Wavelength (same units as delta_wave).

Returns:

np.ndarray | float – Change in velocity in m/s.

fetch_svo_2mass_filter(band)[source]

Return a 2MASS filter bandpass (wavelength Å, transmission).

Prefers the bundled Cohen/IPAC RSR file under hispecdrp/data/filters/. If that file is missing, falls back to downloading from the SVO Filter Profile Service (SVO_FILTER_URL).

Parameters:

band (str) – One of 'J', 'H', or 'K' (case-insensitive).

Returns:
  • wavelength_angstrom (np.ndarray) – Wavelength sample points in Angstrom.

  • transmission (np.ndarray) – Dimensionless transmission, same length as wavelength_angstrom.

Raises:
  • ValueError – If band is not one of J, H, K, or if the table is not 2-column.

  • urllib.error.URLError – On network failure or timeout (30 s) when the bundled file is absent.

References

get_spectrum_path(path, base_dir=None)[source]

Resolve a spectrum file path, optionally relative to a package data directory.

Parameters:
  • path (str) – Absolute path, or a filename / relative path joined to base_dir.

  • base_dir (str or None, optional) – Root directory for relative path. If None, uses hispecdrp/data/templates/ (see _DEFAULT_SPECTRUM_DATA_DIR).

Returns:

str – Absolute filesystem path (os.path.join(base_dir, path) when path is relative). If that file is missing, a same-stem *.h5 sibling is used when present (Dropbox conflicted copy names).

See also

load_btsettl_spectrum

Open resolved BT-Settl HDF5 files.

load_btsettl_spectrum(filepath, wl_min_um=0.8, wl_max_um=3.0, mag_ab=None, filter_band=None, *, wavelengths_are_air=True)[source]

Load wavelength and flux from a BT-Settl spectrum HDF5 file.

The file is expected to have wavelength (in Angstrom) and flux (in 1e-23 erg/cm^2/s/Angstrom) datasets. SVO BT-Settl (CIFIST) HDF5 files also store model parameters on the root attributes temperature (K), surface_gravity (log g cgs), and metallicity; read them with h5py if needed (see hispecdrp/data/templates/README.md).

By default (wavelengths_are_air=True) the HDF5 wavelength grid is treated as air Angstrom and converted to vacuum microns before return, so the template matches vacuum wavelength axes (e.g. HISPEC L2 wave_*, SPIROU-style masks in vacuum nm). Set wavelengths_are_air=False if the file is already on a vacuum grid.

If mag_ab and filter_band are set, the spectrum is normalized to the given AB magnitude in the corresponding 2MASS filter (J, H, or K). The 2MASS profile is fetched from the SVO Filter Profile Service.

Parameters:
  • filepath (str) – Path to the .h5 file (e.g. lte025.0-5.5-0.0a+0.0.BT-Settl.spec.7.h5).

  • wl_min_um (float, optional) – Minimum wavelength in microns. Default is 0.8.

  • wl_max_um (float, optional) – Maximum wavelength in microns. Default is 3.0.

  • mag_ab (float or None, optional) – If set with filter_band, normalize the spectrum to this AB magnitude in that band. Default is None.

  • filter_band (str or None, optional) – One of ‘J’, ‘H’, ‘K’. Used with mag_ab to normalize. Default is None.

  • wavelengths_are_air (bool, optional) – If True (default), convert stored wavelengths from air to vacuum before applying wl_min_um / wl_max_um (interpreted as vacuum microns).

Returns:
  • wavelength (astropy.units.Quantity) – Wavelength array in micron (vacuum when wavelengths_are_air is True).

  • flux (astropy.units.Quantity) – Flux density in erg/s/cm^2/Angstrom (same as file).

Raises:

ImportError – If h5py is not installed.

References

BT-Settl atmosphere models; cite the grid publication appropriate to your file. See hispecdrp/data/templates/README.md for CIFIST / SVO air-wavelength notes.

See also

load_template_from_path

Same data as plain numpy arrays.

vacuum_wavelength_nm_to_air_nm

If you must write vacuum-calibrated grids back to air nm for comparison with archive tables.

load_template_from_path(filepath, wl_min_um=0.8, wl_max_um=3.0)[source]

Load wavelength and flux as plain numpy arrays from a stellar template file.

Currently supports BT-Settl-style HDF5 (e.g. lte*.BT-Settl.spec.*.h5) via load_btsettl_spectrum().

Parameters:
  • filepath (str) – Path to the template spectrum file.

  • wl_min_um (float) – Wavelength clip in vacuum microns (defaults match DEFAULT_STELLAR_TEMPLATE_LOAD_WL_MIN_UM / DEFAULT_STELLAR_TEMPLATE_LOAD_WL_MAX_UM).

  • wl_max_um (float) – Wavelength clip in vacuum microns (defaults match DEFAULT_STELLAR_TEMPLATE_LOAD_WL_MIN_UM / DEFAULT_STELLAR_TEMPLATE_LOAD_WL_MAX_UM).

Returns:
  • wave_um (np.ndarray) – Wavelength in vacuum microns (same convention as load_btsettl_spectrum).

  • flux (np.ndarray) – Flux density in erg/s/cm²/Å (numeric values from the loaded quantity).

Notes

Equivalent to load_btsettl_spectrum() with default wavelengths_are_air=True and astropy quantities stripped to float64.

See also

load_btsettl_spectrum

Full interface with units and optional photometric norm.

resolve_stellar_template_to_log_micron

Natural log wavelength for CCF.

normalize_2mass_band(band)[source]

Return canonical 2MASS band 'J', 'H', or 'K' ('Ks' → 'K').

resolve_stellar_template_to_log_micron(template_path, template_wavelength, template_flux, *, wl_min_um=0.8, wl_max_um=3.0)[source]

Resolve a stellar template to (ln λ, flux) with λ in microns, for CCF.

If template_path is set and either wavelength or flux array is missing, loads from disk using load_template_from_path() over [wl_min_um, wl_max_um] (a broad range; finer clipping may be done per fiber/order downstream).

If both template_wavelength and template_flux are provided (and not overridden by a path-only load), they are validated, sorted in wavelength, and converted to natural log wavelength.

Parameters:
  • template_path (str or None) – Path to BT-Settl (or supported) file.

  • template_wavelength – Optional wavelength (microns, linear) and flux arrays.

  • template_flux – Optional wavelength (microns, linear) and flux arrays.

Returns:
  • template_ln (np.ndarray or None) – \(\ln(\lambda)\) with \(\lambda\) in microns, or None.

  • template_flux (np.ndarray or None) – Flux aligned with template_ln, or None.

Notes

On load failure from template_path, logs an exception and returns (None, None) without re-raising.

See also

load_template_from_path

Disk load used when arrays are missing.

resolve_twomass_mag_ab(*, mag_ab=None, mag_vega=None, filter_band=None)[source]

Resolve optional AB/Vega magnitudes to (mag_ab, band) for template scaling.

mag_vega overrides mag_ab when both are set. A magnitude requires filter_band (2MASS J / H / K / Ks).

twomass_ab_to_vega(mag_ab, band)[source]

Convert a 2MASS AB magnitude to Vega using a fixed per-band offset.

twomass_vega_to_ab(mag_vega, band)[source]

Convert a 2MASS Vega magnitude to AB using a fixed per-band offset.

vacuum_wavelength_nm_to_air_nm(vacuum_wavelength_nm, *, air_density=1.0, max_iter=12, rtol=1e-14)[source]

Convert vacuum wavelength to air wavelength (nanometers).

The forward relation air_wavelength_nm_to_vacuum_nm() depends on refractivity evaluated at air wavelength, so the inverse is not a single closed-form division by a factor evaluated at vacuum λ. This function solves

\[\lambda_\mathrm{vac} = \lambda_\mathrm{air}\, \bigl(1 + 10^{-6} N(\lambda_\mathrm{air})\bigr)\]

by fixed-point iteration

\[\lambda_\mathrm{air}^{(k+1)} = \frac{\lambda_\mathrm{vac}} {1 + 10^{-6} N\bigl(\lambda_\mathrm{air}^{(k)}\bigr)},\]

starting from \(\lambda_\mathrm{air}^{(0)} = \lambda_\mathrm{vac}\). Convergence is rapid because \(10^{-6}N\) is \(\mathcal{O}(10^{-4})\).

Parameters:
  • vacuum_wavelength_nm (array_like) – Wavelength(s) in nanometers (vacuum).

  • air_density (float, optional) – Passed to _edlen_refractivity_ppm_nm().

  • max_iter (int, optional) – Maximum iterations (default 12 is ample for double precision).

  • rtol (float, optional) – Stop when all finite elements satisfy abs(air_new - air) <= rtol * max(abs(air), 1e-30).

Returns:

np.ndarray – Air wavelength(s) in nanometers. Non-finite or non-positive vacuum inputs are mapped to NaN.

Raises:

ValueError – If max_iter < 1.

See also

air_wavelength_nm_to_vacuum_nm

Forward air → vacuum.

Notes

Round-trip air → vac → air matches the original air grid within ~machine precision for typical NIR wavelengths when using the same air_density.