Spectrum classes and functions#
- class specpolFlow.Spectrum(wl, specI, specV, specN1, specN2, specSig, header=None)#
Contains an observed spectrum, usually spectropolarimetric data.
Usually contains arrays:
wl - wavelengths
specI - Stokes I spectrum
specV - polarized spectrum, usually Stokes V
specN1 - the first polarimetric null spectrum
specN2 - the second polarimetric null spectrum
specSig - the formal uncertainties, which apply to the other spectra
- air_to_vacuum()#
Convert the spectrum from wavelength in air to wavelength in vacuum (assuming dry air at 15 C and 1 atmosphere of pressure) and return the modified spectrum.
This function requires the Spectrum to have wavelength in angstroms.
- Return type:
- calc_ew(lineRange, contRange=None, norm='auto', plot=True, verbose=False)#
Calculate the equivalent width, of Stokes I, for a portion of this spectrum.
This function can automatically estimate a continuum level, or a specific value can be given.
This function is a convenience wrapper around Spectrum.individual_line() and LSD.calc_ew()
- Parameters:
lineRange – the wavelength range used for the equivalent width calculation. This should be 2 element list, tuple, or array with start and end values.
contRange – the wavelength range used to estimate the continuum level, using the median value, if norm=’auto’. Multiple ranges can be used, with a list of lists (with the inner list containing start and end values), or an array of dimensions (nRanges, 2). The region inside lineRange is automatically excluded, so contRange can span lineRange.
norm – calculation method for the continuum. The choices are: ‘auto’: the median of Stokes I outside of lineRange and inside contRange, or float: a user defined fixed value.
plot – If True, return a matplotlib figure of the line profile and velocity ranges used, as the last returned value.
verbose – If True print some extra diagnostic information, including the continuum level.
- Returns:
A dictionary containing the equivalent width, its uncertainty, the continuum level, and some other diagnostic information. If plot=True a matplotlib figure is also returned. The equivalent width is in the wavelength units of lambda0,
- coadd(*args, byOrders=True, mergeOrders='none')#
coadd this spectrum with other spectra
Uses the the wavelength grid of this spectrum for the coadded spectrum. Other spectra are interpolated onto this spectrum’s wavelengths before coadding. Coadding here essentially averages spectra weighted by 1/sigma**2. This assumes the spectra are continuum normalized, and have reliable uncertainties.
Spectra can be split into individual spectral orders and then have each order coadded (when byOrders=True) or the orders in the spectra can be merged before coadding (when mergeOrders=’trim’ or =’coadd’). If neither option is used, and there are regions with order overlap, or where wavelength goes backwards, will produce incorrect results with this routine.
- Parameters:
args – other Spectrum objects (or a list or tuple of them) to coadd with this one
byOrders – flag for whether individual orders are coadded (True), or whole spectra are coadded at once assuming no overlap (False). If this is False, orders should already be merged, or the mergeOrders flag should be set to ‘trim’ or ‘coadd’.
mergeOrders – optional method for merging spectral orders before coadding. Options are ‘trim’, ‘coadd’, or ‘none’. See the merge_orders function for details. (If this is not ‘trim’ or ‘coadd’ no merging will be done.) If both this flag and byOrders=True are set, then orders are merged before coadding, effectively overriding byOrders=True.
- Return type:
- concatenate(*args)#
Combine this Spectrum with other Spectrum objects, passed as arguments, concatenating them in order, into a new Spectrum object.
- Parameters:
args – other Spectrum objects (or a list or tuple of them) to concatenate with this one
- Return type:
- convolveR(R)#
Convolve the spectrum with a Gaussian instrumental profile corresponding to a resolution R. (R is the FWHM of the Gaussian)
Note: Uncertainties are not propagated in this routine. The convolution operation introduces strong correlations into the uncertainties for nearby pixels, which is requires careful treatment. This routine should not be used for cases where statistics or uncertainties are important.
- Parameters:
R – the instrumental resolution, unit-less (in the form lambda/delta_lambda)
- Return type:
- doppler_shift(velocity)#
Doppler shift the spectrum according to an input radial velocity.
- Parameters:
velocity – the radial velocity in km/s
- Return type:
- get_orders(ignoreGaps=False)#
Split an observed echelle spectrum into individual echelle orders.
This splits a concatenated spectrum into echelle orders, based on overlap (places where wavelength decreases), and optionally gaps in wavelength between orders.
- Parameters:
ignoreGaps – if True then regions separated by gaps in wavelength are treated as one order, otherwise gaps are used as order edges
- Returns:
a list of Spectrum objects, one for each identified order
- get_orders_in_range(wl1, wl2=None, ignoreGaps=False)#
Split an observed echelle spectrum into individual orders, and return orders that include the specified wavelength range.
This splits a concatenated spectrum into echelle orders, based on overlap (places where wavelength decreases), and optionally gaps in wavelength between orders. Returning the order, or orders, that include any part of the specified wavelength range (wl1 and wl2 can be identical).
- Parameters:
wl1 – the start of the wavelength range to include
wl2 – the end of the wavelength range to include (if not provided, orders including just the point in wavelength wl1 will be returned)
ignoreGaps – if True then regions separated by gaps in wavelength are treated as one order, otherwise gaps are used as order edges
- Returns:
a list of Spectrum objects, one for each relevant order
- individual_line(lambda0, lwidth)#
Select an individual line in the spectrum and return it as an LSD profile object
- Parameters:
lambda0 – wavelength of the line (same units as self.wl)
lwidth – distance from the line center, in wavelength, for the wavelength window used for the line profile. One element: same distance on each side of line center. Two elements: distance to the left and right of line center.
- Return type:
- merge_orders(mode='trim', midpoint=0.5)#
Simple merging of spectral orders, for echelle spectra.
The default mode ‘trim’ simply uses one order up to the midpoint of an overlap region, and then uses the next order past the midpoint. This is more robust against continuum normalization errors but doesn’t optimize the total signal-to-noise.
The mode ‘coadd’ attempts to coadd orders in the overlap region. It interpolates the second order onto the wavelength grid of the first order, then averages the spectra weighted by 1/sigma**2. This optimizes the total signal-to-noise but is vulnerable to continuum normalization errors at the edges of orders. This mode requires reliable uncertainties.
- Parameters:
mode – choice of ‘trim’, ‘coadd’
midpoint – for mode ‘trim’, the fraction of the way through an overlap region treated as the midpoint
- Return type:
- save(fname, saveHeader=True)#
Write the Spectrum into a text .s file in a LibreESPRIT style format. Optionally skip writing the two lines of header.
- Parameters:
saveHeader – optional flag, skip writing the header if False
- specpolFlow.read_spectrum(fname, usecols=None, trimBadPix=False, sortByWavelength=False)#
Read in the observed spectrum and save it.
This follows the .s format from Donati’s LibreESPRIT. Files can either have two lines of header or no header. This supports 6 column spectropolarimetric files (wavelength, Stokes I, Stokes V|Q|U, null1, null2, errors), 3 column spectra (wavelength, flux (Stokes I), errors), and 2 column spectra (wavelength, flux (Stokes I)).
- Parameters:
fname – the name of the file to read.
usecols – optional, tuple or list, explicitly define the columns to use from the file (similar to the numpy.loadtxt() usecols argument). This is only useful if the file is not in a standard 2, 3, or 6 column format. The order of entries in the tuple corresponds to wavelength, Stokes I, Stokes V, N1, N2, and errors. Columns numbers start at 0. If a negative value is given, then nothing is read for that parameter and it is set to 0. E.g.: usecols=(0, 2) reads wavelength from the 1st column and flux (Stokes I) from the 3rd column. usecols=(0, 1, 2, 4, 4, 3) reads wavelength, I, and V as usual, uses the 5th column for N1 and re-uses it for N2, and uses the 4th column for errors. usecols=(0, 1, -1, -1, -1, 3) uses the 1st and 2nd columns for wavelength and flux, then uses no values for V, N1, or N2, and uses the 4th column for errors.
trimBadPix – optionally remove the more obviously bad pixels if True. Removes pixels with negative flux or error bars of zero, pixels with flux within 3sigma of zero (large errors), and pixels with extremely large values.
sortByWavelength – reorder the points in the spectrum to always increase in wavelength, if set to True. Note: if there are multiple spectral orders this will will destroy information about order edges. If you want to merge orders, it is usually better to leave this False and then use Spectrum.merge_orders() after reading the file.
- Return type:
- specpolFlow.plot_obs_lines(spectra=[], lineList=[], depthCut=0.0, maxLabels=100, velSpec=0.0, velLines=0.0, stokes='I', showErr=False, showLegend=False, ax=None)#
Plot observed spectra and/or a line list
This is mostly intended as a quick look tool. This uses the plot_lineList function, and you can construct more tailored to your specific case using that function and matplotlib.
This funciton also binds some keys for navigating around the plot: arrow keys – pan left, right, up, and down; i – zoom in; o – zoom out; z – activate matplotlib’s zoom tool; a – autoscale the zoom to show all data; A – autoscale the y-axis only;
- Parameters:
spectra – the observed spectrum, or a python list containing multiple observations. This can either be Spectrum objects or file names of .s files. Model spectra can be included here too, provided that they are readable as .s files or are in Spectrum objects.
lineList – the line list, or a python list containing multiple line lists. This can either be LineList objects or file names of VALD long format, extract stellar line lists. (Optional, if no lineList is given only spectra are plotted).
depthCut – only lines in the line list with depth values greater than depthCut are plotted.
maxLabels – the labels for the maxLabels deepest lines are drawn in the plot. Tick marks are still drawn for the other lines. Drawing labels is slow, so decreasing maxLabels can improve performance.
velSpec – a single velocity used to Doppler shift all the spectra, or a list of velocities, one for each spectrum (in km/s).
velLines – a single velocity used to Doppler shift all line lists, or a list of velocities, one for each line list (in km/s).
stokes – which Stokes parameter from the spectrum to plot. Options are ‘I’, ‘V’, ‘N1’, ‘N2’, or ‘IV’. The ‘IV’ option will plot Stokes I and also Stokes V, with V shifted vertically above I.
showErr – flag for whether or not to plot errorbars for the data (defaults to False, plotting errorbars can be a bit slow).
showLegend – flag for whether to show a legend, labeling the plotted spectra. The legend will include filenames for the spectra, if filenames were given (otherwise this is just an index in the order the spectra were given).
ax – the matplotlib axes object to use for plotting. If None, then a new figure and axes are created.
- Returns:
a matplotlib figure object, and an axes object containing the plot.