Spectral classes and functions

Contents

Spectral classes and functions#

Classes and functions for managing and processing spectra

Core Functions#

Core functions for spectral data.

dysh.spectra.core.append_doppler_to_spectral_region_qtable(qtable, refspec)[source]#

Set the doppler_convention and doppler_rest attributes to the columns of qtable.

Parameters:
qtableQTable

Table with SpectralAxis as columns.

refspecSpectrum

The reference spectrum whose spectral axis will be used to set the attributes.

dysh.spectra.core.available_smooth_methods()[source]#

The list of smooth methods that dysh understands. These can be passed to various smooth routines via their method keywords.

Returns:
methods: list

The method names allowable to smooth

dysh.spectra.core.average(data, axis=0, weights=None)[source]#

Average a group of spectra or scans.

Parameters:
datandarray

The spectral data, typically with shape (nspect,nchan).

axisint

The axis over which to average the data. Default axis=0 will return the average spectrum if shape is (nspect,nchan)

weightsndarray

The weights to use in averaging. These might typically be system temperature based. The weights array must be the length of the axis over which the average is taken. Default: None will use equal weights

Returns:
averagendarray

The average along the input axis

dysh.spectra.core.baseline(spectrum, order, exclude=None, exclude_region_upper_bounds=True, **kwargs)[source]#

Fit a baseline to spectrum. The code uses Fitter and polynomial to compute the baseline. See the documentation for those modules for details.

Parameters:
spectrumSpectrum

The input spectrum.

orderint

The order of the polynomial series, a.k.a. baseline order.

excludelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to exclude from the fit. The tuple(s) represent a range in the form [lower,upper], inclusive. Examples:

One channel-based region:

>>> [11,51]

Two channel-based regions:

>>> [(11,51),(99,123)]

One Quantity region:

>>> [110.198*u.GHz,110.204*u.GHz].

One compound SpectralRegion:

>>> SpectralRegion([(110.198*u.GHz,110.204*u.GHz),(110.196*u.GHz,110.197*u.GHz)]).

Default: no exclude region

modelstr

One of ‘polynomial’ or ‘chebyshev’, Default: ‘polynomial’

fitterFitter

The fitter to use. Default: LinearLSQFitter (with calc_uncertaintes=True). Be careful when choosing a different fitter to be sure it is optimized for this problem.

exclude_region_upper_boundsbool

Makes the upper bound of any excision region(s) inclusive. Allows excising channel 0 for lower-sideband data, and the last channel for upper-sideband data.

clip_excludebool

Whether to clip the exclude or include regions when they extend outside the spectrum.spectral_axis.

Returns:
modelQuantityModel

Best fit model. See fit_continuum.

dysh.spectra.core.clip_spectral_region_subregions(spectral_region, spectrum)[source]#

Clip the values of the spectral_region.subregions if they extend outside the spectrum.spectral_axis.

dysh.spectra.core.cog_flux(c, flat_tol=0.1)[source]#

Find the flux from the curve of growth.

Parameters:
carray

Curve of growth values.

flat_tolfloat

Tolerance to define the flat portion of the curve of growth. The flat portion is that which is zero within flat_tol times the rms of the slope.

Returns:
fluxfloat

The median of the curve of growth over its flat portion.

flux_stdfloat

The standard deviation of the curve of growth over the flat portion.

slopearray

The median value of the slope for the curve of growth before it becomes flat.

dysh.spectra.core.cog_slope(c, flat_tol=0.1)[source]#

Find slope for curve of growth analysis.

Parameters:
carray

Curve of growth values.

flat_tolfloat

Tolerance to define the flat portion of the curve of growth. The flat portion is that which is zero within flat_tol times the rms of the slope.

Returns:
slopearray

Slope of c.

slope_rmsfloat

Standard deviation of the slope.

flat_idx0int

Index where the slope is consistent with zero.

dysh.spectra.core.curve_of_growth(x, y, vc=None, width_frac=None, bchan=None, echan=None, flat_tol=0.1, fw=1) dict[source]#

Curve of growth analysis based on Yu et al. (2020) [1].

Parameters:
xarray

Velocity values.

yarray

Flux values.

vcfloat

Central velocity of the line in the same units as x. If not provided, it will be estimated from the moment 1 of the x and y values.

width_fraclist

List of fractions of the total flux at which to compute the line width. If 0.25 and 0.85 are not included, they will be added to estimate the concentration as defined in [1].

bchanNone or int

Beginning channel where there is signal. If not provided it will be estimated using fw times the width of the line at the largest width_frac.

echanNone or int

End channel where there is signal. If not provided it will be estimated using fw times the width of the line at the largest width_frac.

flat_tolfloat

Tolerance used to define the flat portion of the curve of growth. The curve of growth will be considered flat when it’s slope is within flat_tol times the standard deviation of the slope from zero.

fwfloat

When estimating the line-free range, use fw times the largest width.

Returns:
resultsdict

Dictionary with the flux (\(F\)), width (\(V\)), flux asymmetry (\(A_F\)), slope asymmetry (\(A_C\)), concentration (\(C_V\)), rms, central velocity (“vel”), redshifted flux (\(F_r\)), blueshifted flux (\(F_b\)),`bchan` and echan, and errors on the flux (“flux_std”), width (“width_std”), central velocity (“vel_std”), redshifted flux (“flux_r_std”), and blueshifted flux (“flux_b_std”). The rms is the standard deviation in the range outside of (bchan,echan).

dysh.spectra.core.data_fshift(y, fshift, method='fft', pad=False, window=True)[source]#

Shift y by fshift channels, where abs(fshift)<1.

Parameters:
yarray

Data to be shifted.

fshiftfloat

Amount to shift the data by. abs(fshift) must be less than 1.

method“fft” | “interpolate”

Method to use for shifting. “fft” uses a phase shift. “interpolate” uses scipy.ndimage.shift.

padbool

Pad the data during the phase shift. Only used if method="fft".

windowbool

Apply a Welch window during phase shift. Only used if method="fft".

dysh.spectra.core.data_ishift(y, ishift, axis=-1, remove_wrap=True, fill_value=nan)[source]#

Shift y by ishift channels, where ishift is a natural number.

Parameters:
yarray

Data to be shifted.

ishiftint

Amount to shift data by.

axisint

Axis along which to apply the shift.

remove_wrapbool

Replace channels that wrap around with fill_value.

fill_valuefloat

Value used to replace the data in channels that wrap around after the shift.

Returns:
new_yarray

Shifted y.

dysh.spectra.core.data_shift(y, s, axis=-1, remove_wrap=True, fill_value=nan, method='fft', pad=False, window=True)[source]#

Shift y by s channels.

Parameters:
yarray

Data to be shifted.

sfloat

Amount to shift the data by.

axisint

Axis along which to apply the shift.

remove_wrapbool

Replace channels that wrap around with fill_value.

fill_valuefloat

Value used to replace the data in channels that wrap around after the shift.

method“fft” | “interpolate”

Method to use for shifting. “fft” uses a phase shift. “interpolate” uses scipy.ndimage.shift.

padbool

Pad the data during the phase shift. Only used if method="fft".

windowbool

Apply a Welch window during phase shift. Only used if method="fft".

dysh.spectra.core.decimate(data, n, meta=None)[source]#

Decimate a data array by n pixels.

Parameters:
datandarray or Quantity

The data to decimate.

nint

Decimation factor of the spectrum by returning every n-th channel.

metadict

Metadata dictionary with CDELT1, CRVAL1, NAXIS1, and CRPIX1 which will be recalculated.

Returns:
tuplendarray or Quantity and dict

A tuple of the decimated data and updated metadata (or None if no meta given).

dysh.spectra.core.exclude_to_region_list(exclude, spectrum, clip_exclude=True)[source]#

Convert an exclusion region, exclude, to a list of SpectralRegion. This is used for baseline fitting.

Parameters:
excludelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to exclude. The tuple(s) represent a range in the form [lower,upper], inclusive. Examples:

One channel-based region:

>>> [11,51]

Two channel-based regions:

>>> [(11,51),(99,123)]

One Quantity region:

>>> [110.198*u.GHz,110.204*u.GHz].

One compound SpectralRegion:

>>> SpectralRegion([(110.198*u.GHz,110.204*u.GHz),(110.196*u.GHz,110.197*u.GHz)]).
spectrumSpectrum

The reference spectrum whose spectral axis will be used when converting between exclude and axis units (e.g. channels to GHz).

clip_excludebool

Whether to clip the edges of the exclude regions when they are outside spectrum.spectral_axis.

Returns:
region_listlist of SpectralRegion

Regions defined in exclude as a list of SpectralRegion.

dysh.spectra.core.exclude_to_spectral_region(exclude, refspec)[source]#

Convert exclude to a SpectralRegion.

Parameters:
excludelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to exclude. The tuple(s) represent a range in the form [lower,upper], inclusive. Examples:

One channel-based region:

>>> [11,51]

Two channel-based regions:

>>> [(11,51),(99,123)]

One Quantity region:

>>> [110.198*u.GHz,110.204*u.GHz].

One compound SpectralRegion:

>>> SpectralRegion([(110.198*u.GHz,110.204*u.GHz),(110.196*u.GHz,110.197*u.GHz)]).
refspec: `~spectra.spectrum.Spectrum`

The reference spectrum whose spectral axis will be used when converting between exclude and axis units (e.g. channels to GHz).

Returns:
srSpectralRegion

A SpectralRegion corresponding to exclude.

dysh.spectra.core.fft_pad(y)[source]#

Pad signal y to the next power of 2 using its edge values.

Parameters:
y1D ndarray

Signal to be padded.

Returns:
padded1D ndarray

Padded signal.

nskipint

Number of samples added to each end of the padded signal.

dysh.spectra.core.fft_shift(y, shift, pad=True, window=True, nan_treatment='fill', fill_value=0, keep_nan=True)[source]#

Shift a signal y by shift amount using a phase shift. This requires taking the inverse FFT of the signal, shifting its phase, and then taking the FFT to shift the signal.

Parameters:
y1D ndarray

Signal to be shifted. Only 1D supported.

shiftfloat

Amount to shift the signal by in channels.

padbool

Pad the signal to prevent aliasing.

windowbool

Apply a Welch window to prevent ringing.

nan_treatment‘fill’

‘fill’ replaces NaN values with fill_value before the FFT.

fill_valuefloat

Value used to replace NaN values. Used if nan_treatment=='fill'.

keep_nanbool

If True the output will keep the NaN values. If False NaN values will be filled.

Returns:
new_y1D ndarray

Phase shifted version of the original signal y.

dysh.spectra.core.find_blanks(data)[source]#

Finds the indices of blanked integrations

Parameters:
datandarray

The spectral data, typically with shape (nspect,nchan).

Returns:
blanksndarray

Array with indices of blanked integrations.

dysh.spectra.core.find_non_blanks(data)[source]#

Finds the indices of integrations that are not blanked.

Parameters:
datandarray

The spectral data, typically with shape (nspect,nchan).

Returns:
blanksndarray

Array with indices of non-blanked integrations.

dysh.spectra.core.find_nonblank_ints(cycle1, cycle2, cycle3=None, cycle4=None)[source]#

Find the indices of integrations that are not blanked.

Parameters:
cycle1ndarray

Data for cycle 1. For example, signal with the noise diode off.

cycle2ndarray

Data for cycle 2. For example, reference with the noise diode off.

cycle3ndarray

Data for cycle 3. For example, signal with the noise diode on. Default is None.

cycle4ndarray

Data for cycle 4. For example, reference with the noise diode on. Default is None.

Returns:
goodrowsarray

Indices of the non-blanked rows.

dysh.spectra.core.get_spectral_equivalency(restfreq, velocity_convention)[source]#
dysh.spectra.core.include_to_exclude_spectral_region(include, refspec)[source]#

Convert an inclusion region to an exclude region.

Parameters:
includelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to exclude from the fit. The tuple(s) represent a range in the form [lower,upper], inclusive. Examples:

One channel-based region:

>>> [11,51]

Two channel-based regions:

>>> [(11,51),(99,123)]

One Quantity region:

>>> [110.198*u.GHz,110.204*u.GHz].

One compound SpectralRegion:

>>> SpectralRegion([(110.198*u.GHz,110.204*u.GHz),(110.196*u.GHz,110.197*u.GHz)]).
refspec: `~spectra.spectrum.Spectrum`

The reference spectrum whose spectral axis will be used when converting between include and axis units (e.g. channels to GHz).

Returns:
exclude_regionSpectralRegion

include as a region to be excluded.

dysh.spectra.core.integration_isnan(data)[source]#

Helper function to calculate a boolean array that indicates whether a collection of integrations is blanked.

Parameters:
datandarray

The spectral data, typically with shape (nspect,nchan).

Returns:
blanksndarray

Array with length nspect with value True where an integration is blanked.

dysh.spectra.core.invert_spectral_region(sr, refspec)[source]#

Invert an spectral region. The spectral region is sorted and the ranges has been merged previously.

Parameters:
srSpectralRegion

Spectral region to invert.

refspecSpectrum

Spectrum to define the boundaries for the inversion.

Returns:
SpectralRegion

Inverted spectral region.

dysh.spectra.core.mask_fshift(mask, fshift)[source]#

