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

Returns:
modelQuantityModel

Best fit model. See fit_continuum.

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.exclude_to_mask(exclude, refspec)[source]#
dysh.spectra.core.exclude_to_region_list(exclude, spectrum, fix_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).

fix_excludebool

See exclude_to_spectral_region for details. Default: True

Returns:
region_listlist of SpectralRegion

Regions defined in exclude as a list of SpectralRegion.

dysh.spectra.core.exclude_to_spectral_region(exclude, refspec, fix_exclude=True)[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).

fix_exclude: bool

If True, fix exclude regions that are out of bounds of the spectral axis to be within the spectral axis. Default: True

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.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, kernel=None, show=False)[source]#

Smooth or Convolve a 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, 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.

kernelnumpy array, 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.

showbool, optional

If set, the kernel is returned, instead of the convolved array. The default is False.

Returns:
sndarray

The new convolved spectrum.

Raises:
Exception

If no valid smoothing method is given.

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

Sort the elements of a SpectralRegion.

Parameters:
spectral_regionSpectralRegion

SpectralRegion to be sorted.

Returns:
sorted_spectral_regionSpectralRegion

Sorted SpectralRegion.

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_unit(spectral_region, refspec, unit=None)[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.

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: Spectrum1D, HistoricalBase

This class contains a spectrum and its attributes. It is built on Spectrum1D with added attributes like baseline model. Note that Spectrum1D 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 Spectrum1D 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 : The stored dataset.

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 information into a quantity.

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

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
shape
spectral_axis

Returns the SpectralCoord object.

spectral_axis_direction
spectral_axis_unit

Deprecated since version v1.1.

spectral_wcs

Returns the spectral axes of the WCS

target
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])

Compute and optionally remove a baseline.

bshow()

Show the baseline model

collapse(method[, axis])

Collapse the flux array given a method.

crop(*points[, wcs])

Crop using real world coordinates.

crop_by_values(*points[, units, wcs])

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

Create a fake spectrum, useful for simple testing.

find_shift(other[, units, frame])

Find the shift required to align this Spectrum with other.

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.

multiply(operand[, operand2])

Performs multiplication by evaluating self * operand.

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

Deprecated since version v1.13.

plot(**kwargs)

Visualize the NDCube.

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

Downsample array by combining contiguous pixels into bins.

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

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

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, kernel])

Smooth or Convolve the Spectrum, optionally decimating it.

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, ...])

Parameters:

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_unit(unit[, ...])

Returns a new spectrum with a different spectral axis unit.

with_spectral_unit(unit[, ...])

Deprecated since version v1.13.

with_velocity_convention(doppler_convention)

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

get_velocity_shift_to

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}

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='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: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

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, **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.

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

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#

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, **kwargs)[source]#

Create a fake spectrum, 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.

**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}

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.

get_velocity_shift_to(toframe)[source]#
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 Spectrum1D

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

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

Visualize the NDCube.

Parameters:
axes: `~astropy.visualization.wcsaxes.WCSAxes` or None:, optional

The axes to plot onto. If None the current axes will be used.

plot_axes: `list`, optional

A list of length equal to the number of pixel dimensions in array axis order. This list selects which cube axes are displayed on which plot axes. For an image plot this list should contain 'x' and 'y' for the plot axes and None for all the other elements. For a line plot it should only contain 'x' and None for all the other elements.

axes_unit: `list`, optional

A list of length equal to the number of world dimensions specifying the units of each axis, or None to use the default unit for that axis.

axes_coordinates: `list`, optional

A list of length equal to the number of pixel dimensions. For each axis the value of the list should either be a string giving the world axis type or None to use the default axis from the WCS.

data_unit: `astropy.units.Unit`

The data is changed to the unit given or the NDCube.unit if not given.

wcs: `astropy.wcs.wcsapi.BaseHighLevelWCS`

The WCS object to define the coordinates of the plot axes.

kwargs

Additional keyword arguments are given to the underlying plotting infrastructure which depends on the dimensionality of the data and whether 1 or 2 plot_axes are defined: - Animations: mpl_animators.ArrayAnimatorWCS - Static 2-D images: matplotlib.pyplot.imshow - Static 1-D line plots: matplotlib.pyplot.plot

