API

The API is under active development and should be considered a strawman design. Feedback is welcomed.

Echelle Spectrum

An abstract base class for a high resolution spectrum, for some echelle order \(m \in ` out of :math:`M\) total orders, each with vectors for wavelength, flux, and uncertainty, e.g. \(F_m(\lambda)\). This class is a subclass of specutils’ Spectrum1D and is intended to have its methods inherited by specific instrument classes.

EchelleSpectrum

class muler.echelle.EchelleSpectrum(*args, **kwargs)

An abstract base class to provide common methods that will be inherited by instrument-specific classes

property ancillary_spectra

The list of conceivable ancillary spectra

apply_boolean_mask(mask)

Apply a boolean mask to the spectrum and any available ancillary spectra

Parameters:

mask (boolean mask, typically a numpy array) – The boolean mask with numpy-style masking: True means “keep” that index and False means discard that index

property available_ancillary_spectra

The list of available ancillary spectra

barycentric_correct()

shift spectrum by barycenter velocity

Returns:

barycenter corrected Spectrum

Return type:

(KeckNIRSPECSpectrum)

deblaze(method='spline')

Remove blaze function from spectrum by interpolating a spline function

Note: It is recommended to remove NaNs before running this operation, otherwise edge effects can be appear from zero-padded edges.

Return type:

blaze corrrected spectrum

estimate_barycorr()

Estimate the Barycentric Correction from the Date and Target Coordinates

Returns:

barycentric_corrections – Barycentric correction for targets in units of m/s

Return type:

float

estimate_uncertainty()

Estimate the uncertainty based on residual after smoothing

Returns:

uncertainty – Typical uncertainty

Return type:

(np.float)

flatten(window_length=101, polyorder=2, return_trend=False, break_tolerance=5, niters=3, sigma=3, mask=None, **kwargs)

Removes the low frequency trend using scipy’s Savitzky-Golay filter. This method wraps scipy.signal.savgol_filter. Abridged from the lightkurve method with the same name for flux time series.

Parameters:
  • window_length (int) – The length of the filter window (i.e. the number of coefficients). window_length must be a positive odd integer.

  • polyorder (int) – The order of the polynomial used to fit the samples. polyorder must be less than window_length.

  • return_trend (bool) – If True, the method will return a tuple of two elements (flattened_spec, trend_spec) where trend_spec is the removed trend.

  • break_tolerance (int) – If there are large gaps in wavelength, flatten will split the flux into several sub-spectra and apply savgol_filter to each individually. A gap is defined as a region in wavelength larger than break_tolerance times the median gap. To disable this feature, set break_tolerance to None.

  • niters (int) – Number of iterations to iteratively sigma clip and flatten. If more than one, will perform the flatten several times, removing outliers each time.

  • sigma (int) – Number of sigma above which to remove outliers from the flatten

  • mask (boolean array with length of self.wavelength) – Boolean array to mask data with before flattening. Flux values where mask is True will not be used to flatten the data. An interpolated result will be provided for these points. Use this mask to remove data you want to preserve, e.g. spectral regions of interest.

  • **kwargs (dict) – Dictionary of arguments to be passed to scipy.signal.savgol_filter.

Returns:

  • flatten_spec (EchelleSpectrum) – New light curve object with long-term trends removed.

  • If return_trend is set to True, this method will also return

  • trend_spec (EchelleSpectrum) – New light curve object containing the trend that was removed.

flatten_by_black_body(Teff)

Flatten the spectrum by a scaled black body, usually after deblazing Note: This method applies mostly to high-bandwidth stellar spectra.

Parameters:

Teff (float) – The effective temperature of the black body in Kelvin units

measure_ew(lower=None, upper=None)

Measure the equivalent width of a given spectrum

Parameters:
  • lower (AstroPy Quantity or float) – The short wavelength limit at which to define the EW lower bound. If the value is a float, it assume Angstrom units.

  • upper (AstroPy Quantity or float) – The long wavelength limit at which to define the EW upper bound. If the value is a float, it assume Angstrom units.