Shift mask by fshift channels. This should only be used when abs(fshift)<1. It expands the mask using binary dilation to account for the spread of the masked values when they are shifted by a fractional number of channels.

Parameters:
maskarray_like

Array with masked values. Either ones and zeros or True and False.

fshiftfloat

Amount to shift by.

Returns:
new_maskarray_like

mask shifted by fshift channels.

Raises:
ValueError

If abs(fshift) is greather than 1.

dysh.spectra.core.mean_data(data, fedge=0.1, nedge=None, median=False)[source]#

Special mean of data to exclude the edges like mean_tsys(), with an option to use the median instead of the mean.

Parameters:
datandarray

The spectral data.

fedgefloat, optional

Fraction of edge channels to exclude at each end, a number between 0 and 1. If nedge is used, this parameter is not used. Default: 0.1, meaning the central 80% bandwidth is used.

nedgeint, optional

Number of edge channels to exclude. nedge cannot be 0. Default: None, meaning use fedge.

medianboolean, optional

Use the median instead of the mean. The default is False.

Returns:
meandatafloat
dysh.spectra.core.mean_tsys(calon, caloff, tcal, mode=0, fedge=0.1, nedge=None)[source]#

Get the system temperature from the neighboring calon and caloff, which reflect the state of the noise diode. We define an extra way to set the edge size, nedge, if you prefer to use number of edge channels instead of the inverse fraction. This implementation recreates GBTIDL’s dcmeantsys.

Parameters:
calonndarray-like

ON calibration

caloffndarray-like

OFF calibration

tcalndarray-like

calibration temperature

modeint

mode=0 Do the mean before the division mode=1 Do the mean after the division

fedgefloat

Fraction of edge channels to exclude at each end, a number between 0 and 1. Default: 0.1, meaning the central 80% bandwidth is used

nedgeint

Number of edge channels to exclude. Default: None, meaning use fedge

Returns:
meanTsysndarray-like

The mean system temperature

dysh.spectra.core.region_to_axis_indices(region, refspec)[source]#
Parameters:
regionSpectralRegion
refspec: `~spectra.spectrum.Spectrum`

The reference spectrum whose spectral axis will be used when converting between exclude and axis units (e.g., channels to GHz).

Returns:
indices2-tuple of int

The array indices in refspec corresponding to region.bounds

dysh.spectra.core.smooth(data, method='hanning', width=1, ndecimate=0, meta=None, kernel=None, mask=None, boundary='extend', nan_treatment='fill', fill_value=nan, preserve_nan=True)[source]#

Smooth or Convolve spectrum, optionally decimating it. A number of methods from astropy.convolution can be selected with the method= keyword.

Default smoothing is hanning.

Parameters:
datandarray

Input data array to smooth. Note smoothing array does not need a WCS since it is channel based.

methodstring, optional

Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.

widthint or float, optional

Effective width of the convolving kernel. Should ideally be an odd number. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final beam in channels (float). We normally assume the input beam has FWHM=1, pending resolution on cases where CDELT1 is not the same as FREQRES. The default is 1.

ndecimateint, optional

Decimation factor of the spectrum by returning every ndecimate-th channel.

meta: dict

metadata dictionary with CDELT1, CRVAL1, CRPIX1, NAXIS1, and FREQRES which will be recalculated if necessary

kernelndarray, optional

A numpy array which is the kernel by which the signal is convolved. Use with caution, as it is assumed the kernel is normalized to one, and is symmetric. Since width is ill-defined here, the user should supply an appropriate number manually. NOTE: not implemented yet. The default is None.

maskNone or ndarray, optional

A “mask” array. Shape must match array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. If None, no masking will be performed unless array is a masked array. If mask is not None and array is a masked array, a pixel is masked if it is masked in either mask or array.mask.

boundarystr, optional
A flag indicating how to handle boundaries:
  • None

    Set the result values to zero where the kernel extends beyond the edge of the array.

  • ‘fill’

    Set values outside the array boundary to fill_value (default).

  • ‘wrap’

    Periodic boundary that wrap to the other side of array.

  • ‘extend’

    Set values outside the array to the nearest array value.

fill_valuefloat, optional

The value to use outside the array when using boundary='fill'. Default value is NaN.

nan_treatment{‘interpolate’, ‘fill’}, optional
The method used to handle NaNs in the input array:
  • 'interpolate': NaN values are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.

  • 'fill': NaN values are replaced by fill_value prior to convolution.

preserve_nanbool, optional

After performing convolution, should pixels that were originally NaN again become NaN?

Returns:
sndarray

The new convolved spectrum.

Raises:
Exception

If no valid smoothing method is given.

dysh.spectra.core.sort_spectral_region_subregions(spectral_region)[source]#
dysh.spectra.core.spectral_region_to_list(spectral_region)[source]#

Turn spectral_region into a list of SpectralRegion. Each subregion in spectral_region will be a list element.

Parameters:
spectral_regionSpectralRegion

SpectralRegion to convert into a list of SpectralRegion.

Returns:
region_listlist of SpectralRegion

Subregions of spectral_region in a list of SpectralRegion.

dysh.spectra.core.spectral_region_to_list_of_tuples(spectral_region)[source]#

Convert spectral_region into a list of tuples compatible with baseline include or exclude arguments.

Parameters:
spectral_regionSpectralRegion

Region to convert to a list of tuples.

dysh.spectra.core.spectral_region_to_unit(spectral_region, refspec, unit=None, append_doppler=True)[source]#

Change the unit of spectral_region to unit using the equivalencies of refspec. If no unit is provided, it will change to the units of refspec._spectral_axis.

Parameters:
spectral_regionSpectralRegion

SpectralRegion whose units will be converted.

refspecSpectrum

The reference spectrum whose spectral axis will be used when converting to unit (e.g. channels to GHz).

unitstr or Quantity

The target units for spectral_region.

append_dopplerbool

Add the doppler_convention and doppler_rest attributes to the columns of the QTable used to convert the spectral_region units.

Returns:
spectral_regionSpectralRegion

SpectralRegion with units of unit.

dysh.spectra.core.sq_weighted_avg(a, axis=0, weights=None)[source]#

Compute the mean square weighted average of an array (2nd moment).

\(v = \sqrt{\frac{\sum_i{w_i~a_i^{2}}}{\sum_i{w_i}}}\)

Parameters:
andarray

The data to average.

axisint

The axis over which to average the data. Default: 0

weightsndarray or None

The weights to use in averaging. The weights array must be the length of the axis over which the average is taken. Default: None will use equal weights.

Returns:
averagendarray

The square root of the squared average of a along the input axis.

dysh.spectra.core.tsys_weight(exposure, delta_freq, tsys)[source]#
Compute the system temperature based weight(s) using the expression:

\(w = t_{exp} \times \delta_\nu / T_{sys}^2,\)

If exposure, delta_freq, or tsys parameters are given as Quantity, they will be converted to seconds, Hz, K, respectively for the calculation. (Not that this really matters since weights are relative to each other)

>>> import astropy.units as u
>>> [3*u.s, 4*u.s]   ### WRONG

Rather, if using Quantity, they have to be Quantity objects, e.g.,

>>> [3, 4]*u.s ### RIGHT!
Parameters:
exposurendarray, float, or Quantity

The exposure time, typically given in seconds.

delta_freqndarray, float, or Quantity

The channel width in frequency units.

tsysndarray, float, or Quantity

The system temperature, typically in K.

Returns:
weightndarray

The weights array

Spectrum#

The Spectrum class to contain and manipulate spectra.

class dysh.spectra.spectrum.Spectrum(*args, **kwargs)[source]#

Bases: Spectrum, HistoricalBase

This class contains a spectrum and its attributes. It is built on Spectrum with added attributes like baseline model. Note that Spectrum can contain multiple spectra but we probably will not use that because the restriction that it can have only one spectral axis conflicts with slight Doppler shifts. See Spectrum for the instantiation arguments.

Attributes:
array_axis_physical_types

Returns the WCS physical types that vary along each array axis.

baseline_model

Returns the computed baseline model or None if it has not yet been computed.

bin_edges
combined_wcs

The WCS transform for the NDCube, including the coordinates specified in .extra_coords.

comments

Get the comment strings.

data

ndarray - like

dimensions
doppler_convention

String representation of the velocity (Doppler) convention

energy

The energy of the spectral axis as a Quantity in units of eV.

equivalencies

Get the spectral axis equivalencies that can be used in converting the axis

exclude_regions

The baseline exclusion region(s) of this spectrum

extra_coords

Coordinates not described by NDCubeABC.wcs which vary along one or more axes.

flux

Converts the stored data and unit and mask into a Quantity object.

frequency

The spectral_axis as a Quantity in units of GHz

global_coords

Coordinate metadata which applies to the whole cube.

history

Get the history strings.

mask

any type : Mask for the dataset, if any.

meta
nchan

The number of channels in the Spectrum

observer

Returns ——- observer : BaseCoordinateFrame or derivative The coordinate frame of the observer if present.

obstime
photon_flux

The flux density of photons as a Quantity, in units of

plotter
psf

Image representation of the PSF for the dataset.

quantity

Unitful representation of the NDCube data.

radial_velocity

The radial velocity(s) of the objects represented by this spectrum.

redshift

The redshift(s) of the objects represented by this spectrum.

rest_value

Rest frequency used in velocity conversions.

shape
spectral_axis

Returns the SpectralCoord object.

spectral_axis_direction
spectral_axis_index
spectral_wcs

Returns the spectral axes of the WCS

subtracted

Has a baseline model been subtracted?”

target

The target object of this spectrum.

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

uncertainty

any type : Uncertainty in the dataset, if any.

unit

Unit : Unit for the dataset, if any.

velocity

Converts the spectral axis array to the given velocity space unit given the rest value.

velocity_convention

Returns the velocity convention

velocity_frame

String representation of the velocity frame

wavelength

The spectral_axis as a Quantity in units of Angstroms

wcs

any type : A world coordinate system (WCS) for the dataset, if any.

weights

The channel weights of this spectrum

Methods

add(operand[, operand2])

Performs addition by evaluating self + operand.

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

align_to(other[, units, frame, remove_wrap, ...])

Align the Spectrum with respect to other.

average(spectra[, weights, align])

Average this Spectrum with spectra.

axis_velocity([unit])

Get the spectral axis in velocity units.

axis_world_coords(*axes[, pixel_corners, wcs])

Returns objects representing the world coordinates of pixel centers for a desired axes.

axis_world_coords_values(*axes[, ...])

Returns the world coordinate values of all pixels for desired axes.

baseline(degree[, exclude, include, color])

Compute and optionally remove a baseline.

bshow()

Show the baseline model

cog([vc, width_frac, bchan, echan, ...])

Curve of growth (CoG) analysis based on Yu et al. (2020) [1].

collapse(method[, axis])

Collapse the flux array given a method.

crop(*points[, wcs, keepdims])

Crop using real world coordinates.

crop_by_values(*points[, units, wcs, keepdims])

Crop using real world coordinates.

decimate(n)

Decimate the Spectrum by n pixels.

divide(operand[, operand2])

Performs division by evaluating self / operand.

explode_along_axis(axis)

Separates slices of NDCubes along a given axis into an NDCubeSequence of (N-1)DCubes.

fake_spectrum([nchan, seed, normal, use_wcs])

Create a fake spectrum with gaussian noise, useful for simple testing.

find_shift(other[, units, frame])

Find the shift required to align this Spectrum with other.

get_selected_regions([unit])

Get selected regions from plot.

get_velocity_in_frame(toframe)

Compute the radial velocity of the Spectrum.target in a new velocity frame.

make_spectrum(data, meta[, use_wcs, ...])

Factory method to create a Spectrum object from a data and header.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

meta_as_table()

Return Spectrum.meta as an Table.

multiply(operand[, operand2])

Performs multiplication by evaluating self * operand.

new_flux_unit(unit[, equivalencies, ...])

normalness()

Compute the p-value if the noise in a spectrum is gaussian using the Anderson-Darling statistic The p-value gives the probability that the spectrum is gaussian.

plot(**kwargs)

Plot the spectrum.

query_lines([chemical_name, ...])

Query locally or remotely for lines and return a table object.

radiometer([roll])

Check the radiometer equation, and return the dimensionless ratio of the measured vs.

rebin(bin_shape[, operation, ...])

Downsample array by combining contiguous pixels into bins.

recomb(line[, cat])

Search for recombination lines of H, He, and C in the frequency range of this Spectrum.

recomball([cat])

Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.

reproject_to(target_wcs[, algorithm, ...])

Reprojects the instance to the coordinates described by another WCS object.

roll([rollmax])

Rolling data to check for channel correllations and channel-to-channel correllations.

savefig(file, **kwargs)

Save the plot

set_convention(doppler_convention)

Set the velocity convention of this Spectrum.

set_frame(toframe)

Set the sky coordinate and doppler tracking reference frame of this Spectrum.

set_radial_velocity_to(radial_velocity)

This sets the radial velocity of the spectrum to be radial_velocity without changing the values of the spectral_axis.

set_redshift_to(redshift)

This sets the redshift of the spectrum to be redshift without changing the values of the spectral_axis.

shift(s[, remove_wrap, fill_value, method])