property plotter#
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 with_velocity_convention.

Parameters:
doppler_convention - str

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:
toframe - str, or ~astropy.coordinates.BaseCoordinateFrame, or ~astropy.coordinates.SkyCoord

The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, etc., or an actual coordinate system 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, kernel=None)[source]#

Smooth or Convolve the Spectrum, optionally decimating it.

Default smoothing is hanning.

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 frequency response. That is, the smoothed Spectrum will have an effective frequency resolution equal to CDELT1*`width`. 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.

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.

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. 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 target#
undo_baseline()[source]#

Undo the most recently computed baseline. If the baseline has been subtracted, it will be added back. 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]#
Parameters:
unitQuantity or str that can be converted to Quantity

The unit to which the axis is to be converted

toframestr

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

doppler_conventionstr

The Doppler velocity covention to use, one of ‘optical’, ‘radio’, or ‘rest’

Returns:
test_spectrum.pyvelocityQuantity

The converted spectral axis velocity

property velocity_frame#

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:
toframe - str, `~astropy.coordinates.BaseCoordinateFrame`, or `~astropy.coordinates.SkyCoord`

The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, etc., or an actual coordinate system 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_convention - str

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)[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: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

alignbool

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

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_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, bintable, calibrate=True, fold=True, shift_method='fft', use_sig=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, debug=False)[source]#

Bases: ScanBase

GBT specific version of Frequency Switch Scan

Parameters:
gbtfitsSDFITSLoad

input SDFITSLoad 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.

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

Attributes:
comments

Get the comment strings.

delta_freq

Get the array of channel frequency width

exposure

The array of exposure (integration) times for FSscan

fdnum

The feed number

folded

Has the FSscan been folded?

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

tsys

The system temperature array.

tsys_weight

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

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, following equations .

calibrated(i)

Return the calibrated Spectrum of this FSscan

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this set of FSscans.

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

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

calibrate(**kwargs)[source]#

Frequency switch calibration, following equations … fold=True or fold=False is required

calibrated(i)[source]#

Return the calibrated Spectrum of this FSscan

Parameters:
iint

The index into the calibrated array

Returns:
spectrumSpectrum
property delta_freq#

Get the array of channel frequency width

df = [ 0.5*(df_ref_on + df_ref_off) + 0.5*(df_sig_on + df_sig_off) ] / 2

Returns:
delta_freq: ~numpy.ndarray

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

property exposure#

The array of exposure (integration) times for FSscan

exposure = [ 0.5*(exp_ref_on + exp_ref_off) + 0.5*(exp_sig_on + exp_sig_off) ] / 2

Returns:
exposure~numpy.ndarray

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

property folded#

Has the FSscan been folded?

Returns:
boolean

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

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for this set of FSscans.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
spectrumSpectrum

The time-averaged spectrum

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

class dysh.spectra.scan.NodScan(gbtfits, scan, beam1, scanrows, calrows, bintable, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>)[source]#

Bases: ScanBase

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

Parameters:
gbtfitsSDFITSLoad

input SDFITSLoad 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.

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, 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.

Attributes:
comments

Get the comment strings.

delta_freq

Get the array of channel frequency width

exposure

The array of exposure (integration) times

fdnum

The feed number

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

tsys

The system temperature array.

tsys_weight

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

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

calibrated(i)

Return the calibrated Spectrum.

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this set of scans.

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

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

calibrate(**kwargs)[source]#

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

calibrated(i)[source]#

Return the calibrated Spectrum.

Parameters:
iint

The index into the calibrated array

Returns:
spectrumSpectrum
property delta_freq#

Get the array of channel frequency width

df = [ 0.5*(df_ref_on + df_ref_off) + 0.5*(df_sig_on + df_sig_off) ] / 2

Returns:
delta_freq: ~numpy.ndarray

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

property exposure#

The array of exposure (integration) times

exposure = [ 0.5*(exp_ref_on + exp_ref_off) + 0.5*(exp_sig_on + exp_sig_off) ] / 2

Returns:
exposure~numpy.ndarray

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

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for this set of scans.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
spectrumSpectrum

The time-averaged spectrum

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

class dysh.spectra.scan.PSScan(gbtfits, scans, scanrows, calrows, bintable, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>)[source]#