Returns:

equivalent width

Return type:

(scalar)

normalize(normalize_by='median')

Normalize the spectrum by a scalar value, usually its median

Parameters:

normalize_by ((string or float or Quantity)) – The flux value or method name to normalize by. Usually this is the median flux “median”, making the resulting flux vector have a median value of 1 (default). The user may optionally pass in the strings “mean” for normalization by the mean flux, or “peak” for normalization by the 90th percentile of the spectrum. If a Quanitity is passed in, it must have equivalent flux units as the spectrum.

Returns:

normalized_spec – Normalized Spectrum

Return type:

(EchelleSpectrum)

plot(ax=None, ylo=0.0, yhi=None, figsize=(10, 4), **kwargs)

Plot a quick look of the spectrum”

Parameters:
  • ax (~matplotlib.axes.Axes) – A matplotlib axes object to plot into. If no axes is provided, a new one will be generated.

  • ylo (scalar) – Lower limit of the y axis

  • yhi (scalar) – Upper limit of the y axis

  • figsize (tuple) – The figure size for the plot

  • label (str) – The legend label to for plt.legend()

Returns:

ax – The axis to display and/or modify

Return type:

(~matplotlib.axes.Axes)

remove_nans()

Remove data points that have NaN fluxes

By default the method removes NaN’s from target, sky, and lfc fibers.

Returns:

finite_spec – Spectrum with NaNs removed

Return type:

(KeckNIRSPECSpectrum)

remove_outliers(threshold=5)

Remove outliers above threshold

Parameters:

threshold (float) – The sigma-clipping threshold (in units of sigma)

Returns:

clean_spec – Cleaned version of input Spectrum

Return type:

(KeckNIRSPECSpectrum)

rv_shift(velocity)

Shift velocity of spectrum in astropy units (or km/s if input velocity is just a float)

smooth_spectrum(return_model=False, optimize_kernel=False, bandwidth=150.0)

Smooth the spectrum using Gaussian Process regression

Parameters:
  • return_model ((bool)) – Whether or not to return the gp model, which takes a wavelength axis as input and outputs the smooth trend

  • optimize_kernel ((bool)) – Whether to optimize the GP hyperparameters: correlation scale and amplitude

  • bandwidth ((float)) – The smoothing bandwidth in Angstroms. Defaults to 150 Angstrom lengthscale.

Returns:

smoothed_spec – Smooth version of input Spectrum

Return type:

(EchelleSpectrum)

property snr

` rac{S}{N}`, the flux divided by the uncertainty

The spectrum should have an input uncertainty, otherwise returns NaNs

Type:

The Signal-to-Noise Ratio

Type:

math

sort()

Sort the spectrum by acending wavelength

Returns:

sorted_spec – Sorted Spectrum

Return type:

(EchelleSpectrum)

to_HDF5(path, file_basename)

Export to spectral order to HDF5 file format This format is required for per-order Starfish input

Parameters:
  • path (str) – The directory destination for the HDF5 file

  • file_basename (str) – The basename of the file to which the order number and extension are appended. Typically source name that matches a database entry.

trim_edges(limits=None)

Trim the order edges, which falloff in SNR

This method applies limits on absolute x pixel values, regardless of the order of previous destructive operations, which may not be the intended behavior in some applications.

Parameters:

limits (tuple) – The index bounds (lo, hi) for trimming the order

Returns:

trimmed_spec – Trimmed version of input Spectrum

Return type:

(EchelleSpectrum)

class muler.echelle.EchelleSpectrumList(*args, **kwargs)

An enhanced container for a list of Echelle spectral orders

deblaze(method='spline')

Remove blaze function from all orders by interpolating a spline function

Note: It is recommended to remove NaNs before running this operation,

otherwise effects can be appear from zero-padded edges.

