enyo.etc.spectrum module¶
Spectrum utilities
Copyright © 2020, Kyle B. Westfall
#.. _pypi https://pypi.org/project/sdss-mangadap/
-
class
enyo.etc.spectrum.ABReferenceSpectrum(wave, resolution=None, regular=True, log=False)[source]¶ Bases:
enyo.etc.spectrum.SpectrumConstruct a spectrum with a constant flux of 3631 Jy.
Inherits from
Spectrum, which we take to mean that the flux is always in units of 1e-17 erg/s/cm^2/angstrom.Parameters: - wave (numpy.ndarray) – Wavelength vector for the spectrum.
- resolution (
float, array-like, optional) – 1D spectral resolution (\($R=\lambda/\Delta\lambda$\)) - regular (
bool, optional) – Spectrum is regularly sampled, either linearly or log-linearly - log (
bool, optional) – Spectrum is sampled in steps of log base 10. If regular is False, this is ignored.
-
class
enyo.etc.spectrum.BlueGalaxySpectrum(redshift=0.0)[source]¶ Bases:
enyo.etc.spectrum.SpectrumAn example blue galaxy spectrum pulled from the MaNGA survey.
-
class
enyo.etc.spectrum.EmissionLineSpectrum(wave, flux, restwave, fwhm, units='ang', redshift=0.0, continuum=None, resolution=None, log=False)[source]¶ Bases:
enyo.etc.spectrum.SpectrumDefine an emission-line spectrum.
Todo
- use MaNGA DAP functions
Flux units are 1e-17 erg/s/cm^2/angstrom.
Parameters: - wave (array-like) – 1D wavelength data in angstroms. Expected to be sampled linearly or geometrically. These are the observed wavelengths.
- flux (array-like) – The total fluxes of one or more emission lines in 1e-17 erg/s/cm^2.
- restwave (array-like) – The central rest wavelengths of one or emission lines in angstroms.
- fwhm (array-like) – The FWHM of the Gaussian line profiles. If the resolution vector is provided, these are assumed to be the intrinsic widths, such that the line included in the spectrum has an observed width determined by the quadrature sum of the intrinsic and instrumental widths. If the resolution vector is not provided, the line simply has the provided FWHM.
- units (
str, array-like, optional) – The units of the provided FWHM data. Must be either ‘km/s’ or ‘ang’. Can be a single string or an array with the units for each provided value. - redshift (scalar-like, optional) – If provided, the emission-line wavelengths are redshifted.
- continuum (array-like, optional) – If provided, this is the 1D continuum placed below the line, which must have the same length as the input wavelength vector. The continuum is 0 if not provided.
- resolution (array-like, optional) – 1D spectral resolution
(\($R=\lambda/\Delta\lambda$\)). If None, the width
of the lines is set by
fwhmonly. - log (
bool, optional) – Spectrum is sampled in steps of log base 10.
-
class
enyo.etc.spectrum.MaunakeaSkySpectrum[source]¶ Bases:
enyo.etc.spectrum.SpectrumThe default, empirical dark night-sky spectrum at Maunakea provided by Chuck Steidel.
-
class
enyo.etc.spectrum.RedGalaxySpectrum(redshift=0.0)[source]¶ Bases:
enyo.etc.spectrum.SpectrumAn example red galaxy spectrum pulled from the MaNGA survey.
-
class
enyo.etc.spectrum.Spectrum(wave, flux, error=None, mask=None, resolution=None, regular=True, log=False, airwave=False, check=True, use_sampling_assessments=False)[source]¶ Bases:
objectDefine a spectrum.
Units are expected to be wavelength in angstroms and flux in 1e-17 erg/s/cm^2/angstrom.
If wavelengths are provided in air (instantiated with
airwave=True), wavelengths are converted to vacuum and the sampling is set to be irregular.Todo
- allow for different units?
Parameters: - wave (array-like) – 1D wavelength data in angstroms. Can be sampled irregularly.
- flux (array-like) – 1D flux data in 1e-17 erg/s/cm^2/angstrom. Use
convert_flux_units(), if necessary. - error (array-like, optional) – 1-sigma error in the flux data
- mask (array-like, optional) – Boolean mask for flux data (True=bad)
- resolution (
float, array-like, optional) – 1D spectral resolution (\($R=\lambda/\Delta\lambda$\)) - regular (
bool, optional) – Spectrum is regularly sampled, either linearly or log-linearly - log (
bool, optional) – Spectrum is sampled in steps of log base 10. If regular is False, this is ignored. - airwave (
bool, optional) – Spectrum wavelengths are provided in air. If True, the wavelengths will be converted to vacuum, and the wavelength step will be set to be irregular (if it isn’t already). - check (
bool, optional) – Check sampling to confirm input. - use_sampling_assessments (
bool, optional) – Override any values provided forregularandlogand assess the spectral sampling directly from the provided wavelength array.
-
static
assess_sampling(wave)[source]¶ Assess the wavelength sampling directly from the wavelength vector.
Parameters: wave (array-like) – Array with the wavelengths. Returns: Two booleans are returned. The first indicates if the wavelength vector is regularly sampled (either linearly or log-linearly), the second indicates if the sampling is log-linear. Return type: tuple
-
flux¶ The flux data vector.
-
classmethod
from_ascii(ifile, wavecol=0, waveunits='angstrom', fluxcol=1, fluxunits='1e-17 erg / (cm2 s angstrom)', errcol=None, ivarcol=None, maskcol=None, rescol=None, **kwargs)[source]¶ Construct a spectrum using data from an ascii file.
Note
- All the columns are 0-indexed. I.e., the first column is column 0.
- The core function used to read the data is numpy.genfromtxt; i.e., anything that can be parsed by that function (e.g., gzipped files), can be parsed by this method. Note that all columns are read as floats. This means that any string columns are converted to nan, and any mask column must have the typical cast of 0 for False and anything else for True.
Parameters: - ifile (
str) – Name of the fits file. - wavecol (
int, optional) – Column index with the wavelength data. - fluxcol (
int, optional) – Column index with the flux data. - fluxunits (
str, optional) – Units of the flux density read from the file. Must be interpretable by astropy.units.Unit. If None, units are assumed to be'1e-17 erg / (cm2 s angstrom)'. - errcol (
int, optional) – Column index with the flux error. If None, no errors will be read. Keyword is mutually exclusive withivarcol. - ivarcol (
int, optional) – Column index with the flux inverse variance. If None, no errors will be read. Otherwise, the data are read and then converted to 1-sigma errors. Keyword is mutually exclusive witherrcol. - maskcol (
int, optional) – Column index with the mask data. If not None, the data in this extension must be castable to a boolean array. If None, all spectral data is assumed to be unmasked. - rescol (
str,int, optional) – Column index with the spectral resolution. If None, the spectral resolution will be undefined. - **kwargs – Keyword arguments passed directly to the class
instantiation (see
Spectrum).
Returns: Object read from the ascii file.
Return type: Raises: ValueError– Raised if botherrcolandivarcolare set.
-
classmethod
from_fits(ifile, waveext='WAVE', waveunits='angstrom', fluxext='FLUX', fluxunits=None, errext=None, ivarext=None, maskext=None, resext=None, tblext=None, **kwargs)[source]¶ Construct a spectrum using data from a fits file.
Fluxes must be in units of flux density (i.e., flux per unit angstrom or Hz).
Todo
- Allow for a “frequency” extension instead of wavelengths?
Parameters: - ifile (
str) – Name of the fits file. - waveext (
str,int, optional) – Extension with the wavelength data. If set to ‘WCS’, the wavelengths are constructed using the WCS in the flux extension header. If the data is instead one column in a binary table extension, seetblext. - waveunits (
str, optional) – Units of the wavelengths in the fits file. WARNING: If you try to build the wavelength array using the WCS in the header, the wavelength array will be converted to angstroms based on the WCS units. If the WCS units are not defined, the values read from the WCS are not altered, but can be fixed using this keyword. - fluxext (
str,int, optional) – Extension with the flux data. If the data is instead one column in a binary table extension, seetblext. All fluxes are expected to be in units of flux density. - fluxunits (
str, optional) – Units of the flux density in the fits file. Must be interpretable by astropy.units.Unit. If None, the code will check the header of the flux extension (or the binary table extension; seetblext) for theBUNITkeyword. If not None, this overrides any units provided by the fits file. If None and noBUNITkeyword is found, the units are assumed to be'1e-17 erg / (cm2 s angstrom)'. - errext (
str,int, optional) – Extension with the flux error. If None, no errors will be read. Keyword is mutually exclusive withivarext. If the data is instead one column in a binary table extension, seetblext. - ivarext (
str,int, optional) – Extension with the flux inverse variance. If None, no errors will be read. Otherwise, the data are read and then converted to 1-sigma errors. Keyword is mutually exclusive witherrext. If the data is instead one column in a binary table extension, seetblext. - maskext (
str,int, optional) – Extension with the mask data. If not None, the data in this extension must be castable to a boolean array. If None, all spectral data is assumed to be unmasked. If the data is instead one column in a binary table extension, seetblext. - resext (
str,int, optional) – Extension with the spectral resolution. If None, the spectral resolution will be undefined. If the data is instead one column in a binary table extension, seetblext. - tblext (
str,int, optional) – Instead of being organized in a series of ImageHDU extensions, the spectral data are in a BinTableHDU with this extension name/index. If provided (not None), the “extension” names/indices provided by the other keywords are instead interpreted as the columns in this binary table. - **kwargs – Keyword arguments passed directly to the class
instantiation (see
Spectrum). NOTE: Ifresolutionis provided as one of the kwargs, it is given priority over theresextkeyword in this method.
Returns: Object read from the fits file.
Return type: Raises: ValueError– Raised if botherrextandivarextare set, or if the wavelength vector is supposed to be built from a WCS, but the data is organized in a binary table.
-
interp(w)[source]¶ Linearly interpolate the flux at a provided wavelength.
Parameters: w ( float, numpy.ndarray) – Wavelength in angstroms. Can be a single wavelength or a wavelength array.
-
magnitude(wavelength=None, band=None, system='AB')[source]¶ Calculate the magnitude of the object in the specified band.
If no arguments are provided, the magnitude is calculated for the entire
fluxvector. Otherwise, the magnitude is calculated at a single wavelength (seewavelength) or over a filter (seeband).Parameters: - wavelength (
float, optional) – The wavelength at which to calculate the magnitude. - band (
FilterResponse, optional) – Object with the filter response function - system (
str, optional) – Photometric system. Currently must beABorVega.
Returns: The one or more magnitude measurements, depending on the input.
Return type: float, numpy.ndarrayRaises: NotImplementedError– Raised if the photometric system is not known.- wavelength (
-
match_resolution(resolution, wave=None)[source]¶ Match the spectral resolution of the spectrum to the provided value.
The object must be a regularly sampled, either linearly or log-linearly (see
log). If it isn’t, useresample().Parameters: - resolution (
float, array-like) – The single value for the spectral resolution (\(R=\lambda/\Delta\lambda\)) or a vector for a wavelength-dependent spectral resolution. If a vector, the length of the vector must exactly match the wavelength vector of the object or the wavelength vector must also be provided (seewave). - wave (numpy.ndarray, optional) – Wavelength vector for the provided spectral
resolution. If None,
resolutionmust either be a single number or a vector with the same length aswave.
Returns: Returns an object with the spectral resolution matched (as best as can be done). If necessary, the spectrum is masked where the spectral resolution could not be matched in detail.
Return type: - resolution (
-
photon_flux(inplace=True)[source]¶ Convert the spectrum from 1e-17 erg/s/cm^2/angstrom to photons/s/cm^2/angstrom.
Parameters: inplace ( bool, optional) – Ifinplace is True, the spectrum is modified in place and None is returned; otherwise, the converted flux vector is returned.Returns: Flux vector in photons/s/cm^2/angstrom if inplace is False; otherwise, nothing is returned.Return type: numpy.ndarray
-
plot(ax=None, show=False, **kwargs)[source]¶ Construct a plot of the spectrum.
Parameters: - ax (matplotlib.axes.Axes) – Axes for the plot. If None, a new instance is
generated using
pyplot.subplot. - show (
bool, optional) – Show the plot instead of just returning the modified matplotlib.axes.Axes instance. - **kwargs – Other keywords (like
color) passed directly topyplot.plot.
Returns: Modified or new instance; returned only if
show is False.Return type: - ax (matplotlib.axes.Axes) – Axes for the plot. If None, a new instance is
generated using
-
redshift(z)[source]¶ Redshift the spectrum.
Spectrum is in 1e-17 erg/s/cm^2/angstrom, so this shifts the wavelength vector by 1+z and rescales the flux by 1+z to keep the flux per observed wavelength constant; this is not the same as surface-brightness dimming, which is not accounted for. S/N is kept fixed.
Parameters: z ( float) – Target redshift
-
resample(wave=None, dwave=None, log=False, step=True)[source]¶ Resample the spectrum to a uniform wavelength grid.
Parameters: - wave (numpy.ndarray, optional) – New wavelength array. Must be linearly or log-linearly sampled. If None, the new wavelength grid covers the full extent of the current grid with a sampling based in the minimum pixel separation (geometrically or linearly) in the current spectrum.
- dwave (
float, optional) – Step for each pixel. Iflogis True, this must be the geometric step; i.e., the difference in the base-10 log of the wavelength of adjacent pixels. - log (
bool, optional) – Flag that the wavelength array is log-linearly sampled. - step (
bool, optional) – Treat the input function as a step function during the resampling integration. If False, use a linear interpolation between pixel samples.
Returns: Returns a resampled version of itself.
Return type:
-
rescale(factor)[source]¶ Rescale the spectrum by the provided factor.
The spectral data are modified in-place; nothing is returned.
Parameters: factor (scalar-like or array-like) – Factor to multiply the fluxes. If it’s a vector, it must have the same length as the existing spectrum.
-
rescale_flux(wave, flux)[source]¶ Rescale the spectrum to be specifically the flux value at the provided wavelength. The input flux should be in units of 1e-17 erg/s/cm^2/angstrom.
Parameters: - wave (
float) – The wavelength at which to base the rescaling. - flux (
float) – The target value of the flux at the provided wavelength.
- wave (
-
rescale_magnitude(new_mag, wavelength=None, band=None, system='AB')[source]¶ Rescale the spectrum to an input magnitude.
Must provide either
wavelengthorband. The object is edited in-place.Parameters: - new_mag (
float) – The target magnitude - wavelength (
float, optional) – The wavelength at which to calculate the magnitude. - band (
FilterResponse, optional) – Object with the filter response function - system (
str, optional) – Photometric system. Currently must beABorVega.
Raises: ValueError– Raised if neitherwavelengthnorbandare provided.NotImplementedError– Raised if the photometric system is not known.
- new_mag (
-
wave¶ The wavelength data vector.
-
wavelength_step()[source]¶ Return the wavelength step per pixel.
Returns: Change in angstroms per pixel. Return type: numpy.ndarray
-
static
wcs_wavelength_vector(wcs, nwave, naxis=1, axis=0)[source]¶ Generate the wavelength vector using the provided astropy.wcs.WCS object.
Returns: Vector with wavelengths defined by wcs.Return type: numpy.ndarray
-
class
enyo.etc.spectrum.VegaSpectrum(waverange=None)[source]¶ Bases:
enyo.etc.spectrum.SpectrumReturn the spectrum of Vega constructed using data from:
https://ssb.stsci.edu/cdbs/calspec/alpha_lyr_stis_009.fits
Downloaded on 3 Apr 2020. Wavelengths are in vacuum.
Parameters: waverange (array-like, optional) – Used to limit the wavelength range of the returned spectrum. The maximum wavelength range of the current spectrum goes from 900 Angstrom to 300 microns.
-
enyo.etc.spectrum.angstroms_per_pixel(wave, log=False, base=10.0, regular=True)[source]¶ Return a vector with the angstroms per pixel at each channel.
When regular=True, the function assumes that the wavelengths are either sampled linearly or geometrically. Otherwise, it calculates the size of each pixel as the difference between the wavelength coordinates. The first and last pixels are assumed to have a width as determined by assuming the coordinate is at its center.
Note
If the regular is False and log is True, the code does not assume the wavelength coordinates are at the geometric center of the pixel.
Parameters: - wave (numpy.ndarray) – (Geometric) centers of the spectrum pixels in angstroms.
- log (numpy.ndarray, optional) – The vector is geometrically sampled.
- base (
float, optional) – Base of the logarithm used in the geometric sampling. - regular (
bool, optional) – The vector is regularly sampled.
Returns: The angstroms per pixel.
Return type: numpy.ndarray
-
enyo.etc.spectrum.convert_flux_density(wave, flux, error=None, density='ang')[source]¶ Convert a spectrum with flux per unit wavelength to per unit frequency or vice versa.
For converting from per unit wavelength, this function returns
\[F_{\nu} = F_{\lambda} \frac{d\lambda}{d\nu} = F_{\lambda} \frac{\lambda^2}{c}.\]The spectrum independent variable (wave) is always expected to be the wavelength in angstroms. The input/output units always expect \(F_{\lambda}\) in \(10^{-17}\ {\rm erg\ s}^{-1}\ {\rm cm}^{-2}\ {\rm A}^{-1}\) and \(F_{\nu}\) in microjanskys (\(10^{-29} {\rm erg\ s}^{-1}\ {\rm cm}^{-2}\ {\rm Hz}^{-1}\)). Beyond this, the function is ignorant of the input/output units. For example, if you provide the function with an input spectrum with \(F_{\lambda}\) in \(10^{-11}\ {\rm erg\ s}^{-1}\ {\rm cm}^{-2}\ {\rm A}^{-1}\), the output will be \(F_{\nu}\) in Janskys.
Parameters: - wave (
float, array-like) – The vector with the wavelengths in angstroms. - flux (
float, array-like) – The vector with the flux density; cf. density. - error (
float, array-like, optional) – The error in the flux measurements. If None, no errors are returned. - density (
str, optional) – The density unit of the input spectrum. Must be either ‘ang’ or ‘Hz’. If the input spectrum is \(F_{\lambda}\) (density=’ang’), the returned spectrum is \(F_{\nu}\).
Returns: The flux with the converted units. If the spectrum errors are not provided, only the flux value or array is returned.
Return type: float, numpy.ndarray,tupleRaises: ValueError– Raised if the wave and flux arguments do not have the same shape.- wave (
-
enyo.etc.spectrum.convert_flux_units(wave, flux, current_units, error=None)[source]¶ Convert flux density units to
'1e-17 erg / (cm2 s angstrom)'.The flux density can be per unit frequency (\(F_{\nu}\)) or per unit wavelength (\(F_{\lambda}\)). If a basic unit conversion from the current units to
'1e-17 erg / (cm2 s angstrom)'fails, it’s assumed that the user provided \(F_{\nu}\). If the conversion from the current units to'1e-29 erg / (cm2 Hz s)'also fails, the method faults.Parameters: - wave (numpy.ndarray) – Wavelength in angstroms.
- flux (numpy.ndarray) – Flux density measurements.
- current_units (
str) – Input units of the flux density. Must be interpretable by astropy.units.Unit. - error (numpy.ndarray) – Error vector. Ignored if None.
Returns: The converted flux vector. If an error vector is provided, it is also returned as the second element.
Return type: numpy.ndarray,
tuple
-
enyo.etc.spectrum.spectral_coordinate_step(wave, log=False, base=10.0)[source]¶ Return the sampling step for the input wavelength vector.
If the sampling is logarithmic, return the change in the logarithm of the wavelength; otherwise, return the linear step in angstroms.
Parameters: - wave (array-like) – Wavelength coordinates of each spectral channel in angstroms.
- log (
bool, optional) – Input spectrum has been sampled geometrically. - base (
float, optional) – If sampled geometrically, the sampling is done using a logarithm with this base. For natural logarithm, use numpy.exp(1).
Returns: Spectral sampling step in either angstroms (log=False) or the step in log(angstroms).
Return type: floatRaises: ValueError– Raised if the wavelength vector is not uniformly (either linearly or log-linearly) sampled to numerical accuracy.