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=Trueinload_btsettl_spectrum().
References
BT-Settl spectral grid (project home / papers; cite per your file version): http://perso.ens-lyon.fr/france.allard/
SVO Filter Profile Service: https://svo2.cab.inta-csic.es/theory/fps3/
spirou-ccf (spectral order / CCF context): https://github.com/edermartioli/spirou-ccf/blob/main/spiroulib.py
See also
air_wavelength_nm_to_vacuum_nm()Air → vacuum (nm).
vacuum_wavelength_nm_to_air_nm()Vacuum → air (nm), inverse pairing.
Functions
|
Bandpass AB magnitude from \(f_\nu\)-weighted integration. |
|
Prefer |
|
Dry-air refractivity \((n - 1)\) in parts per million (ppm). |
|
Load a 2-column wavelength_Angstrom, transmission table from |
|
Convert air wavelength to vacuum wavelength (nanometers). |
|
Convert a change in pixels to a change in wavelength. |
|
Convert a change in velocity to a change in wavelength. |
|
Convert a change in wavelength to a change in velocity. |
|
Return a 2MASS filter bandpass (wavelength Å, transmission). |
|
Resolve a spectrum file path, optionally relative to a package data directory. |
|
Load wavelength and flux from a BT-Settl spectrum HDF5 file. |
|
Load wavelength and flux as plain numpy arrays from a stellar template file. |
|
Return canonical 2MASS band |
Resolve a stellar template to |
|
|
Resolve optional AB/Vega magnitudes to |
|
Convert a 2MASS AB magnitude to Vega using a fixed per-band offset. |
|
Convert a 2MASS Vega magnitude to AB using a fixed per-band offset. |
|
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_nmInverse 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 takeabs(...).- 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.
- delta_wave_to_delta_vel(delta_wave, wave)[source]
Convert a change in wavelength to a change in velocity.
- 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
bandis 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
Cohen et al. 2003, AJ 126, 1090 (2MASS absolute calibration / RSR).
Spanish Virtual Observatory Filter Profile Service (FPS3): https://svo2.cab.inta-csic.es/theory/fps3/
- get_spectrum_path(path, base_dir=None)[source]
Resolve a spectrum file path, optionally relative to a package data directory.
- Parameters:
- Returns:
str – Absolute filesystem path (
os.path.join(base_dir, path)whenpathis relative). If that file is missing, a same-stem*.h5sibling is used when present (Dropboxconflicted copynames).
See also
load_btsettl_spectrumOpen 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) andflux(in 1e-23 erg/cm^2/s/Angstrom) datasets. SVO BT-Settl (CIFIST) HDF5 files also store model parameters on the root attributestemperature(K),surface_gravity(log g cgs), andmetallicity; read them withh5pyif needed (seehispecdrp/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 L2wave_*, SPIROU-style masks in vacuum nm). Setwavelengths_are_air=Falseif the file is already on a vacuum grid.If
mag_abandfilter_bandare 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_abto 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_airis True).flux (astropy.units.Quantity) – Flux density in erg/s/cm^2/Angstrom (same as file).
- Raises:
ImportError – If
h5pyis not installed.
References
BT-Settl atmosphere models; cite the grid publication appropriate to your file. See
hispecdrp/data/templates/README.mdfor CIFIST / SVO air-wavelength notes.See also
load_template_from_pathSame data as plain
numpyarrays.vacuum_wavelength_nm_to_air_nmIf 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) viaload_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 defaultwavelengths_are_air=Trueand astropy quantities stripped tofloat64.See also
load_btsettl_spectrumFull interface with units and optional photometric norm.
resolve_stellar_template_to_log_micronNatural 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_pathis set and either wavelength or flux array is missing, loads from disk usingload_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_wavelengthandtemplate_fluxare 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, orNone.
Notes
On load failure from
template_path, logs an exception and returns(None, None)without re-raising.See also
load_template_from_pathDisk 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_vegaoverridesmag_abwhen both are set. A magnitude requiresfilter_band(2MASSJ/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_nmForward air → vacuum.
Notes
Round-trip
air → vac → airmatches the original air grid within ~machine precision for typical NIR wavelengths when using the sameair_density.