Bases: ScanBase

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

Parameters:
gbtfitsSDFITSLoad

input SDFITSLoad object

scansdict

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.

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

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.

Attributes:
comments

Get the comment strings.

delta_freq

Get the array of channel frequency width

exposure

The array of exposure (integration) times

fdnum

The feed number

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

tsys

The system temperature array.

tsys_weight

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

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

calibrated(i)

Return the calibrated Spectrum.

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this set of scans.

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

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

calibrate(**kwargs)[source]#

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

calibrated(i)[source]#

Return the calibrated Spectrum.

Parameters:
iint

The index into the calibrated array

Returns:
spectrumSpectrum
property delta_freq#

Get the array of channel frequency width

df = [ 0.5*(df_ref_on + df_ref_off) + 0.5*(df_sig_on + df_sig_off) ] / 2

Returns:
delta_freq: ~numpy.ndarray

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

property exposure#

The array of exposure (integration) times

exposure = [ 0.5*(exp_ref_on + exp_ref_off) + 0.5*(exp_sig_on + exp_sig_off) ] / 2

Returns:
exposure~numpy.ndarray

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

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for this set of scans.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns:
spectrumSpectrum

The time-averaged spectrum

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)

class dysh.spectra.scan.ScanBase(sdfits)[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 or more polarizations. Derived classes must implement calibrate().

Attributes:
comments

Get the comment strings.

delta_freq

The array of channel frequency width

exposure

The array of exposure (integration) times.

fdnum

The feed number

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

tsys

The system temperature array.

tsys_weight

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

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

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this scan.

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

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

calibrate(**kwargs)[source]#

Calibrate the Scan data

property fdnum#

The feed number

Returns:
int

The index of the Feed

property ifnum#

The IF number

Returns:
int

The index of the Intermediate Frequency

property is_calibrated#

Have the data been calibrated?

Returns:
bool

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

make_bintable()[source]#

Create a BinaryTableHDU from the calibrated data of this Scan.

Returns:
bBinaryTableHDU

A FITS binary table HDU, suitable for writing out or appending to a HDUList.

property meta#

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#

The number of channels in this scan

Returns:
int

The number of channels in this scan

property npol#

The number of polarizations in this Scan

Returns:
int

The number of polarizations in this Scan

property nrows#

The number of rows in this Scan

Returns:
int

The number of rows in this Scan

property pols#

The polarization number(s)

Returns:
list

The list of integer polarization number(s)

property scan#

The scan number

Returns:
int

The scan number of the integrations in the Scan object

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

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

Parameters:
fileobjstr, file-like or pathlib.Path

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

multifile: bool, optional

If True, write to multiple files if and only if there are multiple SDFITS files in this GBTFITSLoad. Otherwise, write to a single SDFITS file.

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.ScanBlock(*args)[source]#

Bases: UserList, HistoricalBase, SpectralAverageMixin

Attributes:
comments

Get the comment strings.

delta_freq

The array of channel frequency width

exposure

The array of exposure (integration) times.

history

Get the history strings.

tsys

The system temperature array.

tsys_weight

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

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

finalspectrum([weights])

Average all times and polarizations in all scans this ScanBlock

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.

polaverage([weights])

Average all polarizations in all scans in this ScanBlock

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

timeaverage([weights])

Compute the time-averaged spectrum for all scans in this ScanBlock.

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

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

copy

sort

calibrate(**kwargs)[source]#

Calibrate all scans in this ScanBlock

finalspectrum(weights='tsys')[source]#

Average all times and polarizations in all scans this ScanBlock

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
finalspectra: list of `~spectra.spectrum.Spectrum`

List of all the time- and polarization-averaged spectra

polaverage(weights='tsys')[source]#

Average all polarizations in all scans in this ScanBlock

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
polaverage: list of `~spectra.spectrum.Spectrum`

List of all the polarization-averaged spectra

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for all scans in this ScanBlock.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns:
timeaverage: list of Spectrum

List of all the time-averaged spectra

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)

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

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

Parameters:
fileobjstr, file-like or pathlib.Path

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

multifile: bool, optional

If True, write to multiple files if and only if there are multiple SDFITS files in this GBTFITSLoad. Otherwise, write to a single SDFITS file.

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

