spextra.spextra module#

speXtra: A python tool to manage and manipulate astronomical spectra.

class spextra.spextra.ExtinctionCurve(curve_name=None, modelclass=None)#

Bases: ReddeningLaw, ExtCurveContainer

Class to handle extinction curves.

TODO: Implement proper __add__, __sub__, __mul__, etc

Attributes:
curve_comment

Deprecated feature.

curve_name

Name of the extinction curve.

datafile

Name and extension of the file.

description

Description or comment of the file as defined in the library.

filename

Deprecated feature.

is_in_library

Return True if file is part of the parent library.

library
model

Model of the spectrum/bandpass.

name

Deprecated feature.

path

Path to the cached file.

warnings

Dictionary of warning key-value pairs related to spectrum/bandpass.

waverange

Range of waveset.

waveset

Optimal 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)

Load pre-defined extinction model.

from_file(filename, **kwargs)

Create a reddening law from file.

from_spectrum1d(spec[, keep_neg])

Create a spectrum from specutils.Spectrum1D object.

from_vectors(waves, flux[, meta, wave_unit])

Create a Passband directly 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.Spectrum1D object from spectrum.

from_curve_name

from_modelclass

DEFAULT_CURVES = {'calzetti': 'calzetti/starburst', 'mw_dense': 'cardelli/milkyway_dense', 'mw_diffuse': 'cardelli/milkyway_diffuse'}#
from_curve_name(curve_name)#
classmethod from_file(filename, **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) or read_ascii_spec() (if ASCII).

Returns:
redlawReddeningLaw

Empirical reddening law.

from_modelclass(modelclass)#
classmethod from_vectors(waves, flux, meta=None, wave_unit=Unit('Angstrom'))#

Create a Passband directly 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, FilterContainer

Class to handle astronomical filters.

TODO: Implement proper __add__, __sub__, __mul__, etc

Attributes:
datafile

Name and extension of the file.

description

Description or comment of the file as defined in the library.

filename

Deprecated feature.

filter_comment

Deprecated feature.

filter_name

Name of the filter.

is_in_library

Return True if file is part of the parent library.

library
model

Model of the spectrum/bandpass.

name

Deprecated feature.

path

Path to the cached file.

warnings

Dictionary of warning key-value pairs related to spectrum/bandpass.

waverange

Range of waveset.

waveset

Optimal 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 Passband from a file.

from_filter(filtername, **kwargs)

Load pre-defined filter bandpass.

from_filter_name(filter_name)

from_modelclass(modelclass, **kwargs)

from_spectrum1d(spec[, keep_neg])

Create a spectrum from specutils.Spectrum1D object.

from_vectors(waves, trans[, meta, wave_unit])

Create a Passband directly from from array-like.

fwhm(**kwargs)

Calculate FWHM of equivalent gaussian.

gaussian(center, fwhm, peak, **kwargs)

Create a Passband with 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 Passband with 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.Spectrum1D object 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, **kwargs)#

Create a Passband from a file.

Parameters:
filenameTYPE

DESCRIPTION.

Returns:
New Passband instance.
from_filter_name(filter_name)#
from_modelclass(modelclass, **kwargs)#
classmethod from_vectors(waves, trans, meta=None, wave_unit=Unit('Angstrom'))#

Create a Passband directly 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 Passband instance.
classmethod gaussian(center, fwhm, peak, **kwargs)#

Create a Passband with a gaussian shape with given user parameters.

Parameters:
centerTYPE

DESCRIPTION.

fwhmTYPE

DESCRIPTION.

peakTYPE

DESCRIPTION.

Returns:
New Passband instance.
classmethod square(wmin, wmax, transmission)#

Create a Passband with a rectangular shape.

Parameters:
wminTYPE

DESCRIPTION.

wmaxTYPE

DESCRIPTION.

transmissionTYPE

DESCRIPTION.

Returns:
New Passband instance.
class spextra.spextra.Spextrum(template_name=None, modelclass=None, **kwargs)#

Bases: SourceSpectrum, SpectrumContainer

Class 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.BaseSpectrum or SourceSpectrum.

Parameters:
template_nameName of the template to download with format
library/template e.g. “kc96/s0”
modelclassSourceSpectrum or BaseSpectrum
Attributes:
datafile

Name and extension of the file.

description

Description or comment of the file as defined in the library.

filename

Deprecated feature.

is_in_library

Return True if file is part of the parent library.

library
model

Model of the spectrum with given redshift.

name

Deprecated feature.

path

Path to the cached file.

template

Name of the spectrum template.

template_comment

Deprecated feature.

template_name

Deprecated feature.

warnings

Dictionary of warning key-value pairs related to spectrum/bandpass.

wave_max
wave_min
waverange

Range of waveset.

waveset

Optimal wavelengths for sampling the spectrum or bandpass.

z

Redshift of the source spectrum.

z_type

Redshift 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_spectra(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 Passband directly from from an array-like.

from_file(filename, **kwargs)

Wrapper for synphot.SourceSpectrum.from_file() method.

from_spectrum1d(spec[, keep_neg])

Create a spectrum from specutils.Spectrum1D object.

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.Spectrum1D object from spectrum.

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 ew is 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, wmax)#

Return spectrum with given S/N in the specified wavelength range.

classmethod black_body_spectrum(temperature=9500, amplitude=0, filter_curve=None, waves=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 FLAM and FNU units from synphot.units can be used when passing the quantity for amplitude.

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 Passband or synphot.SpectralElement object

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 Spextrum instance.

deredden(curve_name, Av=None, Ebv=0, Rv=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 Spextrum instance.

classmethod emission_line_spectra(center, fwhm, flux, amplitude=<Magnitude 40. mag(AB)>, waves=None)#

Create a emission line spextrum superimpossed to a faint continuum.

Parameters:
center
fwhm
flux
amplitude
waves
Returns:
spexSpextrum

New Spextrum instance.

classmethod flat_spectrum(amplitude=0, waves=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 Spextrum instance.

classmethod from_arrays(waves, flux, meta=None, wave_unit=Unit('Angstrom'), flux_unit=Unit('FLAM'))#

Create a Passband directly 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, **kwargs)#

Wrapper for synphot.SourceSpectrum.from_file() method.

Parameters:
filename
kwargs
Returns:
spexSpextrum

New Spextrum instance.

from_modelclass(modelclass, **kwargs)#
from_template_name(template_name, **kwargs)#
get_flux(wmin=None, wmax=None, filter_curve=None, flux_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 Passband or synphot.SpectralElement object

flux_unit: synphot.units, u.Quantity
Returns:
flux
get_magnitude(filter_curve=None, system_name='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 Passband or synphot.SpectralElement object

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=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 Passband or synphot.SpectralElement object

Returns:
countsu.Quantity array
classmethod powerlaw(alpha=1, x_0=5000, amplitude=0, filter_curve=None, waves=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 Passband or synphot.SpectralElement object

Returns:
spexSpextrum

New Spextrum instance.

rebin_spectra(new_waves)#

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 Spextrum instance.

redden(curve_name, Ebv=0, Av=None, Rv=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 Spextrum instance.

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 Spextrum instance.

Raises:
ValueError

Raised if z or vel are unphysical.

scale_to_magnitude(amplitude, filter_curve=None)#

Scale a Spectrum to a value in a filter.

Copied from scopesim.effects.ter_curves.scale_spectrum with slight modifications.

Parameters:
amplitudeastropy.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 FLAM and FNU units from synphot.units can be used when passing the quantity for amplitude:

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 Passband or synphot.SpectralElement instance

filter_file: str

A file with a transmission curve

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)