Shift the Spectrum by s channels in place.

shift_spectrum_to(*[, redshift, radial_velocity])

This shifts in-place the values of the spectral_axis, given either a redshift or radial velocity.

smooth([method, width, decimate, meta, ...])

Smooth or Convolve the Spectrum, optionally decimating it.

snr([peak, flux, rms])

Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.

squeeze([axis])

Removes all axes with a length of 1.

sratio([mean])

Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.

stats([roll, qac])

Compute some statistics of this Spectrum.

subtract(operand[, operand2])

Performs subtraction by evaluating self - operand.

to(new_unit, **kwargs)

Convert instance to another unit.

undo_baseline()

Undo the most recently computed baseline.

velocity_axis_to([unit, toframe, ...])

Convert the spectral axis to unit in toframe using doppler_convention if converting from frequency/wavelength to velocity.

with_flux_unit(unit[, equivalencies, ...])

Returns a new spectrum with a different flux unit.

with_frame(toframe)

Return a copy of this Spectrum with a new coordinate reference frame.

with_spectral_axis_and_flux_units(...[, ...])

Perform with_spectral_axis_unit() and with_flux_unit() together.

with_spectral_axis_last()

Convenience method to return a new copy of the Spectrum with the spectral axis last.

with_spectral_axis_unit(unit[, ...])

Returns a new spectrum with a different spectral axis unit.

with_spectral_unit(unit[, ...])

with_velocity_convention(doppler_convention)

Returns a copy of this Spectrum with the input velocity convention.

list_to_spectral_region

max

mean

median

min

read

sum

write

align_to(other, units=None, frame=None, remove_wrap=True, fill_value=nan, method='fft')[source]#

Align the Spectrum with respect to other.

Parameters:
otherSpectrum

Target Spectrum to align to.

units{None, astropy.units.quantity.Quantity}

Find the shift to align the two Spectra in these units. If None, the Spectra will be aligned using the units of other.

frame{None, str}

Find the shift in this reference frame. If None will use the frame of other.

remove_wrapbool

If True allow spectrum to wrap around the edges. If False fill channels that wrap with fill_value.

fill_valuefloat

If wrap=False fill channels that wrapped with this value.

method“fft”

Method used to perform the fractional channel shift. “fft” uses a phase shift.

average(spectra, weights: str | ndarray | None = 'tsys', align=False)[source]#

Average this Spectrum with spectra. The resulting average will have an exposure equal to the sum of the exposures, and coordinates and system temperature equal to the weighted average of the coordinates and system temperatures.

Parameters:
spectralist of Spectrum

Spectra to be averaged. They must have the same number of channels. No checks are done to ensure they are aligned.

weights: None, str or ~numpy.ndarray

If None, the channel weights will be equal and set to unity.

If ‘tsys’ the channel weights will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

If ‘spectral’, the weights in each Spectrum will be used.

If an array, it must have shape (len(spectra)+1,) or (len(spectra)+1,nchan) where nchan is the number of channels in the spectra. The first element ofthe weights array will be applied to the current spectrum.

alignbool

If True align the spectra to itself. This uses Spectrum.align_to.

Returns:
averageSpectrum

Averaged spectra.

axis_velocity(unit=Unit('km / s'))[source]#

Get the spectral axis in velocity units. Note: This is not the same as Spectrum.velocity, which includes the source radial velocity.

Parameters:
unitQuantity or str that can be converted to Quantity

The unit to which the axis is to be converted

Returns
——-
velocityQuantity

The converted spectral axis velocity

baseline(degree, exclude=None, include=None, color='k', **kwargs)[source]#

Compute and optionally remove a baseline. The code uses Fitter and polynomial to compute the baseline. See the documentation for those modules for details. This method will set the baseline_model attribute to the fitted model function which can be evaluated over a domain.

Note that include and exclude are mutually exclusive. If both are present, only include will be used.

Parameters:
degreeint

The degree of the polynomial series, a.k.a. baseline order

excludelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to exclude from the fit. The tuple(s) represent a range in the form [lower,upper], inclusive.

Examples:

One channel-based region: [11,51]

Two channel-based regions: [(11,51),(99,123)].

One Quantity region: [110.198*u.GHz,110.204*u.GHz].

One compound SpectralRegion: SpectralRegion([(110.198*u.GHz,110.204*u.GHz),(110.196*u.GHz,110.197*u.GHz)]).

Default: no exclude region

includelist of 2-tuples of int or Quantity, or SpectralRegion

List of region(s) to include in the fit. The tuple(s) represent a range in the form [lower,upper], inclusive. See exclude for examples.

colorstr

The color to plot the baseline model, if remove=False. Can be any type accepted by matplotlib.

modelstr

One of ‘polynomial’, ‘chebyshev’, ‘legendre’, or ‘hermite’ Default: ‘chebyshev’

fitterFitter

The fitter to use. Default: LinearLSQFitter (with calc_uncertaintes=True). Be careful when choosing a different fitter to be sure it is optimized for this problem.

removebool

If True, the baseline is removed from the spectrum. If False, the baseline will be computed and overlaid on the spectrum. Default: False

property baseline_model#

Returns the computed baseline model or None if it has not yet been computed.

bshow()[source]#

Show the baseline model

cog(vc=None, width_frac=None, bchan=None, echan=None, flat_tol=0.1, fw=1, xunit='km/s', vframe=None, doppler_convention=None) dict[source]#

Curve of growth (CoG) analysis based on Yu et al. (2020) [1].

Parameters:
vcfloat

Central velocity of the line. If not provided, it will be estimated from the moment 1 of the Spectrum.

width_fraclist

List of fractions of the total flux at which to compute the line width. If 0.25 and 0.85 are not included, they will be added to estimate the concentration as defined in [1].

bchanint

Beginning channel where there is signal. If not provided it will be estimated using fw times the width of the line at the largest width_frac.

echanint

End channel where there is signal. If not provided it will be estimated using fw times the width of the line at the largest width_frac.

flat_tolfloat

Tolerance used to define the flat portion of the curve of growth. The curve of growth will be considered flat when it’s slope is within flat_tol times the standard deviation of the slope from zero.

fwfloat

When estimating the line-free range, use fw times the largest width.

xunitstr or Quantity

Units for the x axis when computing the CoG.

vframeNone or str

Velocity frame to use. The results will be provided in this velocity frame. If None, the velocity frame of the Spectrum will be used. The velocity frame of the Spectrum won’t be changed.

doppler_conventionNone or {‘radio’, ‘optical’, ‘relativistic’}

The Doppler velocity covention to use when converting to velocity units. If a string, one of ‘optical’, ‘radio’, or ‘relativistic’. If None, it will use the Spectrum.doppler_convention.

Returns:
resultsdict

Dictionary with the flux (\(F\)), width (\(V\)), flux asymmetry (\(A_F\)), slope asymmetry (\(A_C\)), concentration (\(C_V\)), rms, central velocity (“vel”), redshifted flux (\(F_r\)), blueshifted flux (\(F_b\)),`bchan` and echan, and errors on the flux (“flux_std”), width (“width_std”), central velocity (“vel_std”), redshifted flux (“flux_r_std”), and blueshifted flux (“flux_b_std”). The rms is the standard deviation in the range outside of (bchan,echan).

decimate(n)[source]#

Decimate the Spectrum by n pixels.

Parameters:
nint

Decimation factor of the spectrum by returning every n-th channel.

Returns:
sSpectrum

The decimated Spectrum.

property doppler_convention: str#

String representation of the velocity (Doppler) convention

property equivalencies#

Get the spectral axis equivalencies that can be used in converting the axis between km/s and frequency or wavelength

property exclude_regions#

The baseline exclusion region(s) of this spectrum

classmethod fake_spectrum(nchan=1024, seed=None, normal=True, use_wcs=True, **kwargs)[source]#

Create a fake spectrum with gaussian noise, useful for simple testing. A default header is created, which may be modified with kwargs.

Parameters:
nchanint, optional

Number of channels. The default is 1024.

seed{None, int, array_like[ints], numpy.random.SeedSequence, numpy.random.BitGenerator, numpy.random.Generator}, optional

A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then all values must be non-negative and will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Additionally, when passed a BitGenerator, it will be wrapped by Generator. If passed a Generator, it will be returned unaltered. The default is None.

normalbool, optional

If set, the noise is distributed normal with a mean 0.1 and dispersion 0.1. If False, the noise is uniformly distributed between 0 and 1. The default is True.

use_wcsbool, optional

If set, create a WCS object from the metadata. This is computationally expensive, so setting it to False can speed things up when no WCS is needed. The default is True.

**kwargs: dict or key=value

Metadata to put in the header. If the key exists already in the default header, it will be replaced. Otherwise the key and value will be added to the header. Keys are case insensitive.

Returns:
spectrumSpectrum

The spectrum object.

find_shift(other, units=None, frame=None)[source]#

Find the shift required to align this Spectrum with other.

Parameters:
otherSpectrum

Target Spectrum to align to.

units{None, astropy.units.quantity.Quantity}

Find the shift to align the two Spectra in these units. If None, the Spectra will be aligned using the units of other.

frame{None, str}

Find the shift in this reference frame. If None will use the frame of other.

Returns:
shiftfloat

Number of channels that this Spectrum must be shifted to be aligned with other.

property flux#

Converts the stored data and unit and mask into a Quantity object.

Returns:
Quantity

Spectral data as a quantity. Masked values are filled with NaN.

get_selected_regions(unit=None)[source]#

Get selected regions from plot.

get_velocity_in_frame(toframe: str) Quantity[source]#

Compute the radial velocity of the Spectrum.target in a new velocity frame. See get_velocity_in_frame().

Parameters:
toframestr

The coordinate frame to convert to, e.g. ‘hcrs’, ‘icrs’.

Returns:
radial_velocityQuantity

The radial velocity of the source in toframe

list_to_spectral_region(inlist)[source]#
classmethod make_spectrum(data, meta, use_wcs=True, observer_location=None, observer=None)[source]#

Factory method to create a Spectrum object from a data and header. The the data are masked, the Spectrum mask will be set to the data mask.

Parameters:
datandarray

The data array. See Spectrum

metadict

The metadata, typically derived from an SDFITS header. Required items in meta are ‘CTYPE[123]’,’CRVAL[123]’, ‘CUNIT[123]’, ‘VELOCITY’, ‘EQUINOX’, ‘RADESYS’

use_wcsbool

If True, create a WCS object from meta Default: True

observer_locationEarthLocation or str

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in meta. If this parameter is given the special str value ‘from_meta’, then an observer_location will be created from SITELONG, SITELAT, and SITEELEV in the meta dictionary.

observerBaseCoordinateFrame

Coordinate frame for the observer. Will be ignored if DATE-OBS or MJD-OBS are present in meta and observer_location is not None.

Returns:
spectrumSpectrum

The spectrum object

meta_as_table()[source]#

Return Spectrum.meta as an Table.

property nchan: int#

The number of channels in the Spectrum

normalness()[source]#

Compute the p-value if the noise in a spectrum is gaussian using the Anderson-Darling statistic The p-value gives the probability that the spectrum is gaussian. If p>0.05, the spectrum can be considered gaussian. See also “D’Agostino, R. B., & Stephens, M. A. (Eds.). (1986) Goodness-of-fit techniques” , table 4.9

property observer#
Returns:
observerBaseCoordinateFrame or derivative
The coordinate frame of the observer if present.
property obstime#
plot(**kwargs)[source]#

Plot the spectrum.

Parameters:
show_headerbool

Show informational header.

selectbool

Allow selecting regions via click and drag.

oshowlist or Spectrum

Spectra to overlay in the plot.

Other Parameters:
xaxis_unitstr or Unit

The units to use on the x-axis, e.g. “km/s” to plot velocity.

yaxis_unitstr or Unit

The units to use on the y-axis.

xminfloat

Minimum x-axis value, in xaxis_unit.

xmaxfloat

Maximum x-axis value, in yaxis_unit.

yminfloat

Minimum y-axis value, in xaxis_unit.

ymaxfloat

Maximum y-axis value, in yaxis_unit.

xlabelstr

x-axis label.

ylabelstr

y-axis label.

gridbool

Show a plot grid or not.

figsizetuple

Figure size (see matplotlib).

linewidthfloat

Line width, default: 2.0.

drawstylestr

Line style, default ‘default’.

colorstr

Line color, c also works.

titlestr

Plot title.

vel_framestr

The velocity frame (see VELDEF FITS Keyword).

doppler_convention: str

The velocity convention (see VELDEF FITS Keyword).

property plotter#
query_lines(chemical_name: str | None = None, intensity_lower_limit: float | None = None, cat: str = 'gbtlines') Table[source]#

Query locally or remotely for lines and return a table object. The query returns lines with rest frequencies in the range of this Spectrum’s spectral_axis.

Note: If the search parameters result in no matches, a zero-length Table will be returned.

Parameters:
chemical_namestr, optional

Name of the chemical to search for. Treated as a regular expression. An empty set will match any species. Examples:

'H2CO' - 13 species have H2CO somewhere in their formula.

'Formaldehyde' - There are 8 isotopologues of Formaldehyde

(e.g., H213CO).

'formaldehyde' - Thioformaldehyde,Cyanoformaldehyde.

