API¶
SPLAT Classes¶
Spectrum¶
- class splat.core.Spectrum(*args, **kwargs)¶
- Description:
Class for containing spectral and source data from SpeX Prism Library. This is a temporary structure until astropy.specutils is completed
Optional Inputs:
- Parameters:
ismodel -- Set to True to specify spectrum as a model (default = False)
wave_label -- label of wavelength (default = 'Wavelength')
wave_unit -- unit in which wavelength is measured (default = u.micron)
wave_unit_label -- label of the unit of wavelength (default = 'micron')
flux_label -- label of flux density (default = 'F_lambda')
flux_unit -- unit in which flux density is measured (default = u.erg/(u.cm**2 * u.s * u.micron)
flux_unit_label -- label of the unit of flux density (default = 'erg cm^-2 s^-1 micron^-1')
resolution -- Resolution of spectrum (default = median lam/lam step/2.)
slitpixelwidth -- Width of the slit measured in subpixel values (default = 3.33)
slitwidth -- Actual width of the slit, measured in arcseconds. Default value is the
slitpixelwidth
multiplied an assumed (for SpeX) spectrograph pixel scale of 0.15 arcsecondsheader -- header info of the spectrum (default = Table())
filename -- a string containing the spectrum's filename (default = '')
file -- same as filename (default = '')
idkey -- spectrum key of the desired spectrum (default = False)
- Example:
>>> import splat >>> sp = splat.Spectrum(filename='myspectrum.fits') # read in a file >>> sp = splat.Spectrum('myspectrum.fits') # same >>> sp = splat.Spectrum(10002) # read in spectrum with data_key = 10002 >>> sp = splat.Spectrum(wave=wavearray,flux=fluxarray) # create objects with wavelength & flux arrays
Methods
addNoise
([snr])- Purpose:
broaden
(vbroad[, kern, epsilon, method, verbose])- Purpose:
clean
([action, replace_value])- Purpose:
computeSN
([rng, statistic, offset])- Purpose:
Compute a representative S/N value as the median value of S/N among the top 50% of flux values
copy
()- Purpose:
Make a copy of a Spectrum object
export
([filename, clobber, csv, tab, ...])- Purpose:
filterMag
(filt, **kwargs)- Purpose:
fluxCalibrate
(filt, mag, **kwargs)- Purpose:
Flux calibrates a spectrum given a filter and a magnitude. The filter must be one of those listed in splat.FILTERS.keys(). It is possible to specifically set the magnitude to be absolute (by default it is apparent). This function changes the Spectrum object's flux, noise and variance arrays.
fluxMax
([wrange, maskTelluric])- Purpose:
Reports the maximum flux of a Spectrum object ignoring nan's.
info
()- Parameters:
mapTo
(other[, overhang])Purpose: maps spectrum onto the wavelength scale of another spectrum
maskFlux
([mask, replace_noise, ...])- Parameters:
maskWave
(rng[, apply])- Parameters:
normalize
(*args, **kwargs)- Purpose:
plot
(**kwargs)- Purpose:
redden
([av, rv, normalize, a, n])- Purpose:
redshift
(z)- Purpose:
Shifts the wavelength scale by a given (positive) redshift. A negative redshift is interpreted as shifting back to the restframe.
remove
(mask[, others])- Purpose:
replace
(mask, replace_value[, ...])- Purpose:
res
([npixel, method])- Purpose:
reset
()- Purpose:
rotate
(vsini[, epsilon, verbose])- Purpose:
rvShift
(rv)- Purpose:
Shifts the wavelength scale by a given radial velocity. This routine changes the underlying Spectrum object.
sample
(rng[, method, verbose])- Purpose:
save
(*args, **kwargs)- Purpose:
Exports a Spectrum object to either a fits or ascii file, depending on file extension given. If no filename is explicitly given, the Spectrum.filename attribute is used. If the filename does not include the full path, the file is saved in the current directory.
scale
(factor[, noiseonly])- Purpose:
setNoise
([rng, floor])- Purpose:
- Purpose:
smooth
(smv[, resolution, slitwidth])- Purpose:
- Purpose:
toBrightnessTemperature
([limbdarkening, ...])- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
toFlam
()- Purpose:
toFluxUnit
(flux_unit)- Purpose:
toFnu
()- Purpose:
toInstrument
(instrument[, pixel_resolution])- Purpose:
toMicron
()- Purpose:
toSED
()- Purpose:
toSurface
(radius)- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
toWaveUnit
(wave_unit)- Purpose:
toWavelengths
(wave[, force, verbose])- Purpose:
trim
(rng, **kwargs)- Purpose:
updateSourceInfo
([verbose, radius])- Purpose:
- Purpose:
Return the wavelength range of the current Spectrum object.
cleanNoise
flamToFnu
fnuToFlam
toTemperature
- addNoise(snr=0.0)¶
- Purpose:
Adds noise to a spectrum based on either the current uncertainties scaled by optional input S/N
- Required Inputs:
None
- Optional Inputs:
snr: Signal-to-noise ratio to use to scale uncertainty spectrum (default = 0. => use existing S/N)
- Output:
None (spectrum object changed in place)
- Example:
>>> sp = splat.Spectrum(10001) >>> sp.addNoise(snr=10.) >>> sp.computeSN() 9.5702358777108234
- broaden(vbroad, kern=None, epsilon=0.6, method='rotation', verbose=False)¶
- Purpose:
Broadens a spectrum in velocity space using a line spread function (LSF) either based on rotation or gaussian. This routine changes the underlying Spectrum object.
- Required Inputs:
- param vbroad:
broadening width, nominally in km/s
- Optional Inputs:
- param method:
method of broadening, should be one of:
gaussian
: (default) Gaussian broadening, with vbroad equal to Gaussian sigmarotation
: rotational broadening using splat.lsfRotation()delta
: Delta function (no broadening)
- param kern:
input kernel, must be at least three elements wide (default = None)
- param epsilon:
epsilon parameter for limb darkening in rotational broadening (default = 0.6)
- param verbose:
provide extra feedback (default = False)
- Outputs:
None; Spectral flux is smoothed using the desired line spread function. No change is made to noise or other axes
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) >>> sp.broaden(30.,method='rotation') >>> sp.info() History: SPEX_PRISM spectrum successfully loaded Rotationally broadened spectrum by 30.0 km/s
- clean(action='remove', replace_value=0.0)¶
- Purpose:
Cleans a spectrum by either removing or replacing nan values
- Required Inputs:
None
- Optional Inputs:
- param action = 'remove':
specify as either 'remove' or 'replace'
- param replace_value = 0.:
for replace, what value to replace with
- Output:
Spectrum object is modified to have nan pixels "cleaned"
- Example:
>>> import splat,numpy >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.flux[0] = numpy.nan >>> sp.clean() >>> sp.remove(mask) >>> sp.showHistory() SPEX_PRISM spectrum successfully loaded Mask applied to remove 1 pixels
- computeSN(rng=[], statistic='median', offset=0.1)¶
- Purpose:
Compute a representative S/N value as the median value of S/N among the top 50% of flux values
- Output:
the S/N value
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.computeSN() 115.96374031163553
- copy()¶
- Purpose:
Make a copy of a Spectrum object
- export(filename='', clobber=True, csv=False, tab=True, delimiter='\t', save_header=True, save_noise=True, comment='#', file_type='', *args, **kwargs)¶
- Purpose:
Exports a Spectrum object to either a fits or ascii file, depending on file extension given. If no filename is explicitly given, the Spectrum.filename attribute is used. If the filename does not include the full path, the file is saved in the current directory. Spectrum.export and Spectrum.save() function in the same manner.
- Required Inputs:
None
- Optional Inputs:
- param filename:
String specifying the filename to save; filename can also be included as an argument; if not provided, Spectrum.filename is used; alternate keywords: file
- param clobber:
Set to True to overwrite file, or False to raise flag if file exists (default = True)
- param csv:
Set to True to write a CSV (comma-delimited) file (default = False)
- param tab:
Set to True to write a tab-delimited file (default = True)
- param delimiter:
character or string to specify as delimiter between columns (default = ' '); alternate keywords: sep
- param save_header:
set to True to add header to ascii files (default = True)
- param save_noise:
set to True to save the noise column (default = True)
- param comment:
use to specify comment character (default = '#')
- Output:
An ascii or fits file with the data and header
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.export('/Users/adam/myspectrum.txt') >>> from astropy.io import ascii >>> data = ascii.read('/Users/adam/myspectrum.txt',format='tab') >>> data <Table length=564> wavelength flux uncertainty float64 float64 float64 -------------- ----------------- ----------------- 0.645418405533 0.0 nan 0.647664904594 6.71920214475e-16 3.71175052033e-16 0.649897933006 1.26009925777e-15 3.85722895842e-16 0.652118623257 7.23781818374e-16 3.68178778862e-16 0.654327988625 1.94569566622e-15 3.21007116982e-16 ...
- filterMag(filt, **kwargs)¶
- Purpose:
Wrapper for filterMag() function in splat.photometry
Required Inputs:
filter: string specifiying the name of the filter
Optional Inputs:
See filterMag()
Outputs:
Returns tuple containing filter-based spectrophotometic magnitude and its uncertainty
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxCalibrate('2MASS J',15.0) >>> sp.filterMag(sp,'2MASS J') (15.002545668628173, 0.017635234089677564)
- fluxCalibrate(filt, mag, **kwargs)¶
- Purpose:
Flux calibrates a spectrum given a filter and a magnitude. The filter must be one of those listed in splat.FILTERS.keys(). It is possible to specifically set the magnitude to be absolute (by default it is apparent). This function changes the Spectrum object's flux, noise and variance arrays.
Required Inputs:
- Parameters:
filt -- string specifiying the name of the filter
mag -- number specifying the magnitude to scale to
Optional Inputs:
- Parameters:
absolute -- set to True to specify that the given magnitude is an absolute magnitude, which sets the
flux_label
keyword in the Spectrum object to 'Absolute Flux' (default = False)apparent -- set to True to specify that the given magnitude is an apparent magnitude, which sets the
flux_label
flag in the Spectrum object to 'Apparent Flux' (default = False)
Outputs:
None, Spectrum object is changed to a flux calibrated spectrum
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxCalibrate('2MASS J',15.0) >>> splat.filterMag(sp,'2MASS J') (15.002545668628173, 0.017635234089677564)
- fluxMax(wrange=[], maskTelluric=True, **kwargs)¶
- Purpose:
Reports the maximum flux of a Spectrum object ignoring nan's.
- Parameters:
maskTelluric (optional, default = True) -- masks telluric regions
- Output:
maximum flux (with units)
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.normalize() >>> sp.fluxMax() <Quantity 1.0 erg / (cm2 micron s)>
- info()¶
- Parameters:
- None
- mapTo(other, overhang=0.1)¶
Purpose: maps spectrum onto the wavelength scale of another spectrum
- maskFlux(mask=[], replace_noise=True, replace_value=nan, others=[])¶
- Parameters:
- mask = []list or numpy.ndarray [optional]
array with same length as Spectrum object wavelength array that specifies pixels to be masked array values can be floating point, int, or bool, with 1 = True (mask) and 0 = False (don't mask)
- replace_noise = Truebool [optional]
If True, apply the mask to the uncertainty array
- replace_value = numpy.nanfloat [optional]
Value with which to replace masked elements of flux
- others = []]list [optional]
Other elements of the Spectrum object to apply mask (e.g., wave, flags, mask, etc.) These elements should be present and must be the same length as mask
- maskWave(rng, apply=True, **kwargs)¶
- Parameters:
- rnglist of numpy.ndarray
2-element array that specifies the minimum and maximum wavelength range to mask elements can be unitted values or pure numbers (interpretted to be same units as spectrum)
- apply = Truebool [optional]
If True, apply the mask using maskFlux()
- normalize(*args, **kwargs)¶
- Purpose:
Normalize a spectrum to a maximum value of 1 (in its current units) either at a particular wavelength or over a wavelength range
- Required Inputs:
None
- Optional Inputs:
- param wave_range:
choose the wavelength range to normalize; can be a list specifying minimum and maximum or a single wavelength (default = None); alternate keywords: wave_range, range
- Output:
None; spectrum is normalized
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.normalize() >>> sp.fluxMax() <Quantity 1.0 erg / (cm2 micron s)> >>> sp.normalize(waverange=[2.25,2.3]) >>> sp.fluxMax() <Quantity 1.591310977935791 erg / (cm2 micron s)>
- plot(**kwargs)¶
- Purpose:
calls the `plotSpectrum()`_ function, by default showing the noise spectrum and zeropoints. See the `plotSpectrum()`_ API listing for details.
- Output:
A plot of the Spectrum object
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.plot()
- redden(av=0.0, rv=3.1, normalize=False, a=10.0, n=1.33, **kwargs)¶
- Purpose:
Redden a spectrum based on an either Mie theory or a standard interstellar profile using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)
- Required Inputs:
None
- Optional Inputs:
- param av:
Magnitude of reddening A_V (default = 0.)
- param rv:
Normalized extinction parameter, R_V = A(V)/E(B-V) (default = 3.1
- param normalized:
Set to True to normalize reddening function (default = False)
- Outputs:
None; spectral flux is changed
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) # read in a source >>> spr = splat.redden(sp,av=5.,rv=3.2) # redden to equivalent of AV=5
- Note
This routine is still in beta form; only the CCM89 currently works
- redshift(z)¶
- Purpose:
Shifts the wavelength scale by a given (positive) redshift. A negative redshift is interpreted as shifting back to the restframe.
- Example:
>>> import splat >>> sp.redshift(0.56)
- remove(mask, others=[])¶
- Purpose:
Removes elements of wave, flux, noise specified by the True/False array
- Required Input:
- param mask:
Either a mask array (an array of booleans, ints, or floats, where True or 1 removes the element) or a 2-element array that defines the wavelegnth range to mask
- Optional Input:
- param others:
list of other attributes that mask should be applied to(e.g., 'pixel') (default = [])
- Output:
Spectrum object has the flagged pixels removed from wave, flux, noise arrays, and optional vectors
- Example:
>>> import splat, numpy >>> sp = splat.getSpectrum(lucky=True)[0] >>> num = splat.numberList('1-10,18,30-50') >>> mask = [not(p in num) for p in numpy.arange(len(sp.wave))] >>> sp.remove(mask) >>> sp.showHistory() SPEX_PRISM spectrum successfully loaded Mask applied to remove 32 pixels
- replace(mask, replace_value, replace_noise=True, replace_flux=True)¶
- Purpose:
Replaces flux and noise values using a mask and specified value
- Required Inputs:
- param mask:
Either a mask array (an array of booleans, ints, or floats, where True or 1 removes the element) or a 2-element array that defines the wavelength range to replace
- param replace_value:
value with which the masked elements should be replaced
- Optional Inputs:
- param replace_flux = True:
replace elements in the noise array
- param replace_noise = True:
replace elements in the flux array
- Output:
Spectrum object has the flagged pixels replaced in flux, noise arrays, and optional vectors
- Example:
>>> import splat, numpy >>> sp = splat.getSpectrum(lucky=True)[0] >>> num = splat.numberList('1-10,18,30-50') >>> mask = [not(p in num) for p in numpy.arange(len(sp.wave))] >>> sp.replace(mask,numpy.nan) >>> sp.showHistory() SPEX_PRISM spectrum successfully loaded Mask applied to replace 32 pixels with value nan
- res(npixel=1.0, method='median')¶
- Purpose:
Estimate the resolution of the data from the wavelength array
- Required Inputs:
None
- Optional Inputs:
- param:
npixel = 1: number of pixels per resolution element
- param:
method = 'median': what statistic to report back; can be mean, average, median, min, or max
- Outputs:
The resolution of the spectrum (single number)
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.resolution()
- reset()¶
- Purpose:
Restores a Spectrum to its original read-in state, removing scaling and smoothing.
- Required Inputs:
None
- Optional Inputs:
None
- Output:
Spectrum object is restored to original parameters
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxMax() <Quantity 4.561630292384622e-15 erg / (cm2 micron s)> >>> sp.normalize() >>> sp.fluxMax() <Quantity 0.9999999403953552 erg / (cm2 micron s)> >>> sp.reset() >>> sp.fluxMax() <Quantity 4.561630292384622e-15 erg / (cm2 micron s)>
- rotate(vsini, epsilon=0.6, verbose=False)¶
- Purpose:
Rotationally broaden the lines of a spectrum; a shortcut call to Spectrum.broaden()
- Required Inputs:
- param vsini:
Rotational velocity in km/s
- Optional Inputs:
- param epsilon:
epsilon parameter for limb darkening in rotational broadening (default = 0.6)
- param verbose:
provide extra feedback (default = False)
- Outputs:
None; Spectral flux is smoothed by rotational broadening
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) >>> sp.vsini(30.) >>> sp.info() History: SPEX_PRISM spectrum successfully loaded Rotationally broadened spectrum by 30.0 km/s
- rvShift(rv)¶
- Purpose:
Shifts the wavelength scale by a given radial velocity. This routine changes the underlying Spectrum object.
- Example:
>>> import splat >>> import astropy.units as u >>> sp.rvShift(15*u.km/u.s)
- sample(rng, method='median', verbose=False)¶
- Purpose:
Obtains a sample of spectrum over specified wavelength range
- Required Inputs:
- param range:
the range(s) over which the spectrum is sampled
a single 2-element array or array of 2-element arrays
- Optional Inputs:
None
- Example:
TBD
- save(*args, **kwargs)¶
- Purpose:
Exports a Spectrum object to either a fits or ascii file, depending on file extension given. If no filename is explicitly given, the Spectrum.filename attribute is used. If the filename does not include the full path, the file is saved in the current directory.
Spectrum.export() and Spectrum.save function in the same manner.
- scale(factor, noiseonly=False)¶
- Purpose:
Scales a Spectrum object's flux and noise values by a constant factor.
- Required Inputs:
- param factor:
A floating point number used to scale the Spectrum object
- Optional Inputs:
- param noiseonly = False:
scale only the noise and variance, useful when uncertainty is under/over estimated
- Output:
None; spectrum is scaled
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxMax() <Quantity 1.0577336634332284e-14 erg / (cm2 micron s)> >>> sp.computeSN() 124.5198 >>> sp.scale(1.e15) >>> sp.fluxMax() <Quantity 1.0577336549758911 erg / (cm2 micron s)> >>> sp.computeSN() 124.51981
- setNoise(rng=[], floor=0.0)¶
- Purpose:
Sets the noise and variance array of the spectrum based on rough counting statistics; this routine is useful if the input spectrum has no input noise array
- Required Inputs:
One of the following must be provided:
rng: 2-element list specifying the range
floor = 0.: floor of uncertainty in spectrum flux units
- Optional Inputs:
None
- Output:
Updates the noise and variance elements of Spectrum class
- Example:
>>> import splat, numpy >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.normalize() >>> sp.computeSN() # reports 25.9118 >>> sp.noise = [numpy.nan for n in sp.noise]*sp.noise.unit >>> sp.computeSN() # reports nan >>> sp.setNoise([floor=1.e-3) >>> sp.computeSN() # reports 25.5425
- showHistory()¶
- Purpose:
Report history of actions taken on a Spectrum object. This can also be retrieved by printing the attribute Spectrum.history
- Required Inputs:
None
- Optional Inputs:
None
- Output:
List of actions taken on spectrum
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.normalize() >>> sp.fluxCalibrate('2MASS J',15.0) >>> sp.showHistory() Spectrum successfully loaded Spectrum normalized Flux calibrated with 2MASS J filter to an apparent magnitude of 15.0
- smooth(smv, resolution=False, slitwidth=False, **kwargs)¶
- Purpose:
Smoothes a spectrum either by selecting a constant slit width (smooth in spectral dispersion space), pixel width (smooth in pixel space) or resolution (smooth in velocity space). One of these options must be selected for any smoothing to happen. Changes spectrum directly.
- Required Inputs:
None
- Optional Inputs:
- param method:
the type of smoothing window to use; see http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details (default = 'hamming')
- param resolution:
Constant resolution to smooth to; see _smoothToResolution() (default = None)
- param slitPixelWidth:
Number of pixels to smooth in pixel space; see _smoothToSlitPixelWidth() (default = None)
- param slitWidth:
Number of pixels to smooth in angular space; see _smoothToPixelWidth() (default = None)
- Output:
None: spectrum is smoothed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.smooth(resolution=30)
- toAngstrom()¶
- Purpose:
Converts wavelength to Angstrom
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.getSpectrum(lucky=True) >>> sp.wave.unit Unit("micron") >>> sp.toAngstrom() >>> sp.wave.unit Unit("Angstrom")
- toBrightnessTemperature(limbdarkening=False, limbdarkeningcoeff=0.7)¶
- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
- toFlam()¶
- Purpose:
Converts flux density to F_lambda in units of erg/s/cm^2/Hz. There is no change if the spectrum is already in F_lambda units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toFnu() >>> sp.flux.unit Unit("Jy") >>> sp.toFlam() >>> sp.flux.unit Unit("erg / (cm2 micron s)")
- toFluxUnit(flux_unit)¶
- Purpose:
Converts flux and noise arrays to given flux units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.Spectrum(file='somespectrum',wave_unit=u.Angstrom) >>> sp.flux.unit erg / (cm2 micron s) >>> sp.toFluxUnit(u.Watt/u.m/u.m) >>> sp.flux.unit W / m2 >>> sp.toFluxUnit(u.erg/u.s) >>> sp.flux.unit Warning! failed to convert flux unit from W / m2 to erg / s; no change made
- toFnu()¶
- Purpose:
Converts flux density F_nu in units of Jy. There is no change if the spectrum is already in F_nu units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toFnu() >>> sp.flux.unit Unit("Jy")
- toInstrument(instrument, pixel_resolution=3.0, **kwargs)¶
- Purpose:
Converts a spectrum to the parameters for a defined instrument
- Required Inputs:
- param instrument:
the name of an instrument, must be defined in splat.INSTRUMENTS
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
TBD
- toMicron()¶
- Purpose:
Converts wavelength to microns.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.Spectrum(file='somespectrum',wave_unit=u.Angstrom) >>> sp.wave.unit Unit("Angstrom") >>> sp.toMicron() >>> sp.wave.unit Unit("micron")
- toSED()¶
- Purpose:
Converts flux density in F_lambda to lambda x F_lambda with units of erg/s/cm^2.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toSED() >>> sp.flux.unit Unit("erg / (cm2 s)")
- toSurface(radius)¶
- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
Note
UNTESTED, NEED TO ADD IN UNCERTAINTIES
- toWaveUnit(wave_unit)¶
- Purpose:
Converts wavelength to specified units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.Spectrum(file='somespectrum',wave_unit=u.Angstrom) >>> print(sp.wave.unit) Angstrom >>> sp.toWaveUnit(u.micron) >>> print(sp.wave.unit) micron >>> sp.toWaveUnit(u.s) Warning! failed to convert wavelength unit from micron to s; no change made
- toWavelengths(wave, force=True, verbose=False)¶
- Purpose:
Maps a spectrum onto a new wavelength grid via interpolation or integral resampling
- Required Inputs:
- param wave:
wavelengths to map to
- Optional Inputs:
- param force = True:
proceed with conversion even if wavelength ranges are not perfectly in range
- param verbose = False:
provide verbose feedback
- Outputs:
None; Spectrum object is changed
- Example:
TBD
- trim(rng, **kwargs)¶
- Purpose:
Trims a spectrum to be within a certain wavelength range or set of ranges. Data outside of these ranges are excised from the wave, flux and noise arrays. The full spectrum can be restored with the reset() procedure.
- Required Inputs:
- param range:
the range(s) over which the spectrum is retained - a series of nested 2-element arrays
- Optional Inputs:
None
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.smoothfluxMax() <Quantity 1.0577336634332284e-14 erg / (cm2 micron s)> >>> sp.computeSN() 124.5198 >>> sp.scale(1.e15) >>> sp.fluxMax() <Quantity 1.0577336549758911 erg / (cm2 micron s)> >>> sp.computeSN() 124.51981
- updateSourceInfo(verbose=False, radius=<Quantity 10. arcsec>, **kwargs)¶
- Purpose:
Updates the source information for a spectrum object based on the SPLAT Source Database Uses either the spectrum object's or user supplied NAME, DESIGNATION, COORDINATE or RA & DEC If none of these are supplied, no search is done
- Required Inputs:
None
- Optional Inputs:
name: Name of source designation: designation of source in format Jhhmmss[.]ss±ddmmss[.]ss shortname: shortname desigation of source in format Jhhmm±ddmm coordinate: coordinate of object, in astropy SkyCoord format or transferable via properCoordinates() ra, dec: RA and Declination of source in degrees radius: search radius (default = 10 arcseconds) verbose: set to True to provide feedback
- Output:
Spectrum object will have the Source Library keywords added or updated
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.smoothfluxMax() <Quantity 1.0577336634332284e-14 erg / (cm2 micron s)> >>> sp.computeSN() 124.5198 >>> sp.scale(1.e15) >>> sp.fluxMax() <Quantity 1.0577336549758911 erg / (cm2 micron s)> >>> sp.computeSN() 124.51981
- waveRange()¶
- Purpose:
Return the wavelength range of the current Spectrum object.
- Output:
2-element array giving minimum and maximum of wavelength range
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.slitwidth [<Quantity 0.6447611451148987 micron>, <Quantity 2.5517737865448 micron>]
SPLAT Routines¶
Data and Database Access¶
- splat.core.getSpectrum(output='spectra', limit=20, verbose=True, key_name='DATA_KEY', *args, **kwargs)¶
- Parameters:
- output = 'spectra'str [optional]
- Determines what is returned to user; options are:
'spectra': return array of Spectrum objects [default]
'files': return a list of filenames
'table': return pandas table of spectral information (output of `searchLibrary()`_)
- limit = 0int [optional]
Sets limit for the number of returns. Set to < 0 to return unlimited number
- key = 'DATA_KEY'str [optional]
Keyword for the data key in the database file
- verbose = Truebool [optional]
Set to True to provide feedback
- **kwargsadditional keywords
Include additional keywords for `searchLibrary()`_
- splat.core.getStandard(spt, **kwargs)¶
- Purpose:
Gets one of the pre-defined spectral standards from the SPLAT library.
- Parameters:
spt (required) -- Spectral type of standard desired, either string ('M7') or numberic (17)
sd (optional, default = False) -- Set to True to get a subdwarf standard
esd (optional, default = False) -- Set to True to get an extreme subdwarf standard
- Example:
>>> import splat >>> sp = splat.getStandard('M7')[0] Spectrum of VB 8 >>> sparr = splat.getStandard('T5',esd=True) Type esdT5.0 is not in esd standards: try one of the following: ['esdM5.0', 'esdM7.0', 'esdM8.5']
- splat.core.searchLibrary(radius=10.0, instrument='SPEX-PRISM', source_database= SOURCE_KEY NAME ... VSINI_REF NOTE 0 10001 SDSS J000013.54+255418.6 ... NaN NaN 1 10002 2MASS J0000286-124515 ... NaN NaN 2 10003 SDSS J000112.18+153535.5 ... NaN NaN 3 10004 2MASS J00013044+1010146 ... NaN NaN 4 10005 WISE J000131.93-084126.9 ... NaN NaN ... ... ... ... ... ... 2710 12830 SDSS J034707.61+041754.0AB ... NaN NaN 2711 12831 SDSS J034707.61+041754.0B ... NaN NaN 2712 12832 LHS 5097 ... NaN NaN 2713 12833 2MASS J04333153-0211010 ... NaN NaN 2714 12834 2MASS J05102012+2714032 ... NaN NaN [2715 rows x 62 columns], spectra_database= DATA_KEY SOURCE_KEY ... DATA_REFERENCE NOTE 0 10001 10443 ... 2004PASP..116..362C NaN 1 10002 10782 ... 2004AJ....127.2856B NaN 2 10003 10830 ... 2004AJ....127.2856B NaN 3 10004 10916 ... 2004AJ....127.2856B NaN 4 10005 11020 ... 2004AJ....127.2856B NaN ... ... ... ... ... ... 3084 13100 12830 ... BURGASSER-NP NaN 3085 13101 12831 ... BURGASSER-NP NaN 3086 13102 12832 ... BURGASSER-NP NaN 3087 13103 12833 ... BURGASSER-NP NaN 3088 13104 12834 ... BURGASSER-NP NaN [3089 rows x 22 columns], *args, **kwargs)¶
- Purpose:
Searches the SpeX database based on a series of keywords; returns an astropy Table with the source and spectral information corresponding to the selected sources
- Required Parameters:
None
- Optional Parameters:
- param name:
search by source name (e.g.,
name = 'Gliese 570D'
); default = None
- param shortname:
search be short name or list of short names (e.g.
shortname = 'J1457-2124'
); default = None
- param exclude_shortname:
exclude a list of short names (e.g.
excludeshortname = 'J1457-2124'
); default = None
- param designation:
search by full designation (e.g.,
designation = 'J11040127+1959217'
); default = None
- param coordinate:
search around a coordinate by a radius specified by radius keyword (e.g.,
coordinate = [180.,+30.], radius = 10.
); coordinate can be an astropy SkyCoord, list of [RA, DEC], or designation; default = None
- param source, source_key, id, id_key:
search for a specific spectra based on single or list of id number or list of numbers (e.g.,
source_key = [10002,10005]
)
- param data_key:
search for a specific spectra based on single or list of data key numbers (e.g.,
data_key = [10002,10005]
)
- param exclude_data_key:
exclude specific spectra based on single or list of data key numbers (e.g.,
exclude_data_key = [10002,10005]
)
- param file:
search by specific filename or list of filenames (e.g.,
file = 'myspectrum.fits
)
- param exclude_file:
exclude by specific filename or list of filenames (e.g.,
exclude_file = 'myspectrum.fits
)
- param radius:
search radius in arcseconds for coordinate search; default = 10.
- param spt:
search by spectral type, which by default is the SpeX-based type; single value is exact, two-element array gives range (e.g.,
spt = 'M7'
orspt = [24,39]
); can also specify: * :param spex_spt: same asspt
* :param opt_spt: same asspt
for literature optical spectral types * :param nir_spt: same asspt
for literature NIR spectral types * :param lit_spt: same asspt
for literature spectral types from SIMBAD
- param jmag, hmag, kmag:
select based on faint limit or range of J, H or Ks magnitudes (e.g.,
jmag = 11
orjmag = [12,15]
); default = None
- param snr:
search on minimum or range of S/N ratios (e.g.,
snr = 30.
orsnr = [50.,100.]
)
- param subdwarf, young, lowg, binary, sbinary, red, blue, giant, wd, standard, companion, peculiar:
classes to search on or exclude (e.g.,
young = True
,giant = False
)
- param cluster:
select sources in specfic clusters (e.g.,
cluster = 'TWA'
)
- param giant_class or luminosity_class:
select sources based on luminosity class; this does not work for dwarfs (e.g.,
luminosity_class = 'I'
)
- param subdwarf_class or metallicity_class:
select sources based on metallicty class; (e.g.,
metallicity_class = 'sd'
)
- param date:
search by observation date (e.g.,
date = '20040322'
) or range of dates (e.g.,date=[20040301,20040330]
)
- param instrument:
search by instrument; must be designated instrument in splat.INSTRUMENTS variable (e.g.,
instrument = 'SPEX_PRISM'
)
- param reference:
search by list of references (bibcodes) (e.g.,
reference = '2011ApJS..197...19K'
)
- param logic, combine:
search logic, can be
and
(default) oror
- param sort:
by default returned table is sorted by designation; set this parameter to a column name to sort on a different parameter
- param reverse:
set to True to do a reverse sort (default = False)
- param list:
if True, return just a list of the data files (default = False)
- param lucky:
if True, return one randomly selected spectrum from the selected sample (default = False)
- param output:
returns desired column of selected results (default = 'all')
- Example:
>>> import splat >>> print SearchLibrary(shortname = '2213-2136') DATA_KEY SOURCE_KEY DATA_FILE ... SHORTNAME SELECT_2 -------- ---------- ---------------- ... ---------- -------- 11590 11586 11590_11586.fits ... J2213-2136 1.0 11127 11586 11127_11586.fits ... J2213-2136 1.0 10697 11586 10697_11586.fits ... J2213-2136 1.0 10489 11586 10489_11586.fits ... J2213-2136 1.0 >>> print SearchLibrary(shortname = '2213-2136', output = 'OBSERVATION_DATE') OBSERVATION_DATE ---------------- 20110908 20080829 20060902 20051017
Note
Note that this is currently only and AND search - need to figure out how to a full SQL style search
- splat.core.keySource(keys, verbose=True)¶
- Parameters:
- keysint or list
integer or list of integers corresponding to source keys
- verbose = Trueboolean [optional]
set to True to have program return verbose output
- splat.core.keySpectrum(keys, verbose=True)¶
- Parameters:
- keysint or list
integer or list of integers corresponding to source keys
- verbose = Trueboolean [optional]
set to True to have program return verbose output
- splat.core.initiateStandards(spt=[], dwarf=True, subdwarf=False, young=False, allstds=False, dsd=False, sd=False, esd=False, intg=False, vlg=False, reset=True, output=False, verbose=False)¶
- Parameters:
- spt = []None, int, float, str, or list [optional]
spectral type range to limit standards; if empty list or None, reads in all relevant standards
- dwarf = Trueboolean [optional]
by default, read in dwarf standards
- subdwarf = Falseboolean [optional]
read in d/sd, sd and esd standards
- young = Falseboolean [optional]
read in intg and vlg standards
- allstds = Falseboolean [optional]
read in dwarf, subdwarf, and young standards
- dsd = Falseboolean [optional]
read in mild subdwarf standards
- sd = Falseboolean [optional]
read in subdwarf standards
- esd = Falseboolean [optional]
read in extreme subdwarf standards
- int = Falseboolean [optional]
read in intermediate low gravity standards
- vlg = Falseboolean [optional]
read in very low gravity standards
- reset = Falseboolean [optional]
set to True to re-read in spectral standards (replaces those in place)
- output = Falseboolean [optional]
set to True to return the standards dictionary as output
- verbose = Falseboolean [optional]
set to True to have program return verbose output
- splat.core.addUserData(folders=[], default_info={}, verbose=True)¶
- Purpose:
Reads in list of folders with properly processed model sets, checks them, and adds them to the SPECTRAL_MODELS global variable
- Required Inputs:
None
- Optional Inputs:
- param folders = []:
By default model folders are set in the .splat_spectral_models file;
alternately (or in addition) folders of models can be included as an input list. * :param default_info = {}: default parameter set to use for models; superceded by 'info.txt' file if present in model folder * :param verbose = False: provide verbose feedback
- Outputs:
None, simply adds new model sets to SPECTRAL_MODELS global variable
- splat.core.Spectrum.export(self, filename='', clobber=True, csv=False, tab=True, delimiter='\t', save_header=True, save_noise=True, comment='#', file_type='', *args, **kwargs)¶
- Purpose:
Exports a Spectrum object to either a fits or ascii file, depending on file extension given. If no filename is explicitly given, the Spectrum.filename attribute is used. If the filename does not include the full path, the file is saved in the current directory. Spectrum.export and Spectrum.save() function in the same manner.
- Required Inputs:
None
- Optional Inputs:
- param filename:
String specifying the filename to save; filename can also be included as an argument; if not provided, Spectrum.filename is used; alternate keywords: file
- param clobber:
Set to True to overwrite file, or False to raise flag if file exists (default = True)
- param csv:
Set to True to write a CSV (comma-delimited) file (default = False)
- param tab:
Set to True to write a tab-delimited file (default = True)
- param delimiter:
character or string to specify as delimiter between columns (default = ' '); alternate keywords: sep
- param save_header:
set to True to add header to ascii files (default = True)
- param save_noise:
set to True to save the noise column (default = True)
- param comment:
use to specify comment character (default = '#')
- Output:
An ascii or fits file with the data and header
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.export('/Users/adam/myspectrum.txt') >>> from astropy.io import ascii >>> data = ascii.read('/Users/adam/myspectrum.txt',format='tab') >>> data <Table length=564> wavelength flux uncertainty float64 float64 float64 -------------- ----------------- ----------------- 0.645418405533 0.0 nan 0.647664904594 6.71920214475e-16 3.71175052033e-16 0.649897933006 1.26009925777e-15 3.85722895842e-16 0.652118623257 7.23781818374e-16 3.68178778862e-16 0.654327988625 1.94569566622e-15 3.21007116982e-16 ...
- splat.core.Spectrum.save(self, *args, **kwargs)¶
- Purpose:
Exports a Spectrum object to either a fits or ascii file, depending on file extension given. If no filename is explicitly given, the Spectrum.filename attribute is used. If the filename does not include the full path, the file is saved in the current directory.
Spectrum.export() and Spectrum.save function in the same manner.
- splat.core.readSpectrum(file, folder='', file_type='', wave_unit=Unit('micron'), flux_unit=Unit('erg / (micron s cm2)'), dimensionless=False, comment='#', delimiter='', crval1='CRVAL1', cdelt1='CDELT1', catch_sn=True, remove_nans=True, no_zero_noise=True, use_instrument_reader=True, instrument='SPEX-PRISM', instrument_param={}, verbose=False)¶
- Parameters:
- filestring
filename of data to be read in; if full path not provided, routine will search in local directory or in folder indicated by folder keyword; can also pass a URL to a remote file
- folder = ''string [optional]
full path to folder containing file
- file_type = ''string [optional]
- a string indicating some flags that specify what kind of file this is; some examples include:
csv = comma separated file (sets delimiter = ',')
tab or tsv = tab delimited file (sets delimiter = ' ')
pipe = pipe delimited file (sets delimiter = '|')
latex = latex-style table data (sets delimiter = ' & ')
waveheader = wavelength solution is contained within the fits header
wavelog = wavelength solution is logarithmic (common for echelle data)
sdss = sets both waveheader and wavelog
- wave_unit = DEFAULT_WAVE_UNITastropy.unit [optional]
units of wavelength axis, by default specified by the DEFAULT_WAVE_UNIT global parameter
- flux_unit = DEFAULT_FLUX_UNITastropy.unit [optional]
units of flux and uncertainty axes, by default specified by the DEFAULT_FLUX_UNIT global parameter note that you can specify a unitless number
- dimensionless = Falseboolean [optional]
set to True to set the flux units to a dimensionless quantity (for transmission, reflectance)
- comment = '#'string [optional]
for ascii files, character that indicates the file line is a comment (to be ignored)
- delimiter = ''string [optional]
for ascii files, character that separates columns of values
- crval1,cdelt1 = 'CRVAL1','CDELT1'string [optional]
for fits files for which the wavelength solution is embedded in header, these are the keywords containing the zeroth wavelength and linear change coefficient
- catch_sn = Trueboolean [optional]
set to True to check if uncertainty axis is actually signal-to-noise, by checking if median(flux/uncertainty) < 1 [NOTE: NO LONGER IMPLEMENTED]
- remove_nans = Trueboolean [optional]
set to True to remove all wave/flux/noise values for which wave or flux are nan
- no_zero_noise = Trueboolean [optional]
set to True to set all elements of noise array that are zero to numpy.nan; this helps in later computations of S/N or fit statistics
- use_instrument_reader = Truebool [optional]
set to True to use the default instrument read in the DEFAULT-INSTRUMENT global parameter checked against INSTRUMENTS dictionary
- instrument = DEFAULT_INSTRUMENTstring [optional]
instrument by which data was acquired, by default the DEFAULT-INSTRUMENT global parameter checked against INSTRUMENTS dictionary
- instrument_param = {}dict [optional]
instrument-specific parameters to pass to instrument reader
- verbose = Falseboolean [optional]
set to True to have program return verbose output
- splat.utilities.checkInstrument(instrument)¶
- Purpose:
Checks that an instrument name is one of the available instruments, including a check of alternate names
- Required Inputs:
- param:
instrument: A string containing the instrument name to be checked. This should be one of the instruments in the global parameter splat.initialize.INSTRUMENTS
- Optional Inputs:
None
- Output:
A string containing SPLAT's default name for a given instrument, or False if that instrument is not present
Example:
>>> import splat >>> splat.checkInstrument('SPEX PRISM') SPEX-PRISM >>> splat.checkInstrument('LRIS') LRIS-RED >>> splat.checkInstrument('somethingelse') False
- splat.utilities.checkLocation(location)¶
- Purpose:
Duplicate of checkTelescope()
- splat.utilities.checkTelescope(location)¶
- Purpose:
Checks that a location name is one of the telecopes listed in splat.initialize.TELESCOPES, including a check of alternate names
- Required Inputs:
- param:
location: A string containing the telescope/site name to be checked. This should be one of the locations in the global parameter splat.initialize.TELESCOPES
- Optional Inputs:
None
- Output:
A string containing SPLAT's default name for a given telescope, or False if that telecope is not present
Example:
>>> import splat >>> print(splat.checkTelescope('keck')) KECK >>> print(splat.checkTelescope('mauna kea')) KECK >>> print(splat.checkTelescope('somethingelse')) False
- splat.utilities.checkKeys(input, parameters, **kwargs)¶
- Purpose:
Checks the input kwargs keys against the expected parameters of a function to make sure the right parameters are passed.
- Parameters:
input -- input dictionary to a function (i.e., kwargs).
parameters -- allowed parameters for the function
forcekey -- (optional, default = False) if True, raises a Value Error if an incorrect parameter is passed
Spectral Manipulation¶
- splat.core.Spectrum.toFluxUnit(self, flux_unit)¶
- Purpose:
Converts flux and noise arrays to given flux units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.Spectrum(file='somespectrum',wave_unit=u.Angstrom) >>> sp.flux.unit erg / (cm2 micron s) >>> sp.toFluxUnit(u.Watt/u.m/u.m) >>> sp.flux.unit W / m2 >>> sp.toFluxUnit(u.erg/u.s) >>> sp.flux.unit Warning! failed to convert flux unit from W / m2 to erg / s; no change made
- splat.core.Spectrum.toWaveUnit(self, wave_unit)¶
- Purpose:
Converts wavelength to specified units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> import astropy.units as u >>> sp = splat.Spectrum(file='somespectrum',wave_unit=u.Angstrom) >>> print(sp.wave.unit) Angstrom >>> sp.toWaveUnit(u.micron) >>> print(sp.wave.unit) micron >>> sp.toWaveUnit(u.s) Warning! failed to convert wavelength unit from micron to s; no change made
- splat.core.Spectrum.toFnu(self)¶
- Purpose:
Converts flux density F_nu in units of Jy. There is no change if the spectrum is already in F_nu units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toFnu() >>> sp.flux.unit Unit("Jy")
- splat.core.Spectrum.toFlam(self)¶
- Purpose:
Converts flux density to F_lambda in units of erg/s/cm^2/Hz. There is no change if the spectrum is already in F_lambda units.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toFnu() >>> sp.flux.unit Unit("Jy") >>> sp.toFlam() >>> sp.flux.unit Unit("erg / (cm2 micron s)")
- splat.core.Spectrum.toSED(self)¶
- Purpose:
Converts flux density in F_lambda to lambda x F_lambda with units of erg/s/cm^2.
- Required Inputs:
None
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.toSED() >>> sp.flux.unit Unit("erg / (cm2 s)")
- splat.core.Spectrum.toSurface(self, radius)¶
- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
Note
UNTESTED, NEED TO ADD IN UNCERTAINTIES
- splat.core.Spectrum.toBrightnessTemperature(self, limbdarkening=False, limbdarkeningcoeff=0.7)¶
- Purpose:
Convert to surface fluxes given a radius, assuming at absolute fluxes
- splat.core.Spectrum.toTemperature(self)¶
- splat.core.Spectrum.toWavelengths(self, wave, force=True, verbose=False)¶
- Purpose:
Maps a spectrum onto a new wavelength grid via interpolation or integral resampling
- Required Inputs:
- param wave:
wavelengths to map to
- Optional Inputs:
- param force = True:
proceed with conversion even if wavelength ranges are not perfectly in range
- param verbose = False:
provide verbose feedback
- Outputs:
None; Spectrum object is changed
- Example:
TBD
- splat.core.Spectrum.toInstrument(self, instrument, pixel_resolution=3.0, **kwargs)¶
- Purpose:
Converts a spectrum to the parameters for a defined instrument
- Required Inputs:
- param instrument:
the name of an instrument, must be defined in splat.INSTRUMENTS
- Optional Inputs:
None
- Outputs:
None; Spectrum object is changed
- Example:
TBD
- splat.core.Spectrum.redden(self, av=0.0, rv=3.1, normalize=False, a=10.0, n=1.33, **kwargs)¶
- Purpose:
Redden a spectrum based on an either Mie theory or a standard interstellar profile using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)
- Required Inputs:
None
- Optional Inputs:
- param av:
Magnitude of reddening A_V (default = 0.)
- param rv:
Normalized extinction parameter, R_V = A(V)/E(B-V) (default = 3.1
- param normalized:
Set to True to normalize reddening function (default = False)
- Outputs:
None; spectral flux is changed
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) # read in a source >>> spr = splat.redden(sp,av=5.,rv=3.2) # redden to equivalent of AV=5
- Note
This routine is still in beta form; only the CCM89 currently works
- splat.core.Spectrum.normalize(self, *args, **kwargs)¶
- Purpose:
Normalize a spectrum to a maximum value of 1 (in its current units) either at a particular wavelength or over a wavelength range
- Required Inputs:
None
- Optional Inputs:
- param wave_range:
choose the wavelength range to normalize; can be a list specifying minimum and maximum or a single wavelength (default = None); alternate keywords: wave_range, range
- Output:
None; spectrum is normalized
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.normalize() >>> sp.fluxMax() <Quantity 1.0 erg / (cm2 micron s)> >>> sp.normalize(waverange=[2.25,2.3]) >>> sp.fluxMax() <Quantity 1.591310977935791 erg / (cm2 micron s)>
- splat.core.Spectrum.scale(self, factor, noiseonly=False)¶
- Purpose:
Scales a Spectrum object's flux and noise values by a constant factor.
- Required Inputs:
- param factor:
A floating point number used to scale the Spectrum object
- Optional Inputs:
- param noiseonly = False:
scale only the noise and variance, useful when uncertainty is under/over estimated
- Output:
None; spectrum is scaled
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxMax() <Quantity 1.0577336634332284e-14 erg / (cm2 micron s)> >>> sp.computeSN() 124.5198 >>> sp.scale(1.e15) >>> sp.fluxMax() <Quantity 1.0577336549758911 erg / (cm2 micron s)> >>> sp.computeSN() 124.51981
- splat.core.Spectrum.fluxCalibrate(self, filt, mag, **kwargs)¶
- Purpose:
Flux calibrates a spectrum given a filter and a magnitude. The filter must be one of those listed in splat.FILTERS.keys(). It is possible to specifically set the magnitude to be absolute (by default it is apparent). This function changes the Spectrum object's flux, noise and variance arrays.
Required Inputs:
- Parameters:
filt -- string specifiying the name of the filter
mag -- number specifying the magnitude to scale to
Optional Inputs:
- Parameters:
absolute -- set to True to specify that the given magnitude is an absolute magnitude, which sets the
flux_label
keyword in the Spectrum object to 'Absolute Flux' (default = False)apparent -- set to True to specify that the given magnitude is an apparent magnitude, which sets the
flux_label
flag in the Spectrum object to 'Apparent Flux' (default = False)
Outputs:
None, Spectrum object is changed to a flux calibrated spectrum
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxCalibrate('2MASS J',15.0) >>> splat.filterMag(sp,'2MASS J') (15.002545668628173, 0.017635234089677564)
- splat.core.Spectrum.smooth(self, smv, resolution=False, slitwidth=False, **kwargs)¶
- Purpose:
Smoothes a spectrum either by selecting a constant slit width (smooth in spectral dispersion space), pixel width (smooth in pixel space) or resolution (smooth in velocity space). One of these options must be selected for any smoothing to happen. Changes spectrum directly.
- Required Inputs:
None
- Optional Inputs:
- param method:
the type of smoothing window to use; see http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.get_window.html for more details (default = 'hamming')
- param resolution:
Constant resolution to smooth to; see _smoothToResolution() (default = None)
- param slitPixelWidth:
Number of pixels to smooth in pixel space; see _smoothToSlitPixelWidth() (default = None)
- param slitWidth:
Number of pixels to smooth in angular space; see _smoothToPixelWidth() (default = None)
- Output:
None: spectrum is smoothed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.smooth(resolution=30)
- splat.core.Spectrum._smoothToResolution(self, res, oversample=10.0, method='hamming', **kwargs)¶
- Purpose:
Smoothes a spectrum to a constant or resolution (smooth in velocity space). Note that no smoothing is done if requested resolution is greater than the current resolution
- Required Inputs:
- param res:
desired resolution (lambda/delta_lambde)
- Optional Inputs:
- param overscale:
number of samples in the smoothing window (default = 10)
see other optional keywords in Spectrum.smooth()
- Outputs:
None; spectrum is smoothed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.resolution() 120 >>> sp.computeSN() 21.550974 >>> sp.smoothToResolution(50) >>> sp.resolution() 50 >>> sp.computeSN() 49.459522314460855
- splat.core.Spectrum._smoothToSlitWidth(self, width, **kwargs)¶
- Purpose:
Smoothes a spectrum to a constant slit angular width (smooth in dispersion space). Note that no smoothing is done if requested width is greater than the current slit width.
- Required Inputs:
- param width:
smoothing scale in arcseconds
- Optional Inputs:
see other optional keywords in Spectrum.smooth()
- Outputs:
None; spectrum is smoothed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.slitwidth 0.4995 >>> sp.resolution 120 >>> sp.computeSN() 105.41789 >>> sp.smoothToSlitWidth(2.0) >>> sp.slitwidth 2.0 >>> sp.resolution 29.97 >>> sp.computeSN() 258.87135134070593
- splat.core.Spectrum._smoothToSlitPixelWidth(self, width, **kwargs)¶
- Purpose:
Smoothes a spectrum to a constant slit pixel width (smooth in pixel space). C Note that no smoothing is done if requested width is greater than the current slit width.
- Required Inputs:
- param width:
smoothing scale in pixels
- Optional Inputs:
see other optional keywords in Spectrum.smooth()
- Outputs:
None; spectrum is smoothed
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.slitpixelwidth 3.33 >>> sp.resolution 120 >>> sp.computeSN() 105.41789 >>> sp.smoothToSlitPixelWidth(10) >>> sp.slitpixelwidth 10 >>> sp.resolution 39.96 >>> sp.computeSN() 235.77536310249229
- splat.core.Spectrum.maskFlux(self, mask=[], replace_noise=True, replace_value=nan, others=[])¶
- Parameters:
- mask = []list or numpy.ndarray [optional]
array with same length as Spectrum object wavelength array that specifies pixels to be masked array values can be floating point, int, or bool, with 1 = True (mask) and 0 = False (don't mask)
- replace_noise = Truebool [optional]
If True, apply the mask to the uncertainty array
- replace_value = numpy.nanfloat [optional]
Value with which to replace masked elements of flux
- others = []]list [optional]
Other elements of the Spectrum object to apply mask (e.g., wave, flags, mask, etc.) These elements should be present and must be the same length as mask
- splat.core.Spectrum.remove(self, mask, others=[])¶
- Purpose:
Removes elements of wave, flux, noise specified by the True/False array
- Required Input:
- param mask:
Either a mask array (an array of booleans, ints, or floats, where True or 1 removes the element) or a 2-element array that defines the wavelegnth range to mask
- Optional Input:
- param others:
list of other attributes that mask should be applied to(e.g., 'pixel') (default = [])
- Output:
Spectrum object has the flagged pixels removed from wave, flux, noise arrays, and optional vectors
- Example:
>>> import splat, numpy >>> sp = splat.getSpectrum(lucky=True)[0] >>> num = splat.numberList('1-10,18,30-50') >>> mask = [not(p in num) for p in numpy.arange(len(sp.wave))] >>> sp.remove(mask) >>> sp.showHistory() SPEX_PRISM spectrum successfully loaded Mask applied to remove 32 pixels
- splat.core.Spectrum.trim(self, rng, **kwargs)¶
- Purpose:
Trims a spectrum to be within a certain wavelength range or set of ranges. Data outside of these ranges are excised from the wave, flux and noise arrays. The full spectrum can be restored with the reset() procedure.
- Required Inputs:
- param range:
the range(s) over which the spectrum is retained - a series of nested 2-element arrays
- Optional Inputs:
None
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.smoothfluxMax() <Quantity 1.0577336634332284e-14 erg / (cm2 micron s)> >>> sp.computeSN() 124.5198 >>> sp.scale(1.e15) >>> sp.fluxMax() <Quantity 1.0577336549758911 erg / (cm2 micron s)> >>> sp.computeSN() 124.51981
- splat.core.stitch(s1, s2, rng=[], verbose=False, scale=True, **kwargs)¶
- Purpose:
Stitches together two spectra covering different wavelength scales.
- Required Inputs:
- param s1:
first spectrum object
- param s2:
second spectrum object (not necessarily in order)
- Optional Inputs:
- param rng:
range over which spectra are relatively scaled and combined (if desired); if neither spectrum cover this range, then no relative scaling is done and spectra are combined whereever they overlap (default: [])
- param scale:
set to True to relatively scale spectra over rng; if rng is not provided, or spectra to not overlap, this is automatially False (default: True)
- param wave_unit:
wavelength unit of final spectrum (default: wavelength unit of s1)
- param flux_unit:
flux unit of final spectrum (default: flux unit of s1)
- param verbose:
set to True to provide feedback (default: False)
- Output:
New spectrum object of stitched spectrum
- Example:
>>> import splat >>> spopt = splat.Spectrum(file='myopticalspectrum.fits') >>> spnir = splat.Spectrum(file='myopticalspectrum.fits') >>> sp = splat.stitch(spopt,spnir,rng=[0.8,0.9],trim=[0.35,2.4])
- splat.core.Spectrum.addNoise(self, snr=0.0)¶
- Purpose:
Adds noise to a spectrum based on either the current uncertainties scaled by optional input S/N
- Required Inputs:
None
- Optional Inputs:
snr: Signal-to-noise ratio to use to scale uncertainty spectrum (default = 0. => use existing S/N)
- Output:
None (spectrum object changed in place)
- Example:
>>> sp = splat.Spectrum(10001) >>> sp.addNoise(snr=10.) >>> sp.computeSN() 9.5702358777108234
Spectral Classification and Characterization¶
- splat.core.compareSpectra(s1, s2, statistic='chisqr', scale=True, novar2=True, plot=False, verbose=False, **kwargs)¶
- Purpose:
Compare two spectra against each other using a pre-selected statistic. Returns the value of the desired statistic as well as the optimal scale factor.
- Required Parameters:
- param sp1:
First spectrum class object, which sets the wavelength scale
- param sp2:
Second spectrum class object, interpolated onto the wavelength scale of sp1
- Optional Parameters:
- param:
statistic = 'chisqr': string defining which statistic to use in comparison; available options are (also stat):
'chisqr' or 'chi': compare by computing chi squared value (requires spectra with noise values)
'stddev': compare by computing standard deviation
'stddev_norm': compare by computing normalized standard deviation
'absdev': compare by computing absolute deviation
- param:
scale = True: If True, finds the best scale factor to minimize the statistic
- param:
fit_ranges = [range of first spectrum]: 2-element array or nested array of 2-element arrays specifying the wavelength ranges to be used for the fit, assumed to be measured in microns; this is effectively the opposite of mask_ranges (also fit_range, fitrange, fitrng, comprange, comprng)
- param:
mask = numpy.zeros(): Array specifiying which wavelengths to mask; must be an array with length equal to the wavelength scale of
sp1
with only 0 (OK) or 1 (mask).- param:
mask_ranges = None: Multi-vector array setting wavelength boundaries for masking data, assumed to be in microns
- param:
mask_telluric = False: Set to True to mask pre-defined telluric absorption regions
- param:
mask_standard = False: Like
mask_telluric
, with a slightly tighter cut of 0.80-2.35 micron- param:
weights = numpy.ones(): Array specifying the weights for individual wavelengths; must be an array with length equal to the wavelength scale of
sp1
; need not be normalized- param:
novar2 = True: Set to True to compute statistic without considering variance of
sp2
- param:
plot = False: Set to True to plot
sp1
with scaledsp2
and difference spectrum overlaid- param:
verbose = False: Set to True to report things as you're going along
- Output:
statistic and optimal scale factor for the comparison
- Example:
>>> import splat >>> import numpy >>> sp1 = splat.getSpectrum(shortname = '2346-3153')[0] Retrieving 1 file >>> sp2 = splat.getSpectrum(shortname = '1421+1827')[0] Retrieving 1 file >>> sp1.normalize() >>> sp2.normalize() >>> splat.compareSpectra(sp1, sp2, statistic='chisqr') (<Quantity 19927.74527822856>, 0.94360732593223595) >>> splat.compareSpectra(sp1, sp2, statistic='stddev') (<Quantity 3.0237604611215705 erg2 / (cm4 micron2 s2)>, 0.98180983971456637) >>> splat.compareSpectra(sp1, sp2, statistic='absdev') (<Quantity 32.99816249949072 erg / (cm2 micron s)>, 0.98155779612333172) >>> splat.compareSpectra(sp1, sp2, statistic='chisqr', novar2=False) (<Quantity 17071.690727945213>, 0.94029474635786015)
- splat.core.measureIndex(sp, ranges, method='ratio', sample='integrate', nsamples=100, noiseFlag=False, plot=False, verbose=False, **pkwargs)¶
- Purpose:
Measure an index on a spectrum based on defined methodology measure method can be mean, median, integrate index method can be ratio = 1/2, valley = 1-2/3, OTHERS output is index value and uncertainty
# NOTE: NOISE FLAG ERROR IS BACKWARDS HERE
- splat.core.measureIndexSet(sp, ref='burgasser', index_info={}, info=False, verbose=False, indices_keyword='indices', range_keyword='ranges', method_keyword='method', sample_keyword='sample', **kwargs)¶
- Purpose:
Measures indices of
sp
from specified sets. Returns dictionary of indices.- Required Inputs:
- param sp:
Spectrum class object, which should contain wave, flux and noise array elements
- Optional Inputs:
- param ref='burgasser':
string identifying the index set you want to measure, as contained in the variable splat.INDEX_SETS
- param index_info={}:
a dictionary defining the index set to measure; this dictionary should contain within it:
'indices': points to a dictionary containing the index definitions, each of which are also a dictionary containing the
keywords 'range' (the wavelength range),'sample' (spectrum sampling), and 'method'(index calculation method) * alternately, a set of individual dictionaries containing 'range','sample', and 'method' keywords * 'bibcode': optional bibcode citation, if 'indices' keyword is present
- param info=False:
set to True to give the list of avaialble index sets in SPLAT
- param indices_keyword='indices':
alternate keyword name convection for indices
- param range_keyword='ranges':
alternate keyword name convection for index wavelength ranges
- param method_keyword='method':
alternate keyword name convection for spectral sampling
- param sample_keyword='sample':
alternate keyword name convection for index measurement method
- param verbose=False:
set to True to give extra feedback
Additional keyword options for measureIndex()_ can also be supplied
- Output:
A dictionary containing the names of each index pointed to tuple of (measurement,uncertainty)
- Example:
>>> import splat >>> sp = splat.getSpectrum(shortname='1555+0954')[0] >>> splat.measureIndexSet(sp, ref = 'reid') {'H2O-A': (0.896763035762751, 0.0009482437569842745), 'H2O-B': (1.0534404728276665, 0.001329359465953495)}
- splat.plot.visualizeIndices(sp, indices, **kwargs)¶
- Purpose:
Plot index-index plots.
indices should be a dictionary of {'index_name': {'ranges': [[],[]], 'value': #, 'unc': #}, ...} Not currently implemented
- splat.core.measureEW(sp, lc, width=0.0, continuum=[0.0, 0.0], plot=False, file='', continuum_width=False, output_unit=Unit('Angstrom'), nsamp=100, nmc=100, verbose=True, recenter=True, absorption=True, name='', continuum_fit_order=1, debug=False)¶
- splat.core.measureEWElement(sp, element, wave_range=[0.0, 0.0], getNist=False, **kwargs)¶
- splat.core.measureEWSet(sp, ref='rojas', **kwargs)¶
- Purpose:
Measures equivalent widths (EWs) of lines from specified sets. Returns dictionary of indices.
- Parameters:
sp -- Spectrum class object, which should contain wave, flux and noise array elements
set (optional, default = 'rojas') --
string defining which EW measurement set you want to use; options include:
rojas: EW measures from Rojas-Ayala et al. (2012); uses Na I 2.206/2.209 Ca I 2.26 micron lines.
- Example:
>>> import splat >>> sp = splat.getSpectrum(shortname='1555+0954')[0] >>> print splat.measureEWSet(sp, set = 'rojas') {'Na I 2.206/2.209': (1.7484002652013144, 0.23332441577025356), 'Ca I 2.26': (1.3742491939667159, 0.24867705962337672), 'names': ['Na I 2.206/2.209', 'Ca I 2.26'], 'reference': 'EW measures from Rojas-Ayala et al. (2012)'}
- splat.core.classifyByIndex(sp, ref='burgasser', string_flag=True, round_flag=False, remeasure=True, nsamples=100, nloop=5, verbose=False, indices={}, param={}, allmeasures=False, **kwargs)¶
- Purpose:
Determine the spectral type and uncertainty for a spectrum based on indices. Makes use of published index-SpT relations from Reid et al. (2001); Testi et al. (2001); Allers et al. (2007); and Burgasser (2007). Returns 2-element tuple containing spectral type (numeric or string) and uncertainty.
Required Inputs:
- Parameters:
sp -- Spectrum class object, which should contain wave, flux and noise array elements.
Optional Inputs:
- Parameters:
set --
named set of indices to measure and compute spectral type
'burgasser': H2O-J, CH4-J, H2O-H, CH4-H, CH4-K from Burgasser (2007), applicable for types (default)
'allers': H2O from Allers et al. (2007)
'reid':H2O-A and H2O-B from Reid et al. (2001)
'testi': sHJ, sKJ, sH2O_J, sH2O_H1, sH2O_H2, sH2O_K from Testi et al. (2001)
string -- return spectral type as a string using typeToNum (default = False)
round -- rounds off to nearest 0.5 subtypes (default = False)
allmeasures -- Set to True to return all of the index values and individual subtypes (default = False)
remeasure -- force remeasurement of indices (default = True)
nsamples -- number of Monte Carlo samples for error computation (default = 100)
nloop -- number of testing loops to see if spectral type is within a certain range (default = 5)
- Example:
>>> import splat >>> spc = splat.getSpectrum(shortname='0559-1404')[0] >>> splat.classifyByIndex(spc, string=True, set='burgasser', round=True) ('T4.5', 0.2562934083414341)
- splat.core.classifyByStandard(sp, std_class='dwarf', dof=-1, verbose=False, **kwargs)¶
- Purpose:
Determine the spectral type and uncertainty for a spectrum by direct comparison to defined spectral standards. Dwarf standards span M0-T9 and include the standards listed in Burgasser et al. (2006), Kirkpatrick et al. (2010) and Cushing et al. (2011). Comparison to subdwarf and extreme subdwarf standards may also be done. Returns the best match or an F-test weighted mean and uncertainty. There is an option to follow the procedure of Kirkpatrick et al. (2010), fitting only in the 0.9-1.4 micron region.
- Required Parameters:
- param sp:
Spectrum class object, which should contain wave, flux and noise array elements (required)
- Optional Parameters:
- param sptrange:
set to the spectral type range over which comparisons should be made, can be a two-element array of strings or numbers (optional, default = ['M0','T9'])
- param statistic:
string defining which statistic to use in comparison; available options are:
'chisqr': (DEFAULT) compare by computing chi squared value (requires spectra with noise values)
'stddev': compare by computing standard deviation
'stddev_norm': compare by computing normalized standard deviation
'absdev': compare by computing absolute deviation
- param std_class:
the type of standard to compare to; allowed options are 'dwarf' (default), 'subdwarf', 'sd', 'dsd', 'esd', 'lowg', 'vlg', and 'intg'. These can also be set using the following keywords
- param dwarf:
set to True to compare to dwarf standards
- param sd:
set to True to compare to subdwarf standards (subdwarf does the same)
- param dsd:
set to True to compare to dwarf/subdwarf standards
- param esd:
set to True to compare to extreme subdwarf standards
- param vlg:
set to True to compare to very low gravity standards (lowg does the same)
- param intg:
set to True to compare to intermediate gravity standards
- param all:
compare to standards across all metallicity and gravity types
- param method:
set to
'kirkpatrick'
to follow the Kirkpatrick et al. (2010) method, fitting only to the 0.9-1.4 micron band (optional, default = '')
- param best:
set to True to return the best fit standard type (optional, default = True)
- param average:
set to True to return an chi-square weighted type only (optional, default = False)
- param compareto:
set to the single standard (string or number) you want to compare to (optional, default = None)
- param plot:
set to True to generate a plot comparing best fit template to source; can also set keywords associated with plotSpectrum_ routine (optional, default = False)
- param string:
set to True to return spectral type as a string (optional, default = True)
- param return_standard:
set to True to return a Spectrum class of the standard properly scaled (optional, default = False)
- param return_statistic:
set to True to return a best match spectral type and statistic (instead of uncertainty) (optional, default = False)
- param verbose:
set to True to give extra feedback (optional, default = False)
Users can also set keyword parameters defined in plotSpectrum_ and compareSpectra routine.
- Output:
A tuple listing the best match standard and uncertainty based on F-test weighting and systematic uncertainty of 0.5 subtypes
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> result = splat.classifyByStandard(sp,verbose=True) Using dwarf standards Type M3.0: statistic = 5763368.10355, scale = 0.000144521824721 Type M2.0: statistic = 5613862.67356, scale = 0.000406992798674 Type T8.0: statistic = 18949835.2087, scale = 9.70960919364 Type T9.0: statistic = 21591485.163, scale = 29.1529786804 Type L8.0: statistic = 3115605.62687, scale = 1.36392504072 Type L9.0: statistic = 2413450.79206, scale = 0.821131769522 ... Best match to L1.0 spectral standard Best spectral type = L1.0+/-0.5 >>> result ('L1.0', 0.5) >>> splat.classifyByStandard(sp,sd=True,average=True) ('sdL0.0:', 1.8630159149200021)
- splat.core.classifyByTemplate(sp, templates, output='best', nbest=1, maxtemplates=100, plot=False, verbose=False, dof=-1, **kwargs)¶
- Parameters:
- spSpectrum class
spectrum to copmare to templates
- templatesdict
dictionary of spectrum objects, where each key corresponds to the template identifier (e.g., spectral type) and points to a Spectrum class object of the template
- output = 'best'str [optional]
signifies what should be returned by call to classifyByTemplate()
- nbest = 1int [optional]
indicate what number of best-fit templates to return, in order of lowest fit statistic
- maxtemplates = 100int [optional]
maximum number of templates to compare to if time is an issue; -1 is unlimited
- plot = Falsebool [optional]
plot comparison between source and best-fit template
- verbose = Falsebool [optional]
return verbose feedback during execution
- splat.core.classifyGravity(sp, output='classification', verbose=False, **kwargs)¶
- Purpose:
Determine the gravity classification of a brown dwarf using the method of Allers & Liu (2013).
- Parameters:
sp (required) -- Spectrum class object, which should contain wave, flux and noise array elements. Must be between M6.0 and L7.0.
spt (optional, default = False) -- spectral type of
sp
. Must be between M6.0 and L7.0indices (optional, default = 'allers') -- specify indices set using
measureIndexSet
.plot (optional, default = False) -- Set to True to plot sources against closest dwarf spectral standard
allscores (optional, default = False) -- Set to True to return a dictionary containing the gravity scores from individual indices
verbose (optional, default = False) -- Give feedback while computing
- Output:
Either a string specifying the gravity classification or a dictionary specifying the gravity scores for each index
- Example:
>>> import splat >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> splat.classifyGravity(sp) FLD-G >>> result = splat.classifyGravity(sp, allscores = True, verbose=True) Gravity Classification: SpT = L4.0 VO-z: 1.012+/-0.029 => 0.0 FeH-z: 1.299+/-0.031 => 1.0 H-cont: 0.859+/-0.032 => 0.0 KI-J: 1.114+/-0.038 => 1.0 Gravity Class = FLD-G >>> result {'FeH-z': 1.0, 'H-cont': 0.0, 'KI-J': 1.0, 'VO-z': 0.0, 'gravity_class': 'FLD-G', 'score': 0.5, 'spt': 'L4.0'}
- splat.empirical.redden(sp, **kwargs)¶
- Description:
Redden a spectrum based on an either Mie theory or a standard interstellar profile using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)
Usage
>>> import splat >>> sp = splat.Spectrum(10001) # read in a source >>> spr = splat.redden(sp,av=5.,rv=3.2) # redden to equivalent of AV=5
- Note
This routine is still in beta form; only the CCM89 currently works
- splat.core.generateMask(wv, mask=[], mask_range=[-99.0, -99.0], mask_telluric=False, mask_standard=False, **kwargs)¶
- Purpose:
Generates a mask array based on wavelength vector and optional inputs on what to mask.
- Output:
A mask array, where 0 = OK and 1 = ignore
- Example:
Spectrophotometry¶
- splat.photometry.checkFilter(filt, verbose=True)¶
- splat.photometry.filterInfo(fname='', verbose=True, **kwargs)¶
- Purpose:
Prints out the current list of filters in the SPLAT reference library.
- splat.photometry.filterMag(sp, filt, computevalue='vega', nsamples=100, custom=False, notch=False, rsr=False, vegafile='vega_kurucz.txt', filterfolder='/Users/adam/projects/splat/code/splat/splat/..//resources/Filters/', info=False, verbose=False, **kwargs)¶
- Parameters:
- spSpectrum class object
Spectrum to compute spectrophotometry, which should contain wave, flux and noise array elements.
- filterstr
String giving name of filter, which can either be one of the predefined filters listed in splat.FILTERS.keys() or a custom filter name
- computevaluestr, default = 'vega'
Type of value to compute; must be one of vega, ab, energy, photons; can also be set with vega, ab, energy, and photons keywords
- customarray, default = None
A 2 x N vector array specifying the wavelengths and transmissions for a custom filter
- notcharray, default = None:
A 2 element array that specifies the lower and upper wavelengths for a notch filter (100% transmission within, 0% transmission without)
- filterfolderstr, default = splat.FILTER_FOLDER
Optional filepath to folder containing the filter transmission files
- vegafilestr, default = 'vega_kurucz.txt'
Filename containing Vega flux file, either full path or assumed to be within
filterfolder
- nsamplesint, default = 100
Number of samples to use in Monte Carlo error estimation
- infobool default = False:
Set to True to list the predefined filter names available
- verbosebool, default = False
Set to True to receive verbose feedback
- splat.core.Spectrum.filterMag(self, filt, **kwargs)¶
- Purpose:
Wrapper for filterMag() function in splat.photometry
Required Inputs:
filter: string specifiying the name of the filter
Optional Inputs:
See filterMag()
Outputs:
Returns tuple containing filter-based spectrophotometic magnitude and its uncertainty
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] >>> sp.fluxCalibrate('2MASS J',15.0) >>> sp.filterMag(sp,'2MASS J') (15.002545668628173, 0.017635234089677564)
- splat.photometry.filterProfile(filt, filterfolder='/Users/adam/projects/splat/code/splat/splat/..//resources/Filters/', plot=False, file='', verbose=False, **kwargs)¶
- Parameters:
- filterstr
String giving the name of one of the predefined filters listed in splat.FILTERS.keys()
- filterfolderstr, default = splat.FILTER_FOLDER
Optional filepath to folder containing the filter transmission files
- plotbool, default = False
Set to True to plot the filter profile (using visualizeFilter()_)
- filestr, default = ''
Full filepath for plot output; if empty string, no plot created
- verbosebool, default = False
Set to True to receive verbose feedback
- additional plotting options contained in matplotlib.pyplot can be passed as well,
- including color, label, xlim, ylim, xlabel, ylabel, figsize, normalize, and fill
- splat.photometry.magToFlux(mag, filt, **kwargs)¶
- Purpose:
Converts a magnitude into an energy, and vice versa.
- Parameters:
mag -- magnitude on whatever system is defined for the filter or provided (required)
filter -- name of filter, must be one of the specifed filters given by splat.FILTERS.keys() (required)
reverse -- convert energy into magnitude instead (optional, default = False)
ab -- magnitude is on the AB system (optional, default = filter preference)
vega -- magnitude is on the Vega system (optional, default = filter preference)
rsr -- magnitude is on the Vega system (optional, default = filter preference)
units -- units for energy as an astropy.units variable; if this conversion does not work, the conversion is ignored (optional, default = erg/cm2/s)
verbose -- print out information about filter to screen (optional, default = False)
WARNING: THIS CODE IS ONLY PARTIALLY COMPLETE
- splat.photometry.vegaToAB(filt, vegafile='vega_kurucz.txt', filterfolder='/Users/adam/projects/splat/code/splat/splat/..//resources/Filters/', custom=False, notch=False, rsr=False, **kwargs)¶
- splat.photometry.visualizeFilter(fprof, spectrum=None, file='', color='k', linestyle='-', fill=False, legend=False, nsample=100, verbose=True, **kwargs)¶
- Parameters:
- fprofstr or list/array
Either of string or list of strings of predefined filter names listed in splat.FILTERS.keys() or a list of numerical arrays: lists of pairs of numbers => notch filters; list of pairs of number arrays => wave,transmission profiles
- spectrumSpectrum class object, default = None
Assign to a spectrum class object you want to overplot; spectrum should be normalized in advance
- filestr, default = ''
Full filepath for plot output; if empty string, no plot created
- colorstr or list, default = 'k''
single or list of color labels
- linestylestr or list, default = '-''
single or list of linestyles
- fillbool, default = False
Set to True to fill in the filter profile region
- legendbool, default = False
Set to True to include legend
- nsampleint, default = 100
Number of samples for a notch filter
- verbosebool, default = False
Set to True to receive verbose feedback
- additional plotting options contained in matplotlib.pyplot can be passed as well,
- including figsize, xlim, ylim, xlabel, ylabel, wave_unit, normalize, spectrum_scale, spectrum_color, spectrum_alpha
High-resolution Spectroscopic Functions¶
- splat.utilities.baryVel(coord, obstime, location='keck', correction='barycenter')¶
- Purpose:
Computes the barycentric or heliocentric velocity in a direction and from a specific Earth location
- Required Inputs:
- param coord:
Coordinate of source; should be astropy.coordinates.SkyCoord, but can also be converted from splat.propoCoordinates
- param obstime:
A date/time, preferred in astropy.time.Time format but can be converted from splat.properDate
- Optional Inputs:
- param location:
location on Earth, specified by astropy.coordinates.EarthLocation; string of location;
dictionary containing 'ra', 'dec', and 'height'; or array of [ra,dec,height] (default = 'keck') - :param correction: type of correction, can be either 'barycentric' or 'heliocentric' (default = 'heliocentric')
- Output:
The velocity correction in km/s
- Example:
>>> import splat >>> coord = splat.properCoordinates('J15104786-2818174') >>> print(splat.baryVel(coord,'2017-07-31',location='keck') -27.552554878923033 km / s
- splat.utilities.lsfRotation(vsini, vsamp, epsilon=0.6)¶
Purpose:
Generates a line spread function for rotational broadening, based on Gray (1992) Ported over by Chris Theissen and Adam Burgasser from the IDL routine lsf_rotate writting by W. Landsman
Required Inputs:
- param:
vsini: vsini of rotation, assumed in units of km/s
- param:
vsamp: sampling velocity, assumed in unit of km/s. vsamp must be smaller than vsini or else a delta function is returned
Optional Inputs:
- param:
epsilon: limb darkening parameter based on Gray (1992)
Output:
Line spread function kernel with length 2*vsini/vsamp (forced to be odd)
- Example:
>>> import splat >>> kern = lsfRotation(30.,3.) >>> print(kern) array([ 0. , 0.29053574, 0.44558751, 0.55691445, 0.63343877, 0.67844111, 0.69330989, 0.67844111, 0.63343877, 0.55691445, 0.44558751, 0.29053574, 0. ])
- splat.core.Spectrum.rvShift(self, rv)¶
- Purpose:
Shifts the wavelength scale by a given radial velocity. This routine changes the underlying Spectrum object.
- Example:
>>> import splat >>> import astropy.units as u >>> sp.rvShift(15*u.km/u.s)
- splat.core.Spectrum.broaden(self, vbroad, kern=None, epsilon=0.6, method='rotation', verbose=False)¶
- Purpose:
Broadens a spectrum in velocity space using a line spread function (LSF) either based on rotation or gaussian. This routine changes the underlying Spectrum object.
- Required Inputs:
- param vbroad:
broadening width, nominally in km/s
- Optional Inputs:
- param method:
method of broadening, should be one of:
gaussian
: (default) Gaussian broadening, with vbroad equal to Gaussian sigmarotation
: rotational broadening using splat.lsfRotation()delta
: Delta function (no broadening)
- param kern:
input kernel, must be at least three elements wide (default = None)
- param epsilon:
epsilon parameter for limb darkening in rotational broadening (default = 0.6)
- param verbose:
provide extra feedback (default = False)
- Outputs:
None; Spectral flux is smoothed using the desired line spread function. No change is made to noise or other axes
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) >>> sp.broaden(30.,method='rotation') >>> sp.info() History: SPEX_PRISM spectrum successfully loaded Rotationally broadened spectrum by 30.0 km/s
- splat.core.Spectrum.rotate(self, vsini, epsilon=0.6, verbose=False)¶
- Purpose:
Rotationally broaden the lines of a spectrum; a shortcut call to Spectrum.broaden()
- Required Inputs:
- param vsini:
Rotational velocity in km/s
- Optional Inputs:
- param epsilon:
epsilon parameter for limb darkening in rotational broadening (default = 0.6)
- param verbose:
provide extra feedback (default = False)
- Outputs:
None; Spectral flux is smoothed by rotational broadening
- Example:
>>> import splat >>> sp = splat.Spectrum(10001) >>> sp.vsini(30.) >>> sp.info() History: SPEX_PRISM spectrum successfully loaded Rotationally broadened spectrum by 30.0 km/s
Empirical Relationships¶
- splat.empirical.estimateDistance(*args, **kwargs)¶
- Purpose:
Takes the apparent magnitude and either takes or determines the absolute magnitude, then uses the magnitude/distance relation to estimate the distance to the object in parsecs. Returns estimated distance and uncertainty in parsecs
- Parameters:
sp -- Spectrum class object, which should be flux calibrated to its empirical apparent magnitude
mag (optional, default = False) -- apparent magnitude of
sp
mag_unc (optional, default = 0) -- uncertainty of the apparent magnitude
absmag (optional, default = False) -- absolute magnitude of
sp
absmag_unc (optional, default = 0) -- uncertainty of the absolute magnitude
spt (optional, default = False) -- spectral type of
sp
spt_e (optional, default = 0) -- uncertainty of the spectral type
nsamples (optional, default = 100) -- number of samples to use in Monte Carlo error estimation
filter (optional, default = False) --
Name of filter, must be one of the following:
'2MASS J', '2MASS H', '2MASS Ks'
'MKO J', 'MKO H', 'MKO K', MKO Kp', 'MKO Ks'
'NICMOS F090M', 'NICMOS F095N', 'NICMOS F097N', 'NICMOS F108N'
'NICMOS F110M', 'NICMOS F110W', 'NICMOS F113N', 'NICMOS F140W'
'NICMOS F145M', 'NICMOS F160W', 'NICMOS F164N', 'NICMOS F165M'
'NICMOS F166N', 'NICMOS F170M', 'NICMOS F187N', 'NICMOS F190N'
'NIRC2 J', 'NIRC2 H', 'NIRC2 Kp', 'NIRC2 Ks'
'WIRC J', 'WIRC H', 'WIRC K', 'WIRC CH4S', 'WIRC CH4L'
'WIRC CO', 'WIRC PaBeta', 'WIRC BrGamma', 'WIRC Fe2'
'WISE W1', 'WISE W2'
- Example:
>>> import splat >>> sp = splat.getSpectrum(shortname='1555+0954')[0] >>> print splat.estimateDistance(sp) Please specify the filter used to determine the apparent magnitude (nan, nan) >>> print splat.estimateDistance(sp, mag = 12.521, mag_unc = 0.022, absmag = 7.24, absmag_unc = 0.50, spt = 'M3') (116.36999172188771, 33.124820555524224)
- splat.empirical.redden(sp, **kwargs)¶
- Description:
Redden a spectrum based on an either Mie theory or a standard interstellar profile using Cardelli, Clayton, and Mathis (1989 ApJ. 345, 245)
Usage
>>> import splat >>> sp = splat.Spectrum(10001) # read in a source >>> spr = splat.redden(sp,av=5.,rv=3.2) # redden to equivalent of AV=5
- Note
This routine is still in beta form; only the CCM89 currently works
- splat.empirical.typeToColor(spt, color, reference='skrzypek2015', uncertainty=0.0, nsamples=100, verbose=False, forgiving=True, **kwargs)¶
- Purpose:
Takes a spectral type and optionally a color (string) and returns the typical color of the source.
- Required Inputs:
- param spt:
string, integer, float, list or numpy array specify the spectral type(s) to be evaluated
- param color:
string indicating color; e.g., color='SDSS_I-SDSS_Z'; filter names are checked against splat.FILTERS structure
- Optional Inputs:
- param reference:
Abs Mag/SpT relation used to compute the absolute magnitude. Options are:
skrzypek (default): Color trends from Skryzpek et al. (2015). Spectral type range is M5 to T8 Colors include SDSS_I-SDSS_Z, SDSS_Z-UKIDSS_Y, UKIDSS_Y-MKO_J, MKO_J-MKO_H, MKO_H-MKO_K, MKO_K-WISE_W1, WISE_W1-WISE_W2, and combinations therein.
leggett: Color trends from Leggett et al. (2017). Spectral type range is T7.5 to Y2 Colors include MKO_Y-WFC3_F105W, MKO_J-WFC3_F125W, MKO_J-WFC3_F127M, MKO_H-WFC3_F160W, MKO_H-WIRC_CH4S
- param uncertainty:
uncertainty on input spectral types, should be float, list of floats or numpy array (default = 0)
- param nsamples:
number of Monte Carlo samples for error computation (default = 100)
- param verbose:
Give feedback while in operation (default = False)
- Output:
A tuple containing the value and uncertainty (including systematic) of the resulting color. If more than one spectral type is given, this tuple contains two numpy arrays
- Example:
>>> import splat >>> import splat.empirical as spem >>> spem.typeToColor('L3', 'MKO_J-MKO_K') (1.4266666666666665, 0.07) >>> spem.typeToColor(['M5','M6','M7'], 'SDSS_I-SDSS_Z', reference = 'skrzypek', uncertainty=0.5) (array([0.91 , 1.4275 , 1.74333333]), array([0.5624636 , 0.27662768, 0.13987478])) >>> spem.typeToColor('M0', 'SDSS_I-SDSS_Z', ref = 'skrzypek', verbose=True) Using the SpT/color trends from skrzypek2015 Rejected 1 spectral type(s) for being outside relation range (nan, nan)
- splat.empirical.typeToMag(spt, filt, uncertainty=0.0, reference='filippazzo2015', verbose=False, nsamples=100, mask=True, mask_value=nan, **kwargs)¶
- Purpose:
Takes a spectral type and a filter, and returns the expected absolute magnitude based on empirical relations
- Required Inputs:
- param spt:
string or integer of the spectral type
- param filter:
filter for which to retrieve absolute magnitude, which must be defined for the given reference set.
You can check what filters are available by printing splat.SPT_ABSMAG_RELATIONS[reference]['filters'].keys(), where reference is, e.g., 'filippazzo2015'
- Optional Inputs:
- param reference:
Abs Mag/SpT relation used to compute the absolute magnitude (also 'ref' and 'set'). These are defined in splat.SPT_ABSMAG_RELATIONS and are currently as follows:
dahn2002: Abs Mag/SpT relation from Dahn et al. (2002) Allowed spectral type range is M7 to L8, and allowed filters are 2MASS J
hawley2002: Abs Mag/SpT relation from Hawley et al. (2002) Allowed spectral type range is M0 to T6, and allowed filters are 2MASS J
cruz2003: Abs Mag/SpT relation from Cruz et al. (2003) Allowed spectral type range is M6 to L8, and allowed filters are 2MASS J
tinney2003: Abs Mag/SpT relation from Tinney et al. (2003). Allowed spectral type range is L0 to T7.5, and allowed filters are Cousins I, UKIRT Z, J, K and 2MASS J, Ks
burgasser2007: Abs Mag/SpT relation from Burgasser (2007). Allowed spectral type range is L0 to T8, and allowed filters are MKO K.
looper2008: Abs Mag/SpT relation from Looper et al. (2008). Allowed spectral type range is L0 to T8, and allowed filters are 2MASS J, H, Ks.
dupuy2012: Abs Mag/SpT relation from Dupuy & Liu (2012). Allowed spectral type range is M6 to T9, and allowed filters are MKO Y, J, H,K, LP, 2MASS J, H, Ks, and WISE W1, W2.
faherty2012: Abs Mag/SpT relation from Faherty et al. (2012). Allowed spectral type range is L0 to T8, and allowed filters are MKO J, H, K.
tinney2014: Abs Mag/SpT relation from Tinney et al. (2014). Allowed spectral type range is T6.5 to Y2, and allowed filters are MKO J, WISE W2
filippazzo2015 (default): Abs Mag/SpT relation from Filippazzo et al. (2015). Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J and WISE W2.
faherty2016: Abs Mag/SpT relation for field dwarfs from Faherty et al. (2016). Allowed spectral type range is M6 to T9, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3
faherty2016-group: Abs Mag/SpT relation for "group" dwarfs from Faherty et al. (2016). Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3
faherty2016-young: Abs Mag/SpT relation for "young" dwarfs from Faherty et al. (2016). Allowed spectral type range is M7 to L7, and allowed filters are 2MASS J, H, Ks and WISE W1, W2, W3
- param uncertainty:
uncertainty of
spt
(default = 0)- param nsamples:
number of Monte Carlo samples for error computation (default = 100)
- Output:
2 element tuple providing the absolute magnitude and its uncertainty
- Example:
>>> import splat >>> print splat.typeToMag('L3', '2MASS J') (12.730064813273996, 0.4) >>> print splat.typeToMag(21, 'MKO K', ref = 'burgasser') (10.705292820099999, 0.26) >>> print splat.typeToMag(24, '2MASS J', ref = 'faherty') Invalid filter given for Abs Mag/SpT relation from Faherty et al. (2012) (nan, nan) >>> print splat.typeToMag('M0', '2MASS H', ref = 'dupuy') Spectral Type is out of range for Abs Mag/SpT relation from Dupuy & Liu (2012) Abs Mag/SpT relation (nan, nan)
- splat.empirical.typeToTeff(var, uncertainty=[0.0], reference='stephens09', nsamples=100, reverse=False, string=False, verbose=False, mask=True, mask_value=nan, **kwargs)¶
- Purpose:
Returns an effective temperature (Teff) and its uncertainty for a given spectral type (or vice versa) based on an empirical relation
- Required Inputs:
- param inp:
A single or array of either spectral types or effective temperatures (reverse).
If spectral types, these can be ints, floats or strings from 0 (K0) and 49.0 (Y9). If temperatures, these can be ints or floats and assumed to be in units of Kelvin. Note: you must set reverse=True to convert temperature to spectral type.
- Optional Inputs:
- param uncertainty:
uncertainty of spectral type/temperature (default = 0.001; also 'unc', 'spt_e')
- param reference:
Teff/SpT relation used to compute the effective temperature (also 'set'). Options are:
stephens (default): Teff/SpT relation from Stephens et al. (2009). Allowed spectral type range is M6 to T8 and uses alternate coefficients for L3 to T8.
golimowski: Teff/SpT relation from Golimowski et al. (2004). Allowed spectral type range is M6 to T8.
looper: Teff/SpT relation from Looper et al. (2008). Allowed spectral type range is L0 to T8.
marocco: Teff/SpT relation from Marocco et al. (2013). Allowed spectral type range is M7 to T8.
filippazzo: Teff/SpT relation from Filippazzo et al. (2015) <http://adsabs.harvard.edu/abs/2015ApJ...810..158F>`_. Allowed spectral type range is M6 to T9.
faherty: Teff/SpT relation from Faherty et al. (2016) <http://adsabs.harvard.edu/abs/2016ApJS..225...10F>`_.
This relation is defined for normal dwarfs (M7 < SpT < T8), young dwarfs (
-young
and-young2
, M7 < SpT < L7), and young dwarfs in groups (-group
, M7 < SpT < L7) - dupuy: Teff/SpT relation from Dupuy et al. (2017). This relation is defined for Saumon & Marley (2008) models (-saumon
, L1.5 < SpT < T5) and Lyon models (-lyon
, M7 < SpT < T5)- param reverse:
set to True to convert effective temperature to spectral type (default=False)
- param nsamples:
number of samples to use in Monte Carlo error estimation (default=100)
- Output:
A 2-element tuple containing the Teff/SpT and its uncertainty
- Example:
>>> import splat >>> print splat.typeToTeff(20) (2233.4796740905499, 100.00007874571999) >>> print splat.typeToTeff(20, unc = 0.3, ref = 'golimowski') (2305.7500497902788, 127.62548366132124)
- splat.empirical.typeToLuminosity(spt, uncertainty=0.0, reference='filippazzo2015', verbose=False, nsamples=100, reverse=False, **kwargs)¶
- Purpose:
Takes a spectral type and returns the expected scaled log luminosity (log Lbol/Lsun) based on empirical relations
- Required Inputs:
- param spt:
string or integer of the spectral type
- Optional Inputs:
- param reference:
log Lbol/SpT relation reference (also 'ref' and 'set'). These are defined in splat.SPT_LBOL_RELATIONS and are currently as follows:
filippazzo2015 (default): Lbol/SpT relation from Filippazzo et al. (2015) Allowed spectral type range is M6 to T9
- param uncertainty:
uncertainty of
spt
(default = 0)- param reverse:
apply reverse approach: given BC, infer spectral type
- param nsamples:
number of Monte Carlo samples for error computation (default = 100)
- Output:
2 element tuple providing the absolute magnitude and its uncertainty
- Example:
>>> import splat >>> print splat.typeToLuminosity('L3')
- splat.empirical.typeToBC(spt, filt, uncertainty=0.0, reference='filippazzo2015', verbose=False, nsamples=100, reverse=False, **kwargs)¶
- Purpose:
Takes a spectral type and a filter, and returns the expected bolometric correction BC = M_bol - M_filter
- Required Inputs:
- param spt:
string or integer of the spectral type
- param filter:
filter for which to retrieve absolute magnitude, which must be defined for the given reference set.
You can check what filters are available by printing splat.SPT_BC_RELATIONS[reference]['filters'].keys(), where reference is, e.g., 'filippazzo2015'
- Optional Inputs:
- param reference:
Abs Mag/SpT relation used to compute the absolute magnitude (also 'ref' and 'set'). These are defined in splat.SPT_BC_RELATIONS and are currently as follows:
liu2010: BC/SpT relation from Liu et al. (2010) Allowed spectral type range is M6 to T8.5, and allowed filters are MKO J, H, K
dupuy2013: BC/SpT relation from Dupuy & Kraus (2013) Allowed spectral type range is T8 to Y0.5, and allowed filters are MKO Y, J, H
filippazzo2015 (default): BC/SpT relation from Filippazzo et al. (2015) Allowed spectral type range is M6 to T8/9, and allowed filters are 2MASS J, Ks
filippazzo2015-young: BC/SpT relation for young sources from Filippazzo et al. (2015) Allowed spectral type range is M7 to T8, and allowed filters are 2MASS J, Ks
- param uncertainty:
uncertainty of
spt
(default = 0)- param reverse:
apply reverse approach: given BC, infer spectral type
- param nsamples:
number of Monte Carlo samples for error computation (default = 100)
- Output:
2 element tuple providing the absolute magnitude and its uncertainty
- Example:
>>> import splat >>> print splat.typeToBC('L3', '2MASS J')
- splat.utilities.checkAbsMag(ref, filt='', verbose=False)¶
- Purpose:
Checks that an input reference name and filter are among the available sets for typeToMag(), including a check of alternate names
- Required Inputs:
- param ref:
A string containing the reference for absolute magnitude relation,
among the keys and alternate names in splat.SPT_ABSMAG_RELATIONS
- Optional Inputs:
- param filt:
A string containing the filter name, to optionally check if this filter is among those defined in the reference set
- Output:
A string containing SPLAT's default name for a given reference set, or False if that reference is not present
Example:
>>> import splat >>> print(splat.checkEvolutionaryModelName('burrows')) burrows01 >>> print(splat.checkEvolutionaryModelName('allard')) False
- splat.utilities.checkBC(ref, filt='', verbose=False)¶
- Purpose:
Checks that an input reference name and filter are among the available sets for typeToBC(), including a check of alternate names
- Required Inputs:
- param ref:
A string containing the reference for absolute magnitude relation,
among the keys and alternate names in splat.SPT_BC_RELATIONS
- Optional Inputs:
- param filt:
A string containing the filter name, to optionally check if this filter is among those defined in the reference set
- Output:
A string containing SPLAT's default name for a given reference set, or False if that reference is not present
Example:
>>> import splat >>> print(splat.checkBC('filippazzo','2MASS J')) filippazzo2015 >>> print(splat.checkBC('dupuy','2MASS J')) False
- splat.utilities.checkLbol(ref, verbose=False)¶
- Purpose:
Checks that an input reference name are among the available sets for typeToLuminosity(), including a check of alternate names
- Required Inputs:
- param ref:
A string containing the reference for lumiosity/SpT relation,
among the keys and alternate names in splat.SPT_LBOL_RELATIONS
- Optional Inputs:
None
- Output:
A string containing SPLAT's default name for a given reference set, or False if that reference is not present
Example:
>>> import splat >>> print(splat.checkLbol('filippazzo')) filippazzo2015 >>> print(splat.checkBC('burgasser')) False
Conversion Routines¶
- splat.utilities.coordinateToDesignation(c, prefix='J', sep='', split='', decimal=False)¶
- Purpose:
Converts right ascension and declination into a designation string
- Parameters:
c -- RA and Dec coordinate to be converted; can be a SkyCoord object with units of degrees, a list with RA and Dec in degrees, or a string with RA measured in hour angles and Dec in degrees
- Output:
Designation string
- Example:
>>> import splat >>> from astropy.coordinates import SkyCoord >>> c = SkyCoord(238.86, 9.90, unit="deg") >>> print splat.coordinateToDesignation(c) J15552640+0954000 >>> print splat.coordinateToDesignation([238.86, 9.90]) J15552640+0954000 >>> print splat.coordinateToDesignation('15:55:26.4 +09:54:00.0') J15552640+0954000
- splat.utilities.designationToCoordinate(value, icrs=True, **kwargs)¶
- Purpose:
Convert a designation string into a RA, Dec tuple or ICRS SkyCoord objects (default)
- Parameters:
value (required) -- Designation string with RA measured in hour angles and Dec in degrees
icrs (optional, defualt = True) -- returns astropy SkyCoord coordinate in ICRS frame if
True
- Output:
Coordinate, either as [RA, Dec] or SkyCoord object
- Example:
>>> import splat >>> splat.designationToCoordinate('J1555264+0954120') <SkyCoord (ICRS): (ra, dec) in deg (238.8585, 9.90333333)>
- splat.utilities.designationToCoordinateString(designation, delimiter=' ', radec_delimiter=' ')¶
- Purpose:
Convert a designation string into a coordinate string with delimiters between hour, minute, second, etc.
- Required Inputs:
- param designation:
designation, which should be a string of the form 'J12345678+01234567'
- Optional Inputs:
- param:
delimiter = ' ': delimiter between coordinate elements
- param:
radec_delimiter = ' ': delimiter between RA and declination substrings
- Output:
coordinate string of the form '12 34 56.78 +01 23 45.67' (depending on delimiters)
- Example:
>>> import splat >>> splat.designationToCoordinateString('J1555264+0954120') 15 55 26.4 +09 54 12.0 >>> splat.designationToCoordinateString('J155526400+095412000',delimiter=':') 15 55 26.400 +09 54 12.000
- splat.utilities.designationToShortName(value)¶
- Purpose:
Produce a shortened version of designation
- Parameters:
value (required) -- Designation string with RA measured in hour angles and Dec in degrees
- Output:
Shorthand designation string
- Example:
>>> import splat >>> print splat.designationToShortName('J1555264+0954120') J1555+0954
- splat.utilities.typeToNum(inp, subclass='dwarf', error='', uncertainty=0.0, luminosity_class='', metallicity_class='', age_class='', color_class='', peculiar=False, verbose=False, **kwargs)¶
- Purpose:
Converts between string and numeric spectral types, with the option of specifying the class prefix/suffix and uncertainty tags
- Required inputs:
- param inp:
Spectral type to convert. Can convert a number or a string from 0.0 (K0) and 49.0 (Y9).
- Optional inputs:
- param:
error = '': flag to indicate magnitude of classification uncertainty; by default ':' for uncertainty > 1 subtypes and '::' for uncertainty > 2 subtype added as suffix to string output. Can also use err.
- param:
uncertainty = 0: numerical uncertainty of classification; can also use unc
- param:
subclass = 'dwarf': spectral class; options include:
field or fld or alpha: object is a field dwarf - no prefix/suffix to string output
sd or subdwarf: object is a subdwarf - 'sd' prefix to string output
dsd or d/sd: object is an intermediate subdwarf - 'd/sd' prefix to string output
esd: object is an extreme subdwarf - 'esd' prefix to string output
usd: object is an ultra subdwarf - 'usd' prefix to string output
delta: object is a extremely low surface gravity dwarf (~1 Myr) - 'delta' suffix to string output
vlg or gamma or lowg: object is a low surface gravity dwarf (~10 Myr) - 'gamma' suffix to string output
intg or beta: object is an intermediate surface gravity dwarf (~100 Myr) - 'beta' suffix to string output
giant: object is a giant with luminosity class III suffix added to string output
subgiant: object is a subgiant with luminosity class IV suffix added to string output
supergiant: object is a supergiant with luminosity class I suffix added to string output
- param:
metallicity_class = '': metallicity class of object, traditionally represented by 'sd','d/sd','esd','usd', and added on as prefix to string output. Can also use lumclass
- param:
luminosity_class = '': luminosity class of object traditionally represented by roman numerals (e.g., 'III') and added on as suffix to string output. Can also use lumclass
- param:
age_class = '': age class of object, traditionally one of 'alpha', 'beta', 'gamma', 'delta' and added on as suffix to string output (see subclass). Can also use 'ageclass'
- param:
color_class: color class of object, traditionally 'b' (for blue) or 'r' (for red), added as prefix to string output. Can also use 'colorclass'
- param:
peculiar = False: Set to True if object is peculiar, which adds a 'pec' suffix to string output
- param:
verbose = False: Set to True to provide more feedback
- Outputs:
The number or string of a spectral type
- Example:
>>> import splat >>> print splat.typeToNum(30) T0.0 >>> print splat.typeToNum('T0.0') 30.0 >>> print splat.typeToNum(27, peculiar = True, uncertainty = 1.2, lumclass = 'II') L7.0IIp: >>> print splat.typeToNum(50) Spectral type number must be between 0 (K0) and 49.0 (Y9) nan
- splat.utilities.properCoordinates(c, frame='icrs', icrs=True, **kwargs)¶
- Purpose:
Converts various coordinate forms to the proper SkyCoord format. Convertible forms include lists and strings.
- Parameters:
c -- coordinate to be converted. Can be a list (ra, dec) or a string.
- Example:
>>> import splat >>> print splat.properCoordinates([104.79, 25.06]) <SkyCoord (ICRS): ra=104.79 deg, dec=25.06 deg> >>> print splat.properCoordinates('06:59:09.60 +25:03:36.0') <SkyCoord (ICRS): ra=104.79 deg, dec=25.06 deg> >>> print splat.properCoordinates('J06590960+2503360') <SkyCoord (ICRS): ra=104.79 deg, dec=25.06 deg>
- splat.utilities.properDate(din, **kwargs)¶
- Purpose:
Converts various date formats into a standardized date of YYYY-MM-DD
- Parameters:
d -- Date to be converted.
format (Optional, string) -- Optional input format of the following form: * 'YYYY-MM-DD': e.g., 2011-04-03 (this is default output) * 'YYYYMMDD': e.g., 20110403 * 'YYMMDD': e.g., 20110403 * 'MM/DD/YY': e.g., 03/04/11 * 'MM/DD/YYYY': e.g., 03/04/2011 * 'YYYY/MM/DD': e.g., 2011/03/04 * 'DD/MM/YYYY': e.g., 04/03/2011 * 'DD MMM YYYY': e.g., 04 Mar 2011 * 'YYYY MMM DD': e.g., 2011 Mar 04
output (Optional, string) -- Format of the output based on the prior list
- Example:
>>> import splat >>> splat.properDate('20030502') '2003-05-02' >>> splat.properDate('2003/05/02') '02-2003-05' >>> splat.properDate('2003/05/02',format='YYYY/MM/DD') '2003-05-02' >>> splat.properDate('2003/05/02',format='YYYY/MM/DD',output='YYYY MMM DD') '2003 May 02'
Note that the default output format can be read into an astropy.time quantity >>> import splat >>> from astropy.time import Time >>> t = Time(splat.properDate('20030502')) >>> print(t)
2003-05-02 00:00:00.000
- splat.utilities.UVW(coord, distance, mu, rv, e_distance=0.0, e_mu=[0.0, 0.0], e_rv=0.0, nsamp=100, full=False, verbose=False)¶
THIS FUNCTION NEEDS CLEANING
Plotting Routines¶
- splat.plot.plotMap(*args, **kwargs)¶
- Purpose:
Plot coordinates onto an equatorial map grid
- Input:
One or more coordinates, specified as astropy.coordinates.SkyCoord objects, two-element arrays (RA and declination in decimal degrees), or string coordinate designation; the latter two are converted to SkyCoord variables using splat.properCoordinates()
- Parameters:
- projection = 'mollweide'
projection type; see the Basemap documentation
- reference_declination or rdec
a single or array of declinations to indicates as references, useful for denoting pointing limits
- galactic = False
Plot in galactic coordinates (NOT YET IMPLEMENTED)
- ecliptic = False
Plot in ecliptic coordinates (NOT YET IMPLEMENTED)
- extrgalactic or supergalactic = False
Plot in supergalactic coordinates (NOT YET IMPLEMENTED)
- marker or markers or symbol or symbols = 'o'
symbol type; see the matplotlib documentation
- size or sizes or symsize or symsizes = 10
symbol size
- color or colors = 'k'
color of plot symbols
- alpha or alphas = 0.5
transparency of plot symbols
- legend, legends, label or labels = None
list of strings providing legend-style labels for each spectrum plotted
- grid = True:
add a grid
- file or filename or output:
filename or filename base for output
- figsize = (8,6)
set the figure size; set to default size if not indicated
- tight = True:
makes a ``tight'' box plot to elimate extra whitespace
- Example:
>>> import splat >>> import splat.plot as splot >>> s = splat.searchLibrary(young=True) >>> c = [splat.properCoordinates(x) for x in s['DESIGNATION']] >>> splot.plotMap(c)
- splat.plot.plotSpectrum(inp, xrng=[], yrng=[], xlabel='', ylabel='', xlog=False, ylog=False, grid=False, legend=[], legend_location='upper right', fontscale=1, legend_fontscale=1, title='', color='k', colormap=None, linestyle='-', linewidth=1.5, alpha=1.0, show_noise=True, color_noise='k', linestyle_noise='-', linewidth_noise=1.5, alpha_noise=0.5, comparison=None, color_comparison='grey', linestyle_comparison='-', linewidth_comparison=1.5, alpha_comparison=1, residual=False, color_residual='m', linestyle_residual='-', linewidth_residual=1.5, alpha_residual=0.5, telluric=False, color_telluric='grey', linestyle_telluric='-', linewidth_telluric=1.5, alpha_telluric=0.2, features=[], mdwarf=False, ldwarf=False, tdwarf=False, young=False, binary=False, nsamples=100, band=[], band_color='k', band_alpha=0.2, band_label='', band_label_position='bottom', band_width=0.1, show_zero=True, stack=0.0, zeropoint=0.0, color_zero='k', linestyle_zero=':', linewidth_zero=1.5, alpha_zero=0.3, inset=False, inset_xrange=[], inset_yrange=[], inset_position=[0.65, 0.6, 0.2, 0.2], inset_features=False, output='', multiplot=False, multipage=False, layout=[1, 1], figsize=[], tight=True, interactive=False, **kwargs)¶
Primary plotting program for splat Spectrum objects.
- Parameters:
- inpSpectrum objects or array of Spectrum objects or nested array of Spectrum objects
- These are the spectra to be plotted; the input is flexible:
Spec: plot the spectrum Spec
[Spec1, Spec2, ...]: plot multiple spectra together, or separately if multiplot = True
[[Spec1, Spec2], [Spec3, Spec4], ..]: plot multiple sets of spectra (multiplot forced to be True)
- xrange: array of two floats or two unitted astropy quantities, default = [0.85,2.42]
plot range for wavelength axis
- yrangearray of two floats or two unitted astropy quantities, default = [-0.02,1.2] times `fluxMax()`_
plot range for flux axis
- xlabelstring, default = wave.unit
wavelength axis label; by default set by wave.unit in first Spectrum object
- ylabelstring, default = flux.unit
flux axis label; by default set by flux.unit in first Spectrum object
- xlog, ylogbool, default = False
set the x (wavelength) or y (flux) axis to plot as a log scale
- gridbool, default = False
set to True to add a grid
- telluricbool, default = False
indicate telluric absorption features
- featuresarray of strings, default = []
A list of strings indicating chemical features to label on the spectra options include H2O, CH4, CO, TiO, VO, FeH, H2, HI, KI, NaI, SB (for spectral binary)
- mdwarf, ldwarf, tdwarf, young, binaryboolean, default = False
Set to True to add pre-defined features characteristic of these classes
- legendarray of strings, default = []
list of strings providing legend-style labels for each spectrum plotted
- legend_locationstring, default = 'upper right'
place of legend; options are 'upper left', 'center middle', 'lower right' (variations thereof) and 'outside'
- legend_fontscale: float, default = 1
sets the scale factor for the legend fontsize (defaults to fontscale)
- bandarray of two floats or array of arrays of two floatS, default = []
a single or array of 2-element arrays that indicate bands that you want to specifically shade in
- band_colorstring or array of strings, default = 'k'
a single or array of colors to shade the bands
- band_alphafloat or array of floats, default = 0.2
a single or array of alphas to shade the bands (default = 0.2)
- band_labelstring or array of strings, default = ''
a single or array of labels to annotate the bands (default = '')
- band_label_positionstring or array of strings, default = 'bottom'
a single or array of strings indicating the position of the labels; can be 'bottom', 'middle', or 'top' (default = 'bottom')
- stackfloat, default = 0.
numerical offset to stack spectra on top of each other
- zeropointfloat or array of floats, default = 0.
list of offsets for each spectrum, giving finer control than stack
- show_zerobook, default = True
plot the zeropoint(s) of the spectra
- comparison:
a comparison Spectrum to compare in each plot, useful for common reference standard
- show_noiseboolean, default = False
set to True to plot the uncertainty for each spectrum
- residual = False:
plots the residual between two spectra
- color_comparison:
color of comparison source plot lines; by default all grey
- color:
color of plot lines; by default all black
- color_noise:
color of uncertainty lines; by default same as line color but reduced opacity
- colormap:
color map to apply based on matplotlib colormaps; see http://matplotlib.org/api/pyplot_summary.html?highlight=colormaps#matplotlib.pyplot.colormaps
- linestyle or linestyles:
line style of plot lines; by default all solid
- fontscale = 1:
sets a scale factor for the fontsize
- inset = False:
place an inset panel showing a close up region of the spectral data
- inset_xrange = False:
wavelength range for inset panel
- inset_yrange = False:
flux range for inset panel (otherwise set by flux)
- inset_position = [0.65,0.60,0.20,0.20]
position of inset planet in normalized units, in order left, bottom, width, height
- inset_features = False
list of features to label in inset plot
- output:
filename or filename base for output
- multiplot = False:
creates multiple plots, depending on format of input (optional)
- multipage = False:
spreads plots across multiple pages; output file format must be PDF if not set and plots span multiple pages, these pages are output sequentially as separate files
- layout = [1,1]:
defines how multiple plots are laid out on a page
- figsize:
set the figure size; set to default size if not indicated
- interactive = False:
if plotting to window, set this to make window interactive
- tight = True:
makes a ``tight'' box plot to elimate extra whitespace
- Returns:
- array of matplotlib figure objects
Each array element is one of the plots
See also
plotBatch
plots an array of spectra into a grid
plotSequence
plots a sequence of spectra vertically
Examples
Case 1: A simple view of a random spectrum.
>>> import splat >>> import splat.plot as splot >>> spc = splat.getSpectrum(spt='T5',lucky=True)[0] # grab one T5 spectrum >>> spc.plot() # this automatically generates a "quicklook" plot >>> splot.plotSpectrum(spc) # does the same thing >>> splot.plotSpectrum(spc,show_noise=True,tdwarf=True) # shows the spectrum uncertainty and T dwarf absorption features
- Case 2: Viewing a set of spectra for a given object
In this case we'll look at all of the spectra of TWA 30B in the library, sorted by year and compared to the first epoch data This is an example of using multiplot and multipage.
>>> import splat >>> import splat.plot as splot >>> splist = splat.getSpectrum(name = 'TWA 30B') # get all spectra of TWA 30B >>> junk = [sp.normalize([0.9,1.2]) for sp in splist] # normalize the spectra >>> dates = [sp.observation_date for sp in splist] # observation dates >>> spsort = [s for (d,s) in sorted(zip(dates,splist))] # sort spectra by dates >>> dates.sort() # don't forget to sort dates! >>> splot.plotSpectrum(spsort,multiplot=True,layout=[2,2],multipage=True, ... comparison=spsort[0],show_noise=True,mdwarf=True,telluric=True,legend=dates, ... yrange=[0,1.2],legend_location='lower left',color_comparison='m',alpha_comparison=0.5, ... output='TWA30B.pdf')
- Case 3: Display a spectra sequence of L dwarfs
This example uses the list of standard L dwarf spectra contained in SPLAT, and illustrates the stack feature.
>>> import splat >>> import splat.plot as splot >>> spt = [splat.typeToNum(i+20) for i in range(10)] # generate list of L spectral types >>> splat.initiateStandards() # initiate standards >>> splist = [splat.STDS_DWARF_SPEX[s] for s in spt] # extact just L dwarfs >>> junk = [sp.normalize([0.9,1.3]) for sp in splist] # normalize the spectra >>> legend = [sp.name for sp in splist] # set labels to be names >>> splot.plotSpectrum(splist,figsize=[10,20],legend=legend,stack=0.5, # here's our plot statement ... colormap='copper',legend_location='outside',telluric=True, ... xrange=[0.8,2.45],output='lstandards.pdf')
- splat.plot.plotBatch(inp, output='spectra_plot.pdf', comparisons=None, classify=False, normalize=False, normrange=[0.9, 1.4], layout=[2, 2], basecolors=['k', 'm'], legend=[], fontscale=0.7, classify_kwargs={}, plot_kwargs={}, **kwargs)¶
Plots a batch of spectra into a 2x2 set of PDF files, with options of overplotting comparison spectra, including best-match spectral standards inferred from splat.classifyByStandard(). This routine is essentially a wrapper for a specific use case of splat.plot.plotSpectrum().
- Parameters:
- inpSpectrum or string or array of these
A single or list of Spectrum objects or filenames, or the glob search string for a set of files (e.g., '/Data/myspectra/*.fits').
- outputstring, default = 'spectra_plot.pdf'
Filename for PDF file output; full path should be included if not saving to local directory
- comparisonsSpectrum or string or array of these, default = None
list of Spectrum objects or filenames for comparison spectra. If comparisons list is shorter than source list, then the last comparison source will be repeated. If the comparisons list is longer, the list will be truncated.
- classifyboolean, default = False
Set to True to classify sources based on comparison to spectral standards using splat.classifyByStandard(). Specific parameters for classification can be specifed with the classify_kwargs keyword
- normalizeboolean, default = False
Set to True to normalize source and (if passed) comparison spectra.
- normrangelist, default = [0.9,1.4]
Range in micron to compute the normalization
- layoutlist, default = [2,2]
Layout of plots on page (# per row x # per column)
- basecolorslist, default = ['k','m']
Baseline color pair for plotted spectrum and its (optional) comparison template
- legendlist, default = []
Set to list of legends for plots. The number of legends should equal the number of sources and comparisons (if passed) in an alternating sequence. The default is to display the file name for each source and object name for comparison (if passed)
- fontscalefloat, default = 0.7
Scale factor to change font size; default value is optimal for 2x2 layout
- classify_kwargsdict, default = {}
Dictionary of keywords for splat.classifyByStandard()
- plot_kwargsdict, default = {}
Dictionary of additional keywords for splat.plot.plotSpectrum()
- **kwargsdict, optional
Additional keyword parameters
- Returns:
- matplotlib figure object
Figure object containing all of the generated plots
See also
plotSpectrum
primary Spectrum plotting routine
Examples
Case 1: These commands will grab a set of high S/N, optically-classified L5 dwarfs, and plot them into a single multiple-page PDF document in a 2x2 grid with the best fit classification standard overplotted:
>>> import glob, splat >>> import splat.plot as splot >>> splist = splat.getSpectrum(opt_spt='L5',snr=100) >>> splot.plotBatch(splist,classify=True,normalize=True,yrange=[0,1.2],output='comparison.pdf')
Case 2: These commands will grab a list of spectral files, plot them into a single multiple-page PDF document in a 2x2 grid, with the best fit classification standard overplotted. The three calls of plotBatch() produce the same outcome.
>>> import glob, splat >>> import splat.plot as splot >>> files = glob.glob('/home/mydata/*.fits') >>> sp = splot.plotBatch(files,classify=True,output='comparison.pdf') >>> sp = splot.plotBatch('/home/mydata/*.fits',classify=True,output='comparison.pdf') >>> sp = splot.plotBatch([splat.Spectrum(file=f) for f in files],classify=True,output='comparison.pdf')
- splat.plot.plotSequence(spec, type_range=2, std_class='dwarf', spt='', output='', verbose=False, **kwargs)¶
- Purpose:
Visualze compares a spectrum to a sequence of standards laid out vertically. The standards are chosen to be some number of type about the best-guess classification, either passed as a parameter or determined with classifyByStandard(). More than one spectrum can be provided, in which case multiple plots are returned
- Required Inputs:
- param:
spec: A single or series of Spectrum objects or filenames, or the glob search string for a set of files to read in (e.g., '/Data/myspectra/*.fits'). At least one input must be provided
- Optional Inputs:
- param:
spt = '': Default spectral type for source; this input skips classifyByStandard()
- param:
type_range = 2: Number of subtypes to consider above and below best-fit spectral type
- param:
std_type = 'dwarf': Type of standards to compare to. Should be one of the following: 'dwarf' (default), 'sd', 'dsd', 'esd', 'vlg', 'intg'. These can also be defined by setting the equalivalent keyword parameter; e.g., plotSequence(spec,dwarf=True).
- param:
output = '': Filename for output; full path should be include if not saving to current directory. If blank, plot is shown on screen
- param:
verbose = False: Set to True to provide additional feedback
In addition, relevant parameters for `plotSpectrum()`_ and classifyByStandard() may be provided
- Outputs:
A matplotlib figure object containing the plot of the spectrum(a) compared to sequence of standards on screen or saved to file
- Example:
>>> import splat >>> import splat.plot as splot >>> sp = splat.getSpectrum(lucky=True)[0] >>> fig = splat.plotSequence(sp,output='classify.pdf')
Utility Routines¶
- splat.utilities.distributionStats(x, q=[0.16, 0.5, 0.84], weights=None, sigma=None, **kwargs)¶
- Purpose:
Find key values along distributions based on quantile steps. This code is derived almost entirely from triangle.py.
- splat.utilities.integralResample(xh, yh, xl, nsamp=100, method='fast')¶
- Purpose:
A 1D integral smoothing and resampling function that attempts to preserve total flux. Uses
scipy.interpolate.interp1d and scipy.integrate.trapz to perform piece-wise integration
Required Inputs:
- Parameters:
xh -- x-axis values for "high resolution" data
yh -- y-axis values for "high resolution" data
xl -- x-axis values for resulting "low resolution" data, must be contained within high resolution and have fewer values
Optional Inputs:
- Parameters:
nsamp -- Number of samples for stepwise integration
Output:
y-axis values for resulting "low resolution" data
- Example:
>>> # a coarse way of downsampling spectrum >>> import splat, numpy >>> sp = splat.Spectrum(file='high_resolution_spectrum.fits') >>> w_low = numpy.linspace(numpy.min(sp.wave.value),numpy.max(sp.wave.value),len(sp.wave.value)/10.) >>> f_low = splat.integralResample(sp.wave.value,sp.flux.value,w_low) >>> n_low = splat.integralResample(sp.wave.value,sp.noise.value,w_low) >>> sp.wave = w_low*sp.wave.unit >>> sp.flux = f_low*sp.flux.unit >>> sp.noise = n_low*sp.noise.unit
- splat.utilities.reMap(x1, y1, x2, nsamp=100, method='fast')¶
- Purpose:
Maps a function y(x) onto a new grid x'. If x' is higher resolution this is done through interpolation; if x' is lower resolution, this is done by integrating over the relevant pixels
Required Inputs:
- param x1:
x-axis values for original function
- param y1:
y-axis values for original function
- param x2:
x-axis values for output function
Optional Inputs:
- param nsamp:
Number of samples for stepwise integration if going from high resolution to low resolution
Output:
y-axis values for resulting remapped function
- Example:
>>> # a coarse way of downsampling spectrum >>> import splat, numpy >>> sp = splat.Spectrum(file='high_resolution_spectrum.fits') >>> w_low = numpy.linspace(numpy.min(sp.wave.value),numpy.max(sp.wave.value),len(sp.wave.value)/10.) >>> f_low = splat.integralResample(sp.wave.value,sp.flux.value,w_low) >>> n_low = splat.integralResample(sp.wave.value,sp.noise.value,w_low) >>> sp.wave = w_low*sp.wave.unit >>> sp.flux = f_low*sp.flux.unit >>> sp.noise = n_low*sp.noise.unit
- splat.core.readSpectrum(file, folder='', file_type='', wave_unit=Unit('micron'), flux_unit=Unit('erg / (micron s cm2)'), dimensionless=False, comment='#', delimiter='', crval1='CRVAL1', cdelt1='CDELT1', catch_sn=True, remove_nans=True, no_zero_noise=True, use_instrument_reader=True, instrument='SPEX-PRISM', instrument_param={}, verbose=False)¶
- Parameters:
- filestring
filename of data to be read in; if full path not provided, routine will search in local directory or in folder indicated by folder keyword; can also pass a URL to a remote file
- folder = ''string [optional]
full path to folder containing file
- file_type = ''string [optional]
- a string indicating some flags that specify what kind of file this is; some examples include:
csv = comma separated file (sets delimiter = ',')
tab or tsv = tab delimited file (sets delimiter = ' ')
pipe = pipe delimited file (sets delimiter = '|')
latex = latex-style table data (sets delimiter = ' & ')
waveheader = wavelength solution is contained within the fits header
wavelog = wavelength solution is logarithmic (common for echelle data)
sdss = sets both waveheader and wavelog
- wave_unit = DEFAULT_WAVE_UNITastropy.unit [optional]
units of wavelength axis, by default specified by the DEFAULT_WAVE_UNIT global parameter
- flux_unit = DEFAULT_FLUX_UNITastropy.unit [optional]
units of flux and uncertainty axes, by default specified by the DEFAULT_FLUX_UNIT global parameter note that you can specify a unitless number
- dimensionless = Falseboolean [optional]
set to True to set the flux units to a dimensionless quantity (for transmission, reflectance)
- comment = '#'string [optional]
for ascii files, character that indicates the file line is a comment (to be ignored)
- delimiter = ''string [optional]
for ascii files, character that separates columns of values
- crval1,cdelt1 = 'CRVAL1','CDELT1'string [optional]
for fits files for which the wavelength solution is embedded in header, these are the keywords containing the zeroth wavelength and linear change coefficient
- catch_sn = Trueboolean [optional]
set to True to check if uncertainty axis is actually signal-to-noise, by checking if median(flux/uncertainty) < 1 [NOTE: NO LONGER IMPLEMENTED]
- remove_nans = Trueboolean [optional]
set to True to remove all wave/flux/noise values for which wave or flux are nan
- no_zero_noise = Trueboolean [optional]
set to True to set all elements of noise array that are zero to numpy.nan; this helps in later computations of S/N or fit statistics
- use_instrument_reader = Truebool [optional]
set to True to use the default instrument read in the DEFAULT-INSTRUMENT global parameter checked against INSTRUMENTS dictionary
- instrument = DEFAULT_INSTRUMENTstring [optional]
instrument by which data was acquired, by default the DEFAULT-INSTRUMENT global parameter checked against INSTRUMENTS dictionary
- instrument_param = {}dict [optional]
instrument-specific parameters to pass to instrument reader
- verbose = Falseboolean [optional]
set to True to have program return verbose output
- splat.utilities.weightedMeanVar(vals, winp, *args, **kwargs)¶
- Purpose:
Computes weighted mean of an array of values through various methods. Returns weighted mean and weighted uncertainty.
- Required Inputs:
- param vals:
array of values
- param winp:
array of weights associated with
vals
- Optional Inputs:
- param method:
type of weighting to be used. Options include:
default: (default)
winp
is taken to be actual weighting valuesuncertainty: uncertainty weighting, where
winp
is the uncertainties ofvals
ftest: ftest weighting, where
winp
is the chi squared values ofvals
- param weight_minimum:
minimum possible weight value (default = 0.)
- param dof:
effective degrees of freedom (default = len(vals) - 1)
Note
When using
ftest
method, extradof
value is required- Output:
Weighted mean and uncertainty
- Example:
>>> import splat >>> splat.weightedMeanVar([3.52, 5.88, 9.03], [0.65, 0.23, 0.19]) (5.0057009345794379, 4.3809422657000594) >>> splat.weightedMeanVar([3.52, 5.88, 9.03], [1.24, 2.09, 2.29], method = 'uncertainty') (5.0069199363443841, 4.3914329968409946)
- splat.utilities.isNumber(s)¶
- Purpose:
Checks if something is a number.
- Parameters:
s (required) -- object to be checked
- Output:
True or False
- Example:
>>> import splat >>> print splat.isNumber(3) True >>> print splat.isNumber('hello') False
- splat.utilities.isUnit(s)¶
- Purpose:
Checks if something is an astropy unit quantity; written in response to the many ways that astropy now codes unit quantities
- Required Inputs:
- param s:
quantity to be checked
- Optional Inputs:
None
- Output:
True or False
- Example:
>>> import splat >>> import astropy.units as u >>> print splat.isUnit(3) False >>> print splat.isUnit(3.*u.s) True >>> print splat.isUnit(3.*u.s/u.s) True >>> print splat.isUnit((3.*u.s/u.s).value) False
- splat.utilities.numberList(numstr, sort=False)¶
- Purpose:
Convert a string listing of numbers into an array of numbers
- Required Input:
- param numstr:
string indicating number list, e.g., '45,50-67,69,72-90'
- Optional Input:
- param sort:
set to True to sort output list (default = False)
- Output:
list of integers specified by string
- Example:
>>> import splat >>> a = splat.numberList('45,50-67,69,72-90') >>> print(a) [45, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
- splat.utilities.randomSphereAngles(num, longitude_range=[0, 6.283185307179586], latitude_range=[-1.5707963267948966, 1.5707963267948966], exclude_longitude_range=[], exclude_latitude_range=[], degrees=False, **kwargs)¶
- Purpose:
Draw a set of angles from a uniform spherical distribution, with areal inclusion and exclusion constraints. Note that latitude range is assumed to run from -pi/2 to +pi/2
- Required Input:
- param num:
number of points to draw
- Optional Input:
- param:
longitude_range = [0,2pi]: range over longitude to draw values
- param:
latitude_range = [-pi,+pi]: range over latitude to draw values
- param:
exclude_longitude_range = []: range of longitudes to exclude values
- param:
exclude_latitude_range = []: range of latitudes to exclude values
- param:
degrees = False: by default, radians are assumed; set to True to convert to degrees (also checks if inclusion/exclusion ranges are in degrees)
- Output:
2 arrays of longitudes and latitudes drawn uniformly over select area
- Example:
>>> import splat >>> splat.randomSphereAngles(10) (array([ 2.52679013, 0.85193769, 5.98514797, 0.89943465, 5.36310536, 5.34344768, 0.01743906, 4.93856229, 0.06508084, 0.5517308 ]), array([-0.53399501, 0.04208564, 0.03089855, -0.60445954, 0.55800151, 0.80119146, -0.19318715, 0.76230148, -0.5935969 , -0.65839849])) >>> splat.randomSphereAngles(10,latitude_range=[-10,10],degrees=True) (array([ 28.55709202, 297.34760719, 152.79525894, 71.08745583, 153.56948338, 80.68486463, 7.75479896, 100.8408509 , 356.63091754, 66.16572906]), array([ 0.6747939 , -1.00316889, -2.26239023, 9.27397372, -8.96797181, 7.34796163, -1.93175289, 3.07888912, 0.69826684, -5.08428339]))
I/O Routines¶
- splat.utilities.checkOnline(*args)¶
- Purpose:
Checks if SPLAT's URL is accessible from your machine-- that is, checks if you and the host are online. Alternately checks if a given filename is present locally or online
- Example:
>>> import splat >>> spl.checkOnline() True # SPLAT's URL was detected. >>> spl.checkOnline() False # SPLAT's URL was not detected. >>> spl.checkOnline('SpectralModels/BTSettl08/parameters.txt') '' # Could not find this online file.
- splat.utilities.checkOnlineFile(*args)¶
- Purpose:
Checks if SPLAT's URL is accessible from your machine-- that is, checks if you and the host are online. Alternately checks if a given filename is present locally or online
- Example:
>>> import splat >>> spl.checkOnlineFile('SpectralModels/BTSettl08/parameters.txt') '' # Could not find this online file. >>> spl.checkOnlineFile() '' # SPLAT's URL was not detected; you are not online.
- splat.utilities.checkFile(filename, **kwargs)¶
- Purpose:
Checks if a spectrum file exists in the SPLAT's library.
- Parameters:
filename -- A string containing the spectrum's filename.
- Example:
>>> import splat >>> spectrum1 = 'spex_prism_1315+2334_110404.fits' >>> print spl.checkFile(spectrum1) True >>> spectrum2 = 'fake_name.fits' >>> print spl.checkFile(spectrum2) False
- splat.utilities.checkLocal(inputfile)¶
- Purpose:
Checks if a file is present locally or within the SPLAT code directory
- Example:
>>> import splat >>> spl.checkLocal('spl.py') True # found the code >>> spl.checkLocal('parameters.txt') False # can't find this file >>> spl.checkLocal('SpectralModels/BTSettl08/parameters.txt') True # found it
Modeling and Simulation Routines¶
Spectral Modeling Routines¶
- splat.model.getModel(*args, **kwargs)¶
- Purpose:
Redundant routine with loadModel() to match syntax of getSpectrum()
- splat.model.loadModel(modelset='btsettl08', instrument='SPEX-PRISM', raw=False, sed=False, *args, **kwargs)¶
- Purpose:
Loads up a model spectrum based on a set of input parameters. The models may be any one of the following listed below. For parameters between the model grid points, loadModel calls the function _loadInterpolatedModel().
- Required Inputs:
- param:
model: The model set to use; may be one of the following:
nextgen99: model set from Allard et al. (1999) with effective temperatures of 900 to 1600 K (steps of 100 K); surface gravities of 5.0 and 5.5 in units of cm/s^2; and metallicity fixed to solar (alternate designations: nextgen)
cond01: model set from Allard et al. (2001) with effective temperatures of 100 to 4000 K (steps of 100 K); surface gravities of 4.0 to 6.0 in units of cm/s^2 (steps of 0.5 dex); and metallicity fixed to solar; with condensate species removed from the photosphere (alternate designation: cond)
dusty01: model set from Allard et al. (2001) with effective temperatures of 500 to 3000 K (steps of 100 K); surface gravities of 3.5 to 6.0 in units of cm/s^2 (steps of 0.5 dex); and metallicity fixed to solar; with condensate species left in situ (alternate designation: dusty)
burrows06: model set from Burrows et al. (2006) with effective temperatures of 700 to 2000 K (steps of 50 K); surface gravities of 4.5 to 5.5 in units of cm/s^2 (steps of 0.1 dex); metallicity of -0.5, 0.0 and 0.5; and either no clouds or grain size 100 microns (fsed = 'nc' or 'f100'). equilibrium chemistry is assumed. Note that this grid is not completely filled and some gaps have been interpolated (alternate designations: burrows, burrows2006)
btsettl08: (default) model set from Allard et al. (2012) with effective temperatures of 400 to 2900 K (steps of 100 K); surface gravities of 3.5 to 5.5 in units of cm/s^2 (steps of 0.5 dex); and metallicity of -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.3, and 0.5 for temperatures greater than 2000 K only; cloud opacity is fixed in this model, and equilibrium chemistry is assumed. Note that this grid is not completely filled and some gaps have been interpolated (alternate designations: btsettled, btsettl, allard, allard12)
btsettl15: model set from Allard et al. (2015) with effective temperatures of 1200 to 6300 K (steps of 100 K); surface gravities of 2.5 to 5.5 in units of cm/s^2 (steps of 0.5 dex); and metallicity fixed to solar (alternate designations: 'allard15','allard2015','btsettl015','btsettl2015','BTSettl2015')
morley12: model set from Morley et al. (2012) with effective temperatures of 400 to 1300 K (steps of 50 K); surface gravities of 4.0 to 5.5 in units of cm/s^2 (steps of 0.5 dex); and sedimentation efficiency (fsed) of 2, 3, 4 or 5; metallicity is fixed to solar, equilibrium chemistry is assumed, and there are no clouds associated with this model (alternate designations: morley2012)
morley14: model set from Morley et al. (2014) with effective temperatures of 200 to 450 K (steps of 25 K) and surface gravities of 3.0 to 5.0 in units of cm/s^2 (steps of 0.5 dex); metallicity is fixed to solar, equilibrium chemistry is assumed, sedimentation efficiency is fixed at fsed = 5, and cloud coverage fixed at 50% (alternate designations: morley2014)
saumon12: model set from Saumon et al. (2012) with effective temperatures of 400 to 1500 K (steps of 50 K); and surface gravities of 3.0 to 5.5 in units of cm/s^2 (steps of 0.5 dex); metallicity is fixed to solar, equilibrium chemistry is assumed, and no clouds are associated with these models (alternate designations: saumon, saumon2012)
drift: model set from Witte et al. (2011) with effective temperatures of 1700 to 3000 K (steps of 50 K); surface gravities of 5.0 and 5.5 in units of cm/s^2; and metallicities of -3.0 to 0.0 (in steps of 0.5 dex); cloud opacity is fixed in this model, equilibrium chemistry is assumed (alternate designations: witte, witte2011, helling)
madhusudhan11: model set from Madhusudhan et al. (2011) with effective temperatures of 600 K to 1700 K (steps of 50-100 K); surface gravities of 3.5 and 5.0 in units of cm/s^2; and metallicities of 0.0 to 1.0 (in steps of 0.5 dex); there are multiple cloud prescriptions for this model, equilibrium chemistry is assumed (alternate designations: madhusudhan)
- Optional Inputs:
- param:
teff: effective temperature of the model in K (e.g. teff = 1000)
- param:
logg: log10 of the surface gravity of the model in cm/s^2 units (e.g. logg = 5.0)
- param:
z: log10 of metallicity of the model relative to solar metallicity (e.g. z = -0.5)
- param:
fsed: sedimentation efficiency of the model (e.g. fsed = 'f2')
- param:
cld: cloud shape function of the model (e.g. cld = 'f50')
- param:
kzz: vertical eddy diffusion coefficient of the model (e.g. kzz = 2)
- param:
slit: slit weight of the model in arcseconds (e.g. slit = 0.3)
- param:
sed: if set to True, returns a broad-band spectrum spanning 0.3-30 micron (applies only for BTSettl2008 models with Teff < 2000 K)
- param:
folder: string of the folder name containing the model set (default = '')
- param:
filename: string of the filename of the desired model; should be a space-delimited file containing columns for wavelength (units of microns) and surface flux (F_lambda units of erg/cm^2/s/micron) (default = '')
- param:
force: force the filename to be exactly as specified
- param:
fast: set to True to do a fast interpolation if needed, only for Teff and logg (default = False)
- param:
url: string of the url to the SPLAT website (default = 'http://www.browndwarfs.org/splat/')
- Output:
A SPLAT Spectrum object of the interpolated model with wavelength in microns and surface fluxes in F_lambda units of erg/cm^2/s/micron.
Example:
>>> import splat >>> mdl = splat.loadModel(teff=1000,logg=5.0) >>> mdl.info() BTSettl2008 model with the following parmeters: Teff = 1000 K logg = 5.0 cm/s2 z = 0.0 fsed = nc cld = nc kzz = eq Smoothed to slit width 0.5 arcseconds >>> mdl = splat.loadModel(teff=2500,logg=5.0,model='burrows') Input value for teff = 2500 out of range for model set burrows06 Warning: Creating an empty Spectrum object
- splat.model.loadOriginalModel(model='btsettl08', instrument='UNKNOWN', file='', **kwargs)¶
- Purpose:
Loads up an original model spectrum at full resolution/spectral range, based on filename or model parameters.
- Required Inputs:
None
- Optional Inputs:
- param:
model: The model set to use; may be one of the following:
btsettl08: (default) model set from Allard et al. (2012) with effective temperatures of 400 to 2900 K (steps of 100 K); surface gravities of 3.5 to 5.5 in units of cm/s^2 (steps of 0.5 dex); and metallicity of -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.3, and 0.5 for temperatures greater than 2000 K only; cloud opacity is fixed in this model, and equilibrium chemistry is assumed. Note that this grid is not completely filled and some gaps have been interpolated (alternate designations: btsettled, btsettl, allard, allard12)
burrows06: model set from Burrows et al. (2006) with effective temperatures of 700 to 2000 K (steps of 50 K); surface gravities of 4.5 to 5.5 in units of cm/s^2 (steps of 0.1 dex); metallicity of -0.5, 0.0 and 0.5; and either no clouds or grain size 100 microns (fsed = 'nc' or 'f100'). equilibrium chemistry is assumed. Note that this grid is not completely filled and some gaps have been interpolated (alternate designations: burrows, burrows2006)
morley12: model set from Morley et al. (2012) with effective temperatures of 400 to 1300 K (steps of 50 K); surface gravities of 4.0 to 5.5 in units of cm/s^2 (steps of 0.5 dex); and sedimentation efficiency (fsed) of 2, 3, 4 or 5; metallicity is fixed to solar, equilibrium chemistry is assumed, and there are no clouds associated with this model (alternate designations: morley2012)
morley14: model set from Morley et al. (2014) with effective temperatures of 200 to 450 K (steps of 25 K) and surface gravities of 3.0 to 5.0 in units of cm/s^2 (steps of 0.5 dex); metallicity is fixed to solar, equilibrium chemistry is assumed, sedimentation efficiency is fixed at fsed = 5, and cloud coverage fixed at 50% (alternate designations: morley2014)
saumon12: model set from Saumon et al. (2012) with effective temperatures of 400 to 1500 K (steps of 50 K); and surface gravities of 3.0 to 5.5 in units of cm/s^2 (steps of 0.5 dex); metallicity is fixed to solar, equilibrium chemistry is assumed, and no clouds are associated with these models (alternate designations: saumon, saumon2012)
drift: model set from Witte et al. (2011) with effective temperatures of 1700 to 3000 K (steps of 50 K); surface gravities of 5.0 and 5.5 in units of cm/s^2; and metallicities of -3.0 to 0.0 (in steps of 0.5 dex); cloud opacity is fixed in this model, equilibrium chemistry is assumed (alternate designations: witte, witte2011, helling)
madhusudhan: model set from Madhusudhan et al. (2011) with effective temperatures of 600 K to 1700 K (steps of 50-100 K); surface gravities of 3.5 and 5.0 in units of cm/s^2; and metallicities of 0.0 to 1.0 (in steps of 0.5 dex); there are multiple cloud prescriptions for this model, equilibrium chemistry is assumed (alternate designations: madhusudhan)
- param:
teff: effective temperature of the model in K (e.g. teff = 1000)
- param:
logg: log10 of the surface gravity of the model in cm/s^2 units (e.g. logg = 5.0)
- param:
z: log10 of metallicity of the model relative to solar metallicity (e.g. z = -0.5)
- param:
fsed: sedimentation efficiency of the model (e.g. fsed = 'f2')
- param:
cld: cloud shape function of the model (e.g. cld = 'f50')
- param:
kzz: vertical eddy diffusion coefficient of the model (e.g. kzz = 2)
- param:
instrument: instrument the model should be converted to (default = 'raw')
- param:
file: file name for model (default = '' or generated from parameters)
- param:
folder: folder containing file (default = '' or default folder for model set)
- param:
verbose: give lots of feedback
- Output:
A SPLAT Spectrum object of the model with wavelength in microns and surface fluxes in F_lambda units of erg/cm^2/s/micron.
- Example:
>>> import splat >>> mdl = splat.loadOriginalModel(model='btsettl',teff=2600,logg=4.5) >>> mdl.info() btsettl08 Teff=2600 logg=4.5 [M/H]=0.0 atmosphere model with the following parmeters: Teff = 2600 K logg = 4.5 dex z = 0.0 dex fsed = nc cld = nc kzz = eq
If you use this model, please cite Allard, F. et al. (2012, Philosophical Transactions of the Royal Society A, 370, 2765-2777) bibcode = 2012RSPTA.370.2765A
- splat.model.loadTelluric(wave_range=None, ndata=None, linear=True, log=False, output='transmission', source='eso', folder='./', *args)¶
Purpose:
Loads up telluric absorption spectrum from Livingston and Wallace (1991)
Required Inputs:
A wavelength array must be input in one of the following manners:
as an list passed as an argument
wave
; e.g., loadTelluric(wave)by specifying the min and max wavelengths with
wave_range
and number of points withndata
; e.g., loadTelluric(wave_range=[1.3,1.5],ndata=100)
Optional Inputs:
- param:
linear: linear sampling over
wave_range
(default = True)- param:
log: log-linear sampling over
wave_range
(default = False)- param:
folder: set to folder containing the Livingston and Wallace files (default = SPLAT's reference folder)
- param:
output: set to one of the following possible outputs: -
transmission
(default) - a numpy array containing the transmission spectrum -spectrum
- a Spectrum object containing the transmission spectrum
Output:
Either a numpy array or Spectrum object containing the transmission spectrum sampled over the wavelength range provided, with values ranging from 0 to 1
Example:
>>> import splat.model as spmdl >>> trans = spmdl.loadTelluric(wave_range=[1.3,1.5],ndata=1000) >>> print(trans) [ 9.89881739e-01 9.77062180e-01 9.64035135e-01 1.00051461e+00 9.96495927e-01 9.96135086e-01 9.97309832e-01 9.17222383e-01 8.20866597e-01 9.24702335e-01 9.97319517e-01 9.97450808e-01 8.98421113e-01 9.98372247e-01 9.60017183e-01 9.98449332e-01 9.94087424e-01 9.52683627e-01 9.87684348e-01 7.75109019e-01 9.76381023e-01 9.89867274e-01 8.71284143e-01 8.79453464e-01 8.85513893e-01 9.96684751e-01 9.89084643e-01 9.80117987e-01 9.85237657e-01 9.93525954e-01 9.95844421e-01 7.88396747e-01 9.82524939e-01 9.98155509e-01 9.96245824e-01 9.55002105e-01 ... >>> trans = spmdl.loadTelluric(wave_range=[1.3,1.5],ndata=1000,output='spectrum') >>> trans.info() Telluric transmission spectrum
If you use these data, please cite Livingston, W. & Wallace, L. (1991, UNKNOWN, , ) bibcode = 1991aass.book.....L
- splat.model.blackbody(temperature, **kwargs)¶
This program is still in development
- splat.model.modelFitGrid(specin, modelset='btsettl08', instrument='', nbest=1, plot=True, statistic='chisqr', verbose=False, output='fit', radius=<Quantity 0.1 solRad>, radius_tolerance=<Quantity 0.01 solRad>, radius_model='', compute_radius=False, constrain_radius=False, **kwargs)¶
- Purpose:
Fits a spectrum to a grid of atmosphere models, reports the best-fit and weighted average parameters, and returns either a dictionary with the best-fit model parameters or the model itself scaled to the optimal scaling factor. If spectrum is absolutely flux calibrated with the fluxcalibrate() method, the routine will also calculate the equivalent radii of the source. In addition, an input radius can be used to provide an additional constraint on the model
Required inputs:
- Parameters:
spec -- a Spectrum class object, which should contain wave, flux and noise array elements.
Optional inputs:
- Parameters:
model -- set of models to use (
set
andmodel_set
may also be used), from the available models given by loadModel().stat -- the statistic to use for comparing models to spectrum; can be any one of the statistics allowed in compareSpectra() routine (default = chisqr)
nbest -- sets the number of best-fit models to return (default = 1)
weights -- an array of the same length as the spectrum flux array, specifying the weight for each pixel (default: equal weighting)
mask -- an array of the same length as the spectrum flux array, specifying which data to include in comparison statistic as coded by 0 = good data, 1 = bad (masked). The routine generateMask() is called to create a mask, so parameters from that routine may be specified (default: no masking)
compute_radius -- if set to True, force the computation of the radius based on the model scaling factor. This is automatically set to True if the input spectrum is absolutely flux calibrated (default = False)
teff_range -- set to the range of temperatures over which model fitting will be done (
temperature_range
andt_range
may also be used; default = full range of model temperatures)logg_range -- set to the range of surface gravities over which model fitting will be done (
gravity_range
andg_range
may also be used; default = full range of model temperatures)z_range -- set to the range of metallicities over which model fitting will be done (
metallicity_range
may also be used; default = full range of model temperatures)return_model -- set to True to return a Spectrum class of the best-fit model instead of a dictionary of parameters (default = False)
return_mean_parameters -- set to True a dictionary of mean parameters (default = False)
return_all_parameters -- set to True to return all of the parameter sets and fitting values (default = False)
summary -- set to True to report a summary of results (default = True)
output -- a string containing the base filename for outputs associated with this fitting routine (
file
andfilename
may also be used; default = 'fit')plot -- set to True to suppress plotting outputs (default = False)
plot_format -- specifes the file format for output plots (default = pdf)
file_best_comparison -- filename to use for plotting spectrum vs. best-fit model (default = '
OUTPUT``_best_comparison.``PLOT_FORMAT
')file_mean_comparison -- filename to use for plotting spectrum vs. mean parameter model (default = '
OUTPUT``_mean_comparison.``PLOT_FORMAT
')
In addition, the parameters for compareSpectra() , generateMask() and `plotSpectrum()`_ may be used; see SPLAT API for details.
Output:
Default output is a dictionary containing the best-fit model parameters: model name, teff, logg, z, fsed, kzz, cloud and slit, as well as the scaling factor for the model and comparison statistic. If the input spectrum is absolutely flux calibrated, radius is also returned. Alternate outputs include:
a dictionary of the statistic-weighted mean parameters (
return_mean_parameters
= True)a list of dictionaries containing all parameters and fit statistics (
return_all_parameters
= True)a Spectrum class of the best-fit model scaled to the best-fit scaling (
return_model
= True)
- Example:
>>> import splat >>> import splat.model as spmod >>> sp = splat.getSpectrum(shortname='1507-1627')[0] >>> sp.fluxCalibrate('2MASS J',12.32,absolute=True) >>> p = spmod.modelFitGrid(sp,teff_range=[1200,2500],model='Saumon',file='fit1507') Best Parameters to fit to BT-Settl (2008) models: $T_{eff}$=1800.0 K $log g$=5.0 dex(cm / s2) $[M/H]$=-0.0 dex $f_{sed}$=nc $cld$=nc $log \kappa_{zz}$=eq dex(cm2 / s) R=0.143324498969 solRad chi=4500.24997585 Mean Parameters: $T_{eff}$: 1800.0+/-0.0 K $log g$: 5.0+/-0.0 dex(cm / s2) Radius: 0.143324498969+/-0.0 solRad $[M/H]$: 0.0+/-0.0 dex
- splat.model.modelFitMCMC(specin, modelset='BTSettl2008', instrument='SPEX-PRISM', verbose=False, showRadius=False, nsamples=1000, burn=0.1, **kwargs)¶
- Purpose:
Uses Metropolis-Hastings Markov Chain Monte Carlo method to compare a spectrum to atmosphere models. Returns the best estimate of whatever parameters are allowed to vary; can also compute the radius based on the scaling factor.
- Parameters:
spec -- Spectrum class object, which should contain wave, flux and noise array elements (required)
nsamples -- number of MCMC samples (optional, default = 1000)
burn -- the decimal fraction (0 to 1) of the initial steps to be discarded (optional; default = 0.1; alternate keywords
initial_cut
)set -- set of models to use; see loadModel for list (optional; default = 'BTSettl2008'; alternate keywords
model
,models
)verbose -- give lots of feedback (optional; default = False)
showRadius -- set to True so evaluate radius (optional; default = False unless spec is absolute flux calibrated)
Also takes commands for compareSpectra
- Parameters:
output -- filename or filename base for output files (optional; alternate keywords
filename
,filebase
)savestep -- indicate when to save data output; e.g.
savestep = 10
will save the output every 10 samples (optional, default =nsamples
/10)dataformat (optional, default = 'ascii.csv') -- output data format type
initial_guess (optional, default = array of random numbers within allowed ranges) -- array including initial guess of the effective temperature, surface gravity and metallicity of
spec
. Can also set individual guesses of spectral parameters by using initial_temperature or initial_teff, initial_gravity or initial_logg, and initial_metallicity or initial_z.ranges (optional, default = depends on model set) -- array of arrays indicating ranges of the effective temperature, surface gravity and metallicity of the model set. Can also set individual ranges of spectral parameters by using temperature_range or teff_range, gravity_range or logg_range, and metallicity_range or z_range.
step_sizes (optional, default = [50, 0.25, 0.1]) -- an array specifying step sizes of spectral parameters. Can also set individual step sizes by using temperature_step or teff_step, gravity_step or logg_step, and metallicity_step or z_step.
nonmetallicity (optional, default = False) -- if True, sets metallicity = 0
addon (optional, default = False) -- reads in prior calculation and starts from there. Allowed object types are tables, dictionaries and strings.
evolutionary_model (optional, default = 'Baraffe') --
set of evolutionary models to use. See Brown Dwarf Evolutionary Models page for more details. Options include:
'baraffe': Evolutionary models from Baraffe et al. (2003).
'burrows': Evolutionary models from Burrows et al. (1997).
'saumon': Evolutionary models from Saumon & Marley (2008).
emodel (optional, default = 'Baraffe') -- the same as
evolutionary_model
- Example:
>>> import splat >>> import splat.model as spmod >>> sp = splat.getSpectrum(shortname='1047+2124')[0] # T6.5 radio emitter >>> parameters = spmod.modelFitMCMC(sp,initial_guess=[900,5.0,0.0],nsamples=1000)
- splat.model.modelFitEMCEE(specin, mset='BTSettl2008', instrument='SPEX-PRISM', initial={}, nofit=[], showRadius=False, nwalkers=10, nsamples=100, threads=1, burn=0.5, propose_scale=1.1, verbose=False, **kwargs)¶
- Purpose:
Uses the
emcee
package by Dan Foreman-Mackey et al. to perform Goodman & Weare's Affine Invariant Markov chain Monte Carlo (MCMC) Ensemble sampler to fit a spectrum to a set of atmosphere models. Returns the best estimate of the effective temperature, surface gravity, and (if selected) metallicity. Includes an estimate of the time required to run, prompts user if they want to proceed, and shows progress with iterative saving of outcomes- Parameters:
spec -- Spectrum class object, which should contain wave, flux and noise array elements (required)
nwalkers -- number of MCMC walkers, should be at least 20 (optional, default = 20)
nsamples -- number of MCMC samples (optional, default = 500)
threads -- number of threads to run on a multiprocessing machine (optional, default = 1)
burn_fraction -- the fraction of the initial steps to be discarded; e.g., if
burn_fraction = 0.2
, the first 20% of the samples are discarded. (optional, default = 0.5)initial_guess -- array including initial guess of the model parameters. Can also set individual guesses of spectral parameters by using initial_temperature, initial_teff, or t0; initial_gravity, initial_logg or g0; and initial_metallicity, initial_z or z0 (optional, default = array of random numbers within allowed ranges)
limits -- list of 2-element arrays indicating ranges of the model parameters to limit the parameter space. Can also set individual ranges of spectral parameters by using temperature_range, teff_range or t_range; gravity_range, logg_range or g_range; and metallicity_range or z_range (optional, default = depends on model set)
prior_scatter -- array giving the widths of the normal distributions from which to draw prior parameter values (optional, default = [25,0.1,0.1])
model (optional, default = 'BTSettl2008') --
set of models to use (
set
andmodel_set
do the same); options include:'BTSettl2008': model set with effective temperature of 400 to 2900 K, surface gravity of 3.5 to 5.5 and metallicity of -3.0 to 0.5 from Allard et al. (2012)
'burrows06': model set with effective temperature of 700 to 2000 K, surface gravity of 4.5 to 5.5, metallicity of -0.5 to 0.5, and sedimentation efficiency of either 0 or 100 from Burrows et al. (2006)
'morley12': model set with effective temperature of 400 to 1300 K, surface gravity of 4.0 to 5.5, metallicity of 0.0 and sedimentation efficiency of 2 to 5 from Morley et al. (2012)
'morley14': model set with effective temperature of 200 to 450 K, surface gravity of 3.0 to 5.0, metallicity of 0.0 and sedimentation efficiency of 5 from Morley et al. (2014)
'saumon12': model set with effective temperature of 400 to 1500 K, surface gravity of 3.0 to 5.5 and metallicity of 0.0 from Saumon et al. (2012)
'drift': model set with effective temperature of 1700 to 3000 K, surface gravity of 5.0 to 5.5 and metallicity of -3.0 to 0.0 from Witte et al. (2011)
radius (optional, default = False) -- set to True to calculate and returns radius of object [NOT CURRENT IMPLEMENTED]
save (optional, default = True) -- save interim results to a .dat file based on output filename
output (optional, default = None) -- base filename for output (
filename
andoutfile
do the same); outputs will include (each can be set individually with associated keywords): -filename_iterative.dat
: interative saved data -filename_summary.txt
: summary of results -filename_corner.eps
: corner plot of parameters -filename_comparison.eps
: plot spectrum compared to best fit modelplot_format -- file type for diagnostic plots
noprompt (optional, default = False) -- don't prompt user to continue of emcee run will be > 10 minutes
verbose (optional, default = False) -- give lots of feedback
In addition, the parameters for compareSpectra, generateMask_, plotSpectrum_; see SPLAT API for details.
- Note: modelfitEMCEE requires external packages:
- Example:
>>> import splat >>> sp = splat.Spectrum(shortname='1507-1627')[0] >>> spt,spt_e = splat.classifyByStandard(sp) >>> teff,teff_e = splat.typeToTeff(spt) >>> result = modelFitEMCEE(sp,t0=teff,g0=5.0,fit_metallicity=False, >>> nwalkers=50,nsamples=500,output='/Users/adam/test_modelfitEMCEE') Estimated time to compute = 9228 seconds = 153.8 minutes = 2.56 hours = 0.11 days Do you want to continue? [Y/n]: Progress: [**************************************************]
Results are saved in test_modelfitEMCEE_interative.dat, *_chains.pdf, *_comparison.pdf, *_corner.pdf, and *_summary.txt
- splat.model.makeForwardModel(parameters, data, atm=None, binary=False, duplicate=False, model=None, model1=None, model2=None, instkern=None, contfitdeg=5, return_nontelluric=False, checkplots=False, checkprefix='tmp', verbose=False, timecheck=False)¶
- parameters may contain any of the following:
modelparam or modelparam1: dictionary of model parameters for primary if model not provided in model or model1: {modelset,teff,logg,z,fsed,kzz,cld,instrument}
modelparam2: dictionary of model parameters for secondary if model not provided in model2: {modelset,teff,logg,z,fsed,kzz,cld,instrument}
rv or rv1: radial velocity of primary
rv2: radial velocity of secondary
vsini or vsini1: rotational velocity of primary
vsini2: rotational velocity of secondary
f21: relative brightness of secondary to primary (f21 <= 1)
alpha: exponent to scale telluric absorption
vinst: instrument velocity broadening profile if instrkern not provided
vshift: instrument velocity shift
continuum: polynomial coefficients for continuum correction; if not provided, a smooth continuum will be fit out
offset: additive flux offset, useful if there may be residual background continuum
offset_fraction: additive flux offset as a fraction of the median flux, useful if there may be residual background continuum
- splat.model.mcmcForwardModelFit(data, param0, param_var, model=None, limits={}, nwalkers=1, nsteps=100, method='standard', outlier_sigma=0.0, return_threshold=0.9, dof=0.0, binary=False, duplicate=False, secondary_model=None, atm=None, report=True, report_index=10, report_each=False, file='tmp', output='all', verbose=False, **kwargs)¶
- Purpose:
Conducts and Markov Chain Monte Carlo (MCMC) forward modeling fit of a spectrum. This routine assumes the spectral data have already been wavelength calibrated THIS ROUTINE IS CURRENTLY IN DEVELOPMENT
- Required Inputs:
- param data:
Spectrum object containing the data to be modeled
- param param0:
dictionary containing the initial parameters; allowed parameters are the same as those defined in `makeForwardModel()`_
- param param_var:
dictionary containing the scales (gaussian sigmas) over which the parameters are varied at each iteration; should contain the same elements as param0. If a parameter var is set to 0, then that parameter is held fixed
- Optional Inputs:
- param:
limits = {}: dictionary containing the limits of the parameters; each parameter that is limited should be matched to a two-element list defining the upper and lower bounds
- param:
nwalkers = 1: number of MCMC walkers
- param:
nsteps = 100: number of MCMC steps taken by each walker; the actual number of fits is nsteps x # parameters
- param:
dof: degrees of freedom; if not provided, assumed to be the number of datapoints minus the number of varied parameters
- param:
binary = False: set to True to do a binary model fit
- param:
secondary_model = None: if binary = True, use this parameter to specify the model of the secondary
- param:
model = None: Spectrum object containing the spectral model to use if assumed fixed; should be of higher resolution and wider wavelength range than the data
- param:
atm = None: Spectrum object containing the atmospheric/instrumental transmission profile (e.g., `loadTelluric()`_); should be of higher resolution and wider wavelength range than the data
- param:
report = True: set to True to iteratively report the progress of the fit
- param:
report_index = 10: if report = True, the number of steps to provide an interim report
- param:
report_each = False: set to True to save all reports separately (useful for movie making)
- param:
file = 'tmp': file prefix for outputs; should include full path unless in operating in desired folder
- param:
output = 'all': what to return on completion; options include:
'all': (default) return a list of all parameter dictionaries and chi-square values
'best': return only a single dictionary of the best fit parameters and the best fit chi-square value
- param:
verbose = False: provide extra feedback
mcmcForwardModelFit() will also take as inputs the plotting parameters for `mcmcForwardModelReport()`_ and `plotSpectrum()`_
- Outputs:
Depending on what is set for the output parameter, a list or single dictionary containing model parameters, and a list or single best chi-square values. These outputs can be fed into `mcmcForwardModelReport()`_ to visualize the best fitting model and parameters
- Example:
>>> import splat >>> import splat.model as spmdl >>> import astropy.units as u >>> # read in spectrum >>> sp = splat.Spectrum('nirspec_spectrum.txt') >>> # read in and trim model >>> mdl = spmdl.loadModel(model='btsettl',teff=2600,logg=5.0,raw=True) >>> mdl.trim([numpy.min(sp.wave)-0.01*u.micron,numpy.max(sp.wave)+0.01*u.micron]) >>> # read in and trim atmospheric absorption >>> atm = spmdl.loadTelluric(wave_range=[numpy.min(mdl.wave.value)-0.02,numpy.max(mdl.wave.value)+0.02],output='spec') >>> # inital parameters >>> mpar = {'rv': 0., 'vsini': 10., 'vinst': 5., 'alpha': 0.6} >>> mvar = {'rv': 1., 'vsini': 1., 'vinst': 0.2, 'alpha': 0.05} >>> mlim = {'vsini': [0.,500.], 'alpha': [0.,100.]} >>> # do fit >>> pars,chis = spmdl.mcmcForwardModelFit(sp,mdl,mpar,mvar,limits=mlim,atm=atm,nsteps=100,file='fit'') >>> # visualize results >>> spmdl.mcmcForwardModelReport(sp,mdl,pars,chis,file='fit',chiweights=True,plotParameters=['rv','vsini'])
- splat.model.mcmcForwardModelReport(datain, parameters, chis, burn=0.25, dof=0, plotChains=True, plotBest=True, plotMean=True, plotCorner=True, saveParameters=True, plotParameters=None, writeReport=True, vbary=0.0, file='tmp', atm=None, model=None, model2=None, chiweights=False, binary=False, duplicate=False, plotColors=['k', 'magenta', 'r', 'b', 'grey', 'grey'], plotLines=['-', '-', '-', '-', '--', '--'], figsize_compare=[15, 5], verbose=False, corner_smooth=1.0, **kwargs)¶
- Purpose:
Plotting and fit analysis routine for `mcmcForwardModelFit()`_
- Required Inputs:
- param data:
Spectrum object containing the data modeled
- param parameters:
dictionary containing the parameters from the fit; each parameter should be linked to a array
- param chis:
list of the chi-square values (or equivalent statistic) that match the parameter arrays
- Optional Inputs:
- param:
atm = None: Spectrum object containing the atmospheric/instrumental transmission profile (e.g., `loadTelluric()`_)
- param:
burn = 0.25: initial fraction of parameters to throw out ("burn-in")
- param:
dof = 0: degrees of freedom; if not provided, assumed to be the number of datapoints minus the number of varied parameters
- param:
binary = False: set to True if a binary model fit was done
- param:
duplicate = False: set to True if the secondary spectrum has same model parameters as primary
- param:
vbary = 0.: set to a velocity (assumed barycentric) to add to rv values
- param:
model = None: Spectrum object containing the primary spectral model; should be of higher resolution and wider wavelength range than the data
- param:
model2 = None: Spectrum object containing the secondary spectral model; should be of higher resolution and wider wavelength range than the data
- param:
plotParameters = None: array of the parameters to plot, which should be keys in teh parameters input dictionary; if None, all of the parameters are plot
- param:
plotChains = True: set to True to plot the parameter & chi-square value chains
- param:
plotBest = True: set to True to plot the best fit model
- param:
plotMean = True: set to True to plot the mean parameter model
- param:
plotColors = ['k','b','g','magenta','grey','grey']: colors for spectral plot, in order of data, model, model without telluric, difference, upper noise, lower noise
- param:
plotLines = ['-','-','-','-','--','--']: linestyles for spectral plot, in order of data, model, model without telluric, difference, upper noise, lower noise
- param:
plotCorner = True: set to True to plot a corner plot of parameters (requires corner.py package)
- param:
writeReport = True: set to True to write out best and average parameters to a file
- param:
saveParameters = True: save parameters to an excel file
- param:
chiweights = False: apply chi-square weighting for determining mean parameter values
- param:
file = 'tmp': file prefix for outputs; should include full path unless in operating in desired folder
- param:
verbose = False: provide extra feedback
mcmcForwardModelReport() will also take as inputs the plotting parameters for `plotSpectrum()`_
- Outputs:
Depending on the flags set, various plots showing the derived parameters and best fit model for `mcmcForwardModelFit()`_
- Example:
>>> import splat >>> import splat.model as spmdl >>> import astropy.units as u >>> # read in spectrum >>> sp = splat.Spectrum('nirspec_spectrum.txt') >>> # read in and trim model >>> mdl = spmdl.loadModel(model='btsettl',teff=2600,logg=5.0,raw=True) >>> mdl.trim([numpy.min(sp.wave)-0.01*u.micron,numpy.max(sp.wave)+0.01*u.micron]) >>> # read in and trim atmospheric absorption >>> atm = spmdl.loadTelluric(wave_range=[numpy.min(mdl.wave.value)-0.02,numpy.max(mdl.wave.value)+0.02],output='spec') >>> # inital parameters >>> mpar = {'rv': 0., 'vsini': 10., 'vinst': 5., 'alpha': 0.6} >>> mvar = {'rv': 1., 'vsini': 1., 'vinst': 0.2, 'alpha': 0.05} >>> mlim = {'vsini': [0.,500.], 'alpha': [0.,100.]} >>> # do fit >>> pars,chis = spmdl.mcmcForwardModelFit(sp,mdl,mpar,mvar,limits=mlim,atm=atm,nsteps=100,file='fit'') >>> # visualize results >>> spmdl.mcmcForwardModelReport(sp,mdl,pars,chis,file='fit',chiweights=True,plotParameters=['rv','vsini'])
- splat.model.addUserModels(folders=[], default_info={}, verbose=False)¶
- Purpose:
Reads in list of folders with properly processed model sets, checks them, and adds them to the SPECTRAL_MODELS global variable
- Required Inputs:
None
- Optional Inputs:
- param folders = []:
By default model folders are set in the .splat_spectral_models file;
alternately (or in addition) folders of models can be included as an input list. * :param default_info = {}: default parameter set to use for models; superceded by 'info.txt' file if present in model folder * :param verbose = False: provide verbose feedback
- Outputs:
None, simply adds new model sets to SPECTRAL_MODELS global variable
- splat.model.processModelsToInstrument(instrument_parameters={}, instrument='SPEX-PRISM', wave_unit=Unit('micron'), flux_unit=Unit('erg / (micron s cm2)'), pixel_resolution=4.0, wave=[], wave_range=[], resolution=None, template=None, verbose=False, overwrite=False, *args, **kwargs)¶
- Purpose:
Converts raw spectral models into instrument-specific model sets, based on pre-defined or supplied information on wavelength range and resolution or a template spectrum
- Required Inputs:
modelset or set: name of the model set to convert, (for now) must be included in SPLAT distribution; may also be passed as a first argument
instrument or instr: name of the instrument to convert, either a predefined one (splat.INSTRUMENTS.keys()) or place holder for user-specified parameters; may also be passed as a second argument
- Optional Inputs:
If a predefined instrument is not used, user must supply one of the following combinations either as keywords or in an instrument_parameters dictionary parameter:
wave: an array containing the wavelengths to sample to; resolution is assumed 2 pixels per resolution element
wave_range and resolution: the first is a two-element array (assumed in microns if not specified), the second the effective resolution, assuming 2 pixels per resolution element
wave_unit: the unit for the wavelength axis
flux_unit: the unit for the flux density axis
template: a template spectrum object, from which the wave array is selected
pixel_resolution = 4: the number of pixels per resolution element
oversample = 5: by what factor to oversample the spectral data when smoothing
overscan = 0.05: percentage of total wavelength range to overextend in order to deal with edge effects in smoothing
method = 'hanning': filter design for smoothing
- Outputs:
If necessary, creates a folder in the splat.SPECTRAL_MODEL_FOLDER/[modelset]/[instrument] and outputs the model files
- WARNINGS:
there is currently a problem with "extraneaous pixels" for some conversions
- splat.utilities.checkSpectralModelName(model)¶
- Purpose:
Checks that an input model name is one of the available spectral models, including a check of alternate names
- Required Inputs:
- param:
model: A string containing the spectral model to be checked. This should be one of the models listed in loadModel()
- Optional Inputs:
None
- Output:
A string containing SPLAT's default name for a given model set, or False if that model set is not present
Example:
>>> import splat >>> print(splat.checkSpectralModelName('burrows')) burrows06 >>> print(splat.checkSpectralModelName('allard')) BTSettl2008 >>> print(splat.checkSpectralModelName('somethingelse')) False
- splat.model.info(model=None, verbose=False)¶
- Parameters:
- model = Nonestring
name of the model to summarize; set to None to list all models
- verbose = Falsebool [optional]
set to True to return verbose output, including listing all models
Evolutionary Model Routines¶
- splat.utilities.checkEvolutionaryModelName(model)¶
- Purpose:
Checks that an input model name is one of the available evolutionary models, including a check of alternate names
- Required Inputs:
- param:
model: A string containing the evolutionary model to be checked. This should be one of the models listed in splat.EVOLUTIONARY_MODELS.keys()
- Optional Inputs:
None
- Output:
A string containing SPLAT's default name for a given model set, or False if that model set is not present
Example:
>>> import splat >>> print(splat.checkEvolutionaryModelName('burrows')) burrows01 >>> print(splat.checkEvolutionaryModelName('allard')) False
- splat.evolve.loadEvolModel(model='baraffe2003', returnpandas=False, verbose=True, *args, **kwargs)¶
- Purpose:
Reads in the evolutionary model parameters for the models listed below, which are used to interpolate parameters in `modelParameters()`_.
Available models are:
baraffe1997 : Models from Baraffe et al. (1997) for 5 Gyr and 10 Gyr, 0.06 Msol < mass < 0.15 Msol, and [M/H] = -2 to 0 (COND dust prescription)
baraffe1998 : Models from Baraffe et al. (1998) for 1 Myr < age < 10 Gyr, 0.005 Msol < mass < 0.1 Msol, Teff > 1700 K, [M/H] = -0.5 and 1.0, and variations in mixing length and He abundance (COND dust prescription)
baraffe2015 : Models from Baraffe et al. (2015) for 1 Myr < age < 10 Gyr, 0.01 Msol < mass < 1.4 Msol, and solar metallicity
burrows2001 : Models from Burrows et al. (2001) for 1 Myr < age < 10 Gyr, 0.01 Msol < mass < 0.2 Msol, and solar metallicity
chabrier1997 : Models from Chabrier & Baraffe (1997) for 1 Myr < age < 10 Gyr, 0.075 Msol < mass < 0.8 Msol, and [M/H] = -2.0 to 0.0 (COND dust prescription)
saumon2008 : Models from Saumon et al. (2008) for 3 Myr < age < 10 Gyr, 0.002 Msol < mass < 0.085 Msol, Teff < 2500 K, -0.3 < [M/H] < 0.3, and various cloud prescriptions.
Parameter units (in astropy convention) are:
masses: Solar masses
ages: Gyr
temperature: K
gravity: log10 of cm/s/s
luminosity: log10 of Solar luminosities
radius: Solar radii
Models are contained in SPLAT's EvolutionaryModels folder.
Required Inputs:
- param:
model: string of the name of the evolutionary model set to be used; can be baraffe (default), burrows, or saumon
Optional Inputs:
- param:
metallicity: metallicity assumed for evolutionary models; can be either a single value or a list specifying a range. Be sure the given metallicity is included in the model
- param:
cloud: cloud property in Saumon & Marley (2008) models; must be a string and equal to 'nc', 'f2' or 'hybrid' (default).
- param:
y: He fraction in Baraffe et al. (1998) and Chabrier & Baraffe (1997) models. Be sure the value is included in the model
- param:
l_mix: mixing length parameter in Baraffe et al. (1998) models. Be sure the value is included in the model
Output:
Dictionary containing keywords mass, age, temperature, luminosity, gravity, and radius, each linked to the evolutionary parameters retrieved.
- Example:
>>> import splat >>> p = splat.loadEvolModel('saumon',metallicity=-0.3,cloud='nc') You are using saumon's models. >>> for k in list(p.keys()): print('{}: {}'.format(k, p[k][12])) age: 0.15 mass: [ 0.002 0.003 0.004 0.005 0.006 0.007 0.008 0.009 0.01 0.011 0.012 0.013 0.014 0.015 0.016 0.017 0.018 0.019 0.02 0.022 0.024 0.026 0.028 0.03 0.033 0.035 0.038 0.04 0.043 0.045 0.048 0.05 0.053] temperature: [ 353. 418. 471. 523. 585. 642. 695. 748. 806. 893. 1146. 1228. 1114. 1113. 1148. 1183. 1227. 1270. 1316. 1402. 1489. 1572. 1654. 1739. 1853. 1930. 2030. 2096. 2187. 2240. 2316. 2362. 2426.] gravity: [ 3.576 3.746 3.871 3.972 4.056 4.128 4.191 4.246 4.296 4.335 4.337 4.368 4.437 4.479 4.512 4.543 4.571 4.597 4.621 4.665 4.704 4.74 4.772 4.8 4.839 4.861 4.892 4.909 4.931 4.947 4.966 4.978 4.996] luminosity: [-6.691 -6.393 -6.185 -6.006 -5.815 -5.658 -5.527 -5.404 -5.277 -5.098 -4.628 -4.505 -4.709 -4.724 -4.675 -4.627 -4.568 -4.51 -4.45 -4.342 -4.24 -4.146 -4.058 -3.969 -3.856 -3.781 -3.69 -3.628 -3.546 -3.5 -3.432 -3.393 -3.34 ] radius: [ 0.1206 0.1214 0.1214 0.1209 0.1202 0.1195 0.1189 0.1182 0.1178 0.1181 0.123 0.1235 0.1184 0.1167 0.1161 0.1154 0.1151 0.1148 0.1146 0.1142 0.1139 0.1139 0.1138 0.1141 0.1144 0.115 0.1155 0.1163 0.1174 0.118 0.1193 0.12 0.121 ]
- splat.evolve.modelParameters(*model, **kwargs)¶
- Purpose:
Retrieves the evolutionary model parameters given two of the following parameters: mass, age, temperature, luminosity, gravity, or radius. The inputs can be individual values or arrays. Using the input parameters, the associated evolutionary model parameters are computed through log-linear interpolation of the original model grid. Parameters that fall outside the grid return nan.
Required Inputs:
- Param:
model: Either a string of the name of the evolutionary model set, which can be one of baraffe (default), burrows, or saumon; or a dictionary output from loadEvolModel() containing model parameters.
and two (2) of the following:
- Param:
mass: input value or list of values for mass (can also be masses or m)
- Param:
age: input value or list of values for age (can also be ages, time or a)
- Param:
temperature: input value or list of values for temperature (can also be temperatures, teff, temp or t)
- Param:
gravity: input value or list of values for gravity (can also be gravities, grav, logg or g)
- Param:
luminosity: input value or list of values for luminosity (can also be luminosities, lum, lbol or l)
- Param:
radius: input value or list of values for radius (can also be radii, rad and r)
Optional Inputs:
- Param:
Parameters for loadEvolModel() may also be used.
Output:
Dictionary containing keywords mass, age, temperature, luminosity, gravity, and radius, each linked to the evolutionary parameters retrieved.
- Example:
>>> import splat, numpy >>> masses = numpy.random.uniform(0.01,0.1,20) >>> ages = numpy.random.uniform(0.01,10,20) >>> p = splat.modelParameters('baraffe',mass=masses,age=ages) You are using baraffe's models. >>> print(p.temperature) [ 2502.90132332 2818.85920306 1002.64227134 1330.37273021 1192.86976417 500.45609068 2604.99966013 1017.03307609 1774.18267474 1675.12181635 2682.9697321 2512.45223777 346.41152614 2066.19972036 843.28528456 2264.93051445 2767.85660557 348.84214986 922.87030167 2669.27152307] K
- splat.evolve.plotModelParameters(parameters, xparam, yparam, **kwargs)¶
- Purpose:
Plots pairs of physical star parameters and optionally compares to evolutionary model tracks.
- Required Inputs:
- param:
parameters: dictionary or nested set of two arrays containing parameters to be plotted. For dictionary, keywords should include the xparameter and yparameter strings to be plotted. Values associated with keywords can be single numbers or arrays
- param:
xparam: string corresponding to the key in the parameters dictionary to be plot as the x (independent) variable.
- param:
yparam: string corresponding to the key in the parameters dictionary to be plot as the y (dependent) variable.
- Optional Inputs:
- param:
showmodel: set to True to overplot evolutionary model tracks from model (default = True)
- param:
model: either a string of the name of the evolutionary model set, one of baraffe (default), burrows, or saumon; or a dictionary output from loadEvolModel() containing model parameters.
- param:
tracks: string indicating what model tracks to show; can either be mass (default) or age
- param:
file: name of file to output plot (output can also be used)
- param:
show: set to True to show the plot onscreen (default = True)
- param:
figsize: a two-element array defining the figure size (default = [8,6])
- param:
color: color of data symbols (default = 'blue')
- param:
marker: matplotlib marker type for data symbols (default = 'o')
- param:
xlabel: string overriding the x-axis label (default = parameter name and unit)
- param:
ylabel: string overriding the y-axis label (default = parameter name and unit)
- param:
title: string specifying plot title (no title by default)
- param:
tight: set to True to tighten plot to focus on the data points (default = True)
- Output:
A matplotlib plot object. Optionally, can also show plot on screen or output plot to a file.
- Example:
>>> import splat, numpy >>> age_samp = 10.**numpy.random.normal(numpy.log10(1.),0.3,50) >>> mass_samp = numpy.random.uniform(0.001,0.1,50) >>> p = splat.modelParameters('baraffe',age=age_samp,mass=mass_samp) >>> splat.plotModelParameters(p,'age','temperature',showmodels=True,model='baraffe',show=True) [plot of temperature vs age for 50 data points with baraffe models overplotted]
Population Simulation Routines¶
- splat.simulate.UVWpopulation(uvw, e_uvw=[0.0, 0.0, 0.0], nsamp=1000, verbose=False)¶
- Purpose:
Computes the probabilities of a source being within the thin disk, thick disk or halo populations
using the analysis of Bensby et al. 2003
Required Inputs:
- Param:
uvw: array containing the UVW velocities in km/s in right-hand coordinate system
Optional Inputs:
- Param:
e_uvw: uarray containing the uncertainties of UVW in km/s (default = [0.,0.,0.])
- Param:
nsamp: number of Monte Carlo samples for error propogation (default = 1000)
- Param:
verbose: Give feedback (default = False)
Output:
Three value specifying the probability of being in the thin disk, thick disk, or halo (sums to 1)
- Example:
>>> import splat.evolve as spsim >>> pt,pth,ph = spsim.UVWpopulation([20.,-80.,10.],verbose=True) P(thin) = 0.418 P(thick) = 0.581 P(halo) = 0.000 Borderline thin/thick disk star
- splat.simulate.volumeCorrection(coordinate, dmax, dmin=0.0, model='juric', center='sun', nsamp=1000, unit=Unit('pc'), population='all', **kwargs)¶
- Purpose:
Computes the correction between the effective volume searched given an underly stellar density
model and the geometric volume. This program computes the value of the ratio:
$int_0^{x_{max}}{rho(x)x^2dx} / int_0^{x_{max}}{rho(0)x^2dx}$
- Required Inputs:
- param coordinate:
a variable that can be converted to an astropy SkyCoord value with splat.properCoordinates()
- param dmax:
the maximum distance to compute to, or an array of distances, assumed in units of parsec. In the case of an array, the result is the cumulative volume correction up to the corresponding maximum distance
- Optional Inputs:
- param:
model = 'juric': the galactic number density model; currently available:
'juric': (default) Juric et al. (2008, ApJ, 673, 864) called by splat.simulate.galacticDensityJuric()
'disk': exponential disk model parameterized by r1 and h1
'spheroid' or 'halo': spheroid model parameterized by q and n
- param:
population = 'all': depending on model, specifies what population to return. For example, model='juric' can take population='thin disk','thick disk','halo','bulge' or 'all'
- param:
center = 'sun': assumed center point, by default 'sun' but could also be 'galaxy'
- param:
nsamp = number of samples for sampling line of sight
- param:
unit = astropy.units.pc: preferred unit for positional arguments
- Output:
Estimate of the correction factor for the effective volume
- Example:
>>> import splat >>> import splat.simulate as spsim >>> c = splat.properCoordinates('J05591914-1404488') >>> spsim.volumeCorrection(c,10.) 1.0044083458899131 # note: slightly larger than 1 because we are going toward Galactic disk >>> spsim.volumeCorrection(c,10000.) 0.0060593740293862081
- TBD:
flag to return the integrated correction function as a function of distance (cumulative distribution)
flag to just integrate parts of a density distribution (e.g., "thin disk", "halo")
fix error at r = 0
- splat.simulate.galacticPotential(r, z, verbose=False, report='all')¶
- Purpose:
Computes the specific gravitational potential (energy per mass) at a particular radius r and
scaleheight z in the Milky Way Galaxy based on the cylindrically symmetric models of Barros et al. (2016, AandA, 593A, 108)
Required Inputs:
- Param:
r: radial coordinate from center of Galaxy in units of kpc
- Param:
r: vertical coordinate in plane of Galaxy in units of kpc
Optional Inputs:
- Param:
report: set to the following to return specific values: * all: return total potential (default) * disk: return only potential from the disk * halo: return only potential from the halo * bulge: return only potential from the bulge
- Param:
verbose: Give feedback (default = False)
Output:
Specific potential in units of km2/s2
- Example:
>>> import splat.evolve as spsim >>> pot = spsim.galacticPotential(8.5,2.0,verbose=True) Thin disk potential = -16164.669941534123 km2 / s2 Thick disk potential = -2805.8541251994084 km2 / s2 H I disk potential = -4961.194452965543 km2 / s2 H II disk potential = -1320.2381374715114 km2 / s2 Total disk potential = -25251.956657170587 km2 / s2 Bulge potential = -12195.097166319883 km2 / s2 Halo potential = 64175.96074890407 km2 / s2
Specialty Packages¶
EUCLID Analysis Routines¶
- splat.euclid.spexToEuclid(sp)¶
- Purpose:
Convert a SpeX file into EUCLID form, using the resolution and wavelength coverage defined from the Euclid Red Book (Laurijs et al. 2011). This function changes the input Spectrum objects, which can be restored by the Spectrum.reset() method.
- Parameters:
sp -- Spectrum class object, which should contain wave, flux and noise array elements
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] # grab a random file >>> splat.spexToEuclid(sp) >>> min(sp.wave), max(sp.wave) (<Quantity 1.25 micron>, <Quantity 1.8493000000000364 micron>) >>> sp.history [``'Spectrum successfully loaded``', ``'Converted to EUCLID format``'] >>> sp.reset() >>> min(sp.wave), max(sp.wave) (<Quantity 0.6454827785491943 micron>, <Quantity 2.555659770965576 micron>)
- splat.euclid.addEuclidNoise(sp)¶
- Purpose:
Adds Gaussian noise to a EUCLID-formatted spectrum assuming a constant noise model of 3e-15 erg/s/cm2/micron (as extrapolated from the Euclid Red Book; Laurijs et al. 2011 <http://sci.esa.int/euclid/48983-euclid-definition-study-report-esa-sre-2011-12/>`_). Note that noise is added to both flux and (in quadrature) variance. This function creates a new Spectrum object so as not to corrupt the original data.
- Parameters:
sp -- Spectrum class object, which should contain wave, flux and noise array elements
- Output:
Spectrum object with Euclid noise added in
- Example:
>>> import splat >>> sp = splat.getSpectrum(lucky=True)[0] # grab a random file >>> splat.spexToEuclid(sp) >>> sp.normalize() >>> sp.scale(1.e-14) >>> sp.computeSN() 115.96374031163553 >>> sp_noisy = splat.addEculidNoise(sp) >>> sp_noisy.computeSN() 3.0847209519763172
BibTeX Routines¶
- splat.citations.veryShortRef(bib_dict, **kwargs)¶
- Purpose:
Takes a bibtex entry and returns a short (in-line) version of the citation
- Required parameters:
- param bib_tex:
Dictionary output from bibTexParser, else a bibcode that is fed into bibTexParser
- Optional parameters:
None
- Output:
A string of the format
Burgasser et al. (2006)
- splat.citations.shortRef(bib_dict, **kwargs)¶
- Purpose:
Takes a bibtex dictionary and returns a short (in-line) version of the citation
- Required parameters:
- param bib_tex:
Dictionary output from bibTexParser, else a bibcode that is fed into bibTexParser
- Optional parameters:
None
- Output:
A string of the format
Burgasser, A. J., et al. (2006, ApJ, 710, 1142)
- splat.citations.longRef(bib_dict, **kwargs)¶
- Purpose:
Takes a bibtex dictionary and returns a long (in-line) version of the citation
- Required parameters:
- param bib_tex:
Dictionary output from bibTexParser, else a bibcode that is fed into bibTexParser
- Optional parameters:
None
- Output:
A string of the format
Burgasser, A. J., Cruz, K. L., Cushing, M., et al. SpeX Spectroscopy of Unresolved Very Low Mass Binaries. I. Identification of 17 Candidate Binaries Straddling the L Dwarf/T Dwarf Transition. ApJ 710, 1142 (2010)
- splat.citations.veryLongRef(bib_dict, **kwargs)¶
- Purpose:
Takes a bibtex dictionary and returns a long (in-line) version of the citation
- Required parameters:
- param bib_tex:
Dictionary output from bibTexParser, else a bibcode that is fed into bibTexParser
- Optional parameters:
None
- Output:
A string of the format
Burgasser, A. J., Cruz, K. L., Cushing, M., et al. SpeX Spectroscopy of Unresolved Very Low Mass Binaries. I. Identification of 17 Candidate Binaries Straddling the L Dwarf/T Dwarf Transition. ApJ 710, 1142 (2010)
- splat.citations.processBiblibrary(biblibrary, verbose=False)¶
- Purpose
Processes a bibtex .bib library (multiple bibtex entries) into a dictionary whose keys are the bibcode
- Required parameters:
- param biblibrary:
.bib file containing the bibtex entries
- Optional parameters:
- param:
verbose = False: Set to True to provide extensive feedback
- Output:
A dictionary containing the bibtex information, organized by bibcode key
- splat.citations.bibTexParser(bib_input, **kwargs)¶
- Purpose:
Parses a bibtex segment and returns a dictionary of parameter fields
- Required parameters:
- param bib_tex:
String containing bibtex data in standard format
- Optional parameters:
None
- Output:
A dictionary containing the parsed bibtex information
- splat.citations.citeURL(bib_dict, **kwargs)¶
- Purpose:
Generate the URL corresponding to a citation, based on the bibcode and NASA ADS syntax
- Required parameters:
- param bib_tex:
Dictionary output from bibTexParser, else a bibcode that is fed into bibTexParser
- Optional parameters:
None
- Output:
A string of the format
Burgasser, A. J., Cruz, K. L., Cushing, M., et al. SpeX Spectroscopy of Unresolved Very Low Mass Binaries. I. Identification of 17 Candidate Binaries Straddling the L Dwarf/T Dwarf Transition. ApJ 710, 1142 (2010)
Astroquery-based Data Access¶
- splat.database.getPhotometry(coordinate, return_pandas=True, catalog='2MASS', radius=<Quantity 30. arcsec>, sort='sep', limit=-1, info=False, nearest=False, verbose=False, **kwargs)¶
- Purpose
Downloads photometry for a single source coordinate using astroquery. If you are getting data on multiple sources, it is preferable to use splat.database.queryXMatch()
- Required Inputs:
- param:
coordinate: Either an astropy SkyCoord or a variable that can be converted into a SkyCoord using properCoordinates()
- Optional Inputs:
- param radius:
Search radius, nominally in arcseconds although this can be changed by passing an astropy.unit quantity (default = 30 arcseconds)
- param catalog:
Catalog to query, which can be set to the Vizier catalog identifier code or to one of the following preset catalogs:
'2MASS' (or set ``2MASS``=True): the 2MASS All-Sky Catalog of Point Sources (Cutri et al. 2003), Vizier id II/246
'SDSS' (or set ``SDSS``=True): the The SDSS Photometric Catalog, Release 9 (Adelman-McCarthy et al. 2012), Vizier id V/139
'WISE' (or set ``WISE``=True): the WISE All-Sky Data Release (Cutri et al. 2012), Vizier id II/311
'ALLWISE' (or set ``ALLWISE``=True): the AllWISE Data Release (Cutri et al. 2014), Vizier id II/328
'VISTA' (or set ``VISTA``=True): the VIKING catalogue data release 1 (Edge et al. 2013), Vizier id II/329
'CFHTLAS' (or set ``CFHTLAS``=True): the CFHTLS Survey (T0007 release) by (Hudelot et al. 2012), Vizier id II/317
'DENIS' (or set ``DENIS``=True): the DENIS DR3 (DENIS Consortium 2005), Vizier id B/denis/denis
'UKIDSS' (or set ``UKIDSS``=True): the UKIDSS-DR8 LAS, GCS and DXS Surveys (Lawrence et al. 2012), Vizier id II/314
'LEHPM' (or set ``LEHPM``=True): the Liverpool-Edinburgh High Proper Motion Catalogue (Pokorny et al. 2004), Vizier id J/A+A/421/763
'SIPS' (or set ``SIPS``=True): the Southern Infrared Proper Motion Survey (Deacon et al 2005), Vizier id J/A+A/435/363
'UCAC4' (or set ``UCAC4``=True): the UCAC4 Catalogue (Zacharias et al. 2012), Vizier id I/322A
'USNOB' (or set ``USNO``=True): the USNO-B1.0 Catalog (Monet et al. 2003), Vizier id I/284
'LSPM' (or set ``LSPM``=True): the LSPM-North Catalog (Lepine et al. 2005), Vizier id I/298
'GAIA-DR1': the GAIA DR1 Catalog (Gaia Collaboration et al. 2016), Vizier id I/337
'GAIA' or 'GAIA-DR2' (or set ``GAIA``=True): the GAIA DR2 Catalog (REF TBD), Vizier id I/345/gaia2
- param:
sort: String specifying the parameter to sort the returned SIMBAD table by; by default this is the offset from the input coordinate (default = 'sep')
- param:
nearest: Set to True to return on the single nearest source to coordinate (default = False)
- param:
return_pandas: Return a pandas table as opposed to an astropy Table (default = True)
- param:
verbose: Give feedback (default = False)
- Output:
An astropy or pandas Table that contains data from the Vizier query, or a blank Table if no sources are found
Example:
>>> import splat >>> import splat.database as spdb >>> from astropy import units as u >>> c = splat.properCoordinates('J053625-064302') >>> v = spdb.querySimbad(c,catalog='SDSS',radius=15.*u.arcsec) >>> print(v) _r _RAJ2000 _DEJ2000 mode q_mode cl ... r_E_ g_J_ r_F_ i_N_ sep arcs deg deg ... mag mag mag mag arcs ------ ---------- ---------- ---- ------ --- ... ---- ---- ---- ---- ------ 7.860 84.105967 -6.715966 1 3 ... -- -- -- -- 7.860 14.088 84.108113 -6.717206 1 6 ... -- -- -- -- 14.088 14.283 84.102528 -6.720843 1 + 6 ... -- -- -- -- 14.283 16.784 84.099524 -6.717878 1 3 ... -- -- -- -- 16.784 22.309 84.097988 -6.718049 1 + 6 ... -- -- -- -- 22.309 23.843 84.100079 -6.711999 1 + 6 ... -- -- -- -- 23.843 27.022 84.107504 -6.723965 1 + 3 ... -- -- -- -- 27.022
- splat.database.querySimbad(variable, radius=<Quantity 30. arcsec>, sort='sep', reject_type='', nearest=False, iscoordinate=False, isname=False, clean=False, return_pandas=True, verbose=False, **kwargs)¶
- Purpose
Queries SIMBAD using astroquery for a single source If you are getting data on multiple sources, it is preferable to use splat.database.queryXMatch()
- Required Inputs:
- param:
variable: Either an astropy SkyCoord object containing position of a source, a variable that can be converted into a SkyCoord using spl.properCoordinates(), or a string name for a source.
- Optional Inputs:
- param:
radius: Search radius, nominally in arcseconds although can be set by assigning and astropy.unit value (default = 30 arcseconds)
- param:
sort: String specifying the parameter to sort the returned SIMBAD table by; by default this is the offset from the input coordinate (default = 'sep')
- param:
reject_type: Set to string or list of strings to filter out object types not desired. Useful for crowded fields (default = None)
- param:
nearest: Set to True to return on the single nearest source to coordinate (default = False)
- param:
iscoordinate: Specifies that input is a coordinate of some kind (default = False)
- param:
isname: Specifies that input is a name of some kind (default = False)
- param:
clean: Set to True to clean the SIMBAD output and reassign to a predefined set of parameters (default = True)
- param:
return_pandas: Return a pandas table as opposed to an astropy Table (default = True)
- param:
verbose: Give lots of feedback (default = False)
- Output:
An astropy or pandas Table that contains data from the SIMBAD search, or a blank Table if no sources found
Example:
>>> import splat >>> import splat.database as spdb >>> from astropy import units as u >>> c = splat.properCoordinates('J053625-064302') >>> q = spdb.querySimbad(c,radius=15.*u.arcsec,reject_type='**') >>> print(q) NAME OBJECT_TYPE OFFSET ... K_2MASS K_2MASS_E ----------------------- ----------- ------------- ... ------- --------- BD-06 1253B Star 4.8443894429 ... [SST2010] 3 Star 5.74624887682 ... 18.36 0.1 BD-06 1253 Ae* 7.74205447776 ... 5.947 0.024 BD-06 1253A ** 7.75783861347 ... 2MASS J05362590-0643020 brownD* 13.4818185612 ... 12.772 0.026 2MASS J05362577-0642541 Star 13.983717577 ...
- splat.database.queryVizier(coordinate, **kwargs)¶
- splat.database.queryNist(element, wave_range, clean=['Observed'], noclean=False, verbose=True, wavelength_type='vacuum')¶
- splat.database.queryXMatch(db, radius=<Quantity 30. arcsec>, catalog='2MASS', file='', desigCol='DESIGNATION', raCol='RA', decCol='DEC', verbose=False, clean=True, drop_repeats=True, use_select_columns=False, select_columns=[], prefix=None, info=False, debug=False, *args)¶
- Purpose
Queries databases in the XXX XMatch service (REF), including SIMBAD This is the preferred manner for extracting data for large numbers of sources
- Required Inputs:
- param:
db: a pandas Dataframe (FUTURE: astropy Table, dict, or file name for csv, txt or xls file).
This must contain column(s) for designation (specified in desigCol) and/or RA (specified in raCol) and DEC (specified in decCol)
- Optional Inputs:
- param radius:
Search radius, nominally in arcseconds although can be set by assigning and astropy.unit value (default = 30 arcseconds)
- param desigCol:
column in db that specifies source designations ('Jhhmmss[.]s±ddmmss[.]s')
- param raCol:
column in db that specifies source RAs (in degrees)
- param decCol:
column in db that specifies source DECs (in degrees)
- param catalog:
Database to query, which can be set one of the follow presets or any catalog listed in astroquery.xmatch.XMatch.get_available_tables():
'SIMBAD' (or set ``SIMBAD``=True): query SIMBAD (coordinate search only)
'2MASS' (or set ``2MASS``=True): query the 2MASS All-Sky Catalog of Point Sources (Cutri et al. 2003), Vizier id II/246
'SDSS' (or set ``SDSS``=True): query the SDSS Photometric Catalog, Release 12 (NEED REF), Vizier id V/147
'SDSS9' (or set ``SDSS``=True): query the SDSS Photometric Catalog, Release 9 (Adelman-McCarthy et al. 2012), Vizier id V/147
'ALLWISE' (or set ``ALLWISE``=True): the AllWISE Data Release (Cutri et al. 2014), Vizier id II/328
'DENIS' (or set ``DENIS``=True): the DENIS DR3 (DENIS Consortium 2005), Vizier id B/denis/denis
'GAIA-DR1': the GAIA DR1 Catalog (Gaia Collaboration et al. 2016), Vizier id I/337
'GAIA' or 'GAIA-DR2' (or set ``GAIA``=True): the GAIA DR2 Catalog (REF TBD), Vizier id I/345/gaia2, accessed using astroquery.gaia
- param nearest:
Set to True to return only the single nearest source to each coordinate (default = True)
- param clean:
Set to True to clean the SIMBAD output and reassign to a predefined set of parameters (default = True)
- param file:
Write the output to a csv or xlsx file (default = '' or not saved)
- param verbose:
Give lots of feedback (default = False)
- param sort:
String specifying the parameter to sort the returned SIMBAD table by; by default this is the offset from the input coordinate (default = 'sep')
- param return_pandas:
Return a pandas table as opposed to an astropy Table (default = True)
- param reject_type:
Set to string or list of strings to filter out object types not desired. Useful for crowded fields (default = None)
- Output:
A pandas Dataframe that contains data from the search, or a blank frame if no sources found
Example:
>>> import splat >>> from astropy import units as u >>> c = spl.properCoordinates('J053625-064302') >>> q = spl.querySimbad(c,radius=15.*u.arcsec,reject_type='**') >>> print(q) NAME OBJECT_TYPE OFFSET ... K_2MASS K_2MASS_E ----------------------- ----------- ------------- ... ------- --------- BD-06 1253B Star 4.8443894429 ... [SST2010] 3 Star 5.74624887682 ... 18.36 0.1 BD-06 1253 Ae* 7.74205447776 ... 5.947 0.024 BD-06 1253A ** 7.75783861347 ... 2MASS J05362590-0643020 brownD* 13.4818185612 ... 12.772 0.026 2MASS J05362577-0642541 Star 13.983717577 ...
Search