flatten(**kwargs)

Removes the low frequency trend using scipy’s Savitzky-Golay filter. This method wraps scipy.signal.savgol_filter. Abridged from the lightkurve method with the same name for flux time series.

flatten_by_black_body(Teff)

Flatten by black body

normalize(order_index=None)

Normalize all orders to one of the other orders

Parameters:

order_index (int) – User specified order to normalize entire spectrum to. If not specified, normalization_order_index of the EchelleSpectrumList will be used instead.

plot(ylo=0.0, yhi=None, **kwargs)

Plot the entire spectrum list

remove_nans()

Remove all the NaNs

remove_outliers(threshold=5)

Remove all the outliers

Parameters:

threshold (float) – The sigma-clipping threshold (in units of sigma)

rv_shift(velocity)

Shift velocity of spectrum in km s^-1

stitch()

Stitch all the spectra together, assuming zero overlap in wavelength.

to_HDF5(path, file_basename)

Save all spectral orders to the HDF5 file format

trim_edges(limits=None)

Trim all the edges

IGRINS Spectrum

A container for an IGRINS spectrum of \(M=28\) total total orders \(m\), each with vectors for wavelength flux and uncertainty, e.g. \(F_m(\lambda)\).

IGRINSSpectrum

class muler.igrins.IGRINSSpectrum(*args, file=None, order=10, sn_used=False, cached_hdus=None, wavefile=None, **kwargs)

A container for IGRINS spectra

Parameters:
  • file (str) – A path to a reduced IGRINS spectrum from plp of file type .spec.fits or .spec_a0v.fits.

  • order (int) – which spectral order to read

  • cached_hdus (list) – List of two or three fits HDUs, one for the spec.fits/spec_a0v.fits, one for the variance.fits file, and one optional one for the .wave.fits file to reduce file I/O for multiorder access. If provided, must give both (or three) HDUs. Optional, default is None.

  • wavefile (str) – A path to a reduced IGRINS spectrum storing the wavelength solution of file type .wave.fits.

property DEC

The declination from header files

property RA

The right ascension from header files

property ancillary_spectra

The list of conceivable ancillary spectra

property astropy_time

The astropy time based on the header

property site_name

Which pipeline does this spectrum originate from?

class muler.igrins.IGRINSSpectrumList(*args, **kwargs)

An enhanced container for a list of IGRINS spectral orders

static read(file, precache_hdus=True, wavefile=None)

Read in a SpectrumList from a file

Parameters:
  • file ((str)) – A path to a reduced IGRINS spectrum from plp

  • wavefile ((str)) –

muler.igrins.getUncertainityFilepath(filepath)

Returns path for uncertainity file (.variance.fits or .sn.fits)

Will first search for a .variance.fits file but if that does not exist will serach for a .sn.fits file.

Parameters:

filepath (Filepath to fits file storing the data. Can be .spec.fits or .spec_a0v.fits.) –

Returns:

uncertainityFilepath – Returns the file path to the uncertianity (.variance.fits or .sn.fits) file.

Return type:

string

HPF Spectrum

A container for an HPF spectrum of \(M=28\) total total orders \(m\), each with vectors for wavelength flux and uncertainty, e.g. \(F_m(\lambda)\). HPF additionally has a sky fiber and optionally a Laser Frequency Comb fiber. Our experimental API currently ignores the LFC fiber. The sky fiber can be accessed by passing the sky=True kwarg when retrieving the

HPFSpectrum

class muler.hpf.HPFSpectrum(*args, file=None, order=19, cached_hdus=None, **kwargs)

A container for HPF spectra

Parameters:
  • file (str) – A path to a reduced HPF spectrum from Goldilocks or the HPF instrument team

  • order (int) – which spectral order to read

  • cached_hdus (list) – A pre-loaded HDU to reduce file I/O for multiorder access. If provided, must give both HDUs. Optional, default is None.

property DEC

The declination from header files

property RA

