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:
- data
ndarray 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)
- weights
ndarray 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
- data
- Returns:
- average
ndarray The average along the input axis
- average
- dysh.spectra.core.baseline(spectrum, order, exclude=None, exclude_region_upper_bounds=True, **kwargs)[source]#
Fit a baseline to
spectrum. The code usesFitterandpolynomialto compute the baseline. See the documentation for those modules for details.- Parameters:
- spectrum
Spectrum The input spectrum.
- orderint
The order of the polynomial series, a.k.a. baseline order.
- excludelist of 2-tuples of int or
Quantity, orSpectralRegion 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
Quantityregion:>>> [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’
- fitter
Fitter The fitter to use. Default:
LinearLSQFitter(withcalc_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.
- spectrum
- Returns:
- model
QuantityModel Best fit model. See
fit_continuum.
- model
- dysh.spectra.core.data_fshift(y, fshift, method='fft', pad=False, window=True)[source]#
Shift
ybyfshiftchannels, whereabs(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
ybyishiftchannels, whereishiftis 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
ybyschannels.- 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_region_list(exclude, spectrum, fix_exclude=True)[source]#
Convert an exclusion region,
exclude, to a list ofSpectralRegion. This is used for baseline fitting.- Parameters:
- excludelist of 2-tuples of int or
Quantity, orSpectralRegion 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
Quantityregion:>>> [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)]).
- spectrum
Spectrum The reference spectrum whose spectral axis will be used when converting between
excludeand axis units (e.g. channels to GHz).- fix_excludebool
See
exclude_to_spectral_regionfor details. Default: True
- excludelist of 2-tuples of int or
- Returns:
- region_listlist of
SpectralRegion Regions defined in
excludeas a list ofSpectralRegion.
- region_listlist of
- dysh.spectra.core.exclude_to_spectral_region(exclude, refspec, fix_exclude=True)[source]#
Convert
excludeto aSpectralRegion.- Parameters:
- excludelist of 2-tuples of int or
Quantity, orSpectralRegion 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
Quantityregion:>>> [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
excludeand 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
- excludelist of 2-tuples of int or
- Returns:
- sr
SpectralRegion A
SpectralRegioncorresponding toexclude.
- sr
- dysh.spectra.core.fft_shift(y, shift, pad=True, window=True, nan_treatment='fill', fill_value=0, keep_nan=True)[source]#
Shift a signal
ybyshiftamount 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_valuebefore the FFT.- fill_valuefloat
Value used to replace NaN values. Used if
nan_treatment=='fill'.- keep_nanbool
If
Truethe output will keep the NaN values. IfFalseNaN values will be filled.
- y1D
- Returns:
- new_y1D
ndarray Phase shifted version of the original signal
y.
- new_y1D
- dysh.spectra.core.find_non_blanks(data)[source]#
Finds the indices of integrations that are not blanked.
- dysh.spectra.core.find_nonblank_ints(cycle1, cycle2, cycle3=None, cycle4=None)[source]#
Find the indices of integrations that are not blanked.
- Parameters:
- cycle1
ndarray Data for cycle 1. For example, signal with the noise diode off.
- cycle2
ndarray Data for cycle 2. For example, reference with the noise diode off.
- cycle3
ndarray Data for cycle 3. For example, signal with the noise diode on. Default is
None.- cycle4
ndarray Data for cycle 4. For example, reference with the noise diode on. Default is
None.
- cycle1
- Returns:
- goodrows
array Indices of the non-blanked rows.
- goodrows
- 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, orSpectralRegion 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
Quantityregion:>>> [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
includeand axis units (e.g. channels to GHz).
- includelist of 2-tuples of int or
- Returns:
- exclude_region
SpectralRegion includeas a region to be excluded.
- exclude_region
- dysh.spectra.core.integration_isnan(data)[source]#
Helper function to calculate a boolean array that indicates whether a collection of integrations 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:
- calon
ndarray-like ON calibration
- caloff
ndarray-like OFF calibration
- tcal
ndarray-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
- calon
- Returns:
- meanTsys
ndarray-like The mean system temperature
- meanTsys
- dysh.spectra.core.region_to_axis_indices(region, refspec)[source]#
- Parameters:
- region
SpectralRegion - 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).
- region
- Returns:
- indices2-tuple of int
The array indices in
refspeccorresponding toregion.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:
- data
ndarray 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.
- data
- Returns:
- s
ndarray The new convolved spectrum.
- s
- 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_region
SpectralRegion SpectralRegionto be sorted.
- spectral_region
- Returns:
- sorted_spectral_region
SpectralRegion Sorted
SpectralRegion.
- sorted_spectral_region
- dysh.spectra.core.spectral_region_to_list(spectral_region)[source]#
Turn
spectral_regioninto a list ofSpectralRegion. Each subregion inspectral_regionwill be a list element.- Parameters:
- spectral_region
SpectralRegion SpectralRegionto convert into a list ofSpectralRegion.
- spectral_region
- Returns:
- region_listlist of
SpectralRegion Subregions of
spectral_regionin a list ofSpectralRegion.
- region_listlist of
- dysh.spectra.core.spectral_region_to_unit(spectral_region, refspec, unit=None)[source]#
Change the unit of
spectral_regiontounitusing the equivalencies ofrefspec. If nounitis provided, it will change to the units ofrefspec._spectral_axis.- Parameters:
- spectral_region
SpectralRegion SpectralRegionwhose units will be converted.- refspec
Spectrum 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.
- spectral_region
- Returns:
- spectral_region
SpectralRegion SpectralRegion with units of
unit.
- spectral_region
- 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:
- Returns:
- average
ndarray The square root of the squared average of a along the input axis.
- average
- 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, ortsysparameters are given asQuantity, 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 beQuantityobjects, e.g.,>>> [3, 4]*u.s ### RIGHT!
Spectrum#
The Spectrum class to contain and manipulate spectra.
- class dysh.spectra.spectrum.Spectrum(*args, **kwargs)[source]#
Bases:
Spectrum1D,HistoricalBaseThis class contains a spectrum and its attributes. It is built on
Spectrum1Dwith added attributes like baseline model. Note thatSpectrum1Dcan 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. SeeSpectrum1Dfor the instantiation arguments.- Attributes:
array_axis_physical_typesReturns the WCS physical types that vary along each array axis.
baseline_modelReturns the computed baseline model or None if it has not yet been computed.
- bin_edges
combined_wcsThe WCS transform for the NDCube, including the coordinates specified in
.extra_coords.commentsGet the comment strings.
datandarray-like : The stored dataset.- dimensions
doppler_conventionString representation of the velocity (Doppler) convention
energyThe energy of the spectral axis as a
Quantityin units of eV.equivalenciesGet the spectral axis equivalencies that can be used in converting the axis
exclude_regionsThe baseline exclusion region(s) of this spectrum
extra_coordsCoordinates not described by
NDCubeABC.wcswhich vary along one or more axes.fluxConverts the stored data and unit information into a quantity.
frequencyThe
spectral_axisas aQuantityin units of GHzglobal_coordsCoordinate metadata which applies to the whole cube.
historyGet the history strings.
maskany type : Mask for the dataset, if any.
- meta
observerReturns ——- observer :
BaseCoordinateFrameor derivative The coordinate frame of the observer if present.- obstime
photon_fluxThe flux density of photons as a
Quantity, in units of- plotter
psfImage representation of the PSF for the dataset.
radial_velocityThe radial velocity(s) of the objects represented by this spectrum.
redshiftThe redshift(s) of the objects represented by this spectrum.
- rest_value
- shape
spectral_axisReturns the SpectralCoord object.
- spectral_axis_direction
spectral_axis_unitDeprecated since version v1.1.
spectral_wcsReturns the spectral axes of the WCS
- target
uncertaintyany type : Uncertainty in the dataset, if any.
unitUnit: Unit for the dataset, if any.velocityConverts the spectral axis array to the given velocity space unit given the rest value.
velocity_conventionReturns the velocity convention
velocity_frameString representation of the velocity frame
wavelengthThe
spectral_axisas aQuantityin units of Angstromswcsany type : A world coordinate system (WCS) for the dataset, if any.
weightsThe 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
Spectrumwith respect toother.average(spectra[, weights, align])Average this
Spectrumwithspectra.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
Spectrumby 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
Spectrumwithother.make_spectrum(data, meta[, use_wcs, ...])Factory method to create a
Spectrumobject 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_velocitywithout changing the values of thespectral_axis.set_redshift_to(redshift)This sets the redshift of the spectrum to be
redshiftwithout changing the values of thespectral_axis.shift(s[, remove_wrap, fill_value, method])Shift the
Spectrumbyschannels 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 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
Spectrumwith 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
Spectrumwith 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
Spectrumwith respect toother.- Parameters:
- other
Spectrum Target
Spectrumto align to.- units{None,
astropy.units.Quantity} Find the shift to align the two
Spectrain these units. IfNone, theSpectrawill be aligned using the units ofother.- frame{None, str}
Find the shift in this reference frame. If
Nonewill use the frame ofother.- remove_wrapbool
If
Trueallow spectrum to wrap around the edges. IfFalsefill channels that wrap withfill_value.- fill_valuefloat
If
wrap=Falsefill channels that wrapped with this value.- method“fft”
Method used to perform the fractional channel shift. “fft” uses a phase shift.
- other
- average(spectra, weights='tsys', align=False)[source]#
Average this
Spectrumwithspectra. The resultingaveragewill 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
Truealign thespectrato itself. This usesSpectrum.align_to.
- spectralist of
- Returns:
- average
Spectrum Averaged spectra.
- average
- 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.
- baseline(degree, exclude=None, include=None, **kwargs)[source]#
Compute and optionally remove a baseline. The code uses
Fitterandpolynomialto compute the baseline. See the documentation for those modules for details. This method will set thebaseline_modelattribute to the fitted model function which can be evaluated over a domain.Note that
includeandexcludeare mutually exclusive. If both are present, onlyincludewill be used.- Parameters:
- degreeint
The degree of the polynomial series, a.k.a. baseline order
- excludelist of 2-tuples of int or
Quantity, orSpectralRegion 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
Quantityregion: [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, orSpectralRegion List of region(s) to include in the fit. The tuple(s) represent a range in the form [lower,upper], inclusive. See
excludefor examples.- modelstr
One of ‘polynomial’, ‘chebyshev’, ‘legendre’, or ‘hermite’ Default: ‘chebyshev’
- fitter
Fitter The fitter to use. Default:
LinearLSQFitter(withcalc_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.
- 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 toSeedSequenceto derive the initialBitGeneratorstate. One may also pass in aSeedSequenceinstance. Additionally, when passed aBitGenerator, it will be wrapped byGenerator. If passed aGenerator, it will be returned unaltered. The default isNone.- **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:
- spectrum
Spectrum The spectrum object
- spectrum
- find_shift(other, units=None, frame=None)[source]#
Find the shift required to align this
Spectrumwithother.- Parameters:
- other
Spectrum Target
Spectrumto align to.- units{None,
astropy.units.Quantity} Find the shift to align the two
Spectrain these units. IfNone, theSpectrawill be aligned using the units ofother.- frame{None, str}
Find the shift in this reference frame. If
Nonewill use the frame ofother.
- other
- Returns:
- shiftfloat
Number of channels that this
Spectrummust be shifted to be aligned withother.
- classmethod make_spectrum(data, meta, use_wcs=True, observer_location=None, observer=None)[source]#
Factory method to create a
Spectrumobject from a data and header. The the data are masked, theSpectrummask will be set to the data mask.- Parameters:
- data
ndarray The data array. See
Spectrum1D- metadict
The metadata, typically derived from an SDFITS header. Required items in
metaare ‘CTYPE[123]’,’CRVAL[123]’, ‘CUNIT[123]’, ‘VELOCITY’, ‘EQUINOX’, ‘RADESYS’- use_wcsbool
If True, create a WCS object from
metaDefault: True- observer_location
EarthLocationor str Location of the observatory. See
Observatory. This will be transformed toITRSusing the time of observation DATE-OBS or MJD-OBS inmeta. 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.- observer
BaseCoordinateFrame Coordinate frame for the observer. Will be ignored if DATE-OBS or MJD-OBS are present in
metaandobserver_locationis notNone.
- data
- Returns:
- spectrum
Spectrum The spectrum object
- spectrum
- property observer#
- Returns:
- observer
BaseCoordinateFrameor derivative - The coordinate frame of the observer if present.
- observer
- 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 andNonefor all the other elements. For a line plot it should only contain'x'andNonefor 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
Noneto 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
Noneto use the default axis from the WCS.- data_unit: `astropy.units.Unit`
The data is changed to the unit given or the
NDCube.unitif 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#
- set_convention(doppler_convention)[source]#
Set the velocity convention of this
Spectrum. The spectral axis of thisSpectrumwill 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
Spectrumwith a new velocity convention instead, usewith_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
Spectrumbyschannels in place.- Parameters:
- sfloat
Number of channels to shift the
Spectrumby.- remove_wrapbool
If
Falsekeep channels that wrap around the edges. IfTruefill channels that wrap withfill_value.- fill_valuefloat
If
remove_wrap=Truefill 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
Spectrumwill 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- kernel
ndarray, 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:
- Raises:
- Exception
If no valid smoothing method is given.
- ValueError
If
widthis less than one. Ifwidthis less than the spectral resolution (in channels). Ifdecimateis 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_modelattribute is set to None. Exclude regions are untouched.
- velocity_axis_to(unit=Unit('km / s'), toframe=None, doppler_convention=None)[source]#
- Parameters:
- unit
Quantityor 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’
- unit
- Returns:
- test_spectrum.pyvelocity
Quantity The converted spectral axis velocity
- test_spectrum.pyvelocity
- 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
Spectrumwith 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:
- with_velocity_convention(doppler_convention)[source]#
Returns a copy of this
Spectrumwith 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:
- spectrum
Spectrum A new
Spectrumobject withdoppler_conventionas its Doppler convention.
- spectrum
- dysh.spectra.spectrum.average_spectra(spectra, weights='tsys', align=False)[source]#
Average
spectra. The resultingaveragewill 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
Truealign thespectrato the first element. This usesSpectrum.align_to.
- spectralist of
- Returns:
- average
Spectrum Averaged spectra.
- average
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:
ScanBaseGBT specific version of Frequency Switch Scan
- Parameters:
- gbtfits
SDFITSLoad 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
sdfitscorresponding to sig=T (ON) and sig=F (OFF) integrations.- calrowsdict
Dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in
sdfitscorresponding to cal=T (ON) and cal=F (OFF) integrations.- bintableint
The index for BINTABLE in
sdfitscontaining 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_location
EarthLocation Location of the observatory. See
Observatory. This will be transformed toITRSusing the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.
- gbtfits
- Attributes:
commentsGet the comment strings.
delta_freqGet the array of channel frequency width
exposureThe array of exposure (integration) times for FSscan
fdnumThe feed number
foldedHas the FSscan been folded?
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
tsysThe system temperature array.
tsys_weightThe 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
BinaryTableHDUfrom 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:
- spectrum
Spectrum
- spectrum
- 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
- ——-
- spectrum
Spectrum 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:
ScanBaseGBT specific version of Nodding Scan. A nod scan object has one IF, two feeds, and one or more polarizations.
- Parameters:
- gbtfits
SDFITSLoad 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
sdfitscorresponding to ON (signal) and OFF (reference) integrations- calrowsdict
dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in
sdfitscorresponding to cal=T (ON) and cal=F (OFF) integrations.- bintableint
the index for BINTABLE in
sdfitscontaining 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_location
EarthLocation Location of the observatory. See
Observatory. This will be transformed toITRSusing the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.
- gbtfits
- Attributes:
commentsGet the comment strings.
delta_freqGet the array of channel frequency width
exposureThe array of exposure (integration) times
fdnumThe feed number
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
tsysThe system temperature array.
tsys_weightThe 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
BinaryTableHDUfrom 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:
- spectrum
Spectrum
- spectrum
- 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
- ——-
- spectrum
Spectrum 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:
ScanBaseGBT specific version of Position Switch Scan. A position switch scan object has one IF, one feed, and one or more polarizations.
- Parameters:
- gbtfits
SDFITSLoad 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
sdfitscorresponding to ON (signal) and OFF (reference) integrations- calrowsdict
dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in
sdfitscorresponding to cal=T (ON) and cal=F (OFF) integrations.- bintableint
the index for BINTABLE in
sdfitscontaining 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_location
EarthLocation Location of the observatory. See
Observatory. This will be transformed toITRSusing the time of observation DATE-OBS or MJD-OBS in the SDFITS header. The default is the location of the GBT.
- gbtfits
- Attributes:
commentsGet the comment strings.
delta_freqGet the array of channel frequency width
exposureThe array of exposure (integration) times
fdnumThe feed number
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
tsysThe system temperature array.
tsys_weightThe 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
BinaryTableHDUfrom 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:
- spectrum
Spectrum
- spectrum
- 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:
- spectrum
Spectrum 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)- spectrum
- class dysh.spectra.scan.ScanBase(sdfits)[source]#
Bases:
HistoricalBase,SpectralAverageMixinThis 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:
commentsGet the comment strings.
delta_freqThe array of channel frequency width
exposureThe array of exposure (integration) times.
fdnumThe feed number
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
tsysThe system temperature array.
tsys_weightThe 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
Create a
BinaryTableHDUfrom 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
- 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
BinaryTableHDUfrom the calibrated data of this Scan.- Returns:
- b
BinaryTableHDU A FITS binary table HDU, suitable for writing out or appending to a
HDUList.
- b
- 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 anOSErrorifFalseand the output file exists. Default isFalse.- checksumbool
When
Trueadds bothDATASUMandCHECKSUMcards to the headers of all HDU’s written to the file.
- fileobjstr, file-like or
- Returns:
- None.
- class dysh.spectra.scan.ScanBlock(*args)[source]#
Bases:
UserList,HistoricalBase,SpectralAverageMixin- Attributes:
commentsGet the comment strings.
delta_freqThe array of channel frequency width
exposureThe array of exposure (integration) times.
historyGet the history strings.
tsysThe system temperature array.
tsys_weightThe 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
- 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)- timeaverage: list of
- 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 anOSErrorifFalseand the output file exists. Default isFalse.- checksumbool
When
Trueadds bothDATASUMandCHECKSUMcards to the headers of all HDU’s written to the file.
- fileobjstr, file-like or
- Returns:
- None.
- class dysh.spectra.scan.SpectralAverageMixin[source]#
Bases:
object- Attributes:
delta_freqThe array of channel frequency width
exposureThe array of exposure (integration) times.
tsysThe system temperature array.
tsys_weightThe 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
- 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
- ——-
- spectrum
Spectrum 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_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_location
EarthLocation Location of the observatory. See
Observatory. This will be transformed toITRSusing 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:
commentsGet the comment strings.
delta_freqThe array of channel frequency width
exposureThe array of exposure (integration) times.
fdnumThe feed number
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
tsysThe system temperature array.
tsys_weightThe 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
BinaryTableHDUfrom 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
- 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
- ——-
- spectrum
Spectrum 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:
ScanBaseGBT specific version of Total Power Scan
- Parameters:
- gbtfits
SDFITSLoad 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
sdfitscorresponding to sigstate integrations- calrowsdict
dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in
sdfitscorresponding to cal=T (ON) and cal=F (OFF) integrations forscan- bintableint
the index for BINTABLE in
sdfitscontaining 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.
- gbtfits
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 withcal=TandREFCALOFF= integrations withcal=F.- Attributes:
calstateThe requested calibration state
commentsGet the comment strings.
delta_freqGet the array of channel frequency width.
exposureThe array of exposure (integration) times.
fdnumThe feed number
historyGet the history strings.
ifnumThe IF number
is_calibratedHave the data been calibrated?
metaThe metadata of this Scan.
nchanThe number of channels in this scan
npolThe number of polarizations in this Scan
nrowsThe number of rows in this Scan
polsThe polarization number(s)
scanThe scan number
sigstateThe requested signal state
tsysThe system temperature array.
tsys_weightThe 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 the data according to the CAL/SIG table above
finalspectrum([weights])Average all times and polarizations in this Scan
make_bintable()Create a
BinaryTableHDUfrom 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
- 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
- delta_freq:
- 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:
- exposure
ndarray The exposure time in units of the EXPOSURE keyword in the SDFITS header
- exposure
- 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
- ——-
- spectrum
Spectrum 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)