spextra.spextra module#
speXtra: A python tool to manage and manipulate astronomical spectra.
- class spextra.spextra.ExtinctionCurve(curve_name: str | None = None, modelclass=None)#
Bases:
ReddeningLaw,ExtCurveContainerClass to handle extinction curves.
TODO: Implement proper __add__, __sub__, __mul__, etc
- Attributes:
curve_commentDeprecated feature.
curve_nameName of the extinction curve.
datafileName and extension of the file.
descriptionDescription or comment of the file as defined in the library.
filenameDeprecated feature.
is_in_libraryReturn True if file is part of the parent library.
- library
modelModel of the spectrum/bandpass.
nameDeprecated feature.
pathPath to the cached file.
warningsDictionary of warning key-value pairs related to spectrum/bandpass.
waverangeRange of
waveset.wavesetOptimal wavelengths for sampling the spectrum or bandpass.
Methods
__call__(wavelengths)Sample the spectrum or bandpass.
avgwave([wavelengths])Calculate the average wavelength.
barlam([wavelengths])Calculate mean log wavelength.
extinction_curve(ebv[, wavelengths])Generate extinction curve.
force_extrapolation()Force the underlying model to extrapolate.
from_extinction_model(modelname, **kwargs)from_file(filename, **kwargs)Create a reddening law from file.
from_spectrum1d(spec[, keep_neg])Create a spectrum from
specutils.Spectrum1Dobject.from_vectors(waves, flux[, meta, wave_unit])Create a
Passbanddirectly from from array-like.integrate([wavelengths, integration_type])Perform integration.
pivot([wavelengths])Calculate pivot wavelength.
plot([wavelengths])Plot the spectrum.
remove()Remove the file.
taper([wavelengths])Taper the spectrum or bandpass.
to_fits(filename[, wavelengths])Write the reddening law to a FITS file.
to_spectrum1d([wavelengths])Create a
specutils.Spectrum1Dobject from spectrum.from_curve_name
from_modelclass
- DEFAULT_CURVES = {'calzetti': 'calzetti/starburst', 'mw_dense': 'cardelli/milkyway_dense', 'mw_diffuse': 'cardelli/milkyway_diffuse'}#
- classmethod from_file(filename: pathlib.Path | str, **kwargs)#
Create a reddening law from file.
If filename has ‘fits’ or ‘fit’ suffix, it is read as FITS. Otherwise, it is read as ASCII.
- Parameters:
- filenamestr
Reddening law filename.
- kwargsdict
Keywords acceptable by
read_fits_spec()(if FITS) orread_ascii_spec()(if ASCII).
- Returns:
- redlaw
ReddeningLaw Empirical reddening law.
- redlaw
- from_modelclass(modelclass)#
- classmethod from_vectors(waves, flux, meta: dict | None = None, wave_unit: Unit = Unit('Angstrom'))#
Create a
Passbanddirectly from from array-like.- Parameters:
- waves: list-like
- flux: list-like
- meta: dictionary containing the metadata
- wave_unit: u.Quantity, defaulted to angstroms
- flux_unit: u.Quantiy, defaulted to FLAM
- Returns:
- Passband
- class spextra.spextra.Passband(filter_name=None, modelclass=None, **kwargs)#
Bases:
SpectralElement,FilterContainerClass to handle astronomical filters.
TODO: Implement proper __add__, __sub__, __mul__, etc
- Attributes:
datafileName and extension of the file.
descriptionDescription or comment of the file as defined in the library.
filenameDeprecated feature.
filter_commentDeprecated feature.
filter_nameName of the filter.
is_in_libraryReturn True if file is part of the parent library.
- library
modelModel of the spectrum/bandpass.
nameDeprecated feature.
pathPath to the cached file.
warningsDictionary of warning key-value pairs related to spectrum/bandpass.
waverangeRange of
waveset.wavesetOptimal wavelengths for sampling the spectrum or bandpass.
Methods
__call__(wavelengths)Sample the spectrum or bandpass.
avgwave([wavelengths])Calculate the average wavelength.
barlam([wavelengths])Calculate mean log wavelength.
check_overlap(other[, wavelengths, threshold])Check for wavelength overlap between two spectra.
efficiency([wavelengths])Calculate dimensionless efficiency.
emflx(area[, wavelengths])Calculate equivalent monochromatic flux.
equivwidth(**kwargs)Calculate bandpass equivalent width.
force_extrapolation()Force the underlying model to extrapolate.
from_file(filename, **kwargs)Create a
Passbandfrom a file.from_filter(filtername, **kwargs)from_filter_name(filter_name)from_modelclass(modelclass, **kwargs)from_spectrum1d(spec[, keep_neg])Create a spectrum from
specutils.Spectrum1Dobject.from_vectors(waves, trans[, meta, wave_unit])Create a
Passbanddirectly from from array-like.fwhm(**kwargs)Calculate FWHM of equivalent gaussian.
gaussian(center, fwhm, peak, **kwargs)Create a
Passbandwith a gaussian shape with given user parameters.integrate([wavelengths, integration_type])Perform integration.
photbw([wavelengths, threshold])Calculate the bandpass RMS width as in IRAF SYNPHOT.
pivot([wavelengths])Calculate pivot wavelength.
plot([wavelengths])Plot the spectrum.
rectwidth([wavelengths])Calculate bandpass rectangular width.
remove()Remove the file.
rmswidth([wavelengths, threshold])Calculate the bandpass RMS width.
square(wmin, wmax, transmission)Create a
Passbandwith a rectangular shape.taper([wavelengths])Taper the spectrum or bandpass.
tlambda(**kwargs)Calculate throughput at bandpass average wavelength.
to_fits(filename[, wavelengths])Write the bandpass to a FITS file.
to_spectrum1d([wavelengths])Create a
specutils.Spectrum1Dobject from spectrum.tpeak([wavelengths])Calculate peak bandpass throughput.
unit_response(area[, wavelengths])Calculate unit response of this bandpass.
wpeak([wavelengths])Calculate wavelength at peak throughput.
- DEFAULT_FILTERS = {'B': 'etc/B', 'BrGamma': 'Gemini/NIRI.BrG-G0218', 'F105W': 'HST/WFC3_IR.F105W', 'F110W': 'HST/WFC3_IR.F110W', 'F125W': 'HST/WFC3_IR.F125W', 'F140W': 'HST/WFC3_IR.F140W', 'F160W': 'HST/WFC3_IR.F160W', 'F435W': 'HST/ACS_WFC.F435W', 'F475W': 'HST/ACS_WFC.F475W', 'F606W': 'HST/ACS_WFC.F606W', 'F775W': 'HST/ACS_WFC.F775W', 'F814W': 'HST/ACS_WFC.F814W', 'F850LP': 'HST/ACS_WFC.F850LP', 'FUV': 'GALEX/GALEX.FUV', 'G': 'GAIA/GAIAO.G', 'H': 'etc/H', 'HAlpha': 'Gemini/GMOS-N.Ha', 'I': 'etc/I', 'J': 'etc/J', 'K': 'etc/K', 'Ks': '2MASS/2MASS.Ks', 'L': 'etc/L', 'M': 'etc/M', 'N': 'etc/N', 'NUV': 'GALEX/GALEX.NUV', 'PaBeta': 'Gemini/NIRI.PaBeta-G0221', 'Q': 'etc/Q', 'R': 'etc/R', 'U': 'etc/U', 'V': 'etc/V', 'W1': 'WISE/WISE.W1', 'W2': 'WISE/WISE.W2', 'W3': 'WISE/WISE.W3', 'W4': 'WISE/WISE.W4', 'Y': 'etc/Y', 'Z': 'etc/Z', 'ch1': 'Spitzer/IRAC.I1', 'ch2': 'Spitzer/IRAC.I2', 'ch3': 'Spitzer/IRAC.I3', 'ch4': 'Spitzer/IRAC.I4', 'g': 'SLOAN/SDSS.g', 'i': 'SLOAN/SDSS.i', 'r': 'SLOAN/SDSS.r', 'u': 'SLOAN/SDSS.u', 'z': 'SLOAN/SDSS.z'}#
- classmethod from_file(filename: pathlib.Path | str, **kwargs)#
Create a
Passbandfrom a file.- Parameters:
- filenameTYPE
DESCRIPTION.
- Returns:
- New
Passbandinstance.
- New
- from_modelclass(modelclass, **kwargs)#
- classmethod from_vectors(waves, trans, meta: dict | None = None, wave_unit: Unit = Unit('Angstrom'))#
Create a
Passbanddirectly from from array-like.- Parameters:
- waves: list-like
- trans: list-like
- meta: dictionary containing the metadata
- wave_unit: u.Quantity, defaulted to angstroms
- Returns:
- New
Passbandinstance.
- New
- class spextra.spextra.Spextrum(template_name=None, modelclass=None, **kwargs)#
Bases:
SourceSpectrum,SpectrumContainerClass to handle spectra.
This class download, load, stores and manipulates the spectra.
This class can be initialized with a remote file which will be downloaded from the database or with a
synphot.BaseSpectrumorSourceSpectrum.- Parameters:
- template_nameName of the template to download with format
- library/template e.g. “kc96/s0”
- modelclassSourceSpectrum or BaseSpectrum
- Attributes:
datafileName and extension of the file.
descriptionDescription or comment of the file as defined in the library.
filenameDeprecated feature.
is_in_libraryReturn True if file is part of the parent library.
- library
modelModel of the spectrum with given redshift.
nameDeprecated feature.
pathPath to the cached file.
templateName of the spectrum template.
template_commentDeprecated feature.
template_nameDeprecated feature.
warningsDictionary of warning key-value pairs related to spectrum/bandpass.
- wave_max
- wave_min
waverangeRange of
waveset.wavesetOptimal wavelengths for sampling the spectrum or bandpass.
zRedshift of the source spectrum.
z_typeRedshift behavior.
Methods
__call__(wavelengths[, flux_unit])Sample the spectrum.
add_abs_lines(center, ew, fwhm)Add an absorption line to a spectrum.
add_emi_lines(center, fwhm, flux)Add emission lines to an
Spextrum.add_noise(wmin, wmax)Return spectrum with given S/N in the specified wavelength range.
avgwave([wavelengths])Calculate the average wavelength.
barlam([wavelengths])Calculate mean log wavelength.
black_body_spectrum([temperature, ...])Produce a blackbody spectrum for a given temperature.
cut(wave_min, wave_max)Cut the spectrum between wmin and wmax.
deredden(curve_name[, Av, Ebv, Rv])De-redden a spectrum.
emission_line_spectrum(center, fwhm, flux[, ...])Create a emission line spextrum superimpossed to a faint continuum.
flat_spectrum([amplitude, waves])Create a flat spectrum in the preferred system scaled to a magnitude.
force_extrapolation()Force the underlying model to extrapolate.
from_arrays(waves, flux[, meta, wave_unit, ...])Create a
Passbanddirectly from from an array-like.from_file(filename, **kwargs)Call
synphot.SourceSpectrum.from_file()method.from_spectrum1d(spec[, keep_neg])Create a spectrum from
specutils.Spectrum1Dobject.from_vega(**kwargs)Load Vega spectrum.
get_flux([wmin, wmax, filter_curve, flux_unit])Return the flux within a passband.
get_magnitude([filter_curve, system_name])Obtain the magnitude in filter for a user specified photometric system.
integrate([wavelengths, integration_type])Perform integration.
logrebin()TODO: Estimate optimal rebinning factors here.
normalize(renorm_val[, band, wavelengths, ...])Renormalize the spectrum to the given Quantity and band.
photons_in_range([wmin, wmax, area, ...])Return the number of photons between wave_min and wave_max.
pivot([wavelengths])Calculate pivot wavelength.
plot([wavelengths, flux_unit, area, vegaspec])Plot the spectrum.
powerlaw([alpha, x_0, amplitude, ...])Return a power law spectrum.
rebin_spectra(new_waves)Rebin a synphot spectra to a new wavelength grid conserving flux.
redden(curve_name[, Ebv, Av, Rv])Attenuate a spectrum with a extinction curve normalized to a E(B-V).
redshift([z, vel])Red- or blueshift a spectrum.
remove()Remove the file.
scale_to_magnitude(amplitude[, filter_curve])Scale a Spectrum to a value in a filter.
smooth(sigma)Smooth the Spectrum with a Gaussian Kernel.
taper([wavelengths])Taper the spectrum or bandpass.
to_fits(filename[, wavelengths, flux_unit, ...])Write the spectrum to a FITS file.
to_spectrum1d([wavelengths])Create a
specutils.Spectrum1Dobject from spectrum.emission_line_spectra
from_modelclass
from_template_name
- DEFAULT_SPECTRA = {'sirus': 'ref/sirius', 'sun': 'ref/sunHR', 'vega': 'ref/vega'}#
- add_abs_lines(center, ew, fwhm)#
Add an absorption line to a spectrum.
With center, fwhm and equivalent width specified by the user. It also supports emission lines if
ewis negative.TODO: accept different profiles (Lorentz1D, Voigt1D, etc)
- Parameters:
- center: float, list, np.ndarray, u.Quantity
The center of the line
- fwhm: float, list, np.ndarray, u.Quantity
The FWHM of the line
- ew: float, list, np.ndarray, u.Quantity
The Equivalent Width of the line
- Returns:
- Spextrum
- add_emi_lines(center, fwhm, flux)#
Add emission lines to an
Spextrum.TODO: accept different profiles (Lorentz1D, Voigt1D, etc)
- Parameters:
- center: float, list, np.ndarray, u.Quantity
The center of the line
- fwhm: float, list, np.ndarray, u.Quantity
The FWHM of the line
- flux: float, list, np.ndarray, u.Quantity
The Equivalent Width of the line
- Returns:
- Spextrum
- add_noise(wmin: Quantity, wmax: Quantity)#
Return spectrum with given S/N in the specified wavelength range.
- classmethod black_body_spectrum(temperature: ~astropy.units.quantity.Quantity = <Quantity 9500. K>, amplitude: ~astropy.units.quantity.Quantity = <Magnitude 0. mag(AB)>, filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None, waves: ~typing.Optional[~astropy.units.quantity.Quantity] = None)#
Produce a blackbody spectrum for a given temperature.
And scale it to a magnitude in a filter.
- Parameters:
- temperature: the temperature in Kelvin degrees
- amplitude: ``astropy.Quantity``, float
The value that the spectrum should have in the given filter. Acceptable astropy quantities are:
u.mag : Vega magnitudes
u.ABmag : AB magnitudes
u.STmag : HST magnitudes
u.Jy : Jansky per filter bandpass
Additionally the
FLAMandFNUunits fromsynphot.unitscan be used when passing the quantity foramplitude.- filter_curvestr
Name of a filter from
a generic filter name (see
FILTER_DEFAULTS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
a filename with the filter file
a
Passbandorsynphot.SpectralElementobject
- Returns:
- a scaled black-body spectrum
- cut(wave_min, wave_max)#
Cut the spectrum between wmin and wmax.
- Parameters:
- wave_min: float, u.Quantity,
- wave_max: float, u.Quantity,
- Returns:
- spexSpextrum
New
Spextruminstance.
- deredden(curve_name: str, Av: float | None = None, Ebv: float = 0.0, Rv: float = 3.1)#
De-redden a spectrum.
- Parameters:
- curve_name: str, name of the extinction curve
- Av: float, Av parameter
- Ebv: float, E(B-V) color excess
- Returns:
- spexSpextrum
New attenuated
Spextruminstance.
- classmethod emission_line_spectra(*args, **kwargs)#
- classmethod emission_line_spectrum(center: ~astropy.units.quantity.Quantity, fwhm: ~astropy.units.quantity.Quantity, flux, amplitude: ~astropy.units.quantity.Quantity = <Magnitude 40. mag(AB)>, waves: ~typing.Optional[~astropy.units.quantity.Quantity] = None)#
Create a emission line spextrum superimpossed to a faint continuum.
- Parameters:
- center
- fwhm
- flux
- amplitude
- waves
- Returns:
- spexSpextrum
New
Spextruminstance.
- classmethod flat_spectrum(amplitude: ~astropy.units.quantity.Quantity = <Magnitude 0. mag(AB)>, waves: ~typing.Optional[~astropy.units.quantity.Quantity] = None)#
Create a flat spectrum in the preferred system scaled to a magnitude.
Defaults to a zero magnitude spectrum.
- Parameters:
- amplitude: float, u.Quantity
amplitude/magnitude of the reference spectrum, default=0 default is u.ABmag for vega use u.mag
- waves: The waveset of the reference spectrum if not Vega
if not provided they will be created at a resolution of R~800
- Returns:
- spexSpextrum
New
Spextruminstance.
- classmethod from_arrays(waves, flux, meta: dict | None = None, wave_unit: Unit = Unit('Angstrom'), flux_unit: Unit = Unit('FLAM'))#
Create a
Passbanddirectly from from an array-like.- Parameters:
- waves: array-like
- flux: array-like
- meta: dictionary containing the metadata
- wave_unit: u.Quantity, defaulted to angstroms
- flux_unit: u.Quantiy, defaulted to FLAM
- Returns:
- Passband
- classmethod from_file(filename: pathlib.Path | str, **kwargs)#
Call
synphot.SourceSpectrum.from_file()method.- Parameters:
- filename
- kwargs
- Returns:
- spexSpextrum
New
Spextruminstance.
- from_modelclass(modelclass, **kwargs)#
- get_flux(wmin=None, wmax=None, filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None, flux_unit: Unit = Unit('FLAM'))#
Return the flux within a passband.
- Parameters:
- wminfloat, u.Quantity
minimum wavelength
- wmaxfloat, u.Quantity
maximum wavelength
- filter_curvestr
Name of a filter from
a generic filter name (see
DEFAULT_FILTERS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
the path to the file containing the filter (see
Passband)a
Passbandorsynphot.SpectralElementobject
- flux_unit: synphot.units, u.Quantity
- Returns:
- flux
- get_magnitude(filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None, system_name: str = 'AB')#
Obtain the magnitude in filter for a user specified photometric system.
- Parameters:
- filter_curvestr
Name of a filter from
a generic filter name (see
DEFAULT_FILTERS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
the path to the file containing the filter (see
Passband)a
Passbandorsynphot.SpectralElementobject
- system_name: str
The photometric system Vega, AB or ST
- Returns:
- spectruma Spextrum
Input spectrum scaled to the given amplitude in the given filter.
- logrebin()#
TODO: Estimate optimal rebinning factors here. Returns ——- a Spextrum with a log rebinned in wavelength
- photons_in_range(wmin=None, wmax=None, area=<Quantity 1. cm2>, filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None)#
Return the number of photons between wave_min and wave_max.
Or within a bandpass (filter).
- Parameters:
- wmin
[Angstrom]
- wmax
[Angstrom]
- areau.Quantity
[cm2]
- filter_curvestr
Name of a filter from
a generic filter name (see
DEFAULT_FILTERS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
the path to the file containing the filter (see
Passband)a
Passbandorsynphot.SpectralElementobject
- Returns:
- countsu.Quantity array
- classmethod powerlaw(alpha=1, x_0: ~astropy.units.quantity.Quantity = <Quantity 5000. Angstrom>, amplitude: ~astropy.units.quantity.Quantity = <Magnitude 0. mag(AB)>, filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None, waves: ~typing.Optional[~astropy.units.quantity.Quantity] = None)#
Return a power law spectrum.
F(lambda) ~ lambda^alpha scaled to a magnitude (amplitude) in a particular band.
- Parameters:
- alphaThe spectral slope
- x_0float, u.Quantity
Pivot wavelength
- amplitudefloat, u.Quantity
normalize the spectrum to that quantity
- filter_curvestr
Name of a filter from
a generic filter name (see
FILTER_DEFAULTS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
a filename with the filter file
a
Passbandorsynphot.SpectralElementobject
- Returns:
- spexSpextrum
New
Spextruminstance.
- rebin_spectra(new_waves: Quantity)#
Rebin a synphot spectra to a new wavelength grid conserving flux.
Grid does not need to be linear and can be at higher or lower resolution.
- Parameters:
- new_waves: an array of the output wavelenghts in Angstroms but other
- units can be specified.
- Returns:
- spexSpextrum
New rebinned
Spextruminstance.
- redden(curve_name: str, Ebv: float = 0.0, Av: float | None = None, Rv: float = 3.1)#
Attenuate a spectrum with a extinction curve normalized to a E(B-V).
- Parameters:
- curve_name: str, name of the extinction curve
- Av: float, Av parameter
- Ebv: float, E(B-V) color excess
- Returns:
- spexSpextrum
New attenuated
Spextruminstance.
- redshift(z=0, vel=0)#
Red- or blueshift a spectrum.
- Parameters:
- zTYPE, optional
Redshift. The default is 0.
- velTYPE, optional
Radial velocity. If no unit are present it is assumed to be in m/s. The default is 0.
- Returns:
- spexSpextrum
New
Spextruminstance.
- Raises:
- ValueError
Raised if
zorvelare unphysical.
- scale_to_magnitude(amplitude: Quantity, filter_curve: str | spextra.spextra.Passband | synphot.spectrum.SpectralElement | None = None)#
Scale a Spectrum to a value in a filter.
Copied from scopesim.effects.ter_curves.scale_spectrum with slight modifications.
- Parameters:
- amplitude
astropy.Quantity, float The value that the spectrum should have in the given filter. Acceptable astropy quantities are:
u.mag : Vega magnitudes
u.ABmag : AB magnitudes
u.STmag : HST magnitudes
u.Jy : Jansky per filter bandpass
Additionally the
FLAMandFNUunits fromsynphot.unitscan be used when passing the quantity foramplitude:- filter_curvestr
Name of a filter from
a generic filter name (see
DEFAULT_FILTERS)a spanish-vo filter service ref. (e.g.
"Paranal/HAWKI.Ks")a filter in the spextra database
the path to a filename containing the curve (see
Passband)a
Passbandorsynphot.SpectralElementinstance
- filter_file: str
A file with a transmission curve
- amplitude
- Returns:
- spectruma Spectrum
Input spectrum scaled to the given amplitude in the given filter
- smooth(sigma)#
Smooth the Spectrum with a Gaussian Kernel.
Expressed in km/s (or other velocity unit).
The spectra is first log-rebinned so it has a constant velocity spacing and after that is smoothed with a gaussian kernel.
- Parameters:
- sigma: u.Quantity, width of the Kernel in
- Returns:
- smoothed spextrum
- property wave_max#
- property wave_min#
- spextra.spextra.get_vega_spectrum()#
Retrieve the Vega spectrum from the database.
Notes
- To access wavelength and fluxes use::
spex = get_vega_spectrum() waves, fluxes = spex.waveset, spex(spex.waveset)