The right ascension from header files

property ancillary_spectra

The list of conceivable ancillary spectra

property astropy_time

The astropy time based on the header

blaze_divide_flats(flat, order=19)

Remove blaze function from spectrum by dividing by flat spectrum

Returns:

blaze corrrected spectrum using flat fields

Return type:

(HPFSpectrum)

deblaze(method='template')

Override the default spline deblazing with HPF-custom blaze templates.

Parameters:

method ((Str)) – Either “template” or “spline” (default: template)

get_static_A0V_template(method='PHOENIX')

Get the static A0V template for HPF, as estimated by either Vega or PHOENIX

Parameters:

method ((Str)) – What template to use. Currently only a state PHOENIX model is supported. Other A0V templates may be added in the future, such as Vega. (default: PHOENIX)

get_static_TelFit_template()

Get the static TelFit template for HPF

A convenience function for getting a quicklook Telluric template

get_static_blaze_template(method='Goldilocks')

Get the static blaze template for HPF, as estimated by Goldilocks

Parameters:

method ((Str)) – Either “Goldilocks” or “2021_median” (default: Goldilocks)

get_static_sky_ratio_template()

Get the static sky ratio template for HPF, as estimated from twilight flats

property lfc

Sky fiber spectrum stored as its own HPFSpectrum object

mask_tellurics(method='TelFit', threshold=0.999, dilation=5)

Mask known telluric lines based on a static TelFit template or heuristics

Note: This method is for quicklook purpsoes, it misses many unknown tellurics

Parameters:
  • method ((str)) – The method for telluric masking: “TelFit” or “heuristics” Default is TelFit.

  • dilation ((int)) – The number of pixels adjacent to the threshold mask to include in a dilated mask. This control parameter accounts for velocity offsets between the template and observed telluric spectrum.

Returns:

sky_subtractedSpec – Sky subtracted Spectrum

Return type:

(HPFSpectrum)

property pipeline

Which pipeline does this spectrum originate from?

property provenance

What is the provenance of each spectrum?

property sky

Sky fiber spectrum stored as its own HPFSpectrum object

sky_subtract(method='scalar')

Subtract sky spectrum from science spectrum, with refinements for sky throughput

Note: This operation does not wavelength shift or scale the sky spectrum

Parameters:

method ((str)) – The method for sky subtraction: “naive”, “scalar”, or “vector”, as described in Gully-Santiago et al. in prep. Default is scalar.

Returns:

sky_subtractedSpec – Sky subtracted Spectrum

Return type:

(HPFSpectrum)

property spectrographname

What’s the name of the spectrograph?

class muler.hpf.HPFSpectrumList(*args, **kwargs)

An enhanced container for a list of HPF spectral orders

deblaze()

Deblaze the entire spectrum

static read(file, precache_hdus=True)

Read in a SpectrumList from a file

Parameters:

file ((str)) – A path to a reduced HPF spectrum from plp

sky_subtract(method='vector')

Sky subtract the entire spectrum

KeckNIRSPEC Spectrum

A container for a Keck NIRSPEC high resolution spectrum, for some echelle order \(m \in ` out of :math:`M\) total orders, each with vectors for wavelength, flux, and uncertainty, e.g. \(F_m(\lambda)\). KeckNIRSPEC already has been sky subtracted, but the subtracted sky signal is contained as the spectrum.sky attribute for reference.

KeckNIRSPECSpectrum

class muler.nirspec.KeckNIRSPECSpectrum(*args, file=None, order=63, **kwargs)

A container for Keck NIRSPEC spectra

Parameters:

file (str) – A path to a reduced Keck NIRSPEC spectrum from NSDRP

property DEC

The declination from header files

property RA

The right ascension from header files

property ancillary_spectra

The list of conceivable ancillary spectra

property astropy_time

The astropy time based on the header

property flat

Flat spectrum stored as its own KeckNIRSPECSpectrum object

property pipeline