'formaldehyde',chem_re_flags=re.I - Formaldehyde,thioformaldehyde,

and Cyanoformaldehyde.

' H2CO ' - Just 1 species, H2CO. The spaces prevent including

others.

intensity_lower_limitfloat, optional

Lower limit on the intensity in the logarithmic CDMS/JPL scale. This corresponds to the ‘intintensity’ column in the returned table.

catstr or Path

The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the columns parameter.

  • 'gbtlines' is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.

  • 'gbtrecomb' is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.

Returns:
~astropy.table.Table

An astropy table containing the results of the search

radiometer(roll=0)[source]#

Check the radiometer equation, and return the dimensionless ratio of the measured vs. expected noise. Generally this number is 1.0 or higher, unless for example channels were hanning correlated, measured noise will be lower.

User is responsible for selecting the channels, via e.g. indexing:

r1 = sp0[1000:2000].radiometer()

Parameters:
rollint

Subtract the data of channel i+roll from channel i before computing the rms. This helps reduce artifacts due to bad baselines or channel-to-channel correlations. A value of 1 or 2 is recommended. See also the roll function where a series of roll values can be checked. The default is 0 (no roll).

Returns:
ratioreal

The ratio of measured to expected RMS.

recomb(line, cat: str = 'gbtrecomb') Table[source]#

Search for recombination lines of H, He, and C in the frequency range of this Spectrum.

Parameters:
linestr

A string describing the line or series to search for, e.g. “Hydrogen”, “Halpha”, “Hebeta”, “C”, “carbon”.

catstr or Path

The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the columns parameter.

  • 'gbtlines' is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.

  • 'gbtrecomb' is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.

Returns:
~astropy.table.Table

An astropy table containing the results of the search

recomball(cat: str = 'gbtrecomb') Table[source]#

Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.

Parameters:
catstr or Path

The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the columns parameter.

  • 'gbtlines' is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.

  • 'gbtrecomb' is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.

Returns:
~astropy.table.Table

An astropy table containing the results of the search

property rest_value: Quantity#

Rest frequency used in velocity conversions.

Returns:
~astropy.units.quantity.Quantity.Quantity

The rest frequency as a Quantity object

roll(rollmax=1)[source]#

Rolling data to check for channel correllations and channel-to-channel correllations. For all roll’s from 1 to rollmax the RMS in the rolled data is compared to the raw RMS. For well behaved (and baseline subtracted) data the ratio of the raw RMS to the rolled RMS should approach 1.0. Note: rolling the data is shifting the data by “roll” channels.

Parameters:
rollmaxint

Roll the data by values 1 through rollmax. The default is 1.

Returns:
ratiolist

The ratios of raw RMS by the rolled RMS. The list has a length of rollmax.

savefig(file, **kwargs)[source]#

Save the plot

set_convention(doppler_convention)[source]#

Set the velocity convention of this Spectrum. The spectral axis of this Spectrum will be replaced with a new spectral axis with the input velocity convention. The header ‘VELDEF’ value will be changed accordingly.

To make a copy of this Spectrum with a new velocity convention instead, use Spectrum.with_velocity_convention.

Parameters:
doppler_conventionstr

The velocity convention, one of ‘radio’, ‘optical’, ‘relativistic’

set_frame(toframe)[source]#

Set the sky coordinate and doppler tracking reference frame of this Spectrum. The header ‘CTYPE1’ will be changed accordingly.

To make a copy of this Spectrum with new coordinate referece frmae instead, use with_frame.

Parameters:
toframestr, BaseCoordinateFrame, or SkyCoord

The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, an actual coordinate system instance, or a sky coordinate instance.

shift(s, remove_wrap=True, fill_value=nan, method='fft')[source]#

Shift the Spectrum by s channels in place.

Parameters:
sfloat

Number of channels to shift the Spectrum by.

remove_wrapbool

If False keep channels that wrap around the edges. If True fill channels that wrap with fill_value.

fill_valuefloat

If remove_wrap=True fill channels that wrapped with this value.

method“fft”

Method used to perform the fractional channel shift. “fft” uses a phase shift.

smooth(method='hanning', width=1, decimate=0, meta=None, mask=None, boundary='extend', nan_treatment='fill', fill_value=nan, preserve_nan=True)[source]#

Smooth or Convolve the Spectrum, optionally decimating it.

Default smoothing is hanning.

Parameters:
methodstring

Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.

widthint

Effective width of the convolving kernel. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final frequency response. That is, the smoothed Spectrum will have an effective frequency resolution equal to CDELT1*`width`. The default is 1.

decimateint

Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution)

maskNone or numpy.ndarray

A “mask” array. Shape must match array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. If None, no masking will be performed unless array is a masked array. If mask is not None and array is a masked array, a pixel is masked if it is masked in either mask or array.mask.

boundarystr
A flag indicating how to handle boundaries:
  • None

    Set the result values to zero where the kernel extends beyond the edge of the array.

  • ‘fill’

    Set values outside the array boundary to fill_value (default).

  • ‘wrap’

    Periodic boundary that wrap to the other side of array.

  • ‘extend’

    Set values outside the array to the nearest array value.

fill_valuefloat

The value to use outside the array when using boundary='fill'. Default value is NaN.

nan_treatment{‘interpolate’, ‘fill’}
The method used to handle NaNs in the input array:
  • 'interpolate': NaN values are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.

  • 'fill': NaN values are replaced by fill_value prior to convolution.

preserve_nanbool

After performing convolution, should pixels that were originally NaN again become NaN?

Returns:
sSpectrum

The new, possibly decimated, convolved Spectrum.

Raises:
Exception

If no valid smoothing method is given.

ValueError

If width is less than one. If width is less than the spectral resolution (in channels). If decimate is not an integer.

snr(peak=True, flux=False, rms=None)[source]#

Signal-to-noise (S/N) ratio, measured either in channel or total flux mode. Make sure the spectrum has been baseline substracted, or the snr is meaningless. See also sratio(), the signal ratio.

Parameters:
peakbool

If True, the largest positive deviation from the mean is compared to the rms. If False, the largest negative deviation from the mean is compared to the rms. For normal noise the returned snr value depends on the number of channels via the error function.

fluxbool

If True, the integrated flux over the spectrum is compared to the expected flux given pure noise. If False, channel based snr is computed, also controlled by the value of the peak in the spectrum.

See also Specutils Analysis.

rmsNone or Quantity}

If given, this is the RMS used in the S/N computations. By default it is determined from the Spectrum.stats(roll=1)["rms"] value of the Spectrum.

Returns:
ratiofloat

The S/N, either flux or channel based

sratio(mean=0.0)[source]#

Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum. The Spectrum must have been baseline subtracted before using this function, otherwise the results will not make sense.

Parameters:
meanfloat

At your own risk, don’t use this, should do a baseline subtraction before. If not, this could be used as a cheat.

Returns:
ratioreal

The signal ratio, between -1 and 1, 0 being pure noise.

stats(roll=0, qac=False)[source]#

Compute some statistics of this Spectrum. The mean, rms, median, data minimum and data maximum are calculated. Note this works with slicing, so, e.g., myspectrum[45:153].stats() will return the statistics of the slice.

Parameters:
rollint

Return statistics on a ‘rolled’ array differenced with the original array. If there is no correllaton between channels, a roll=1 would return an RMS sqrt(2) larger than that of the input array. Another advantage of rolled statistics it will remove most slow variations, thus RMS/sqrt(2) might be a better indication of the underlying RMS. Note that for roll > 1, the RMS is already corrected by sqrt(2), so they can be directly compared. Default: 0

qacbool

If set, the returned simple string contains mean,rms,datamin,datamax for easier visual regression. Based on some legacy code. Default: False

Returns:
statsdict

Dictionary consisting of (mean,median,rms,datamin,datamax)

property subtracted#

Has a baseline model been subtracted?”

Returns:
True if a baseline model has been subtracted, False otherwise
property target#

The target object of this spectrum.

Returns:
targetSkyCoord

The sky coordinate object

property tscale#
The descriptive brightness unit of the data. One of
  • ‘Raw’ : raw value, e.g., count

  • ‘Ta’ : Antenna Temperature in K

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere in K

  • ‘Flux’: flux density in Jansky

Returns:
tscalestr or None

Brightness unit string. If there is no TSCALE in the header, None is returned.

property tscale_fac#

The factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density. This is the average of the values by which the integrations in the spectrum have been scaled.

Returns:
tscale_facfloat or None

The scale factor. If there is no TSCALFAC in the header, None is returned.

undo_baseline()[source]#

Undo the most recently computed baseline. If the baseline has been subtracted, it will be added back to the data. The baseline_model attribute is set to None. Exclude regions are untouched.

velocity_axis_to(unit=Unit('km / s'), toframe=None, doppler_convention=None)[source]#

Convert the spectral axis to unit in toframe using doppler_convention if converting from frequency/wavelength to velocity.

Parameters:
unitQuantity or str that can be converted to Quantity

The unit to which the spectral axis is to be converted.

toframestr

The coordinate frame to convert to, e.g. ‘hcrs’, ‘icrs’.

doppler_conventionNone or {‘optical’, ‘radio’, ‘relativistic’}

The Doppler convention to use when converting to velocity. One of ‘optical’, ‘radio’, or ‘relativistic’.

Returns:
velocityQuantity

The converted spectral axis in units of unit.

property velocity_frame: str#

String representation of the velocity frame

property weights#

The channel weights of this spectrum

with_frame(toframe)[source]#

Return a copy of this Spectrum with a new coordinate reference frame.

Parameters:
toframestr, BaseCoordinateFrame, or SkyCoord

The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, an actual coordinate system instance, or a sky coordinate instance.

Returns:
spectrumSpectrum

A new Spectrum object with the rest frame set to toframe.

with_velocity_convention(doppler_convention)[source]#

Returns a copy of this Spectrum with the input velocity convention. The header ‘VELDEF’ value will be changed accordingly.

Parameters:
doppler_conventionstr

The velocity convention, one of ‘radio’, ‘optical’, ‘relativistic’

Returns:
spectrumSpectrum

A new Spectrum object with doppler_convention as its Doppler convention.

