Spectral classes and functions#
Classes and functions for managing and processing spectra
Core Functions#
Core functions for spectral data.
- dysh.spectra.core.append_doppler_to_spectral_region_qtable(qtable, refspec)[source]#
Set the
doppler_conventionanddoppler_restattributes to the columns ofqtable.- Parameters:
- qtable
QTable Table with
SpectralAxisas columns.- refspec
Spectrum The reference spectrum whose spectral axis will be used to set the attributes.
- qtable
- dysh.spectra.core.available_smooth_methods()[source]#
The list of smooth methods that dysh understands. These can be passed to various smooth routines via their
methodkeywords.- Returns:
- methods: list
The method names allowable to
smooth
- dysh.spectra.core.average(data, axis=0, weights=None)[source]#
Average a group of spectra or scans.
- Parameters:
- 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.
- clip_excludebool
Whether to clip the exclude or include regions when they extend outside the
spectrum.spectral_axis.
- spectrum
- Returns:
- model
QuantityModel Best fit model. See
fit_continuum.
- model
- dysh.spectra.core.clip_spectral_region_subregions(spectral_region, spectrum)[source]#
Clip the values of the
spectral_region.subregionsif they extend outside thespectrum.spectral_axis.
- dysh.spectra.core.cog_flux(c, flat_tol=0.1)[source]#
Find the flux from the curve of growth.
- Parameters:
- carray
Curve of growth values.
- flat_tolfloat
Tolerance to define the flat portion of the curve of growth. The flat portion is that which is zero within
flat_toltimes the rms of the slope.
- Returns:
- fluxfloat
The median of the curve of growth over its flat portion.
- flux_stdfloat
The standard deviation of the curve of growth over the flat portion.
- slopearray
The median value of the slope for the curve of growth before it becomes flat.
- dysh.spectra.core.cog_slope(c, flat_tol=0.1)[source]#
Find slope for curve of growth analysis.
- Parameters:
- carray
Curve of growth values.
- flat_tolfloat
Tolerance to define the flat portion of the curve of growth. The flat portion is that which is zero within
flat_toltimes the rms of the slope.
- Returns:
- slopearray
Slope of
c.- slope_rmsfloat
Standard deviation of the slope.
- flat_idx0int
Index where the slope is consistent with zero.
- dysh.spectra.core.curve_of_growth(x, y, vc=None, width_frac=None, bchan=None, echan=None, flat_tol=0.1, fw=1) dict[source]#
Curve of growth analysis based on Yu et al. (2020) [1].
- Parameters:
- xarray
Velocity values.
- yarray
Flux values.
- vcfloat
Central velocity of the line in the same units as
x. If not provided, it will be estimated from the moment 1 of thexandyvalues.- width_fraclist
List of fractions of the total flux at which to compute the line width. If 0.25 and 0.85 are not included, they will be added to estimate the concentration as defined in [1].
- bchanNone or int
Beginning channel where there is signal. If not provided it will be estimated using
fwtimes the width of the line at the largestwidth_frac.- echanNone or int
End channel where there is signal. If not provided it will be estimated using
fwtimes the width of the line at the largestwidth_frac.- flat_tolfloat
Tolerance used to define the flat portion of the curve of growth. The curve of growth will be considered flat when it’s slope is within
flat_toltimes the standard deviation of the slope from zero.- fwfloat
When estimating the line-free range, use
fwtimes the largest width.
- Returns:
- resultsdict
Dictionary with the flux (\(F\)), width (\(V\)), flux asymmetry (\(A_F\)), slope asymmetry (\(A_C\)), concentration (\(C_V\)), rms, central velocity (“vel”), redshifted flux (\(F_r\)), blueshifted flux (\(F_b\)),`bchan` and
echan, and errors on the flux (“flux_std”), width (“width_std”), central velocity (“vel_std”), redshifted flux (“flux_r_std”), and blueshifted flux (“flux_b_std”). The rms is the standard deviation in the range outside of (bchan,echan).
- dysh.spectra.core.data_fshift(y, fshift, method='fft', pad=False, window=True)[source]#
Shift
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.decimate(data, n, meta=None)[source]#
Decimate a data array by
npixels.- Parameters:
- data
ndarrayorQuantity The data to decimate.
- nint
Decimation factor of the spectrum by returning every n-th channel.
- metadict
Metadata dictionary with CDELT1, CRVAL1, NAXIS1, and CRPIX1 which will be recalculated.
- data
- Returns:
- tuple
ndarrayorQuantityand dict A tuple of the decimated
dataand updated metadata (or None if nometagiven).
- tuple
- dysh.spectra.core.exclude_to_region_list(exclude, spectrum, clip_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).- clip_excludebool
Whether to clip the edges of the exclude regions when they are outside
spectrum.spectral_axis.
- 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)[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).
- 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=None, 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. Default is
None.- 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.invert_spectral_region(sr, refspec)[source]#
Invert an spectral region. The spectral region is sorted and the ranges has been merged previously.
- Parameters:
- sr
SpectralRegion Spectral region to invert.
- refspec
Spectrum Spectrum to define the boundaries for the inversion.
- sr
- Returns:
SpectralRegionInverted spectral region.
- dysh.spectra.core.make_channel_slice(channel: list | None)[source]#
Create a slice object from a [first,last] channel list. If
channelis None, then slice(0,None) is returned.- Parameters:
- channellist|None
A length 2 list containing the first and last channel numbers
- Returns:
- slice
a slice object representing [first:last]
- dysh.spectra.core.mask_fshift(mask, fshift)[source]#
Shift
maskbyfshiftchannels. This should only be used whenabs(fshift)<1. It expands the mask using binary dilation to account for the spread of the masked values when they are shifted by a fractional number of channels.- Parameters:
- maskarray_like
Array with masked values. Either ones and zeros or True and False.
- fshiftfloat
Amount to shift by.
- Returns:
- new_maskarray_like
maskshifted byfshiftchannels.
- Raises:
- ValueError
If
abs(fshift)is greather than 1.
- dysh.spectra.core.mean_data(data, fedge=0.1, nedge=None, median=False)[source]#
Special mean of data to exclude the edges like mean_tsys(), with an option to use the median instead of the mean.
- Parameters:
- data
ndarray The spectral data.
- fedgefloat, optional
Fraction of edge channels to exclude at each end, a number between 0 and 1. If
nedgeis used, this parameter is not used. Default: 0.1, meaning the central 80% bandwidth is used.- nedgeint, optional
Number of edge channels to exclude. nedge cannot be 0. Default: None, meaning use
fedge.- medianboolean, optional
Use the median instead of the mean. The default is False.
- data
- Returns:
- meandatafloat
- dysh.spectra.core.mean_tsys(calon, caloff, tcal, mode=0, fedge=0.1, nedge=None)[source]#
Get the system temperature from the neighboring calon and caloff, which reflect the state of the noise diode. We define an extra way to set the edge size, nedge, if you prefer to use number of edge channels instead of the inverse fraction. This implementation recreates GBTIDL’s
dcmeantsys.- Parameters:
- 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, kernel='hanning', width=1, ndecimate=0, meta=None, mask=None, boundary='extend', nan_treatment='fill', fill_value=nan, preserve_nan=True)[source]#
Smooth or Convolve spectrum, optionally decimating it. A number of methods from astropy.convolution can be selected with the method= keyword.
Default smoothing is hanning.
- Parameters:
- data
ndarray Input data array to smooth. Note smoothing array does not need a WCS since it is channel based.
- kernel{“hanning”, “boxcar”, “gaussian”}, optional
Smoothing kernel. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.
- widthint or float, optional
Effective width of the convolving kernel. Should ideally be an odd number. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final beam in channels (float). We normally assume the input beam has FWHM=1, pending resolution on cases where CDELT1 is not the same as FREQRES. The default is 1.
- ndecimateint, optional
Decimation factor of the spectrum by returning every
ndecimate-th channel.- meta: dict
metadata dictionary with CDELT1, CRVAL1, CRPIX1, NAXIS1, and FREQRES which will be recalculated if necessary
- maskNone or
ndarray, optional A “mask” array. Shape must match
array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. IfNone, no masking will be performed unlessarrayis a masked array. Ifmaskis notNoneandarrayis a masked array, a pixel is masked if it is masked in eithermaskorarray.mask.- boundarystr, optional
- A flag indicating how to handle boundaries:
NoneSet the
resultvalues to zero where the kernel extends beyond the edge of the array.
- ‘fill’
Set values outside the array boundary to
fill_value(default).
- ‘wrap’
Periodic boundary that wrap to the other side of
array.
- ‘extend’
Set values outside the array to the nearest
arrayvalue.
- fill_valuefloat, optional
The value to use outside the array when using
boundary='fill'. Default value isNaN.- nan_treatment{‘interpolate’, ‘fill’}, optional
- The method used to handle NaNs in the input
array: 'interpolate':NaNvalues are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.'fill':NaNvalues are replaced byfill_valueprior to convolution.
- The method used to handle NaNs in the input
- preserve_nanbool, optional
After performing convolution, should pixels that were originally NaN again become NaN?
- data
- Returns:
- s
ndarray The new convolved spectrum.
- s
- Raises:
- Exception
If no valid smoothing method is given.
- 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_list_of_tuples(spectral_region)[source]#
Convert
spectral_regioninto a list of tuples compatible withbaselineincludeorexcludearguments.- Parameters:
- spectral_region
SpectralRegion Region to convert to a list of tuples.
- spectral_region
- dysh.spectra.core.spectral_region_to_unit(spectral_region, refspec, unit=None, append_doppler=True)[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.- append_dopplerbool
Add the
doppler_conventionanddoppler_restattributes to the columns of theQTableused to convert thespectral_regionunits.
- 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:
Spectrum,HistoricalBaseThis class contains a spectrum and its attributes. It is built on
Spectrumwith added attributes like baseline model. Note thatSpectrumcan 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. SeeSpectrumfor 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- 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 and mask into a
Quantityobject.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
nchanThe number of channels in the Spectrum
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.
quantityUnitful representation of the NDCube data.
radial_velocityThe radial velocity(s) of the objects represented by this spectrum.
redshiftThe redshift(s) of the objects represented by this spectrum.
rest_valueRest frequency used in velocity conversions.
- shape
spectral_axisReturns the SpectralCoord object.
- spectral_axis_direction
- spectral_axis_index
spectral_wcsReturns the spectral axes of the WCS
subtractedHas a baseline model been subtracted?”
targetThe target object of this spectrum.
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
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, color])Compute and optionally remove a baseline.
bshow()Show the baseline model
check_stats(rms[, rtol])Check statistics of a spectrum compared to pre-set value(s) to a relative tolerance.
cog([vc, width_frac, bchan, echan, ...])Curve of growth (CoG) analysis based on Yu et al. (2020) [1].
collapse(method[, axis])Collapse the flux array given a method.
crop(*points[, wcs, keepdims])Crop using real world coordinates.
crop_by_values(*points[, units, wcs, keepdims])Crop using real world coordinates.
decimate(n)Decimate the
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, normal, use_wcs])Create a fake spectrum with Gaussian noise, useful for simple testing.
find_shift(other[, units, frame])Find the shift required to align this
Spectrumwithother.get_selected_regions([unit])Get selected regions from plot.
get_velocity_in_frame(toframe)Compute the radial velocity of the
Spectrum.targetin a new velocity frame.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.
Return
Spectrum.metaas anTable.multiply(operand[, operand2])Performs multiplication by evaluating
self*operand.new_flux_unit(unit[, equivalencies, ...])Compute the p-value to check if the noise in a spectrum is Gaussian using the Anderson-Darling statistic.
plot(**kwargs)Plot the spectrum.
query_lines([chemical_name, ...])Query locally or remotely for lines and return a table object.
radiometer([roll])Check the radiometer equation, and return the dimensionless ratio of the measured vs.
rebin(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
recomb(line[, cat, columns])Search for recombination lines of H, He, and C in the frequency range of this Spectrum.
recomball([cat, columns])Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.
reproject_to(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
roll([rollmax])Rolling data to check for channel correllations and channel-to-channel correllations.
savefig(file, **kwargs)Save the plot
set_convention(doppler_convention)Set the velocity convention of this
Spectrum.set_frame(toframe)Set the sky coordinate and doppler tracking reference frame of this Spectrum.
set_radial_velocity_to(radial_velocity)This sets the radial velocity of the spectrum to be
radial_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([kernel, width, decimate, meta, ...])Smooth or Convolve the
Spectrum, optionally decimating it.snr([peak, flux, rms])Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.
squeeze([axis])Removes all axes with a length of 1.
sratio([mean])Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.
stats([roll, qac])Compute some statistics of this
Spectrum.subtract(operand[, operand2])Performs subtraction by evaluating
self-operand.to(new_unit, **kwargs)Convert instance to another unit.
Undo the most recently computed baseline.
velocity_axis_to([unit, toframe, ...])Convert the spectral axis to
unitintoframeusingdoppler_conventionif converting from frequency/wavelength to velocity.with_flux_unit(unit[, equivalencies, ...])Returns a new spectrum with a different flux unit.
with_frame(toframe)Return a copy of this
Spectrumwith a new coordinate reference frame.with_spectral_axis_and_flux_units(...[, ...])Perform
with_spectral_axis_unit()andwith_flux_unit()together.with_spectral_axis_last()Convenience method to return a new copy of the Spectrum with the spectral axis last.
with_spectral_axis_unit(unit[, ...])Returns a new spectrum with a different spectral axis unit.
with_spectral_unit(unit[, ...])with_velocity_convention(doppler_convention)Returns a copy of this
Spectrumwith the input velocity convention.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.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: str | ndarray | None = '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: None, str or ~numpy.ndarray
If None, the channel weights will be equal and set to unity.
If ‘tsys’ the channel weights will be calculated as:
\(w = t_{exp} \times \delta\nu/T_{sys}^2\)
If ‘spectral’, the weights in each Spectrum will be used.
If an array, it must have shape
(len(spectra)+1,)or(len(spectra)+1,nchan)wherenchanis the number of channels in the spectra. The first element ofthe weights array will be applied to the current spectrum.- 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.- Parameters:
- unit
Quantityor str that can be converted to Quantity The unit to which the axis is to be converted
- Returns
- ——-
- velocity
Quantity The converted spectral axis velocity
- unit
- baseline(degree, exclude=None, include=None, color='k', **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.- colorstr
The color to plot the baseline model, if remove=False. Can be any type accepted by matplotlib.
- model{‘chebyshev’, ‘polynomial’, ‘legendre’, ‘hermite’}
Model to describe the baseline. 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. If False, the baseline will be computed and overlaid on the spectrum. Default: False
- property baseline_model#
Returns the computed baseline model or None if it has not yet been computed.
- check_stats(rms, rtol=1e-05)[source]#
Check statistics of a spectrum compared to pre-set value(s) to a relative tolerance. Currently only the RMS is compared.
- Parameters:
- rmsfloat or
Quantity Value of the expected RMS value. If a float is given the comparison is only done on the value of the Quantity.
- rtolfloat
Relative tolerance with which the value is compared. See also np.isclose(). Default: 1e-05
- rmsfloat or
- cog(vc=None, width_frac=None, bchan=None, echan=None, flat_tol=0.1, fw=1, xunit='km/s', vframe=None, doppler_convention=None) dict[source]#
Curve of growth (CoG) analysis based on Yu et al. (2020) [1].
- Parameters:
- vcfloat
Central velocity of the line. If not provided, it will be estimated from the moment 1 of the
Spectrum.- width_fraclist
List of fractions of the total flux at which to compute the line width. If 0.25 and 0.85 are not included, they will be added to estimate the concentration as defined in [1].
- bchanint
Beginning channel where there is signal. If not provided it will be estimated using
fwtimes the width of the line at the largestwidth_frac.- echanint
End channel where there is signal. If not provided it will be estimated using
fwtimes the width of the line at the largestwidth_frac.- flat_tolfloat
Tolerance used to define the flat portion of the curve of growth. The curve of growth will be considered flat when it’s slope is within
flat_toltimes the standard deviation of the slope from zero.- fwfloat
When estimating the line-free range, use
fwtimes the largest width.- xunitstr or
Quantity Units for the x axis when computing the CoG.
- vframeNone or str
Velocity frame to use. The results will be provided in this velocity frame. If None, the velocity frame of the
Spectrumwill be used. The velocity frame of theSpectrumwon’t be changed.- doppler_conventionNone or {‘radio’, ‘optical’, ‘relativistic’}
The Doppler velocity covention to use when converting to velocity units. If a string, one of ‘optical’, ‘radio’, or ‘relativistic’. If None, it will use the
Spectrum.doppler_convention.
- Returns:
- resultsdict
Dictionary with the flux (\(F\)), width (\(V\)), flux asymmetry (\(A_F\)), slope asymmetry (\(A_C\)), concentration (\(C_V\)), rms, central velocity (“vel”), redshifted flux (\(F_r\)), blueshifted flux (\(F_b\)),`bchan` and
echan, and errors on the flux (“flux_std”), width (“width_std”), central velocity (“vel_std”), redshifted flux (“flux_r_std”), and blueshifted flux (“flux_b_std”). The rms is the standard deviation in the range outside of (bchan,echan).
- property equivalencies#
Get the spectral axis equivalencies that can be used in converting the axis between km/s and frequency or wavelength
- property exclude_regions#
The baseline exclusion region(s) of this spectrum
- classmethod fake_spectrum(nchan=1024, seed=None, normal=True, use_wcs=True, **kwargs)[source]#
Create a fake spectrum with Gaussian noise, useful for simple testing. A default header is created, which may be modified with kwargs.
- Parameters:
- nchanint, optional
Number of channels. The default is 1024.
- seed{None, int, array_like[ints],
numpy.random.SeedSequence,numpy.random.BitGenerator,numpy.random.Generator}, optional A seed to initialize the
BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then all values must be non-negative and will be passed 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.- normalbool, optional
If set, the noise is distributed normal with a mean 0.1 and dispersion 0.1. If False, the noise is uniformly distributed between 0 and 1. The default is True.
- use_wcsbool, optional
If set, create a WCS object from the metadata. This is computationally expensive, so setting it to False can speed things up when no WCS is needed. The default is True.
- **kwargs: dict or key=value
Metadata to put in the header. If the key exists already in the default header, it will be replaced. Otherwise the key and value will be added to the header. Keys are case insensitive.
- Returns:
- 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.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.
- property flux#
Converts the stored data and unit and mask into a
Quantityobject.- Returns:
QuantitySpectral data as a quantity. Masked values are filled with NaN.
- get_velocity_in_frame(toframe: str) Quantity[source]#
Compute the radial velocity of the
Spectrum.targetin a new velocity frame. Seeget_velocity_in_frame().- Parameters:
- toframestr
The coordinate frame to convert to, e.g. ‘hcrs’, ‘icrs’.
- Returns:
- radial_velocity
Quantity The radial velocity of the source in
toframe
- radial_velocity
- 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
Spectrum- 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
- normalness()[source]#
Compute the p-value to check if the noise in a spectrum is Gaussian using the Anderson-Darling statistic. If p>0.05, the spectrum can be considered Gaussian. See also “D’Agostino, R. B., & Stephens, M. A. (Eds.). (1986) Goodness-of-fit techniques” , table 4.9
- property observer#
- Returns:
- observer
BaseCoordinateFrameor derivative - The coordinate frame of the observer if present.
- observer
- property obstime#
- plot(**kwargs)[source]#
Plot the spectrum.
- Parameters:
- show_headerbool
Show informational header.
- selectbool
Allow selecting regions via click and drag.
- oshowlist or
Spectrum Spectra to overlay in the plot.
- oshow_kwargsdict
Dictionary with parameters for
SpectrumPlot.oshow. These include color, linestyle, label, and alpha.
- Other Parameters:
- xaxis_unitstr or
Unit The units to use on the x-axis, e.g. “km/s” to plot velocity.
- yaxis_unitstr or
Unit The units to use on the y-axis.
- xminfloat
Minimum x-axis value, in
xaxis_unit.- xmaxfloat
Maximum x-axis value, in
yaxis_unit.- yminfloat
Minimum y-axis value, in
xaxis_unit.- ymaxfloat
Maximum y-axis value, in
yaxis_unit.- xlabelstr
x-axis label.
- ylabelstr
y-axis label.
- labelstr
Label for legend.
- alphafloat
Alpha value for the plot. Between 0 and 1.
- gridbool
Show a plot grid or not.
- figsizetuple
Figure size (see matplotlib).
- linewidthfloat
Line width, default: 2.0.
- drawstylestr
Line style, default ‘default’.
- colorstr
Line color, c also works.
- titlestr
Plot title.
- vel_framestr
The velocity frame (see VELDEF FITS Keyword).
- doppler_convention: str
The velocity convention (see VELDEF FITS Keyword).
- xaxis_unitstr or
- property plotter#
- query_lines(chemical_name: str | None = None, intensity_lower_limit: float | None = None, cat: str = 'gbtlines', columns: str | list | None = None) Table[source]#
Query locally or remotely for lines and return a table object. The query returns lines with rest frequencies in the range of this Spectrum’s spectral_axis. The redshift value in the attribute
Spectrum.redshiftwill be applied.Note: If the search parameters result in no matches, a zero-length Table will be returned.
- Parameters:
- chemical_namestr, optional
Name of the chemical to search for. Treated as a regular expression. An empty set will match any species. Examples:
'H2CO'- 13 species have H2CO somewhere in their formula.'Formaldehyde'- There are 8 isotopologues of Formaldehyde(e.g., H213CO).
'formaldehyde'- Thioformaldehyde,Cyanoformaldehyde.'formaldehyde',chem_re_flags=re.I- Formaldehyde,thioformaldehyde,and Cyanoformaldehyde.
' H2CO '- Just 1 species, H2CO. The spaces prevent includingothers.
- intensity_lower_limitfloat, optional
Lower limit on the intensity in the logarithmic CDMS/JPL scale. This corresponds to the ‘intintensity’ column in the returned table.
- catstr or Path
The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the
columnsparameter.'gbtlines'is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.'gbtrecomb'is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.
- columns: str or list or None
The query result columns to include in the returned table. Any of [‘species_id’, ‘name’, ‘chemical_name’, ‘resolved_QNs’, ‘linelist’, ‘LovasASTIntensity’, ‘lower_state_energy’, ‘upper_state_energy’, ‘sijmu2’, ‘sij’, ‘aij’, ‘intintensity’, ‘Lovas_NRAO’, ‘rest_frequency’, ‘obs_frequency’, ‘lower_state_energy_K’, ‘upper_state_energy_K’, ‘upperStateDegen’, ‘moleculeTag’, ‘qnCode’, ‘labref_Lovas_NIST’, ‘rel_int_HFS_Lovas’, ‘unres_quantum_numbers’, ‘lineid’, ‘transition_in_space’, ‘transition_in_G358’, ‘obsref_Lovas_NIST’, ‘source_Lovas_NIST’, ‘telescope_Lovas_NIST’, ‘searchErrorMessage’]. The default is None which means all columns.
- Returns:
TableAn astropy table containing the results of the search
- radiometer(roll=0)[source]#
Check the radiometer equation, and return the dimensionless ratio of the measured vs. expected noise. Generally this number is 1.0 or higher, unless for example channels were hanning correlated, measured noise will be lower.
User is responsible for selecting the channels, via e.g. indexing:
r1 = sp0[1000:2000].radiometer()
Note that the current
getsigreffunction may not set the exposure time correctly, and thus come up with the wrong result from the radiometer function. See issue #800 GreenBankObservatory/dysh#800- Parameters:
- rollint
Subtract the data of channel
i+rollfrom channelibefore computing the rms. This helps reduce artifacts due to bad baselines or channel-to-channel correlations. A value of 1 or 2 is recommended. See also therollfunction where a series ofrollvalues can be checked. The default is 0 (no roll).
- Returns:
- ratioreal
The ratio of measured to expected RMS.
- recomb(line, cat: str = 'gbtrecomb', columns: str | list | None = None) Table[source]#
Search for recombination lines of H, He, and C in the frequency range of this Spectrum. The redshift value in the attribute
Spectrum.redshiftwill be applied.- Parameters:
- linestr
A string describing the line or series to search for, e.g. “Hydrogen”, “Halpha”, “Hebeta”, “C”, “carbon”.
- catstr or Path
The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the
columnsparameter.'gbtlines'is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.'gbtrecomb'is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.
- columns: str or list or None
The query result columns to include in the returned table. Any of [‘species_id’, ‘name’, ‘chemical_name’, ‘resolved_QNs’, ‘linelist’, ‘LovasASTIntensity’, ‘lower_state_energy’, ‘upper_state_energy’, ‘sijmu2’, ‘sij’, ‘aij’, ‘intintensity’, ‘Lovas_NRAO’, ‘rest_frequency’, ‘obs_frequency’, ‘lower_state_energy_K’, ‘upper_state_energy_K’, ‘upperStateDegen’, ‘moleculeTag’, ‘qnCode’, ‘labref_Lovas_NIST’, ‘rel_int_HFS_Lovas’, ‘unres_quantum_numbers’, ‘lineid’, ‘transition_in_space’, ‘transition_in_G358’, ‘obsref_Lovas_NIST’, ‘source_Lovas_NIST’, ‘telescope_Lovas_NIST’, ‘searchErrorMessage’]. The default is None which means all columns.
- Returns:
TableAn astropy table containing the results of the search
- recomball(cat: str = 'gbtrecomb', columns: str | list | None = None) Table[source]#
Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog. The redshift value in the attribute
Spectrum.redshiftwill be applied.- Parameters:
- catstr or Path
The catalog to use. One of: [‘splatalogue’, ‘gbtlines’, ‘gbtrecomb’] (minimum string match) or a valid Path to a local astropy-compatible table. The local table must have all the columns listed in the
columnsparameter.'gbtlines'is a local catalog of spectral lines between 300 MHz and 120 GHz with CDMS/JP log(intensity) > -9.'gbtrecomb'is a local catalog of H, He, and C recombination lnes between 300 MHz and 120 GHz.
- columns: str or list or None
The query result columns to include in the returned table. Any of [‘species_id’, ‘name’, ‘chemical_name’, ‘resolved_QNs’, ‘linelist’, ‘LovasASTIntensity’, ‘lower_state_energy’, ‘upper_state_energy’, ‘sijmu2’, ‘sij’, ‘aij’, ‘intintensity’, ‘Lovas_NRAO’, ‘rest_frequency’, ‘obs_frequency’, ‘lower_state_energy_K’, ‘upper_state_energy_K’, ‘upperStateDegen’, ‘moleculeTag’, ‘qnCode’, ‘labref_Lovas_NIST’, ‘rel_int_HFS_Lovas’, ‘unres_quantum_numbers’, ‘lineid’, ‘transition_in_space’, ‘transition_in_G358’, ‘obsref_Lovas_NIST’, ‘source_Lovas_NIST’, ‘telescope_Lovas_NIST’, ‘searchErrorMessage’]. The default is None which means all columns.
- Returns:
TableAn astropy table containing the results of the search
- property rest_value: Quantity#
Rest frequency used in velocity conversions.
- Returns:
- ~astropy.units.quantity.quantity.Quantity
The rest frequency as a Quantity object
- roll(rollmax=1)[source]#
Rolling data to check for channel correllations and channel-to-channel correllations. For all roll’s from 1 to rollmax the RMS in the rolled data is compared to the raw RMS. For well behaved (and baseline subtracted) data the ratio of the raw RMS to the rolled RMS should approach 1.0. Note: rolling the data is shifting the data by “roll” channels.
- Parameters:
- rollmaxint
Roll the data by values 1 through
rollmax. The default is 1.
- Returns:
- ratiolist
The ratios of raw RMS by the rolled RMS. The list has a length of
rollmax.
- 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, useSpectrum.with_velocity_convention.- Parameters:
- doppler_conventionstr
The velocity convention, one of ‘radio’, ‘optical’, ‘relativistic’
- set_frame(toframe)[source]#
Set the sky coordinate and doppler tracking reference frame of this Spectrum. The header ‘CTYPE1’ will be changed accordingly.
To make a copy of this Spectrum with new coordinate reference frame instead, use
with_frame.- Parameters:
- toframestr or
BaseCoordinateFrameorSkyCoord The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, an actual coordinate system instance, or a sky coordinate instance.
- toframestr or
- 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(kernel='hanning', width=1, decimate=0, meta=None, mask=None, boundary='extend', nan_treatment='fill', fill_value=nan, preserve_nan=True)[source]#
Smooth or Convolve the
Spectrum, optionally decimating it.Default smoothing is hanning.
- Parameters:
- kernel{“hanning”, “boxcar”, “gaussian”}
Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.
- widthint
Effective width of the convolving kernel. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final frequency response. That is, the smoothed
Spectrumwill have an effective frequency resolution equal to CDELT1*`width`. The default is 1.- decimateint
Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution)
- maskNone or
numpy.ndarray A “mask” array. Shape must match
array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. IfNone, no masking will be performed unlessarrayis a masked array. Ifmaskis notNoneandarrayis a masked array, a pixel is masked if it is masked in eithermaskorarray.mask.- boundarystr
- A flag indicating how to handle boundaries:
NoneSet the
resultvalues to zero where the kernel extends beyond the edge of the array.
- ‘fill’
Set values outside the array boundary to
fill_value(default).
- ‘wrap’
Periodic boundary that wrap to the other side of
array.
- ‘extend’
Set values outside the array to the nearest
arrayvalue.
- fill_valuefloat
The value to use outside the array when using
boundary='fill'. Default value isNaN.- nan_treatment{‘interpolate’, ‘fill’}
- The method used to handle NaNs in the input
array: 'interpolate':NaNvalues are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.'fill':NaNvalues are replaced byfill_valueprior to convolution.
- The method used to handle NaNs in the input
- preserve_nanbool
After performing convolution, should pixels that were originally NaN again become NaN?
- Returns:
- Raises:
- Exception
If no valid smoothing kernel is given.
- ValueError
If
widthis less than one. Ifwidthis less than the spectral resolution (in channels). Ifdecimateis not an integer.
- snr(peak=True, flux=False, rms=None)[source]#
Signal-to-noise (S/N) ratio, measured either in channel or total flux mode. Make sure the spectrum has been baseline substracted, or the snr is meaningless. See also
sratio(), the signal ratio.- Parameters:
- peakbool
If True, the largest positive deviation from the mean is compared to the rms. If False, the largest negative deviation from the mean is compared to the rms. For normal noise the returned snr value depends on the number of channels via the error function.
- fluxbool
If True, the integrated flux over the spectrum is compared to the expected flux given pure noise. If False, channel based snr is computed, also controlled by the value of the peak in the spectrum.
See also Specutils Analysis.
- rmsNone or
Quantity} If given, this is the RMS used in the S/N computations. By default it is determined from the
Spectrum.stats(roll=1)["rms"]value of theSpectrum.
- Returns:
- ratiofloat
The S/N, either flux or channel based
- sratio(mean=0.0)[source]#
Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum. The
Spectrummust have been baseline subtracted before using this function, otherwise the results will not make sense.- Parameters:
- meanfloat
At your own risk, don’t use this, should do a baseline subtraction before. If not, this could be used as a cheat.
- Returns:
- ratioreal
The signal ratio, between -1 and 1, 0 being pure noise.
- stats(roll=0, qac=False)[source]#
Compute some statistics of this
Spectrum. The mean, rms, median, data minimum and data maximum are calculated. Note this works with slicing, so, e.g.,myspectrum[45:153].stats()will return the statistics of the slice.- Parameters:
- rollint
Return statistics on a ‘rolled’ array differenced with the original array. If there is no correllaton between channels, a roll=1 would return an RMS sqrt(2) larger than that of the input array. Another advantage of rolled statistics it will remove most slow variations, thus RMS/sqrt(2) might be a better indication of the underlying RMS. Note that for roll > 1, the RMS is already corrected by sqrt(2), so they can be directly compared. Default: 0
- qacbool
If set, the returned simple string contains mean,rms,datamin,datamax for easier visual regression. Based on some legacy code. Default: False
- Returns:
- statsdict
Dictionary consisting of (mean,median,rms,datamin,datamax)
- property subtracted#
Has a baseline model been subtracted?”
- Returns:
- True if a baseline model has been subtracted, False otherwise
- property target#
The target object of this spectrum.
- Returns:
- target
SkyCoord The sky coordinate object
- target
- property tscale#
- The descriptive brightness unit of the data. One of
‘Raw’ : raw value, e.g., count
‘Ta’ : Antenna Temperature in K
‘Ta*’ : Antenna temperature corrected to above the atmosphere in K
‘Flux’: flux density in Jansky
- Returns:
- tscalestr or None
Brightness unit string. If there is no TSCALE in the header, None is returned.
- property tscale_fac#
The factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density. This is the average of the values by which the integrations in the spectrum have been scaled.
- Returns:
- tscale_facfloat or None
The scale factor. If there is no TSCALFAC in the header, None is returned.
- undo_baseline()[source]#
Undo the most recently computed baseline. If the baseline has been subtracted, it will be added back to the data. The
baseline_modelattribute is set to None. Exclude regions are untouched.
- velocity_axis_to(unit=Unit('km / s'), toframe=None, doppler_convention=None)[source]#
Convert the spectral axis to
unitintoframeusingdoppler_conventionif converting from frequency/wavelength to velocity.- Parameters:
- unit
Quantityor str that can be converted toQuantity The unit to which the spectral axis is to be converted.
- toframestr
The coordinate frame to convert to, e.g. ‘hcrs’, ‘icrs’.
- doppler_conventionNone or {‘optical’, ‘radio’, ‘relativistic’}
The Doppler convention to use when converting to velocity. One of ‘optical’, ‘radio’, or ‘relativistic’.
- unit
- Returns:
- velocity
Quantity The converted spectral axis in units of
unit.
- velocity
- property weights#
The channel weights of this spectrum
- with_frame(toframe)[source]#
Return a copy of this
Spectrumwith a new coordinate reference frame.- Parameters:
- toframestr,
BaseCoordinateFrame, orSkyCoord The coordinate reference frame identifying string, as used by astropy, e.g. ‘hcrs’, ‘icrs’, an actual coordinate system instance, or a sky coordinate instance.
- toframestr,
- 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_conventionstr
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, history=None)[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: None, str or ~numpy.ndarray
If None, the channel weights will be equal and set to unity.
If ‘tsys’ the channel weights will be calculated as:
\(w = t_{exp} \times \delta\nu/T_{sys}^2\)
If ‘spectral’, the
weightsarray in each Spectrum will be used.If an array, it must have shape
(len(spectra),)or(len(spectra),nchan)wherenchanis the number of channels in the spectra.- alignbool
If
Truealign thespectrato the first element. This usesSpectrum.align_to.- history
dysh.log.HistoricalBase History to append to the averaged spectra.
- 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, fdnum, ifnum, plnum, bintable, calibrate=True, fold=True, shift_method='fft', use_sig=True, smoothref=1, apply_flags=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tsys=None, tcal=None, nocal: bool = False, channel: list | None = None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#
Bases:
ScanBaseGBT specific version of Frequency Switch Scan
- Parameters:
- gbtfits
GBTFITSLoad input GBTFITSLoad object
- scanint
Scan number that contains integrations with a series of sig/ref and calon/caloff states.
- sigrows :dict
Dictionary containing with keys ‘ON’ and ‘OFF’ containing list of rows in
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.- fdnum: int
The feed number
- ifnumint
The IF number
- plnumint
The polarization number
- 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.
- tscalestr, optional
- The brightness scale unit for the output scan, must be one of (case-insensitive)
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’
- ap_efffloat or None
Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None,
dyshwill calculate it as described inaperture_efficiency(). Only one ofap_efforsurface_errorcan be provided.- surface_error: Quantity or None
Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None,
dyshwill use the known GBT surface error model. Only one ofap_efforsurface_errorcan be provided.- zenith_opacity: float, optional
The zenith opacity to use in calculating the scale factors for the integrations. Default:None
- 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.- tsysfloat or
ndarray If given, this is the system temperature in Kelvin. It overrides the values calculated using the noise diodes. If not given, and signal and reference are scan numbers, the system temperature will be calculated from the reference scan and the noise diode. If not given, and the reference is a
Spectrum, the reference system temperature as given in the metadata header will be used. The default is to use the noise diode or the metadata, as appropriate.- channel: list or None
An inclusive list of
[firstchan, lastchan]to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range[firstchan,lastchan]will be used. If a reference spectrum has been given, it will also be trimmed to[firstchan,lastchan]. If channels have already been selected throughselect_channel(), a ValueError will be raised. Ifvaneis provided,tsyswill be ignored.- vane
VaneSpectrumor None Vane calibration spectrum. This will be used to derive the system temperature. If provided,
tsyswill be ignored.
- gbtfits
- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
foldedHas the FSscan been folded?
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
scanThe scan number
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)Frequency switch calibration.
get_vane_tcal()Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
undo_baseline()Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- calibrate(**kwargs)[source]#
Frequency switch calibration.
- Parameters:
- foldbool
Fold the spectrum or not. Required keyword.
- property folded#
Has the FSscan been folded?
- Returns:
- boolean
True if the signal and reference integrations have been folded. False if not.
- class dysh.spectra.scan.NodScan(gbtfits, scan, beam1, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, tsys=None, tcal=None, nocal=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, channel=None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#
Bases:
ScanBaseGBT specific version of Nodding Scan. A nod scan object has one IF, two feeds, and one polarization.
- Parameters:
- gbtfits
GBTFITSLoad input GBTFITSLoad object
- scandict
dictionary with keys ‘ON’ and ‘OFF’ containing unique list of ON (signal) and OFF (reference) scan numbers NOTE: there should be one ON and one OFF, a pair. There should be at least two beams (the nodding beams) which will be resp. on source in each scan.
- beam1: bool
Is this scan BEAM1 or BEAM2? BEAM1 is defined as being on source in the first scan of the pair, BEAM2 in the second of the pair
- scanrowsdict
dictionary with keys ‘ON’ and ‘OFF’ containing the list of rows in
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.- fdnum: int
The feed number
- ifnumint
The IF number
- plnumint
The polarization number
- 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
If True, apply flags before calibration.
- tsysfloat
User provided value for the system temperature. If
vaneis provided,tsyswill be ignored.- nocalbool
True if the noise diode was not fired. False if it was fired.
- tscalestr, optional
- The brightness scale unit for the output scan, must be one of (case-insensitive)
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’
- ap_efffloat or None
Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None,
dyshwill calculate it as described inaperture_efficiency(). Only one ofap_efforsurface_errorcan be provided.- surface_error: Quantity or None
Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None,
dyshwill use the known GBT surface error model. Only one ofap_efforsurface_errorcan be provided.- zenith_opacity: float, optional
The zenith opacity to use in calculating the scale factors for the integrations. Default:None
- 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.- channel: list or None
An inclusive list of
[firstchan, lastchan]to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range[firstchan,lastchan]will be used. If a reference spectrum has been given, it will also be trimmed to[firstchan,lastchan]. If channels have already been selected throughselect_channel(), a ValueError will be raised.- vane
VaneSpectrumor None Vane calibration spectrum. This will be used to derive the system temperature. If provided,
tsyswill be ignored.
- gbtfits
- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
scanThe scan number
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)NodScan calibration
get_vane_tcal()Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
undo_baseline()Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- class dysh.spectra.scan.PSScan(gbtfits, scan, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tscale='ta', zenith_opacity=0.0, refspec=None, tsys=None, ap_eff=None, surface_error=None, tcal=None, nocal=False, channel=None, vane: ~dysh.spectra.vane.VaneSpectrum | None = None)[source]#
Bases:
ScanBaseGBT specific version of Position Switch Scan. A position switch scan object has one IF, one feed, and one polarization
- Parameters:
- gbtfits
GBTFITSLoad Input GBTFITSLoad object.
- scandict
dictionary with keys ‘ON’ and ‘OFF’ containing unique list of ON (signal) and OFF (reference) scan numbers NOTE: there should be one ON and one OFF, a pair.
- scanrowsdict
dictionary with keys ‘ON’ and ‘OFF’ containing the list of rows in
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.- fdnum: int
The feed number.
- ifnumint
The intermediate frequency (IF) number.
- plnumint
The polarization number.
- 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
If >1 smooth the reference with a boxcar kernel with a width of
smooth_refchannels. The default is to not smooth the reference.- 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.- tscalestr, optional
- The brightess unit scale for the output scan, must be one of (case-insensitive)
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default: ‘ta’
- zenith_opacity: float, optional
The zenith opacity to use in calculating the scale factors for the integrations. Default: None
- refspecint or
Spectrum, optional If given, the Spectrum will be used as the reference rather than using scan data.
- tsysfloat or
ndarray If given, this is the system temperature in Kelvin. It overrides the values calculated using the noise diodes. If not given, and signal and reference are scan numbers, the system temperature will be calculated from the reference scan and the noise diode. If not given, and the reference is a
Spectrum, the reference system temperature as given in the metadata header will be used. The default is to use the noise diode or the metadata, as appropriate. Ifvaneis provided,tsyswill be ignored.- ap_efffloat or None
Aperture efficiency to be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None,
dyshwill calculate it as described inaperture_efficiency(). Only one ofap_efforsurface_errorcan be provided.- surface_error: Quantity or None
Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None,
dyshwill use the known GBT surface error model. Only one ofap_efforsurface_errorcan be provided.- channel: list or None
An inclusive list of
[firstchan, lastchan]to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range[firstchan,lastchan]will be used. If a reference spectrum has been given, it will also be trimmed to[firstchan,lastchan]. If channels have already been selected throughselect_channel(), a ValueError will be raised.- vane
VaneSpectrumor None Vane calibration spectrum. This will be used to derive the system temperature. If provided,
tsyswill be ignored.
- gbtfits
- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
refscanThe scan number associated with the reference.
refspecThe reference Spectrum if one was given at construction.
scanThe scan number
sigscanThe scan number associated with the signal
sigspecThe signal Spectrum if one was given at construction.
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)Position switch calibration, following equations 1 and 2 in the GBTIDL calibration manual
get_vane_tcal()Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
undo_baseline()Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- calibrate(**kwargs)[source]#
Position switch calibration, following equations 1 and 2 in the GBTIDL calibration manual
- property refscan: int | None#
The scan number associated with the reference.
- Returns:
- int or None;
Integer scan number or None if the reference was a Spectrum object
- class dysh.spectra.scan.ScanBase(sdfits, smoothref, apply_flags, observer_location, fdnum=-1, ifnum=-1, plnum=-1, tsys=None, tcal=None, ap_eff=None, surface_error=None, zenith_opacity=None, channel=None)[source]#
Bases:
HistoricalBase,SpectralAverageMixinThis class describes the common interface to all Scan classes. A Scan represents one scan number, one IF, one feed, and one polarization. Derived classes must implement
calibrate().- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
scanThe scan number
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)Calibrate the Scan data
Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- property ap_eff: ndarray#
The aperture efficiencies for the integrations in this Scan
- Returns:
- ap_eff
ndarray The aperture efficiencies, an array of floats between 0 and 1, one value per integration.
- ap_eff
- property baseline_model#
Returns the subtracted baseline model or None if it has not yet been computed.
- getspec(i: int, use_wcs: bool = True) Spectrum[source]#
Return the i-th calibrated Spectrum from this Scan.
- Parameters:
- Returns:
- spectrum
Spectrum
- spectrum
- property is_calibrated: bool#
Have the data been calibrated?
- Returns:
- bool
True if the data have been calibrated, False if not.
- property is_scaled: bool#
Is this Scan scaled to something other than antenna temperature \(T_A\).
- Returns:
- is_scaledbool
True if scale is e.g \(T_A^*\) or Flux (\(S_\nu\)).
- property meta: dict#
The metadata of this Scan. The metadata is a list of dictionaries, the length of which is equal to the number of calibrated integrations in the Scan.
- Returns:
- dict
Dictionary containing the metadata of this Scan
- property nchan: int#
The number of channels in this scan.
- Returns:
- int
The number of channels in this scan.
- property nint: int#
The number of integrations in this scan.
- Returns:
- int
The number of integrations in this scan.
- scale(tscale: str, zenith_opacity: float | None = None)[source]#
Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity. If data are already scaled, they will be unscaled first.
- Parameters:
- tscalestr
- Strings representing valid options for scaling spectral data, specifically
‘Ta’ : Antenna Temperature in K
‘Ta*’ : Antenna temperature corrected to above the atmosphere in K
‘Flux’: flux density in Jansky
This parameter is case-insensitive.
- zenith_opacityfloat, optional
The zenith opacity. Required if
tscaleis ‘Ta*’ or ‘Flux’.
- Returns:
- None
- Raises:
- TypeError
If scaling to the
tscaleunit is not applicable to the scan type, e.g., a total power scan.- ValueError
If
tscaleis unrecognized orzenith_opacityis negative.
- property scan: int#
The scan number
- Returns:
- int
The scan number of the integrations in the Scan object
- subtract_baseline(model, tol: int = 1, force: bool = False)[source]#
Subtract a (previously computed) baseline model from every integration in this Scan.
- Parameters:
- model
Model The baseline model to subtract. This is typically a
QuantityModelderived by removing a baseline from a similar spectrum.- tolint, optional
The maximum number of channels on either end of the spectrum to extrapolate the baseline model, if the spectral domain of the baseline model is smaller than the spectral axis of the Scan. For instance, if
tol=1, then one channel on the low frequency and one channel on the high frequency end are allowed to be extrapolated. The default is 1.- forcebool, optional
Force subtraction of the input baseline model, even if another baseline model has been previously subtracted. Note: The previous baseline model will not be undone (added back in) before subtraction of the input baseline model. The default is False.
- model
- Returns:
- None
- Raises:
- ValueError
If the data are not yet calibrated or the tolerance
tolis exceeded.
- property subtracted: bool#
Has a baseline model been subtracted?
- Returns:
- True if a baseline model has been subtracted, False otherwise
- property surface_error: Quantity#
The dish surface errors for the integrations in this Scan
- Returns:
- surface_error
Quantity The surface_errors with dimension length, one value per integration.
- surface_error
- timeaverage(weights='tsys', use_wcs=True)[source]#
Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a
ScanBlock, it will average all the integrations in all Scans contained in theScanBlock.- Parameters:
- weights: None, str or `~numpy.ndarray`
If None, the channel weights will be equal and set to unity.
If ‘tsys’ the channel weights will be calculated as:
\(w = t_{exp} \times \delta\nu/T_{sys}^2\)
If an array, it must have shape
(Nint,)or(Nint,nchan)whereNintis the number of integrations in the Scan or ScanBlock andnchanis the number of channels in the Scan.- use_wcsbool
Create a WCS object for the resulting
Spectrum. Creating a WCS object adds computation time to the creation of aSpectrumobject. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.
- Returns:
- spectrum
Spectrum The time-averaged spectrum. The weights array of the Spectrum will have shape
(nchan,)and will be set to the sum of the input weights.
Note
Data that are masked will have values set to zero. This is a feature of
numpy.ma.average. Data mask fill value is NaN (np.nan)- spectrum
- property tscale: str#
- The descriptive brightness unit of the data. One of
‘Raw’ : raw value, e.g., count
‘Ta’ : Antenna Temperature in K
‘Ta*’ : Antenna temperature corrected to above the atmosphere in K
‘Flux’: flux density in Jansky
- Returns:
- tscalestr
Brightness unit string.
- property tscale_fac: ndarray#
The factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
- Returns:
- tscale_fac
ndarray An array of floats, one per integration in the scan.
- tscale_fac
- property tunit: Unit#
The brightness unit (temperature or flux density) of this Scan’s data
- Returns:
- tunit
Unit The brightness unit
- tunit
- undo_baseline()[source]#
Undo the applied (subtracted) baseline. The subtracted baseline will be added back to the data. The
baseline_modelattribute is set to None.
- write(fileobj, flags=True, output_verify='exception', overwrite=False, checksum=False)[source]#
Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- Parameters:
- fileobjstr, file-like or
pathlib.Path File to write to. If a file object, must be opened in a writeable mode.
- flags: bool, optional
If True, write the applied flags to a
FLAGScolumn in the binary table.- output_verifystr
Output verification option. Must be one of
"fix","silentfix","ignore","warn", or"exception". May also be any combination of"fix"or"silentfix"with"+ignore",+warn, or+exception" (e.g. ``"fix+warn"). See https://docs.astropy.org/en/latest/io/fits/api/verification.html for more info- overwritebool, optional
If
True, overwrite the output file if it exists. Raises 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_freqReturns
durationReturns
exposureReturns
historyGet the history strings.
nchanThe number of channels in the first Scan in this ScanBlock.
nintThe total number of integrations in this Scanblock
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scaled from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperatures for all scans in this ScanBlock
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this ScanBlocks’s data
weightsThe weights associated with the Scans and integrations in this ScanBlock
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
append(item)S.append(value) -- append value to the end of the sequence
calibrate(**kwargs)Calibrate all scans in this ScanBlock
clear()count(value)extend(other)S.extend(iterable) -- extend sequence by appending elements from the iterable
index(value, [start, [stop]])Raises ValueError if the value is not present.
insert(i, item)S.insert(index, value) -- insert value before index
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
pop([index])Raise IndexError if list is empty or index is out of range.
remove(item)S.remove(value) -- remove first occurrence of value.
reverse()S.reverse() -- reverse IN PLACE
scale(tscale, zenith_opacity)Scale all the data in this
ScanBlockto the given brightness scale and zenith opacity.smooth([kernel, width, decimate])Smooth all scans in this ScanBlock.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration of every Scan in this ScanBlock.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
For all Scans in this ScanBlock, undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBlock
copy
sort
- property delta_freq#
- Returns:
- delta_freq
ndarray The channel frequency spacings for all scans in this ScanBlock
- delta_freq
- property nchan#
The number of channels in the first Scan in this ScanBlock. (Assumes number of channels in each enclosed Scan are the same).
- Returns:
- int
The number of channels in this ScanBlock.
- property nint#
The total number of integrations in this Scanblock
- Returns:
- int
The number of integerationsin this ScanBlock.
- scale(tscale, zenith_opacity)[source]#
Scale all the data in this
ScanBlockto the given brightness scale and zenith opacity. If data are already scaled, they will be unscaled first.- Parameters:
- tscalestr
- Strings representing valid options for scaling spectral data, specifically
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
This parameter is case-insensitive.
- zenith_opacityfloat
The zenith opacity
- Returns:
- None
- Raises:
- TypeError
If scaling to temperature is not applicable to the scan type, e.g., a total power scan.
- ValueError
if
tscaleis unrecognized orzenith_opacityis negative.
- smooth(kernel='hanning', width=1, decimate=0)[source]#
Smooth all scans in this ScanBlock. Smooth or convolve the calibrated data arrays in the contained scans, optionally decimating the data. A number of kernels from
astropy.convolutioncan be selected with thekernelkeyword.Default smoothing kernel is hanning.
Note: Any previously computed/removed baseline will remain unchanged.
- Parameters:
- kernel{‘hanning’, ‘boxcar’, ‘gaussian’}, optional
Smoothing kernel. Minimum match applies. The default is ‘hanning’.
- widthint, optional
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. For ‘gaussian’ this is the FWHM of the final spectral resolution. The default is 1.
- decimateint, optional
Decimation factor of the spectrum by returning every
decimatechannel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution) The default is 0, meaning decimation is bywidth.
- Returns:
- None
- subtract_baseline(model, tol: int = 1, force: bool = False)[source]#
Subtract a (previously computed) baseline model from every integration of every Scan in this ScanBlock.
- Parameters:
- model
Model The baseline model to subtract. This is typically a
QuantityModelderived by removing a baseline from a similar spectrum.- tolint, optional
The maximum number of channels on either end of the spectrum to extrapolate the baseline model, if the spectral domain of the baseline model is smaller than the spectral axis of the Scan. For instance, if
tol=1, then one channel on the low frequency and one channel on the high frequency end are allowed to be extrapolated. The default is 1.- forcebool, optional
Force subtraction of the input baseline model, even if another baseline model has been previously subtracted. Note: The previous baseline model will not be undone (added back in) before subtraction of the input baseline model. The default is False.
- model
- Returns:
- None
- Raises:
- ValueError
If the data are not yet calibrated or the tolerance
tolis exceeded.
- timeaverage(weights='tsys', use_wcs: bool = True)[source]#
Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a
ScanBlock, it will average all the integrations in all Scans contained in theScanBlock.- Parameters:
- weights: None, str or `~numpy.ndarray`
If None, the channel weights will be equal and set to unity.
If ‘tsys’ the channel weights will be calculated as:
\(w = t_{exp} \times \delta\nu/T_{sys}^2\)
If an array, it must have shape
(Nint,)or(Nint,nchan)whereNintis the number of integrations in the Scan or ScanBlock andnchanis the number of channels in the Scan.- use_wcsbool
Create a WCS object for the resulting
Spectrum. Creating a WCS object adds computation time to the creation of aSpectrumobject. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.
- Returns:
- spectrum
Spectrum The time-averaged spectrum. The weights array of the Spectrum will have shape
(nchan,)and will be set to the sum of the input weights.
Note
Data that are masked will have values set to zero. This is a feature of
numpy.ma.average. Data mask fill value is NaN (np.nan)- spectrum
- property tscale#
- The descriptive brightness unit of the data. One of
‘Raw’ : raw value, e.g., count
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
- Returns:
- tscalestr
brightness unit string
- property tscale_fac#
The factor(s) by which the data have been scaled from antenna temperature to corrected antenna temperature or flux density.
- Returns:
- tscale_fac
ndarray An array of floats, one per integration in the ScanBlock.
- tscale_fac
- property tsys#
The system temperatures for all scans in this ScanBlock
- Returns:
- tsys
ndarray The system temperatures for all scans in this ScanBlock
- tsys
- property tunit#
The brightness unit (temperature or flux density) of this ScanBlocks’s data
- Returns:
- tunit
Unit The brightness unit
- tunit
- undo_baseline()[source]#
For all Scans in this ScanBlock, undo the applied (subtracted) baseline. The subtracted baseline will be added back to the data. The Scan’s baseline_model` attribute is set to None.
- property weights: list#
The weights associated with the Scans and integrations in this ScanBlock
- Returns:
- list
A list containing the weight arrays for each scan. Because Scans can have different numbers of integrations, this is a list instead of a numpy array.
- write(fileobj, flags=True, output_verify='exception', overwrite=False, checksum=False)[source]#
Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBlock
- Parameters:
- fileobjstr, file-like or
pathlib.Path File to write to. If a file object, must be opened in a writeable mode.
- flags: bool, optional
If True, write the applied flags to a
FLAGScolumn in the binary table.- output_verifystr
Output verification option. Must be one of
"fix","silentfix","ignore","warn", or"exception". May also be any combination of"fix"or"silentfix"with"+ignore",+warn, or+exception" (e.g. ``"fix+warn"). See https://docs.astropy.org/en/latest/io/fits/api/verification.html for more info- overwritebool, optional
If
True, overwrite the output file if it exists. Raises 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.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
weightsThe weights for each integration after an averaging operation.
Methods
plot(**kwargs)Plot the data as a waterfall.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
- property delta_freq: ndarray#
The array of channel frequency width. How the channel width is calculated varies for different derived classes. See
_calc_delta_freq().- Returns:
- delta_freq:
ndarray The channel frequency width in units of the CDELT1 keyword in the SDFITS header.
- delta_freq:
- property duration: ndarray#
The array of duration times. How the duration is calculated varies for different derived classes. See
_calc_exposure(). Duration includes the blanking time, exposure does not, soduration>=exposure.- Returns:
- duration
ndarray The duration time in units of the DURATION keyword in the SDFITS header.
- duration
- property exposure: ndarray#
The array of exposure (integration) times. How the exposure is calculated varies for different derived classes. See
_calc_exposure().- Returns:
- exposure
ndarray The exposure time in units of the EXPOSURE keyword in the SDFITS header.
- exposure
- smooth(kernel='hanning', width=1, decimate=0)[source]#
Smooth or convolve the underlying calibrated data array, optionally decimating the data.
A number of kernels from
astropy.convolutioncan be selected with thekernelkeyword.Note: Any previously computed/removed baseline will remain unchanged.
- Parameters:
- kernel{‘hanning’, ‘boxcar’, ‘gaussian’}, optional
Smoothing kernel. Minimum match applies. The default is ‘hanning’.
- widthint, optional
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. For ‘gaussian’ this is the FWHM of the desired spectral resolution. The default is 1.
- decimateint, optional
Decimation factor of the spectrum by returning every
decimatechannel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution) The default is 0, meaning decimation is bywidth.
- Returns:
- None
- Raises:
- ValueError
If no valid smoothing
kernelis given or ifwidthis less than 1.
- timeaverage(weights: str | ndarray = 'tsys', use_wcs=True) Spectrum[source]#
Compute the time-averaged spectrum. For a Scan this will average all the integrations in the Scan, according to the given weights. For a
ScanBlock, it will average all the integrations in all Scans contained in theScanBlock.- Parameters:
- weights: None, str or `~numpy.ndarray`
If None, the channel weights will be equal and set to unity.
If ‘tsys’ the channel weights will be calculated as:
\(w = t_{exp} \times \delta\nu/T_{sys}^2\)
If an array, it must have shape
(Nint,)or(Nint,nchan)whereNintis the number of integrations in the Scan or ScanBlock andnchanis the number of channels in the Scan.- use_wcsbool
Create a WCS object for the resulting
Spectrum. Creating a WCS object adds computation time to the creation of aSpectrumobject. There may be cases where the WCS is not needed, so setting this boolean to False will save computation.
- Returns:
- spectrum
Spectrum The time-averaged spectrum. The weights array of the Spectrum will have shape
(nchan,)and will be set to the sum of the input weights.
Note
Data that are masked will have values set to zero. This is a feature of
numpy.ma.average. Data mask fill value is NaN (np.nan)- spectrum
- property tsys_weight: ndarray#
The system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\). See
tsys_weight()
- property weights: ndarray#
The weights for each integration after an averaging operation. If
Scan.timeaverage()has not been called, the weights will be unity. The weights array can have shape(nint,)or(nint,nchan)depending on howtimeaverage()was called.
- class dysh.spectra.scan.SubBeamNodScan(sigtp, reftp, fdnum, ifnum, plnum, calibrate=True, smoothref=1, apply_flags=False, tscale='ta', ap_eff=None, surface_error=None, zenith_opacity=None, tcal=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, weights='tsys', nocal=False, vane: ~dysh.spectra.vane.VaneSpectrum | None = None, **kwargs)[source]#
Bases:
ScanBase- Parameters:
- sigtp: list of `~dysh.spectra.scan.TPScan`
Signal total power scans
- reftp: list of `~dysh.spectra.scan.TPScan`
Reference total power scans
- fdnum: int
The feed number
- ifnumint
The IF number
- plnumint
The polarization number
- calibrate: bool
Whether or not to calibrate the data.
- smoothref: int
the number of channels in the reference to boxcar smooth prior to calibration
- apply_flagsboolean, optional. If True, apply flags before calibration.
- tscalestr, optional
- The brightness scale unit for the output scan, must be one of (case-insensitive)
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
If ‘ta*’ or ‘flux’ the zenith opacity must also be given. Default:’ta’
- ap_efffloat or None
Aperture efficiency o be used when scaling data to brightness temperature of flux. The provided aperture efficiency must be a number between 0 and 1. If None,
dyshwill calculate it as described inaperture_efficiency(). Only one ofap_efforsurface_errorcan be provided.- surface_error: Quantity or None
Surface rms error, in units of length (typically microns), to be used in the Ruze formula when calculating the aperture efficiency. If None,
dyshwill use the known GBT surface error model. Only one ofap_efforsurface_errorcan be provided.- zenith_opacity: float, optional
The zenith opacity to use in calculating the scale factors for the integrations. Default:None
- 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’
- vane
VaneSpectrumor None Vane calibration spectrum. This will be used to derive the system temperature.
- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
scanThe scan number
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)Calibrate the SubBeamNodScan data
get_vane_tcal()Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
undo_baseline()Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- class dysh.spectra.scan.TPScan(gbtfits, scan, sigstate, calstate, scanrows, calrows, fdnum, ifnum, plnum, bintable, calibrate=True, smoothref=1, apply_flags=False, tsys=None, tcal=None, observer_location=<EarthLocation (882593.9465029, -4924896.36541728, 3943748.74743984) m>, tscale='Raw', channel=None)[source]#
Bases:
ScanBaseGBT specific version of Total Power Scan
- Parameters:
- gbtfits
GBTFITSLoad input GBTFITSLoad object
- scan: int
scan number
- sigstatebool
Select the signal state used to form the data. True means select sig=’T’, False to select sig=’F’. None means select both. See table below for explanation.
- calstatebool
Select the calibration state used to form the data. True means select cal=’T’, False to select cal=’F’. None means select both. See table below for explanation.
- scanrowslist-like
the list of rows in
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- fdnum: int
The feed number
- ifnumint
The IF number
- plnumint
The polarization number
- 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.
- 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.- tscalestr, optional
- The brightess unit scale for the output scan, must be one of (case-insensitive)
‘Raw’ : raw value, e.g., count
‘Ta’ : Antenna Temperature
‘Ta*’ : Antenna temperature corrected to above the atmosphere
‘Flux’ : flux density in Jansky
Default: ‘Raw’
- channel: list or None
An inclusive list of
[firstchan, lastchan]to use in the calibration. The channel list is zero-based. If provided, only data channels in the inclusive range[firstchan,lastchan]will be used. If a reference spectrum has been given, it will also be trimmed to[firstchan,lastchan]. If channels have already been selected throughselect_channel(), a ValueError will be raised.- Notes
- —–
- How the total power and system temperature are calculated, depending on signal and reference state parameters:
CAL
SIG
RESULT
TSYS
None
None
data = 0.5* (REFCALON + REFCALOFF), regardless of sig state
use all CAL states, all SIG states
None
True
data = 0.5* (REFCALON + REFCALOFF), where sig = ‘T’
use all CAL states, SIG=’T’
None
False
data = 0.5* (REFCALON + REFCALOFF), where sig = ‘F’
use all CAL states, SIG=’F’
True
None
data = REFCALON, regardless of sig state
use all CAL states, all SIG states
False
None
data = REFCALOFF, regardless of sig state
use all CAL states, all SIG states
True
True
data = REFCALON, where sig=’T’
use all CAL states, SIG=’T’
True
False
data = REFCALON, where sig=’F’
use all CAL states, SIG=’F’
False
True
data = REFCALOFF where sig=’T’
use all CAL states, SIG=’T’
False
False
data = REFCALOFF, where sig=’F’
use all CAL states, SIG=’F’
- where `REFCALON` = integrations with `cal=T` and `REFCALOFF` = integrations with `cal=F`.
- gbtfits
- Attributes:
ap_effThe aperture efficiencies for the integrations in this Scan
baseline_modelReturns the subtracted baseline model or None if it has not yet been computed.
calibratedReturns the calibrated integrations in the Scan as a numpy array.
calstateThe requested calibration state
commentsGet the comment strings.
delta_freqThe array of channel frequency width.
durationThe array of duration times.
exposureThe array of exposure (integration) times.
fdnumThe feed number.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
is_calibratedHave the data been calibrated?
is_scaledIs this Scan scaled to something other than antenna temperature \(T_A\).
metaThe metadata of this Scan.
nchanThe number of channels in this scan.
nintThe number of integrations in this scan.
nrowsThe number of rows in this scan.
plnumThe polarization number.
scanThe scan number
sigstateThe requested signal state
subtractedHas a baseline model been subtracted?
surface_errorThe dish surface errors for the integrations in this Scan
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor(s) by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
tsysThe system temperature array.
tsys_weightThe system temperature weighting array computed from current \(T_{sys}\), \(t_{int}\), and \(\delta\nu\).
tunitThe brightness unit (temperature or flux density) of this Scan’s data
weightsThe weights for each integration after an averaging operation.
zenith_opacityThe zenith opacity of this Scan, used to calculated aperture efficiency.
Methods
add_comment(comment[, add_time])Add one or more comments to the class metadata.
add_history(history[, add_time])Add one or more history entries to the class metadata
calibrate(**kwargs)Calibrate the total power data according to the CAL/SIG table above
get_vane_tcal()Get the tcal value for the vane.
getspec(i[, use_wcs])Return the i-th calibrated Spectrum from this Scan.
merge_commentary(other)Merge the history and comments from another HistoricalBase instance.
plot(**kwargs)Plot the data as a waterfall.
scale(tscale[, zenith_opacity])Scale the data to the given brightness scale (temperature or flux density) using the zenith opacity.
smooth([kernel, width, decimate])Smooth or convolve the underlying calibrated data array, optionally decimating the data.
subtract_baseline(model[, tol, force])Subtract a (previously computed) baseline model from every integration in this Scan.
timeaverage([weights, use_wcs])Compute the time-averaged spectrum.
total_power(i)Return the i-th total power spectrum in this Scan.
undo_baseline()Undo the applied (subtracted) baseline.
write(fileobj[, flags, output_verify, ...])Write an SDFITS format file (FITS binary table HDU) of the calibrated data in this ScanBase
- property calstate#
The requested calibration state
- Returns:
- bool
True if calibration state is on (‘T’ in the SDFITS header), False otherwise (‘F’)
- property sigstate#
The requested signal state
- Returns:
- bool
True if signal state is on (‘T’ in the SDFITS header), False otherwise (‘F’)
TCal#
TCal class
- class dysh.spectra.tcal.TCal(name, snu, *args, **kwargs)[source]#
Bases:
SpectrumNoise diode temperature. This behaves as a
Spectrumwith the addition of thenameandsnuattributes, which hold the name of the source used to derive the noise diode temperature and its flux density.- 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- 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 and mask into a
Quantityobject.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
nameCalibration source name.
nchanThe number of channels in the Spectrum
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.
quantityUnitful representation of the NDCube data.
radial_velocityThe radial velocity(s) of the objects represented by this spectrum.
redshiftThe redshift(s) of the objects represented by this spectrum.
rest_valueRest frequency used in velocity conversions.
- shape
snuCalibration source flux density.
spectral_axisReturns the SpectralCoord object.
- spectral_axis_direction
- spectral_axis_index
spectral_wcsReturns the spectral axes of the WCS
subtractedHas a baseline model been subtracted?”
targetThe target object of this spectrum.
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
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, color])Compute and optionally remove a baseline.
bshow()Show the baseline model
check_stats(rms[, rtol])Check statistics of a spectrum compared to pre-set value(s) to a relative tolerance.
cog([vc, width_frac, bchan, echan, ...])Curve of growth (CoG) analysis based on Yu et al. (2020) [R475e759f9d5f-1].
collapse(method[, axis])Collapse the flux array given a method.
crop(*points[, wcs, keepdims])Crop using real world coordinates.
crop_by_values(*points[, units, wcs, keepdims])Crop using real world coordinates.
decimate(n)Decimate the
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, normal, use_wcs])Create a fake spectrum with Gaussian noise, useful for simple testing.
find_shift(other[, units, frame])Find the shift required to align this
Spectrumwithother.from_spectrum(spectrum, name, snu[, data])get_selected_regions([unit])Get selected regions from plot.
get_tcal([frac, method, dtype])Reduce the temperature of the noise diode to a single value.
get_velocity_in_frame(toframe)Compute the radial velocity of the
Spectrum.targetin a new velocity frame.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.
meta_as_table()Return
Spectrum.metaas anTable.multiply(operand[, operand2])Performs multiplication by evaluating
self*operand.new_flux_unit(unit[, equivalencies, ...])normalness()Compute the p-value to check if the noise in a spectrum is Gaussian using the Anderson-Darling statistic.
plot(**kwargs)Plot the spectrum.
query_lines([chemical_name, ...])Query locally or remotely for lines and return a table object.
radiometer([roll])Check the radiometer equation, and return the dimensionless ratio of the measured vs.
rebin(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
recomb(line[, cat, columns])Search for recombination lines of H, He, and C in the frequency range of this Spectrum.
recomball([cat, columns])Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.
reproject_to(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
roll([rollmax])Rolling data to check for channel correllations and channel-to-channel correllations.
savefig(file, **kwargs)Save the plot
set_convention(doppler_convention)Set the velocity convention of this
Spectrum.set_frame(toframe)Set the sky coordinate and doppler tracking reference frame of this Spectrum.
set_radial_velocity_to(radial_velocity)This sets the radial velocity of the spectrum to be
radial_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(*args, **kwargs)Smooth or convolve
TCal, optionally decimating it.snr([peak, flux, rms])Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.
squeeze([axis])Removes all axes with a length of 1.
sratio([mean])Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.
stats([roll, qac])Compute some statistics of this
Spectrum.subtract(operand[, operand2])Performs subtraction by evaluating
self-operand.to(new_unit, **kwargs)Convert instance to another unit.
undo_baseline()Undo the most recently computed baseline.
velocity_axis_to([unit, toframe, ...])Convert the spectral axis to
unitintoframeusingdoppler_conventionif converting from frequency/wavelength to velocity.with_flux_unit(unit[, equivalencies, ...])Returns a new spectrum with a different flux unit.
with_frame(toframe)Return a copy of this
Spectrumwith a new coordinate reference frame.with_spectral_axis_and_flux_units(...[, ...])Perform
with_spectral_axis_unit()andwith_flux_unit()together.with_spectral_axis_last()Convenience method to return a new copy of the Spectrum with the spectral axis last.
with_spectral_axis_unit(unit[, ...])Returns a new spectrum with a different spectral axis unit.
with_spectral_unit(unit[, ...])with_velocity_convention(doppler_convention)Returns a copy of this
Spectrumwith the input velocity convention.max
mean
median
min
read
sum
write
- classmethod from_spectrum(spectrum, name, snu, data=None)[source]#
Returns a
TCalobject given aSpectrumobject.- Parameters:
- spectrum
Spectrum Spectrum object. Its attributes will be copied into the
TCalobject, except for thedataandfluxattributes which can be defined by thedataparameter.- namestr
Name of the calibrator used to derive the noise diode temperature.
- snu
ndarray The flux values of the calibrator source.
- dataNone or
ndarray Noise diode temperature values. If None, then it will use the
fluxattribute ofspectrum. If set, the values will define thefluxattribute of theTCalobject.
- spectrum
- Returns:
- get_tcal(frac=0.1, method=<function nanmean>, dtype=<class 'numpy.float32'>)[source]#
Reduce the temperature of the noise diode to a single value.
- Parameters:
- fracfloat
The fraction of the channels to discard on both ends of the spectrum. Default: 0.1
- methodcallable
The function used to reduce the values. Default :
numpy.nanmean- dtypestr or dtype
Typecode or data-type to which the output value,
tcalis cast.
- Returns:
- tcalfloat
The noise diode temperature reduced using
methodover the channel range defined byfrac.
- property name#
Calibration source name.
- property nchan#
The number of channels in the Spectrum
- smooth(*args, **kwargs)[source]#
Smooth or convolve
TCal, optionally decimating it.- Parameters:
- kernel{“hanning”, “boxcar”, “gaussian”}
Smoothing method. Valid are: ‘hanning’, ‘boxcar’ and ‘gaussian’. Minimum match applies. The default is ‘hanning’.
- widthint
Effective width of the convolving kernel. For ‘hanning’ this should be 1, with a 0.25,0.5,0.25 kernel. For ‘boxcar’ an even value triggers an odd one with half the signal at the edges, and will thus not reproduce GBTIDL. For ‘gaussian’ this is the FWHM of the final frequency response. That is, the smoothed
Spectrumwill have an effective frequency resolution equal to CDELT1*`width`. The default is 1.- decimateint
Decimation factor of the spectrum by returning every decimate channel. -1: no decimation 0: use the width parameter >1: user supplied decimation (use with caution)
- maskNone or
numpy.ndarray A “mask” array. Shape must match
array, and anything that is masked (i.e., not 0/False) will be set to NaN for the convolution. IfNone, no masking will be performed unlessarrayis a masked array. Ifmaskis notNoneandarrayis a masked array, a pixel is masked if it is masked in eithermaskorarray.mask.- boundarystr
- A flag indicating how to handle boundaries:
NoneSet the
resultvalues to zero where the kernel extends beyond the edge of the array.
- ‘fill’
Set values outside the array boundary to
fill_value(default).
- ‘wrap’
Periodic boundary that wrap to the other side of
array.
- ‘extend’
Set values outside the array to the nearest
arrayvalue.
- fill_valuefloat
The value to use outside the array when using
boundary='fill'. Default value isNaN.- nan_treatment{‘interpolate’, ‘fill’}
- The method used to handle NaNs in the input
array: 'interpolate':NaNvalues are replaced with interpolated values using the kernel as an interpolation function. Note that if the kernel has a sum equal to zero, NaN interpolation is not possible and will raise an exception.'fill':NaNvalues are replaced byfill_valueprior to convolution.
- The method used to handle NaNs in the input
- preserve_nanbool
After performing convolution, should pixels that were originally NaN again become NaN?
- Returns:
TCalSmoothed noise diode temperature.
- property snu#
Calibration source flux density.
VaneSpectrum#
VaneSpectrum
- class dysh.spectra.vane.VaneSpectrum(vane, scan, fdnum, ifnum, plnum, tcal=None, twarm=None, zenith_opacity=None, tatm=None, tbkg=None, *args, **kwargs)[source]#
Bases:
SpectrumVane calibration spectrum.
- Parameters:
- vane
ndarray Vane power values. The values will define the
dataattribute of theVaneSpectrumobject.- scanint
Scan number.
- fdnumint
The feed number.
- ifnumint
The intermediate frequency (IF) number.
- plnumint
The polarization number.
- tcalNone or float
The calibration temperature in K. If
None, it will be estimated usingget_tcal().- twarmNone or float
The vane temperature in K. If
None, it will be inferred from the TWARM column.- zenith_opacityfloat or None
The zenith opacity in nepers. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tatmfloat or None
The atmospheric temperature towards the zenith in K. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tbkgfloat or None
The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).
- vane
- 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- 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.fdnumThe feed number.
fluxConverts the stored data and unit and mask into a
Quantityobject.frequencyThe
spectral_axisas aQuantityin units of GHzglobal_coordsCoordinate metadata which applies to the whole cube.
historyGet the history strings.
ifnumThe intermediate frequency (IF) number.
maskany type : Mask for the dataset, if any.
- meta
nchanThe number of channels in the Spectrum
observerReturns ——- observer :
BaseCoordinateFrameor derivative The coordinate frame of the observer if present.- obstime
photon_fluxThe flux density of photons as a
Quantity, in units ofplnumThe polarization number.
- plotter
psfImage representation of the PSF for the dataset.
quantityUnitful representation of the NDCube data.
radial_velocityThe radial velocity(s) of the objects represented by this spectrum.
redshiftThe redshift(s) of the objects represented by this spectrum.
rest_valueRest frequency used in velocity conversions.
scanThe scan number.
- shape
spectral_axisReturns the SpectralCoord object.
- spectral_axis_direction
- spectral_axis_index
spectral_wcsReturns the spectral axes of the WCS
subtractedHas a baseline model been subtracted?”
targetThe target object of this spectrum.
tscaleThe descriptive brightness unit of the data.
tscale_facThe factor by which the data have been scale from antenna temperature to corrected antenna temperature or flux density.
twarmVane temperature in K.
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, color])Compute and optionally remove a baseline.
bshow()Show the baseline model
check_stats(rms[, rtol])Check statistics of a spectrum compared to pre-set value(s) to a relative tolerance.
cog([vc, width_frac, bchan, echan, ...])Curve of growth (CoG) analysis based on Yu et al. (2020) [Re28fcf3e3187-1].
collapse(method[, axis])Collapse the flux array given a method.
crop(*points[, wcs, keepdims])Crop using real world coordinates.
crop_by_values(*points[, units, wcs, keepdims])Crop using real world coordinates.
decimate(n)Decimate the
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, normal, use_wcs])Create a fake spectrum with Gaussian noise, useful for simple testing.
find_shift(other[, units, frame])Find the shift required to align this
Spectrumwithother.from_spectrum(spectrum, scan, fdnum, ifnum, ...)Returns a
VaneSpectrumobject given aSpectrumobject.get_selected_regions([unit])Get selected regions from plot.
get_tcal(ref[, mjd, freq, elev, ...])Calibration temperature.
get_tsys(ref[, tcal])Compute the system temperature.
get_velocity_in_frame(toframe)Compute the radial velocity of the
Spectrum.targetin a new velocity frame.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.
meta_as_table()Return
Spectrum.metaas anTable.multiply(operand[, operand2])Performs multiplication by evaluating
self*operand.new_flux_unit(unit[, equivalencies, ...])normalness()Compute the p-value to check if the noise in a spectrum is Gaussian using the Anderson-Darling statistic.
plot(**kwargs)Plot the spectrum.
query_lines([chemical_name, ...])Query locally or remotely for lines and return a table object.
radiometer([roll])Check the radiometer equation, and return the dimensionless ratio of the measured vs.
rebin(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
recomb(line[, cat, columns])Search for recombination lines of H, He, and C in the frequency range of this Spectrum.
recomball([cat, columns])Fetch all recombination lines of H, He, C in the frequency range of this Spectrum from the catalog.
reproject_to(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
roll([rollmax])Rolling data to check for channel correllations and channel-to-channel correllations.
savefig(file, **kwargs)Save the plot
set_convention(doppler_convention)Set the velocity convention of this
Spectrum.set_frame(toframe)Set the sky coordinate and doppler tracking reference frame of this Spectrum.
set_radial_velocity_to(radial_velocity)This sets the radial velocity of the spectrum to be
radial_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([kernel, width, decimate, meta, ...])Smooth or Convolve the
Spectrum, optionally decimating it.snr([peak, flux, rms])Signal-to-noise (S/N) ratio, measured either in channel or total flux mode.
squeeze([axis])Removes all axes with a length of 1.
sratio([mean])Signal ratio: (pSum+nSum)/(pSum-nSum) Here pSum and nSum are the sum of positive and negative values respectively in the spectrum.
stats([roll, qac])Compute some statistics of this
Spectrum.subtract(operand[, operand2])Performs subtraction by evaluating
self-operand.to(new_unit, **kwargs)Convert instance to another unit.
undo_baseline()Undo the most recently computed baseline.
velocity_axis_to([unit, toframe, ...])Convert the spectral axis to
unitintoframeusingdoppler_conventionif converting from frequency/wavelength to velocity.with_flux_unit(unit[, equivalencies, ...])Returns a new spectrum with a different flux unit.
with_frame(toframe)Return a copy of this
Spectrumwith a new coordinate reference frame.with_spectral_axis_and_flux_units(...[, ...])Perform
with_spectral_axis_unit()andwith_flux_unit()together.with_spectral_axis_last()Convenience method to return a new copy of the Spectrum with the spectral axis last.
with_spectral_axis_unit(unit[, ...])Returns a new spectrum with a different spectral axis unit.
with_spectral_unit(unit[, ...])with_velocity_convention(doppler_convention)Returns a copy of this
Spectrumwith the input velocity convention.max
mean
median
min
read
sum
write
- property fdnum#
The feed number.
- classmethod from_spectrum(spectrum, scan, fdnum, ifnum, plnum, vane=None, tcal=None, twarm=None, zenith_opacity=None, tatm=None, tbkg=None)[source]#
Returns a
VaneSpectrumobject given aSpectrumobject.- Parameters:
- spectrum
Spectrum Spectrum object. Its attributes will be copied into the
VaneSpectrumobject, except for thedataandfluxattributes which can be defined by thevaneparameter.- scanint
Scan number.
- fdnumint
The feed number.
- ifnumint
The intermediate frequency (IF) number.
- plnumint
The polarization number.
- vaneNone or
ndarray Vane power values. If None, then it will use the
fluxattribute ofspectrum. If set, the values will define thedataattribute of theVaneSpectrumobject.- tcalNone or float
The calibration temperature in K. If
None, it will be estimated usingget_tcal().- twarmNone or float
The vane temperature in K. If
None, it will be inferred from the TWARM column.- zenith_opacityfloat or None
The zenith opacity in nepers. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tatmfloat or None
The atmospheric temperature towards the zenith in K. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tbkgfloat or None
The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).
- spectrum
- Returns:
VaneSpectrumA
VaneSpectrumobject.
- get_tcal(ref, mjd: float | None = None, freq: Quantity | None = None, elev: Quantity | None = None, zenith_opacity: float | None = None, tatm: float | None = None, twarm: float | None = None, tbkg: float = 2.725)[source]#
Calibration temperature.
- Parameters:
- ref
Spectrum Reference spectrum used to derive \(T_{\mathrm{cal}}\).
- mjdfloat or None
Modified Julian date. If None, will use DATE-OBS in
ref.meta.- freq
Quantityor None Frequency at which to compute the calibration temperature. If None, will use OBSFREQ in
ref.meta.- elev
Quantityor None Elevation at which to evaluate the airmass. If None, will use ELEVATIO in
ref.meta.- twarmNone or float
The vane temperature in K. If
None, it will be inferred from the TWARM column.- zenith_opacityfloat or None
The zenith opacity in nepers. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tatmfloat or None
The atmospheric temperature towards the zenith in K. If
None, it will be retrieved from the GBO weather forecast scripts (only available at GBO). IfNoneand not at GBO,tcalwill equaltwarm(accurate to approximately 10%).- tbkgfloat or None
The background temperature in K. Default is the CMB temperature at 3 mm (2.725 K).
- ref
- Returns:
- tcalfloat
Calibration temperature for the vane in K.
- get_tsys(ref, tcal=None)[source]#
Compute the system temperature.
- Parameters:
- ref
Spectrum The reference spectrum.
- tcalNone or float
The calibration temperature in K. If
None, it will be estimated usingget_tcal().
- ref
- Returns:
- tsysfloat
The system temperature in K.
- property ifnum#
The intermediate frequency (IF) number.
- property plnum#
The polarization number.
- property scan#
The scan number.
- property twarm#
Vane temperature in K.