Which pipeline does this spectrum originate from?

property sky

Sky fiber spectrum stored as its own KeckNIRSPECSpectrum object

sky_subtract(force=False)

Subtract sky spectrum from science spectrum

Returns:

sky_subtractedSpec – Sky subtracted Spectrum

Return type:

(KeckNIRSPECSpectrum)

class muler.nirspec.KeckNIRSPECSpectrumList(*args, **kwargs)

An enhanced container for a list of KeckNIRSPEC spectral orders

static read(files)

Read in a SpectrumList from a file

Parameters:

file ((str)) – A path to a reduced KeckNIRSPEC spectrum from plp

muler.utilities.apply_numpy_mask(spec, mask)

Applies a boolean mask to an input spectrum, numpy-style (True=Keep, False=Discard)

Parameters:
  • spec (Spectrum1D-like object) – Object storing spectrum

  • mask (boolean mask, typically a numpy array) – The boolean mask with numpy-style masking: True means “keep” that index and False means discard that index

muler.utilities.combine_spectra(spec_list)

Combines spectra assuming they are aligned pixel-by-pixel

muler.utilities.combine_spectra_misaligned(spec_list, pixel_midpoints=None, propagate_uncertainty=False)

Combines spectra that might not be aligned pixel-by-pixel

Misaligned spectra can arise when significant Radial Velocity shifts have been applied before combination. This method is not suitable for precision radial velocities.

Parameters:
  • spec_list (list of Spectrum1D-like objects) – A list of spectra, with each spectrum possessing at least some overlap with the others

  • propagate_uncertainty (boolean or String) – How to propagate uncertainty: if True and uncertainties are provided, it will propagate them. If False, it will determine uncertainties from sample standard deviation of the mean. If “max”, and uncertainties are provided, it will take whichever is higher.

  • pixel_midpoints (numpy.float or astropy.Quantity) – A vector of wavelength coordinates that represent the desired pixel midpoints of the output spectrum. If None, the coordinates are determined from the input, using coarse bin spacings from the first input spectrum

Returns:

combined_spec – Returns a spectrum of the same subclass as the input spectrum, with the flux values taking the weighted mean of the bins defined by pixel_midpoints. The metadata is copied from the first spectrum in the list: we make no attempt to combine metadata from the multiple input spectra. If input spectra have uncertainties, they are propagated using a formula for weighting the input uncertainties. If input spectra do not have uncertainties, they are estimated from the sample standard deviation of the mean estimator.

Return type:

Spectrum1D-like object

muler.utilities.concatenate_orders(spec_list1, spec_list2)

Combine two EchelleSpectrumList objects into one. For example, combine IGRINS H and K bands.

Parameters:
  • spec_list1 (EchelleSpectrumList object) – Echelle spectrum with multiple orders

  • spec_list2 (EchelleSpectrumList object) – Echelle spectrum with multiple orders to append onto the first list.

muler.utilities.is_list(check_this)

Checks if a given object is some sort of list or array object. For example, checks if a given object is an EchelleSpectrumList or single number for band math.

Parameters check_this: Object to check

Returns:

  • True (Object has more than one element (e.g. is a list or array))

  • False (Object has a single element (e.g. a single variable like 10.0))

muler.utilities.resample_list(spec_to_resample, specList, **kwargs)

Resample a single EchelleSpectrum or Spectrum1D object into a EchelleSpectrumList object. Useful for converting models into echelle spectra with multiple orders.

Parameters:
  • spec_to_resample (EchelleSpectrum or specutils Spectrum1D object) – Object storing spectrum (typically of a model) to be resampled onto the same grid as specList.

  • specList (EchelleSpectrumList object) – Object storing an echelle spectrum (spectrum with multiple orders) with the wavelength grid to which spec_to_resample will be resampled.

  • **kwargs (optional) – Extra arguments to be passed to specutils.manipulation.resample which is run to resample spec_to_resample to each order in specList