exposure

The array of exposure (integration) times.

tsys

The system temperature array.

tsys_weight

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

Methods

finalspectrum([weights])

Average all times and polarizations in this Scan

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this scan.

property delta_freq#

The array of channel frequency width

property exposure#

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

Returns:
exposure~numpy.ndarray

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

finalspectrum(weights=None)[source]#

Average all times and polarizations in this Scan

polaverage(weights=None)[source]#

Average all polarizations in this Scan

timeaverage(weights=None)[source]#

Compute the time-averaged spectrum for this scan.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
spectrumSpectrum

The time-averaged spectrum

.. 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#

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

class dysh.spectra.scan.SubBeamNodScan(sigtp, reftp, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, **kwargs)[source]#

Bases: ScanBase

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

Signal total power scans

reftp: list ~spectra.scan.TPScan

Reference total power scans

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.
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’

Attributes:
comments

Get the comment strings.

delta_freq

The array of channel frequency width

exposure

The array of exposure (integration) times.

fdnum

The feed number

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

tsys

The system temperature array.

tsys_weight

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

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

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this scan.

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

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

calibrated

calibrate(**kwargs)[source]#

Calibrate the SubBeamNodScan data

calibrated(i)[source]#
property delta_freq#

The array of channel frequency width

property exposure#

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

Returns:
exposure~numpy.ndarray

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

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for this scan.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
spectrumSpectrum

The time-averaged spectrum

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

class dysh.spectra.scan.TPScan(gbtfits, scan, sigstate, calstate, scanrows, calrows, bintable, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>)[source]#

Bases: ScanBase

GBT specific version of Total Power Scan

Parameters:
gbtfitsSDFITSLoad

input SDFITSLoad 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

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.

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:
calstate

The requested calibration state

comments

Get the comment strings.

delta_freq

Get the array of channel frequency width.

exposure

The array of exposure (integration) times.

fdnum

The feed number

history

Get the history strings.

ifnum

The IF number

is_calibrated

Have the data been calibrated?

meta

The metadata of this Scan.

nchan

The number of channels in this scan

npol

The number of polarizations in this Scan

nrows

The number of rows in this Scan

pols

The polarization number(s)

scan

The scan number

sigstate

The requested signal state

tsys

The system temperature array.

tsys_weight

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

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

calc_tsys(**kwargs)

Calculate the system temperature array, according to table above.

calibrate()

Calibrate the data according to the CAL/SIG table above

finalspectrum([weights])

Average all times and polarizations in this Scan

make_bintable()

Create a BinaryTableHDU from the calibrated data of this Scan.

merge_commentary(other)

Merge the history and comments from another HistoricalBase instance.

polaverage([weights])

Average all polarizations in this Scan

timeaverage([weights])

Compute the time-averaged spectrum for this set of scans.

total_power(i)

Return the total power spectrum

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

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

tpmeta

calc_tsys(**kwargs)[source]#

Calculate the system temperature array, according to table above.

calibrate()[source]#

Calibrate the 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 delta_freq#

Get the array of channel frequency width. The value depends on the cal state:

CAL

\(\Delta\nu\)

None

\(0.5 * ( \Delta\nu_{REFON}+ \Delta\nu_{REFOFF} )\)

True

\(\Delta\nu_{REFON}\)

False

\(\Delta\nu_{REFOFF}\)

Returns:
delta_freq: ndarray

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

property exposure#

The array of exposure (integration) times. The value depends on the cal state:

CAL

EXPOSURE

None

\(t_{EXP,REFON} + t_{EXP,REFOFF}\)

True

\(t_{EXP,REFON}\)

False

\(t_{EXP,REFOFF}\)

Returns:
exposurendarray

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

property sigstate#

The requested signal state

Returns:
bool

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

timeaverage(weights='tsys')[source]#

Compute the time-averaged spectrum for this set of scans.

Parameters:
weights: str

‘tsys’ or None. If ‘tsys’ the weight will be calculated as:

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

Default: ‘tsys’

Returns
——-
spectrumSpectrum

The time-averaged spectrum

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

total_power(i)[source]#

Return the total power spectrum

Parameters:
iint

The index into the data array

Returns:
spectrumSpectrum
tpmeta(i)[source]#