dysh.spectra.spectrum.ascii_spectrum_writer_basic(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.ascii_spectrum_writer_commented_header(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.ascii_spectrum_writer_fixed_width(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.ascii_spectrum_writer_ipac(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.average_spectra(spectra, weights='tsys', align=False, history=None)[source]#

Average spectra. The resulting average will have an exposure equal to the sum of the exposures, and coordinates and system temperature equal to the weighted average of the coordinates and system temperatures.

Parameters:
spectralist of Spectrum

Spectra to be averaged. They must have the same number of channels. No checks are done to ensure they are aligned.

weights: None, str or ~numpy.ndarray

If None, the channel weights will be equal and set to unity.

If ‘tsys’ the channel weights will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

If ‘spectral’, the weights array in each Spectrum will be used.

If an array, it must have shape (len(spectra),) or (len(spectra),nchan) where nchan is the number of channels in the spectra.

alignbool

If True align the spectra to the first element. This uses Spectrum.align_to.

historydysh.log.HistoricalBase

History to append to the averaged spectra.

Returns:
averageSpectrum

Averaged spectra.

dysh.spectra.spectrum.spectrum_reader_ecsv(fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_reader_fits(fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_reader_gbtidl(fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_writer_ecsv(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_writer_fits(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_writer_mrt(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_writer_sdfits(spectrum, fileobj, **kwargs)[source]#
dysh.spectra.spectrum.spectrum_writer_votable(spectrum, fileobj, **kwargs)[source]#

Scan#

The classes that define various types of Scan and their calibration methods.

class dysh.spectra.scan.FSScan(gbtfits, scan, sigrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, fold=True, shift_method='fft', use_sig=True, smoothref=1, apply_flags=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tsys=None, tcal=None, nocal: bool = False, channel: list | None = None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#

Bases: ScanBase

GBT specific version of Frequency Switch Scan

Parameters:
gbtfitsGBTFITSLoad

input GBTFITSLoad object

scanint

Scan number that contains integrations with a series of sig/ref and calon/caloff states.

sigrows :dict

Dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in sdfits corresponding to sig=T (ON) and sig=F (OFF) integrations.

calrowsdict

Dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in sdfits corresponding to cal=T (ON) and cal=F (OFF) integrations.

fdnum: int

The feed number

ifnumint

The IF number

plnumint

The polarization number

bintableint

The index for BINTABLE in sdfits containing the scans.

calibratebool

Whether or not to calibrate the data. If true, data will be calibrated as TSYS*(ON-OFF)/OFF. Default: True

foldbool

Whether or not to fold the spectrum. Default: True

shift_methodstr

Method to use when shifting the spectra for folding. One of ‘fft’ or ‘interpolate’. ‘fft’ uses a phase shift in the time domain. ‘interpolate’ interpolates the signal. Default: ‘fft’

use_sigbool

Whether to use the sig as the sig, or the ref as the sig. Default: True

smoothref: int

The number of channels in the reference to boxcar smooth prior to calibration.

apply_flagsboolean, optional. If True, apply flags before calibration.
tscalestr, optional
The brightness scale unit for the output scan, must be one of (case-insensitive)
  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’

ap_efffloat or None

Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None, dysh will calculate it as described in aperture_efficiency(). Only one of ap_eff or surface_error can be provided.

surface_error: Quantity or None

Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None, dysh will use the known GBT surface error model. Only one of ap_eff or surface_error can be provided.

zenith_opacity: float, optional

The zenith opacity to use in calculating the scale factors for the integrations. Default:None

observer_locationEarthLocation

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.

tsysfloat or ndarray

If given, this is the system temperature in Kelvin. It overrides the values calculated using the noise diodes. If not given, and signal and reference are scan numbers, the system temperature will be calculated from the reference scan and the noise diode. If not given, and the reference is a Spectrum, the reference system temperature as given in the metadata header will be used. The default is to use the noise diode or the metadata, as appropriate.

channel: list or None

An inclusive list of [firstchan, lastchan] to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range [firstchan,lastchan] will be used. If a reference spectrum has been given, it will also be trimmed to [firstchan,lastchan]. If channels have already been selected through select_channel(), a ValueError will be raised. If vane is provided, tsys will be ignored.

vaneVaneSpectrum or None

Vane calibration spectrum. This will be used to derive the system temperature. If provided, tsys will be ignored.

Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

folded

Has the FSscan been folded?

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

scan

The scan number

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

Frequency switch calibration.

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

calibrate(**kwargs)[source]#

Frequency switch calibration.

Parameters:
foldbool

Fold the spectrum or not. Required keyword.

property folded#

Has the FSscan been folded?

Returns:
boolean

True if the signal and reference integrations have been folded. False if not.

class dysh.spectra.scan.NodScan(gbtfits, scan, beam1, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, tsys=None, tcal=None, nocal=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, channel=None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#

Bases: ScanBase

GBT specific version of Nodding Scan. A nod scan object has one IF, two feeds, and one polarization.

Parameters:
gbtfitsGBTFITSLoad

input GBTFITSLoad object

scandict

dictionary with keys ‘ON’ and ‘OFF’ containing unique list of ON (signal) and OFF (reference) scan numbers NOTE: there should be one ON and one OFF, a pair. There should be at least two beams (the nodding beams) which will be resp. on source in each scan.

beam1: bool

Is this scan BEAM1 or BEAM2? BEAM1 is defined as being on source in the first scan of the pair, BEAM2 in the second of the pair

scanrowsdict

dictionary with keys ‘ON’ and ‘OFF’ containing the list of rows in sdfits corresponding to ON (signal) and OFF (reference) integrations

calrowsdict

dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in sdfits corresponding to cal=T (ON) and cal=F (OFF) integrations.

fdnum: int

The feed number

ifnumint

The IF number

plnumint

The polarization number

bintableint

The index for BINTABLE in sdfits containing the scans

calibrate: bool

Whether or not to calibrate the data. If true, data will be calibrated as TSYS*(ON-OFF)/OFF. Default: True

smoothref: int

The number of channels in the reference to boxcar smooth prior to calibration (if applicable)

apply_flagsboolean

If True, apply flags before calibration.

tsysfloat

User provided value for the system temperature. If vane is provided, tsys will be ignored.

nocalbool

True if the noise diode was not fired. False if it was fired.

tscalestr, optional
The brightness scale unit for the output scan, must be one of (case-insensitive)
  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’

ap_efffloat or None

Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None, dysh will calculate it as described in aperture_efficiency(). Only one of ap_eff or surface_error can be provided.

surface_error: Quantity or None

Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None, dysh will use the known GBT surface error model. Only one of ap_eff or surface_error can be provided.

zenith_opacity: float, optional

The zenith opacity to use in calculating the scale factors for the integrations. Default:None

observer_locationEarthLocation

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.

channel: list or None

An inclusive list of [firstchan, lastchan] to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range [firstchan,lastchan] will be used. If a reference spectrum has been given, it will also be trimmed to [firstchan,lastchan]. If channels have already been selected through select_channel(), a ValueError will be raised.

vaneVaneSpectrum or None

Vane calibration spectrum. This will be used to derive the system temperature. If provided, tsys will be ignored.

Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

scan

The scan number

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

NodScan calibration

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

calibrate(**kwargs)[source]#

NodScan calibration

class dysh.spectra.scan.PSScan(gbtfits, scan, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tscale='ta', zenith_opacity=0.0, refspec=None, tsys=None, ap_eff=None, surface_error=None, tcal=None, nocal=False, channel=None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#

Bases: ScanBase

GBT specific version of Position Switch Scan. A position switch scan object has one IF, one feed, and one polarization

Parameters:
gbtfitsGBTFITSLoad

Input GBTFITSLoad object.

scandict

dictionary with keys ‘ON’ and ‘OFF’ containing unique list of ON (signal) and OFF (reference) scan numbers NOTE: there should be one ON and one OFF, a pair.

scanrowsdict

dictionary with keys ‘ON’ and ‘OFF’ containing the list of rows in sdfits corresponding to ON (signal) and OFF (reference) integrations.

calrowsdict

dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in sdfits corresponding to cal=T (ON) and cal=F (OFF) integrations.

fdnum: int

The feed number.

ifnumint

The intermediate frequency (IF) number.

plnumint

The polarization number.

bintableint

The index for BINTABLE in sdfits containing the scans.

calibrate: bool

Whether or not to calibrate the data. If true, data will be calibrated as TSYS*(ON-OFF)/OFF. Default: True

smoothref: int

If >1 smooth the reference with a boxcar kernel with a width of smooth_ref channels. The default is to not smooth the reference.

apply_flagsboolean, optional

If True, apply flags before calibration.

observer_locationEarthLocation

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.

tscalestr, optional
The brightess unit scale for the output scan, must be one of (case-insensitive)
  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default: ‘ta’

zenith_opacity: float, optional

The zenith opacity to use in calculating the scale factors for the integrations. Default: None

refspecint or Spectrum, optional

If given, the Spectrum will be used as the reference rather than using scan data.

tsysfloat or ndarray

If given, this is the system temperature in Kelvin. It overrides the values calculated using the noise diodes. If not given, and signal and reference are scan numbers, the system temperature will be calculated from the reference scan and the noise diode. If not given, and the reference is a Spectrum, the reference system temperature as given in the metadata header will be used. The default is to use the noise diode or the metadata, as appropriate. If vane is provided, tsys will be ignored.

ap_efffloat or None

Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None, dysh will calculate it as described in aperture_efficiency(). Only one of ap_eff or surface_error can be provided.

surface_error: Quantity or None

Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None, dysh will use the known GBT surface error model. Only one of ap_eff or surface_error can be provided.

channel: list or None

An inclusive list of [firstchan, lastchan] to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range [firstchan,lastchan] will be used. If a reference spectrum has been given, it will also be trimmed to [firstchan,lastchan]. If channels have already been selected through select_channel(), a ValueError will be raised.

vaneVaneSpectrum or None

Vane calibration spectrum. This will be used to derive the system temperature. If provided, tsys will be ignored.

Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

refscan

The scan number associated with the reference.

refspec

The reference Spectrum if one was given at construction.

scan

The scan number

sigscan

The scan number associated with the signal

sigspec

The signal Spectrum if one was given at construction.

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

Position switch calibration, following equations 1 and 2 in the GBTIDL calibration manual

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

calibrate(**kwargs)[source]#

Position switch calibration, following equations 1 and 2 in the GBTIDL calibration manual

property refscan: int | None#

The scan number associated with the reference.

Returns:
int or None;

Integer scan number or None if the reference was a Spectrum object

property refspec: Spectrum | None#

The reference Spectrum if one was given at construction.

Returns:
Spectrum or None;

Spectrum object if given as reference or None.

property sigscan: int#

The scan number associated with the signal

property sigspec: Spectrum | None#

The signal Spectrum if one was given at construction.

Returns:
Spectrum or None;

Spectrum object if given as signal or None.

class dysh.spectra.scan.ScanBase(sdfits, smoothref, apply_flags, observer_location, fdnum=-1, ifnum=-1, plnum=-1, tsys=None, tcal=None, ap_eff=None, surface_error=None, zenith_opacity=None, channel=None)[source]#

Bases: HistoricalBase, SpectralAverageMixin

This class describes the common interface to all Scan classes. A Scan represents one scan number, one IF, one feed, and one polarization. Derived classes must implement calibrate().

Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

scan

The scan number

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

Calibrate the Scan data

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

property ap_eff: ndarray#

The aperture efficiencies for the integrations in this Scan

Returns:
ap_effndarray

The aperture efficiencies, an array of floats between 0 and 1, one value per integration.

property baseline_model#

Returns the subtracted baseline model or None if it has not yet been computed.

abstract calibrate(**kwargs)[source]#

Calibrate the Scan data

property calibrated: ndarray#

Returns the calibrated integrations in the Scan as a numpy array.

property fdnum: int#

The feed number.

Returns:
int

The index of the feed.

get_vane_tcal()[source]#

Get the tcal value for the vane.

getspec(i: int, use_wcs: bool = True) Spectrum[source]#

Return the i-th calibrated Spectrum from this Scan.

Parameters:
iint

The index into the calibrated array

use_wcsbool

Create a WCS object for the resulting Spectrum. Creating a WCS object adds computation time to the creation of a Spectrum object. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.

Returns:
spectrumSpectrum
property ifnum: int#

The intermediate frequency (IF) number.

Returns:
int

The index of the IF.

property is_calibrated: bool#

Have the data been calibrated?

Returns:
bool

True if the data have been calibrated, False if not.

property is_scaled: bool#

Is this Scan scaled to something other than antenna temperature \(T_A\).

Returns:
is_scaledbool

True if scale is e.g \(T_A^*\) or Flux (\(S_\nu\)).

property meta: dict#

The metadata of this Scan. The metadata is a list of dictionaries, the length of which is equal to the number of calibrated integrations in the Scan.

Returns:
dict

Dictionary containing the metadata of this Scan

property nchan: int#

The number of channels in this scan.

Returns:
int

The number of channels in this scan.

property nint: int#

The number of integrations in this scan.

Returns:
int

The number of integrations in this scan.

property nrows: int#

The number of rows in this scan.

Returns:
int

The number of rows in this scan.

property plnum: int#

The polarization number.

Returns:
int

The polarization number.

plot(**kwargs)[source]#
scale(tscale: str, zenith_opacity: float | None = None)[source]#

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity. If data are already scaled, they will be unscaled first.

Parameters:
tscalestr
Strings representing valid options for scaling spectral data, specifically
  • ‘Ta’ : Antenna Temperature in K

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere in K

  • ‘Flux’: flux density in Jansky

This parameter is case-insensitive.

zenith_opacityfloat, optional

The zenith opacity. Required if tscale is ‘Ta*’ or ‘Flux’.

Returns:
None
Raises:
TypeError

If scaling to the tscale unit is not applicable to the scan type, e.g., a total power scan.

ValueError

If tscale is unrecognized or zenith_opacity is negative.

property scan: int#

The scan number

Returns:
int

The scan number of the integrations in the Scan object

subtract_baseline(model, tol: int = 1, force: bool = False)[source]#

Subtract a (previously computed) baseline model from every integration in this Scan.

Parameters:
modelModel

The baseline model to subtract. This is typically a QuantityModel derived by removing a baseline from a similar spectrum.

tolint, optional

The maximum number of channels on either end of the spectrum to extrapolate the baseline model, if the spectral domain of the baseline model is smaller than the spectral axis of the Scan. For instance, if tol=1, then one channel on the low frequency and one channel on the high frequency end are allowed to be extrapolated. The default is 1.

forcebool, optional

Force subtraction of the input baseline model, even if another baseline model has been previously subtracted. Note: The previous baseline model will not be undone (added back in) before subtraction of the input baseline model. The default is False.

Returns:
None
Raises:
ValueError

If the data are not yet calibrated or the tolerance tol is exceeded.

property subtracted: bool#

Has a baseline model been subtracted?

Returns:
True if a baseline model has been subtracted, False otherwise
property surface_error: Quantity#

The dish surface errors for the integrations in this Scan

Returns:
surface_errorQuantity

The surface_errors with dimension length, one value per integration.

timeaverage(weights='tsys', use_wcs=True)[source]#

Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a ScanBlock, it will average all the integrations in all Scans contained in the ScanBlock.

Parameters:
weights: None, str or `~numpy.ndarray`

If None, the channel weights will be equal and set to unity.

If ‘tsys’ the channel weights will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

If an array, it must have shape (Nint,) or (Nint,nchan) where Nint is the number of integrations in the Scan or ScanBlock and nchan is the number of channels in the Scan.

use_wcsbool

Create a WCS object for the resulting Spectrum. Creating a WCS object adds computation time to the creation of a Spectrum object. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.

Returns:
spectrumSpectrum

The time-averaged spectrum. The weights array of the Spectrum will have shape (nchan,) and will be set to the sum of the input weights.

Note

Data that are masked will have values set to zero. This is a feature of numpy.ma.average. Data mask fill value is NaN (np.nan)

property tscale: str#
The descriptive brightness unit of the data. One of
  • ‘Raw’ : raw value, e.g., count

  • ‘Ta’ : Antenna Temperature in K

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere in K

  • ‘Flux’: flux density in Jansky

Returns:
tscalestr

Brightness unit string.

property tscale_fac: ndarray#

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

Returns:
tscale_facndarray

An array of floats, one per integration in the scan.

property tunit: Unit#

The brightness unit (temperature or flux density) of this Scan’s data

Returns:
tunitUnit

The brightness unit

undo_baseline()[source]#

Undo the applied (subtracted) baseline. The subtracted baseline will be added back to the data. The baseline_model attribute is set to None.

write(fileobj, flags=True, output_verify='exception', overwrite=False, checksum=False)[source]#

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

Parameters:
fileobjstr, file-like or pathlib.Path

File to write to. If a file object, must be opened in a writeable mode.

flags: bool, optional

If True, write the applied flags to a FLAGS column in the binary table.

output_verifystr

Output verification option. Must be one of "fix", "silentfix", "ignore", "warn", or "exception". May also be any combination of "fix" or "silentfix" with "+ignore", +warn, or +exception" (e.g. ``"fix+warn"). See https://docs.astropy.org/en/latest/io/fits/api/verification.html for more info

overwritebool, optional

If True, overwrite the output file if it exists. Raises an OSError if False and the output file exists. Default is False.

checksumbool

When True adds both DATASUM and CHECKSUM cards to the headers of all HDU’s written to the file.

Returns:
None.
property zenith_opacity: float | None#

The zenith opacity of this Scan, used to calculated aperture efficiency.

Returns:
zenith_opacity: float or None

A non-negative float. If None, no zenith opacity was set for this scan (e.g. TPScan); the data cannot be scaled.

class dysh.spectra.scan.ScanBlock(*args)[source]#

Bases: UserList, HistoricalBase, SpectralAverageMixin

Attributes:
comments

Get the comment strings.

delta_freq

Returns

duration

Returns

exposure

Returns

history

Get the history strings.

nchan

The number of channels in the first Scan in this ScanBlock.

nint

The total number of integrations in this Scanblock

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scaled from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperatures for all scans in this ScanBlock

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this ScanBlocks’s data

weights

The weights associated with the Scans and integrations in this ScanBlock

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

append(item)

S.append(value) -- append value to the end of the sequence

calibrate(**kwargs)

Calibrate all scans in this ScanBlock

clear()

count(value)

extend(other)

S.extend(iterable) -- extend sequence by appending elements from the iterable

index(value, [start, [stop]])

Raises ValueError if the value is not present.

insert(i, item)

S.insert(index, value) -- insert value before index

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

pop([index])

Raise IndexError if list is empty or index is out of range.

remove(item)

S.remove(value) -- remove first occurrence of value.

reverse()

S.reverse() -- reverse IN PLACE

scale(tscale, zenith_opacity)

Scale all the data in this ScanBlock to the given brightness scale and zenith opacity.

smooth([method, width, decimate, kernel])

Smooth all scans in this ScanBlock.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration of every Scan in this ScanBlock.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

For all Scans in this ScanBlock, undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBlock

copy

plot

sort

calibrate(**kwargs)[source]#

Calibrate all scans in this ScanBlock

property delta_freq#
Returns:
delta_freqndarray

The channel frequency spacings for all scans in this ScanBlock

property duration#
Returns:
durationndarray

The duration times for all scans in this ScanBlock

property exposure#
Returns:
exposurendarray

The exposure times for all scans in this ScanBlock

property nchan#

The number of channels in the first Scan in this ScanBlock. (Assumes number of channels in each enclosed Scan are the same).

Returns:
int

The number of channels in this ScanBlock.

property nint#

The total number of integrations in this Scanblock

Returns:
int

The number of integerationsin this ScanBlock.

plot(**kwargs)[source]#
scale(tscale, zenith_opacity)[source]#

Scale all the data in this ScanBlock to the given brightness scale and zenith opacity. If data are already scaled, they will be unscaled first.

Parameters:
tscalestr
Strings representing valid options for scaling spectral data, specifically
  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

This parameter is case-insensitive.

zenith_opacityfloat

The zenith opacity

Returns:
None
Raises:
TypeError

If scaling to temperature is not applicable to the scan type, e.g., a total power scan.

ValueError

if tscale is unrecognized or zenith_opacity is negative.

smooth(method='hanning', width=1, decimate=0, kernel=None)[source]#

Smooth all scans in this ScanBlock. Smooth or convolve the calibrated data arrays in contained Scans, optionally decimating the data. A number of methods from astropy.convolution can be selected with the method keyword.

Default smoothing is hanning.

Note: Any previously computed/removed baseline will remain unchanged.

Parameters:
methodstring, optional

Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.

widthint, optional

Effective width of the convolving kernel. Should ideally be an odd number. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final beam. We normally assume the input beam has FWHM=1, pending resolution on cases where CDELT1 is not the same as FREQRES. The default is 1.

decimateint, optional

Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution) The default is 0, meaning decimation is by width

kernelndarray, optional

A numpy array which is the kernel by which the signal is convolved. Use with caution, as it is assumed the kernel is normalized to one, and is symmetric. Since width is ill-defined here, the user should supply an appropriate number manually. NOTE: not implemented yet. The default is None.

Raises
——
Exception

If no valid smoothing method is given.

Returns:
None
subtract_baseline(model, tol: int = 1, force: bool = False)[source]#

Subtract a (previously computed) baseline model from every integration of every Scan in this ScanBlock.

Parameters:
modelModel

The baseline model to subtract. This is typically a QuantityModel derived by removing a baseline from a similar spectrum.

tolint, optional

The maximum number of channels on either end of the spectrum to extrapolate the baseline model, if the spectral domain of the baseline model is smaller than the spectral axis of the Scan. For instance, if tol=1, then one channel on the low frequency and one channel on the high frequency end are allowed to be extrapolated. The default is 1.

forcebool, optional

Force subtraction of the input baseline model, even if another baseline model has been previously subtracted. Note: The previous baseline model will not be undone (added back in) before subtraction of the input baseline model. The default is False.

Returns:
None
Raises:
ValueError

If the data are not yet calibrated or the tolerance tol is exceeded.

timeaverage(weights='tsys', use_wcs: bool = True)[source]#

Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a ScanBlock, it will average all the integrations in all Scans contained in the ScanBlock.

Parameters:
weights: None, str or `~numpy.ndarray`

If None, the channel weights will be equal and set to unity.

If ‘tsys’ the channel weights will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

If an array, it must have shape (Nint,) or (Nint,nchan) where Nint is the number of integrations in the Scan or ScanBlock and nchan is the number of channels in the Scan.

use_wcsbool

Create a WCS object for the resulting Spectrum. Creating a WCS object adds computation time to the creation of a Spectrum object. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.

Returns:
spectrumSpectrum

The time-averaged spectrum. The weights array of the Spectrum will have shape (nchan,) and will be set to the sum of the input weights.

Note

Data that are masked will have values set to zero. This is a feature of numpy.ma.average. Data mask fill value is NaN (np.nan)

property tscale#
The descriptive brightness unit of the data. One of
  • ‘Raw’ : raw value, e.g., count

  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

Returns:
tscalestr

brightness unit string

property tscale_fac#

The factor(s) by which the data have been scaled from antenna temperature to corrected antenna temperature or flux density.

Returns:
tscale_facndarray

An array of floats, one per integration in the ScanBlock.

property tsys#

The system temperatures for all scans in this ScanBlock

Returns:
tsysndarray

The system temperatures for all scans in this ScanBlock

property tunit#

The brightness unit (temperature or flux density) of this ScanBlocks’s data

Returns:
tunitUnit

The brightness unit

undo_baseline()[source]#

For all Scans in this ScanBlock, undo the applied (subtracted) baseline. The subtracted baseline will be added back to the data. The Scan’s baseline_model` attribute is set to None.

property weights: list#

The weights associated with the Scans and integrations in this ScanBlock

Returns:
list

A list containing the weight arrays for each scan. Because Scans can have different numbers of integrations, this is a list instead of a numpy array.

write(fileobj, flags=True, output_verify='exception', overwrite=False, checksum=False)[source]#

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBlock

Parameters:
fileobjstr, file-like or pathlib.Path

File to write to. If a file object, must be opened in a writeable mode.

flags: bool, optional

If True, write the applied flags to a FLAGS column in the binary table.

output_verifystr

Output verification option. Must be one of "fix", "silentfix", "ignore", "warn", or "exception". May also be any combination of "fix" or "silentfix" with "+ignore", +warn, or +exception" (e.g. ``"fix+warn"). See https://docs.astropy.org/en/latest/io/fits/api/verification.html for more info

overwritebool, optional

If True, overwrite the output file if it exists. Raises an OSError if False and the output file exists. Default is False.

checksumbool

When True adds both DATASUM and CHECKSUM cards to the headers of all HDU’s written to the file.

Returns:
None.
class dysh.spectra.scan.SpectralAverageMixin[source]#

Bases: object

Attributes:
delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

weights

The weights for each integration after an averaging operation.

Methods

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

property delta_freq: ndarray#

The array of channel frequency width. How the channel width is calculated varies for different derived classes. See _calc_delta_freq().

Returns:
delta_freq: ndarray

The channel frequency width in units of the CDELT1 keyword in the SDFITS header.

property duration: ndarray#

The array of duration times. How the duration is calculated varies for different derived classes. See _calc_exposure(). Duration includes the blanking time, exposure does not, so duration>=exposure.

Returns:
durationndarray

The duration time in units of the DURATION keyword in the SDFITS header.

property exposure: ndarray#

The array of exposure (integration) times. How the exposure is calculated varies for different derived classes. See _calc_exposure().

Returns:
exposurendarray

The exposure time in units of the EXPOSURE keyword in the SDFITS header.

smooth(method='hanning', width=1, decimate=0)[source]#

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

A number of methods from astropy.convolution can be selected with the method keyword.

Default smoothing is hanning.

Note: Any previously computed/removed baseline will remain unchanged.

Parameters:
method{‘hanning’, ‘boxcar’, ‘gaussian’}, optional

Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.

widthint, optional

Effective width of the convolving kernel. Should ideally be an odd number. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final beam. We normally assume the input beam has FWHM=1, pending resolution on cases where CDELT1 is not the same as FREQRES. The default is 1.

decimateint, optional

Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution) The default is 0, meaning decimation is by width

Returns:
None
Raises:
ValueError

If no valid smoothing method is given.

timeaverage(weights: str | ndarray = 'tsys', use_wcs=True) Spectrum[source]#

Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a ScanBlock, it will average all the integrations in all Scans contained in the ScanBlock.

Parameters:
weights: None, str or `~numpy.ndarray`

If None, the channel weights will be equal and set to unity.

If ‘tsys’ the channel weights will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

If an array, it must have shape (Nint,) or (Nint,nchan) where Nint is the number of integrations in the Scan or ScanBlock and nchan is the number of channels in the Scan.

use_wcsbool

Create a WCS object for the resulting Spectrum. Creating a WCS object adds computation time to the creation of a Spectrum object. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.

Returns:
spectrumSpectrum

The time-averaged spectrum. The weights array of the Spectrum will have shape (nchan,) and will be set to the sum of the input weights.

Note

Data that are masked will have values set to zero. This is a feature of numpy.ma.average. Data mask fill value is NaN (np.nan)

property tsys#

The system temperature array.

Returns:
tsysndarray

System temperature values in K.

property tsys_weight: ndarray#

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\). See tsys_weight()

property weights: ndarray#

The weights for each integration after an averaging operation. If Scan.timeaverage() has not been called, the weights will be unity. The weights array can have shape (nint,) or (nint,nchan) depending on how timeaverage() was called.

class dysh.spectra.scan.SubBeamNodScan(sigtp, reftp, fdnum, ifnum, plnum, calibrate=True, smoothref=1, apply_flags=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, tcal=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, weights='tsys', nocal=False, vane: ~dysh.spectra.vane.VaneSpectrum | None = None, **kwargs)[source]#

Bases: ScanBase

Parameters:
sigtp: list of `~dysh.spectra.scan.TPScan`

Signal total power scans

reftp: list of `~dysh.spectra.scan.TPScan`

Reference total power scans

fdnum: int

The feed number

ifnumint

The IF number

plnumint

The polarization number

calibrate: bool

Whether or not to calibrate the data.

smoothref: int

the number of channels in the reference to boxcar smooth prior to calibration

apply_flagsboolean, optional. If True, apply flags before calibration.
tscalestr, optional
The brightness scale unit for the output scan, must be one of (case-insensitive)
  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’

ap_efffloat or None

Aperture efficiency o be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None, dysh will calculate it as described in aperture_efficiency(). Only one of ap_eff or surface_error can be provided.

surface_error: Quantity or None

Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None, dysh will use the known GBT surface error model. Only one of ap_eff or surface_error can be provided.

zenith_opacity: float, optional

The zenith opacity to use in calculating the scale factors for the integrations. Default:None

observer_locationEarthLocation

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.

weights: str

Weighting scheme to use when averaging the signal and reference scans ‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

\(w = t_{exp} \times \delta\nu/T_{sys}^2\)

Default: ‘tsys’

vaneVaneSpectrum or None

Vane calibration spectrum. This will be used to derive the system temperature.

Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

scan

The scan number

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

Calibrate the SubBeamNodScan data

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

calibrate(**kwargs)[source]#

Calibrate the SubBeamNodScan data

class dysh.spectra.scan.TPScan(gbtfits, scan, sigstate, calstate, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, tsys=None, tcal=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tscale='Raw', channel=None)[source]#

Bases: ScanBase

GBT specific version of Total Power Scan

Parameters:
gbtfitsGBTFITSLoad

input GBTFITSLoad object

scan: int

scan number

sigstatebool

Select the signal state used to form the data. True means select sig=’T’, False to select sig=’F’. None means select both. See table below for explanation.

calstatebool

Select the calibration state used to form the data. True means select cal=’T’, False to select cal=’F’. None means select both. See table below for explanation.

scanrowslist-like

the list of rows in sdfits corresponding to sigstate integrations

calrowsdict

dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in sdfits corresponding to cal=T (ON) and cal=F (OFF) integrations for scan

fdnum: int

The feed number

ifnumint

The IF number

plnumint

The polarization number

bintableint

the index for BINTABLE in sdfits containing the scans

calibrate: bool

whether or not to calibrate the data. If True, the data will be (calon + caloff)*0.5, otherwise it will be SDFITS row data. Default:True

smoothref: int

the number of channels in the reference to boxcar smooth prior to calibration

apply_flagsboolean, optional. If True, apply flags before calibration.
observer_locationEarthLocation

Location of the observatory. See Observatory. This will be transformed to ITRS using the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.

tscalestr, optional
The brightess unit scale for the output scan, must be one of (case-insensitive)
  • ‘Raw’ : raw value, e.g., count

  • ‘Ta’ : Antenna Temperature

  • ‘Ta*’ : Antenna temperature corrected to above the atmosphere

  • ‘Flux’ : flux density in Jansky

Default: ‘Raw’

channel: list or None

An inclusive list of [firstchan, lastchan] to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range [firstchan,lastchan] will be used. If a reference spectrum has been given, it will also be trimmed to [firstchan,lastchan]. If channels have already been selected through select_channel(), a ValueError will be raised.

Notes
—–
How the total power and system temperature are calculated, depending on signal and reference state parameters:

CAL

SIG

RESULT

TSYS

None

None

data = 0.5* (REFCALON + REFCALOFF), regardless of sig state

use all CAL states, all SIG states

None

True

data = 0.5* (REFCALON + REFCALOFF), where sig = ‘T’

use all CAL states, SIG=’T’

None

False

data = 0.5* (REFCALON + REFCALOFF), where sig = ‘F’

use all CAL states, SIG=’F’

True

None

data = REFCALON, regardless of sig state

use all CAL states, all SIG states

False

None

data = REFCALOFF, regardless of sig state

use all CAL states, all SIG states

True

True

data = REFCALON, where sig=’T’

use all CAL states, SIG=’T’

True

False

data = REFCALON, where sig=’F’

use all CAL states, SIG=’F’

False

True

data = REFCALOFF where sig=’T’

use all CAL states, SIG=’T’

False

False

data = REFCALOFF, where sig=’F’

use all CAL states, SIG=’F’

where `REFCALON` = integrations with `cal=T` and `REFCALOFF` = integrations with `cal=F`.
Attributes:
ap_eff

The aperture efficiencies for the integrations in this Scan

baseline_model

Returns the subtracted baseline model or None if it has not yet been computed.

calibrated

Returns the calibrated integrations in the Scan as a numpy array.

calstate

The requested calibration state

comments

Get the comment strings.

delta_freq

The array of channel frequency width.

duration

The array of duration times.

exposure

The array of exposure (integration) times.

fdnum

The feed number.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

is_calibrated

Have the data been calibrated?

is_scaled

Is this Scan scaled to something other than antenna temperature \(T_A\).

meta

The metadata of this Scan.

nchan

The number of channels in this scan.

nint

The number of integrations in this scan.

nrows

The number of rows in this scan.

plnum

The polarization number.

scan

The scan number

sigstate

The requested signal state

subtracted

Has a baseline model been subtracted?

surface_error

The dish surface errors for the integrations in this Scan

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

tsys

The system temperature array.

tsys_weight

The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).

tunit

The brightness unit (temperature or flux density) of this Scan’s data

weights

The weights for each integration after an averaging operation.

zenith_opacity

The zenith opacity of this Scan, used to calculated aperture efficiency.

Methods

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

calibrate(**kwargs)

Calibrate the total power data according to the CAL/SIG table above

get_vane_tcal()

Get the tcal value for the vane.

getspec(i[, use_wcs])

Return the i-th calibrated Spectrum from this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

scale(tscale[, zenith_opacity])

Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.

smooth([method, width, decimate])

Smooth or convolve the underlying calibrated data array, optionally decimating the data.

subtract_baseline(model[, tol, force])

Subtract a (previously computed) baseline model from every integration in this Scan.

timeaverage([weights, use_wcs])

Compute the time-averaged spectrum.

total_power(i)

Return the i-th total power spectrum in this Scan.

undo_baseline()

Undo the applied (subtracted) baseline.

write(fileobj[, flags, output_verify, ...])

Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase

plot

calibrate(**kwargs)[source]#

Calibrate the total power data according to the CAL/SIG table above

property calstate#

The requested calibration state

Returns:
bool

True if calibration state is on (‘T’ in the SDFITS header), False otherwise (‘F’)

property sigstate#

The requested signal state

Returns:
bool

True if signal state is on (‘T’ in the SDFITS header), False otherwise (‘F’)

total_power(i)[source]#

Return the i-th total power spectrum in this Scan. This is a synonym for calibrated()

Parameters:
iint

The index into the data array

Returns:
spectrumSpectrum

TCal#

TCal class

class dysh.spectra.tcal.TCal(name, snu, *args, **kwargs)[source]#

Bases: Spectrum

Noise diode temperature. This behaves as a Spectrum with the addition of the name and snu attributes, which hold the name of the source used to derive the noise diode temperature and its flux density.

Attributes:
array_axis_physical_types

Returns the WCS physical types that vary along each array axis.

baseline_model

Returns the computed baseline model or None if it has not yet been computed.

bin_edges
combined_wcs

The WCS transform for the NDCube, including the coordinates specified in .extra_coords.

comments

Get the comment strings.

data

ndarray - like

dimensions
doppler_convention

String representation of the velocity (Doppler) convention

energy

The energy of the spectral axis as a Quantity in units of eV.

equivalencies

Get the spectral axis equivalencies that can be used in converting the axis

exclude_regions

The baseline exclusion region(s) of this spectrum

extra_coords

Coordinates not described by NDCubeABC.wcs which vary along one or more axes.

flux

Converts the stored data and unit and mask into a Quantity object.

frequency

The spectral_axis as a Quantity in units of GHz

global_coords

Coordinate metadata which applies to the whole cube.

history

Get the history strings.

mask

any type : Mask for the dataset, if any.

meta
name

Calibration source name.

nchan

The number of channels in the Spectrum

observer

Returns ——- observer : BaseCoordinateFrame or derivative The coordinate frame of the observer if present.

obstime
photon_flux

The flux density of photons as a Quantity, in units of

plotter
psf

Image representation of the PSF for the dataset.

quantity

Unitful representation of the NDCube data.

radial_velocity

The radial velocity(s) of the objects represented by this spectrum.

redshift

The redshift(s) of the objects represented by this spectrum.

rest_value

Rest frequency used in velocity conversions.

shape
snu

Calibration source flux density.

spectral_axis

Returns the SpectralCoord object.

spectral_axis_direction
spectral_axis_index
spectral_wcs

Returns the spectral axes of the WCS

subtracted

Has a baseline model been subtracted?”

target

The target object of this spectrum.

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

uncertainty

any type : Uncertainty in the dataset, if any.

unit

Unit : Unit for the dataset, if any.

velocity

Converts the spectral axis array to the given velocity space unit given the rest value.

velocity_convention

Returns the velocity convention

velocity_frame

String representation of the velocity frame

wavelength

The spectral_axis as a Quantity in units of Angstroms

wcs

any type : A world coordinate system (WCS) for the dataset, if any.

weights

The channel weights of this spectrum

Methods

add(operand[, operand2])

Performs addition by evaluating self + operand.

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

align_to(other[, units, frame, remove_wrap, ...])

Align the Spectrum with respect to other.

average(spectra[, weights, align])

Average this Spectrum with spectra.

axis_velocity([unit])

Get the spectral axis in velocity units.

axis_world_coords(*axes[, pixel_corners, wcs])

Returns objects representing the world coordinates of pixel centers for a desired axes.

axis_world_coords_values(*axes[, ...])

Returns the world coordinate values of all pixels for desired axes.

baseline(degree[, exclude, include, color])

Compute and optionally remove a baseline.

bshow()

Show the baseline model

cog([vc, width_frac, bchan, echan, ...])

Curve of growth (CoG) analysis based on Yu et al. (2020) [R475e759f9d5f-1].

collapse(method[, axis])

Collapse the flux array given a method.

crop(*points[, wcs, keepdims])

Crop using real world coordinates.

crop_by_values(*points[, units, wcs, keepdims])

Crop using real world coordinates.

decimate(n)

Decimate the Spectrum by n pixels.

divide(operand[, operand2])

Performs division by evaluating self / operand.

explode_along_axis(axis)

Separates slices of NDCubes along a given axis into an NDCubeSequence of (N-1)DCubes.

fake_spectrum([nchan, seed, normal, use_wcs])

Create a fake spectrum with gaussian noise, useful for simple testing.

find_shift(other[, units, frame])

Find the shift required to align this Spectrum with other.

from_spectrum(spectrum, name, snu[, data])

Returns a TCal object given a Spectrum object.

get_selected_regions([unit])

Get selected regions from plot.

get_tcal([frac, method, dtype])

Reduce the temperature of the noise diode to a single value.

get_velocity_in_frame(toframe)

Compute the radial velocity of the Spectrum.target in a new velocity frame.

make_spectrum(data, meta[, use_wcs, ...])

Factory method to create a Spectrum object from a data and header.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

meta_as_table()

Return Spectrum.meta as an Table.

multiply(operand[, operand2])

Performs multiplication by evaluating self * operand.

new_flux_unit(unit[, equivalencies, ...])

normalness()

Compute the p-value if the noise in a spectrum is gaussian using the Anderson-Darling statistic The p-value gives the probability that the spectrum is gaussian.

plot(**kwargs)

Plot the spectrum.

query_lines([chemical_name, ...])

Query locally or remotely for lines and return a table object.

radiometer([roll])

Check the radiometer equation, and return the dimensionless ratio of the measured vs.

rebin(bin_shape[, operation, ...])

Downsample array by combining contiguous pixels into bins.

recomb(line[, cat])

Search for recombination lines of H, He, and C in the frequency range of this Spectrum.

recomball([cat])

Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.

reproject_to(target_wcs[, algorithm, ...])

Reprojects the instance to the coordinates described by another WCS object.

roll([rollmax])

Rolling data to check for channel correllations and channel-to-channel correllations.

savefig(file, **kwargs)

Save the plot

set_convention(doppler_convention)

Set the velocity convention of this Spectrum.

set_frame(toframe)

Set the sky coordinate and doppler tracking reference frame of this Spectrum.

set_radial_velocity_to(radial_velocity)

This sets the radial velocity of the spectrum to be radial_velocity without changing the values of the spectral_axis.

set_redshift_to(redshift)

This sets the redshift of the spectrum to be redshift without changing the values of the spectral_axis.

shift(s[, remove_wrap, fill_value, method])

Shift the Spectrum by s channels in place.

shift_spectrum_to(*[, redshift, radial_velocity])

This shifts in-place the values of the spectral_axis, given either a redshift or radial velocity.

smooth(*args, **kwargs)

Smooth or convolve TCal, optionally decimating it.

snr([peak, flux, rms])

Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.

squeeze([axis])

Removes all axes with a length of 1.

sratio([mean])

Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.

stats([roll, qac])

Compute some statistics of this Spectrum.

subtract(operand[, operand2])

Performs subtraction by evaluating self - operand.

to(new_unit, **kwargs)

Convert instance to another unit.

undo_baseline()

Undo the most recently computed baseline.

velocity_axis_to([unit, toframe, ...])

Convert the spectral axis to unit in toframe using doppler_convention if converting from frequency/wavelength to velocity.

with_flux_unit(unit[, equivalencies, ...])

Returns a new spectrum with a different flux unit.

with_frame(toframe)

Return a copy of this Spectrum with a new coordinate reference frame.

with_spectral_axis_and_flux_units(...[, ...])

Perform with_spectral_axis_unit() and with_flux_unit() together.

with_spectral_axis_last()

Convenience method to return a new copy of the Spectrum with the spectral axis last.

with_spectral_axis_unit(unit[, ...])

Returns a new spectrum with a different spectral axis unit.

with_spectral_unit(unit[, ...])

with_velocity_convention(doppler_convention)

Returns a copy of this Spectrum with the input velocity convention.

list_to_spectral_region

max

mean

median

min

read

sum

write

classmethod from_spectrum(spectrum, name, snu, data=None)[source]#

Returns a TCal object given a Spectrum object.

Parameters:
spectrumSpectrum

Spectrum object. Its attributes will be copied into the TCal object, except for the data and flux attributes which can be defined by the data parameter.

namestr

Name of the calibrator used to derive the noise diode temperature.

snundarray

The flux values of the calibrator source.

dataNone or ndarray

Noise diode temperature values. If None, then it will use the flux attribute of spectrum. If set, the values will define the flux attribute of the TCal object.

Returns:
TCal

The TCal object.

get_tcal(frac=0.1, method=<function nanmean>, dtype=<class 'numpy.float32'>)[source]#

Reduce the temperature of the noise diode to a single value.

Parameters:
fracfloat

The fraction of the channels to discard on both ends of the spectrum. Default: 0.1

methodcallable

The function used to reduce the values. Default : numpy.nanmean

dtypestr or dtype

Typecode or data-type to which the output value, tcal is cast.

Returns:
tcalfloat

The noise diode temperature reduced using method over the channel range defined by frac.

property name#

Calibration source name.

property nchan#

The number of channels in the Spectrum

smooth(*args, **kwargs)[source]#

Smooth or convolve TCal, optionally decimating it.

Parameters:
methodstring

Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.

widthint

Effective width of the convolving kernel. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final frequency response. That is, the smoothed Spectrum will have an effective frequency resolution equal to CDELT1*`width`. The default is 1.

decimateint

Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution)

maskNone or numpy.ndarray

A “mask” array. Shape must match array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. If None, no masking will be performed unless array is a masked array. If mask is not None and array is a masked array, a pixel is masked if it is masked in either mask or array.mask.

boundarystr
A flag indicating how to handle boundaries:
  • None

    Set the result values to zero where the kernel extends beyond the edge of the array.

  • ‘fill’

    Set values outside the array boundary to fill_value (default).

  • ‘wrap’

    Periodic boundary that wrap to the other side of array.

  • ‘extend’

    Set values outside the array to the nearest array value.

fill_valuefloat

The value to use outside the array when using boundary='fill'. Default value is NaN.

nan_treatment{‘interpolate’, ‘fill’}
The method used to handle NaNs in the input array:
  • 'interpolate': NaN values are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.

  • 'fill': NaN values are replaced by fill_value prior to convolution.

preserve_nanbool

After performing convolution, should pixels that were originally NaN again become NaN?

Returns:
TCal

Smoothed noise diode temperature.

property snu#

Calibration source flux density.

VaneSpectrum#

VaneSpectrum

class dysh.spectra.vane.VaneSpectrum(vane, scan, fdnum, ifnum, plnum, tcal=None, twarm=None, zenith_opacity=None, tatm=None, tbkg=None, *args, **kwargs)[source]#

Bases: Spectrum

Vane calibration spectrum.

Parameters:
vanendarray

Vane power values. The values will define the data attribute of the VaneSpectrum object.

scanint

Scan number.

fdnumint

The feed number.

ifnumint

The intermediate frequency (IF) number.

plnumint

The polarization number.

tcalNone or float

The calibration temperature in K. If None, it will be estimated using get_tcal().

twarmNone or float

The vane temperature in K. If None, it will be inferred from the TWARM column.

zenith_opacityfloat or None

The zenith opacity in nepers. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tatmfloat or None

The atmospheric temperature towards the zenith in K. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tbkgfloat or None

The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).

Attributes:
array_axis_physical_types

Returns the WCS physical types that vary along each array axis.

baseline_model

Returns the computed baseline model or None if it has not yet been computed.

bin_edges
combined_wcs

The WCS transform for the NDCube, including the coordinates specified in .extra_coords.

comments

Get the comment strings.

data

ndarray - like

dimensions
doppler_convention

String representation of the velocity (Doppler) convention

energy

The energy of the spectral axis as a Quantity in units of eV.

equivalencies

Get the spectral axis equivalencies that can be used in converting the axis

exclude_regions

The baseline exclusion region(s) of this spectrum

extra_coords

Coordinates not described by NDCubeABC.wcs which vary along one or more axes.

fdnum

The feed number.

flux

Converts the stored data and unit and mask into a Quantity object.

frequency

The spectral_axis as a Quantity in units of GHz

global_coords

Coordinate metadata which applies to the whole cube.

history

Get the history strings.

ifnum

The intermediate frequency (IF) number.

mask

any type : Mask for the dataset, if any.

meta
nchan

The number of channels in the Spectrum

observer

Returns ——- observer : BaseCoordinateFrame or derivative The coordinate frame of the observer if present.

obstime
photon_flux

The flux density of photons as a Quantity, in units of

plnum

The polarization number.

plotter
psf

Image representation of the PSF for the dataset.

quantity

Unitful representation of the NDCube data.

radial_velocity

The radial velocity(s) of the objects represented by this spectrum.

redshift

The redshift(s) of the objects represented by this spectrum.

rest_value

Rest frequency used in velocity conversions.

scan

The scan number.

shape
spectral_axis

Returns the SpectralCoord object.

spectral_axis_direction
spectral_axis_index
spectral_wcs

Returns the spectral axes of the WCS

subtracted

Has a baseline model been subtracted?”

target

The target object of this spectrum.

tscale

The descriptive brightness unit of the data.

tscale_fac

The factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.

twarm

Vane temperature in K.

uncertainty

any type : Uncertainty in the dataset, if any.

unit

Unit : Unit for the dataset, if any.

velocity

Converts the spectral axis array to the given velocity space unit given the rest value.

velocity_convention

Returns the velocity convention

velocity_frame

String representation of the velocity frame

wavelength

The spectral_axis as a Quantity in units of Angstroms

wcs

any type : A world coordinate system (WCS) for the dataset, if any.

weights

The channel weights of this spectrum

Methods

add(operand[, operand2])

Performs addition by evaluating self + operand.

add_comment(comment[, add_time])

Add one or more comments to the class metadata.

add_history(history[, add_time])

Add one or more history entries to the class metadata

align_to(other[, units, frame, remove_wrap, ...])

Align the Spectrum with respect to other.

average(spectra[, weights, align])

Average this Spectrum with spectra.

axis_velocity([unit])

Get the spectral axis in velocity units.

axis_world_coords(*axes[, pixel_corners, wcs])

Returns objects representing the world coordinates of pixel centers for a desired axes.

axis_world_coords_values(*axes[, ...])

Returns the world coordinate values of all pixels for desired axes.

baseline(degree[, exclude, include, color])

Compute and optionally remove a baseline.

bshow()

Show the baseline model

cog([vc, width_frac, bchan, echan, ...])

Curve of growth (CoG) analysis based on Yu et al. (2020) [Re28fcf3e3187-1].

collapse(method[, axis])

Collapse the flux array given a method.

crop(*points[, wcs, keepdims])

Crop using real world coordinates.

crop_by_values(*points[, units, wcs, keepdims])

Crop using real world coordinates.

decimate(n)

Decimate the Spectrum by n pixels.

divide(operand[, operand2])

Performs division by evaluating self / operand.

explode_along_axis(axis)

Separates slices of NDCubes along a given axis into an NDCubeSequence of (N-1)DCubes.

fake_spectrum([nchan, seed, normal, use_wcs])

Create a fake spectrum with gaussian noise, useful for simple testing.

find_shift(other[, units, frame])

Find the shift required to align this Spectrum with other.

from_spectrum(spectrum, scan, fdnum, ifnum, ...)

Returns a VaneSpectrum object given a Spectrum object.

get_selected_regions([unit])

Get selected regions from plot.

get_tcal(ref[, mjd, freq, elev, ...])

Calibration temperature.

get_tsys(ref[, tcal])

Compute the system temperature.

get_velocity_in_frame(toframe)

Compute the radial velocity of the Spectrum.target in a new velocity frame.

make_spectrum(data, meta[, use_wcs, ...])

Factory method to create a Spectrum object from a data and header.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

meta_as_table()

Return Spectrum.meta as an Table.

multiply(operand[, operand2])

Performs multiplication by evaluating self * operand.

new_flux_unit(unit[, equivalencies, ...])

normalness()

Compute the p-value if the noise in a spectrum is gaussian using the Anderson-Darling statistic The p-value gives the probability that the spectrum is gaussian.

plot(**kwargs)

Plot the spectrum.

query_lines([chemical_name, ...])

Query locally or remotely for lines and return a table object.

radiometer([roll])

Check the radiometer equation, and return the dimensionless ratio of the measured vs.

rebin(bin_shape[, operation, ...])

Downsample array by combining contiguous pixels into bins.

recomb(line[, cat])

Search for recombination lines of H, He, and C in the frequency range of this Spectrum.

recomball([cat])

Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.

reproject_to(target_wcs[, algorithm, ...])

Reprojects the instance to the coordinates described by another WCS object.

roll([rollmax])

Rolling data to check for channel correllations and channel-to-channel correllations.

savefig(file, **kwargs)

Save the plot

set_convention(doppler_convention)

Set the velocity convention of this Spectrum.

set_frame(toframe)

Set the sky coordinate and doppler tracking reference frame of this Spectrum.

set_radial_velocity_to(radial_velocity)

This sets the radial velocity of the spectrum to be radial_velocity without changing the values of the spectral_axis.

set_redshift_to(redshift)

This sets the redshift of the spectrum to be redshift without changing the values of the spectral_axis.

shift(s[, remove_wrap, fill_value, method])

Shift the Spectrum by s channels in place.

shift_spectrum_to(*[, redshift, radial_velocity])

This shifts in-place the values of the spectral_axis, given either a redshift or radial velocity.

smooth([method, width, decimate, meta, ...])

Smooth or Convolve the Spectrum, optionally decimating it.

snr([peak, flux, rms])

Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.

squeeze([axis])

Removes all axes with a length of 1.

sratio([mean])

Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.

stats([roll, qac])

Compute some statistics of this Spectrum.

subtract(operand[, operand2])

Performs subtraction by evaluating self - operand.

to(new_unit, **kwargs)

Convert instance to another unit.

undo_baseline()

Undo the most recently computed baseline.

velocity_axis_to([unit, toframe, ...])

Convert the spectral axis to unit in toframe using doppler_convention if converting from frequency/wavelength to velocity.

with_flux_unit(unit[, equivalencies, ...])

Returns a new spectrum with a different flux unit.

with_frame(toframe)

Return a copy of this Spectrum with a new coordinate reference frame.

with_spectral_axis_and_flux_units(...[, ...])

Perform with_spectral_axis_unit() and with_flux_unit() together.

with_spectral_axis_last()

Convenience method to return a new copy of the Spectrum with the spectral axis last.

with_spectral_axis_unit(unit[, ...])

Returns a new spectrum with a different spectral axis unit.

with_spectral_unit(unit[, ...])

with_velocity_convention(doppler_convention)

Returns a copy of this Spectrum with the input velocity convention.

list_to_spectral_region

max

mean

median

min

read

sum

write

property fdnum#

The feed number.

classmethod from_spectrum(spectrum, scan, fdnum, ifnum, plnum, vane=None, tcal=None, twarm=None, zenith_opacity=None, tatm=None, tbkg=None)[source]#

Returns a VaneSpectrum object given a Spectrum object.

Parameters:
spectrumSpectrum

Spectrum object. Its attributes will be copied into the VaneSpectrum object, except for the data and flux attributes which can be defined by the vane parameter.

scanint

Scan number.

fdnumint

The feed number.

ifnumint

The intermediate frequency (IF) number.

plnumint

The polarization number.

vaneNone or ndarray

Vane power values. If None, then it will use the flux attribute of spectrum. If set, the values will define the data attribute of the VaneSpectrum object.

tcalNone or float

The calibration temperature in K. If None, it will be estimated using get_tcal().

twarmNone or float

The vane temperature in K. If None, it will be inferred from the TWARM column.

zenith_opacityfloat or None

The zenith opacity in nepers. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tatmfloat or None

The atmospheric temperature towards the zenith in K. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tbkgfloat or None

The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).

Returns:
VaneSpectrum

A VaneSpectrum object.

get_tcal(ref, mjd: float | None = None, freq: Quantity | None = None, elev: Quantity | None = None, zenith_opacity: float | None = None, tatm: float | None = None, twarm: float | None = None, tbkg: float = 2.725)[source]#

Calibration temperature.

Parameters:
refSpectrum

Reference spectrum used to derive \(T_{\mathrm{cal}}\).

mjdfloat or None

Modified Julian date. If None, will use DATE-OBS in ref.meta.

freqQuantity or None

Frequency at which to compute the calibration temperature. If None, will use OBSFREQ in ref.meta.

elevQuantity or None

Elevation at which to evaluate the airmass. If None, will use ELEVATIO in ref.meta.

twarmNone or float

The vane temperature in K. If None, it will be inferred from the TWARM column.

zenith_opacityfloat or None

The zenith opacity in nepers. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tatmfloat or None

The atmospheric temperature towards the zenith in K. If None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). If None and not at GBO, tcal will equal twarm (accurate to approximately 10%).

tbkgfloat or None

The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).

Returns:
tcalfloat

Calibration temperature for the vane in K.

get_tsys(ref, tcal=None)[source]#

Compute the system temperature.

Parameters:
refSpectrum

The reference spectrum.

tcalNone or float

The calibration temperature in K. If None, it will be estimated using get_tcal().

Returns:
tsysfloat

The system temperature in K.

property ifnum#

The intermediate frequency (IF) number.

property plnum#

The polarization number.

property scan#

The scan number.

property twarm#

Vane temperature in K.