Spectrum1D¶
- class specutils.Spectrum1D(flux=None, spectral_axis=None, wcs=None, velocity_convention=None, rest_value=None, redshift=None, radial_velocity=None, bin_specification=None, **kwargs)[source]¶
Bases:
OneDSpectrumMixin
,NDCube
,NDIOMixin
,NDArithmeticMixin
Spectrum container for 1D spectral data.
Note that “1D” in this case refers to the fact that there is only one spectral axis.
Spectrum1D
can contain “vector 1D spectra” by having theflux
have a shape with dimension greater than 1. The requirement is that the last dimension offlux
match the length of thespectral_axis
.For multidimensional spectra that are all the same shape but have different spectral axes, use a
SpectrumCollection
. For a collection of spectra that have different shapes, useSpectrumList
. For more on this topic, see Overview of How Specutils Represents Spectra.- Parameters:
- flux
Quantity
The flux data for this spectrum. This can be a simple
Quantity
, or an existingSpectrum1D
orNDCube
object.- spectral_axis
Quantity
orSpectralAxis
Dispersion information with the same shape as the last (or only) dimension of flux, or one greater than the last dimension of flux if specifying bin edges.
- wcs
WCS
orWCS
WCS information object that either has a spectral component or is only spectral.
- velocity_convention{“relativistic”, “optical”, “radio”}
Convention used for velocity conversions.
- rest_value
Quantity
Any quantity supported by the standard spectral equivalencies (wavelength, energy, frequency, wave number). Describes the rest value of the spectral axis for use with velocity conversions.
- redshift
See
redshift
for more information.- radial_velocity
See
radial_velocity
for more information.- bin_specificationstr
Either “edges” or “centers” to indicate whether the
spectral_axis
values represent edges of the wavelength bin, or centers of the bin.- uncertainty
NDUncertainty
Contains uncertainty information along with propagation rules for spectrum arithmetic. Can take a unit, but if none is given, will use the unit defined in the flux.
- mask
ndarray
-like Array where values in the flux to be masked are those that
astype(bool)
converts to True. (For example, integer arrays are not masked where they are 0, and masked for any other value.)- metadict
Arbitrary container for any user-specific information to be carried around with the spectrum container object.
- flux
Attributes Summary
Returns the WCS physical types that vary along each array axis.
The WCS transform for the NDCube, including the coordinates specified in
.extra_coords
.ndarray
-like : The stored dataset.The energy of the spectral axis as a
Quantity
in units of eV.Coordinates not described by
NDCubeABC.wcs
which vary along one or more axes.Converts the stored data and unit information into a quantity.
The
spectral_axis
as aQuantity
in units of GHzCoordinate metadata which applies to the whole cube.
any type : Mask for the dataset, if any.
dict
-like : Additional meta information about the dataset.The flux density of photons as a
Quantity
, in units of photons per cm^2 per second per spectral_axis unitA
MatplotlibPlotter
instance providing visualization methods.Image representation of the PSF for the dataset.
The radial velocity(s) of the objects represented by this spectrum.
Read and parse gridded N-dimensional data and return as an NDData-derived object.
The redshift(s) of the objects represented by this spectrum.
Returns the SpectralCoord object.
Deprecated since version v1.1.
Returns the spectral axes of the WCS
any type : Uncertainty in the dataset, if any.
Unit
: Unit for the dataset, if any.Converts the spectral axis array to the given velocity space unit given the rest value.
Returns the velocity convention
The
spectral_axis
as aQuantity
in units of Angstromsany type : A world coordinate system (WCS) for the dataset, if any.
Write this CCDData object out in the specified format.
Methods Summary
add
(operand[, operand2])Performs addition by evaluating
self
+operand
.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.
collapse
(method[, axis])Collapse the flux array given a method.
crop
(*points[, wcs])Crop using real world coordinates.
crop_by_values
(*points[, units, wcs])Crop using real world coordinates.
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.
max
(**kwargs)mean
(**kwargs)median
(**kwargs)min
(**kwargs)multiply
(operand[, operand2])Performs multiplication by evaluating
self
*operand
.new_flux_unit
(unit[, equivalencies, ...])Converts the flux data to the specified unit.
plot
(*args, **kwargs)A convenience function for the plotters default
plot()
method.rebin
(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
reproject_to
(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
set_radial_velocity_to
(radial_velocity)This sets the radial velocity of the spectrum to be
radial_velocity
without changing the values of thespectral_axis
.set_redshift_to
(redshift)This sets the redshift of the spectrum to be
redshift
without changing the values of thespectral_axis
.shift_spectrum_to
(*[, redshift, radial_velocity])This shifts in-place the values of the
spectral_axis
, given either a redshift or radial velocity.subtract
(operand[, operand2])Performs subtraction by evaluating
self
-operand
.sum
(**kwargs)to
(new_unit, **kwargs)Convert instance to another unit.
with_spectral_unit
(unit[, ...])Returns a new spectrum with a different spectral axis unit.
with_velocity_convention
(velocity_convention)Attributes Documentation
- array_axis_physical_types¶
- bin_edges¶
- combined_wcs¶
- dimensions¶
- extra_coords¶
- flux¶
Converts the stored data and unit information into a quantity.
- Returns:
Quantity
Spectral data as a quantity.
- frequency¶
The
spectral_axis
as aQuantity
in units of GHz
- global_coords¶
- mask¶
any type : Mask for the dataset, if any.
Masks should follow the
numpy
convention that valid data points are marked byFalse
and invalid ones withTrue
.
- photon_flux¶
The flux density of photons as a
Quantity
, in units of photons per cm^2 per second per spectral_axis unit
- plotter = None¶
A
MatplotlibPlotter
instance providing visualization methods.The type of this attribute can be changed to provide custom visualization functionality.
- psf¶
- radial_velocity¶
The radial velocity(s) of the objects represented by this spectrum. May be scalar (if this spectrum’s
flux
is 1D) or vector. Note that the concept of “RV of a spectrum” can be ambiguous, so the interpretation is set to some extent by either the user, or operations (like template fitting) that set this attribute when they are run on a spectrum.
- read¶
Read and parse gridded N-dimensional data and return as an NDData-derived object.
This function provides the NDDataBase interface to the astropy unified I/O layer. This allows easily reading a file in the supported data formats, for example:
>>> from astropy.nddata import CCDData >>> dat = CCDData.read('image.fits')
Get help on the available readers for
CCDData
using the``help()`` method:>>> CCDData.read.help() # Get help reading CCDData and list supported formats >>> CCDData.read.help('fits') # Get detailed help on CCDData FITS reader >>> CCDData.read.list_formats() # Print list of available formats
For more information see:
- Parameters:
- *argstuple, optional
Positional arguments passed through to data reader. If supplied the first argument is the input filename.
- formatstr, optional
File format specifier.
- cachebool, optional
Caching behavior if file is a URL.
- **kwargsdict, optional
Keyword arguments passed through to data reader.
- Returns:
- out
NDData
subclass NDData-basd object corresponding to file contents
- out
- redshift¶
The redshift(s) of the objects represented by this spectrum. May be scalar (if this spectrum’s
flux
is 1D) or vector. Note that the concept of “redshift of a spectrum” can be ambiguous, so the interpretation is set to some extent by either the user, or operations (like template fitting) that set this attribute when they are run on a spectrum.
- rest_value¶
- shape¶
- spectral_axis¶
Returns the SpectralCoord object.
- spectral_axis_direction¶
- spectral_axis_unit¶
Deprecated since version v1.1: The spectral_axis_unit function is deprecated and may be removed in a future version. Use spectral_axis.unit instead.
Returns the units of the spectral axis.
- spectral_wcs¶
Returns the spectral axes of the WCS
- uncertainty¶
any type : Uncertainty in the dataset, if any.
Should have an attribute
uncertainty_type
that defines what kind of uncertainty is stored, such as'std'
for standard deviation or'var'
for variance. A metaclass defining such an interface isNDUncertainty
but isn’t mandatory.
- velocity¶
Converts the spectral axis array to the given velocity space unit given the rest value.
These aren’t input parameters but required Spectrum attributes
- Parameters:
- unitstr or ~`astropy.units.Unit`
The unit to convert the dispersion array to.
- rest~`astropy.units.Quantity`
Any quantity supported by the standard spectral equivalencies (wavelength, energy, frequency, wave number).
- type{“doppler_relativistic”, “doppler_optical”, “doppler_radio”}
The type of doppler spectral equivalency.
- redshift or radial_velocity
If present, this shift is applied to the final output velocity to get into the rest frame of the object.
- Returns:
- ~`astropy.units.Quantity`
The converted dispersion array in the new dispersion space.
- velocity_convention¶
Returns the velocity convention
- wavelength¶
The
spectral_axis
as aQuantity
in units of Angstroms
- wcs¶
any type : A world coordinate system (WCS) for the dataset, if any.
- write¶
Write this CCDData object out in the specified format.
This function provides the NDData interface to the astropy unified I/O layer. This allows easily writing a file in many supported data formats using syntax such as:
>>> from astropy.nddata import CCDData >>> dat = CCDData(np.zeros((12, 12)), unit='adu') # 12x12 image of zeros >>> dat.write('zeros.fits')
Get help on the available writers for
CCDData
using the``help()`` method:>>> CCDData.write.help() # Get help writing CCDData and list supported formats >>> CCDData.write.help('fits') # Get detailed help on CCDData FITS writer >>> CCDData.write.list_formats() # Print list of available formats
For more information see:
- Parameters:
- *argstuple, optional
Positional arguments passed through to data writer. If supplied the first argument is the output filename.
- formatstr, optional
File format specifier.
- **kwargsdict, optional
Keyword arguments passed through to data writer.
Methods Documentation
- classmethod add(operand, operand2=None, **kwargs)¶
Performs addition by evaluating
self
+operand
.- Parameters:
- operand, operand2
NDData
-like instance If
operand2
isNone
or not given it will perform the operationself
+operand
. Ifoperand2
is given it will performoperand
+operand2
. If the method was called on a class rather than on the instanceoperand2
must be given.- propagate_uncertainties
bool
orNone
, optional If
None
the result will have no uncertainty. IfFalse
the result will have a copied version of the first operand that has an uncertainty. IfTrue
the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties areNDUncertainty
-like. Default isTrue
.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
None
was added as valid parameter value.- handle_maskcallable,
'first_found'
orNone
, optional If
None
the result will have no mask. If'first_found'
the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the resultsmask
and if necessary provide a copy. Default isnumpy.logical_or
.New in version 1.2.
- handle_metacallable,
'first_found'
orNone
, optional If
None
the result will have no meta. If'first_found'
the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the resultsmeta
and if necessary provide a copy. Default isNone
.New in version 1.2.
- compare_wcscallable,
'first_found'
orNone
, optional If
None
the result will have no wcs and no comparison between the wcs of the operands is made. If'first_found'
the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare thewcs
. The resultingwcs
will be like ifFalse
was given otherwise it raises aValueError
if the comparison was not successful. Default is'first_found'
.New in version 1.2.
- uncertainty_correlationnumber or
ndarray
, optional The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.
New in version 1.2.
- kwargs
Any other parameter that should be passed to the callables used.
- operand, operand2
- Returns:
- result
NDData
-like The resulting dataset
- result
Notes
If a
callable
is used formask
,wcs
ormeta
the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargs
and must start with"wcs_"
(for wcs callable) or"meta_"
(for meta callable). This startstring is removed before the callable is called."first_found"
can also be abbreviated with"ff"
.
- axis_world_coords(*axes, pixel_corners=False, wcs=None)¶
Returns objects representing the world coordinates of pixel centers for a desired axes.
- Parameters:
- axes: `int` or `str`, or multiple `int` or `str`, optional
Axis number in numpy ordering or unique substring of
ndcube.NDCube.wcs.world_axis_physical_types
of axes for which real world coordinates are desired. Not specifying axes inputs causes results for all axes to be returned.- pixel_corners: `bool`, optional
If
True
then instead of returning the coordinates at the centers of the pixels, the coordinates at the pixel corners will be returned. This increases the size of the output by 1 in all dimensions as all corners are returned.- wcs: `astropy.wcs.wcsapi.BaseHighLevelWCS`, optional
The WCS object to used to calculate the world coordinates. Although technically this can be any valid WCS, it will typically be
self.wcs
,self.extra_coords
, orself.combined_wcs
combining both the WCS and extra coords. Default=self.wcs- Returns
- ——-
- axes_coords: iterable
An iterable of “high level” objects giving the real world coords for the axes requested by user. For example, a tuple of
SkyCoord
objects. The types returned are determined by the WCS object. The dimensionality of these objects should match that of their corresponding array dimensions, unlesspixel_corners=True
in which case the length along each axis will be 1 greater than the number of pixels.- Examples
- ——–
- >>> NDCube.axis_world_coords(‘lat’, ‘lon’) # doctest: +SKIP
- >>> NDCube.axis_world_coords(2) # doctest: +SKIP
- axis_world_coords_values(*axes, pixel_corners=False, wcs=None)¶
Returns the world coordinate values of all pixels for desired axes. In contrast to
ndcube.NDCube.axis_world_coords()
, this method returnsQuantity
objects. Which only provide units rather than full coordinate metadata provided by high-level coordinate objects.- Parameters:
- axes: `int` or `str`, or multiple `int` or `str`, optional
Axis number in numpy ordering or unique substring of
ndcube.NDCube.wcs.world_axis_physical_types
of axes for which real world coordinates are desired. axes=None implies all axes will be returned.- pixel_corners: `bool`, optional
If
True
then coordinates at pixel corners will be returned rather than at pixel centers. This increases the size of the output along each dimension by 1 as all corners are returned.- wcs: `~astropy.wcs.wcsapi.BaseHighLevelWCS` or `~ndcube.ExtraCoordsABC`, optional
The WCS object to be used to calculate the world coordinates. Although technically this can be any valid WCS, it will typically be
self.wcs
,self.extra_coords
, orself.combined_wcs
, combing both the WCS and extra coords. Defaults to the.wcs
property.
- Returns:
- axes_coords:
tuple
ofQuantity
An iterable of raw coordinate values for all pixels for the requested axes. The returned units are determined by the WCS object. The dimensionality of these objects should match that of their corresponding array dimensions, unless
pixel_corners=True
in which case the length along each axis will be 1 greater than the number of pixels.
- axes_coords:
Examples
>>> NDCube.axis_world_coords_values('lat', 'lon') >>> NDCube.axis_world_coords_values(2)
- collapse(method, axis=None)[source]¶
Collapse the flux array given a method. Will collapse either to a single value (default), over a specified numerical axis or axes if specified, or over the spectral or non-spectral axes if
physical_type
is specified.If the collapse leaves the spectral axis unchanged, a
Spectrum1D
will be returned. Otherwise anQuantity
array will be returned.Note that these calculations are not currently uncertainty-aware, but do respect masks.
- Parameters:
- methodstr, function
The method by which the flux will be collapsed. String options are ‘mean’, ‘min’, ‘max’, ‘sum’, and ‘median’. Also accepts a function as input, which must take an
astropy.units.Quantity
array as input and accept an ‘axis’ argument.- axisint, tuple, str, optional
The axis or axes over which to collapse the flux array. May also be a string, either ‘spectral’ to collapse over the spectral axis, or ‘spatial’ to collapse over all other axes.
- Returns:
- crop(*points, wcs=None)¶
Crop using real world coordinates. This method crops the NDCube to the smallest bounding box in pixel space that contains all the provided world coordinate points.
This function takes the points defined as high-level astropy coordinate objects such as
SkyCoord
,SpectralCoord
, etc.- Parameters:
- points: iterable of iterables
Tuples of high level coordinate objects e.g.
SkyCoord
. Each iterable of coordinate objects represents a single location in the data array in real world coordinates.The coordinates of the points as they are passed to
world_to_array_index
. Therefore their number and order must be compatible with the API of that method, i.e. they must be passed in world order.- wcs: `~astropy.wcs.wcsapi.BaseHighLevelWCS` or `~ndcube.ExtraCoordsABC`
The WCS to use to calculate the pixel coordinates based on the input. Will default to the
.wcs
property if not given. While any valid WCS could be used it is expected that either the.wcs
or.extra_coords
properties will be used.
- Returns:
NDCubeABC
Examples
An example of cropping a region of interest on the Sun from a 3-D image-time cube: >>> point1 = [SkyCoord(-50*u.deg, -40*u.deg, frame=frames.HeliographicStonyhurst), None] # doctest: +SKIP >>> point2 = [SkyCoord(0*u.deg, -6*u.deg, frame=frames.HeliographicStonyhurst), None] # doctest: +SKIP >>> NDCube.crop(point1, point2) # doctest: +SKIP
- crop_by_values(*points, units=None, wcs=None)¶
Crop using real world coordinates. This method crops the NDCube to the smallest bounding box in pixel space that contains all the provided world coordinate points.
This function takes points as iterables of low-level coordinate objects, i.e.
Quantity
objects. This differs fromcrop()
which takes high-level coordinate objects requiring all the relevant coordinate information such as coordinate frame etc. Hence this method’s API is more basic but less explicit.- Parameters:
- points: iterable
Tuples of coordinate values, the length of the tuples must be equal to the number of world dimensions. These points are passed to
wcs.world_to_array_index_values
so their units and order must be compatible with that method.- units: `str` or `~astropy.units.Unit`
If the inputs are set without units, the user must set the units inside this argument as
str
orUnit
objects. The length of the iterable must equal the number of world dimensions and must have the same order as the coordinate points.- wcs: `~astropy.wcs.wcsapi.BaseHighLevelWCS` or `~ndcube.ExtraCoordsABC`
The WCS to use to calculate the pixel coordinates based on the input. Will default to the
.wcs
property if not given. While any valid WCS could be used it is expected that either the.wcs
or.extra_coords
properties will be used.
- Returns:
NDCubeABC
Examples
An example of cropping a region of interest on the Sun from a 3-D image-time cube: >>> NDCube.crop_by_values((-600, -600, 0), (0, 0, 0), units=(u.arcsec, u.arcsec, u.s)) # doctest: +SKIP
- classmethod divide(operand, operand2=None, **kwargs)¶
Performs division by evaluating
self
/operand
.- Parameters:
- operand, operand2
NDData
-like instance If
operand2
isNone
or not given it will perform the operationself
/operand
. Ifoperand2
is given it will performoperand
/operand2
. If the method was called on a class rather than on the instanceoperand2
must be given.- propagate_uncertainties
bool
orNone
, optional If
None
the result will have no uncertainty. IfFalse
the result will have a copied version of the first operand that has an uncertainty. IfTrue
the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties areNDUncertainty
-like. Default isTrue
.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
None
was added as valid parameter value.- handle_maskcallable,
'first_found'
orNone
, optional If
None
the result will have no mask. If'first_found'
the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the resultsmask
and if necessary provide a copy. Default isnumpy.logical_or
.New in version 1.2.
- handle_metacallable,
'first_found'
orNone
, optional If
None
the result will have no meta. If'first_found'
the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the resultsmeta
and if necessary provide a copy. Default isNone
.New in version 1.2.
- compare_wcscallable,
'first_found'
orNone
, optional If
None
the result will have no wcs and no comparison between the wcs of the operands is made. If'first_found'
the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare thewcs
. The resultingwcs
will be like ifFalse
was given otherwise it raises aValueError
if the comparison was not successful. Default is'first_found'
.New in version 1.2.
- uncertainty_correlationnumber or
ndarray
, optional The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.
New in version 1.2.
- kwargs
Any other parameter that should be passed to the callables used.
- operand, operand2
- Returns:
- result
NDData
-like The resulting dataset
- result
Notes
If a
callable
is used formask
,wcs
ormeta
the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargs
and must start with"wcs_"
(for wcs callable) or"meta_"
(for meta callable). This startstring is removed before the callable is called."first_found"
can also be abbreviated with"ff"
.
- explode_along_axis(axis)¶
Separates slices of NDCubes along a given axis into an NDCubeSequence of (N-1)DCubes.
- Parameters:
- axis
int
The array axis along which the data is to be changed.
- axis
- Returns:
- result
ndcube.NDCubeSequence
- result
- classmethod multiply(operand, operand2=None, **kwargs)¶
Performs multiplication by evaluating
self
*operand
.- Parameters:
- operand, operand2
NDData
-like instance If
operand2
isNone
or not given it will perform the operationself
*operand
. Ifoperand2
is given it will performoperand
*operand2
. If the method was called on a class rather than on the instanceoperand2
must be given.- propagate_uncertainties
bool
orNone
, optional If
None
the result will have no uncertainty. IfFalse
the result will have a copied version of the first operand that has an uncertainty. IfTrue
the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties areNDUncertainty
-like. Default isTrue
.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
None
was added as valid parameter value.- handle_maskcallable,
'first_found'
orNone
, optional If
None
the result will have no mask. If'first_found'
the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the resultsmask
and if necessary provide a copy. Default isnumpy.logical_or
.New in version 1.2.
- handle_metacallable,
'first_found'
orNone
, optional If
None
the result will have no meta. If'first_found'
the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the resultsmeta
and if necessary provide a copy. Default isNone
.New in version 1.2.
- compare_wcscallable,
'first_found'
orNone
, optional If
None
the result will have no wcs and no comparison between the wcs of the operands is made. If'first_found'
the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare thewcs
. The resultingwcs
will be like ifFalse
was given otherwise it raises aValueError
if the comparison was not successful. Default is'first_found'
.New in version 1.2.
- uncertainty_correlationnumber or
ndarray
, optional The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.
New in version 1.2.
- kwargs
Any other parameter that should be passed to the callables used.
- operand, operand2
- Returns:
- result
NDData
-like The resulting dataset
- result
Notes
If a
callable
is used formask
,wcs
ormeta
the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargs
and must start with"wcs_"
(for wcs callable) or"meta_"
(for meta callable). This startstring is removed before the callable is called."first_found"
can also be abbreviated with"ff"
.
- new_flux_unit(unit, equivalencies=None, suppress_conversion=False)¶
Converts the flux data to the specified unit. This is an in-place change to the object.
- Parameters:
- unitstr or
Unit
The unit to convert the flux array to.
- equivalencieslist of equivalencies
Custom equivalencies to apply to conversions. Set to spectral_density by default.
- suppress_conversionbool
Set to true if updating the unit without converting data values.
- unitstr or
- Returns:
Spectrum1D
A new spectrum with the converted flux array
- plot(*args, **kwargs)¶
A convenience function for the plotters default
plot()
method.Calling this method is the same as calling
cube.plotter.plot
, the behaviour of this method can change if thendcube.NDCube.plotter
class is set to a differentPlotter
class.
- rebin(bin_shape, operation=<function mean>, operation_ignores_mask=False, handle_mask=<function all>, propagate_uncertainties=False, new_unit=None, **kwargs)¶
Downsample array by combining contiguous pixels into bins.
Values in bins are determined by applying a function to the pixel values within it. The number of pixels in each bin in each dimension is given by the bin_shape input. This must be an integer fraction of the cube’s array size in each dimension. If the NDCube instance has uncertainties attached, they are propagated depending on binning method chosen.
- Parameters:
- bin_shapearray-like
The number of pixels in a bin in each dimension. Must be the same length as number of dimensions in data. Each element must be in int. If they are not they will be rounded to the nearest int.
- operationfunction
Function applied to the data to derive values of the bins. Default is
numpy.mean
- operation_ignores_mask: `bool`
Determines how masked values are handled. If False (default), masked values are excluded when calculating rebinned value. If True, masked values are used in calculating rebinned value.
- handle_mask: `None` or function
Function to apply to each bin in the mask to calculate the new mask values. If
None
resultant mask isNone
. Default isnumpy.all
- propagate_uncertainties: `bool` or function.
If False, uncertainties are dropped. If True, default algorithm is used (
propagate_rebin_uncertainties
) Can also be set to a function which performs custom uncertainty propagation. Additional kwargs provided to this method are passed onto this function. See Notes section on how to write a custompropagate_uncertainties
function.- new_unit: `astropy.units.Unit`, optional
If the rebinning operation alters the data unit, the new unit can be provided here.
- kwargs
All kwargs are passed to the error propagation function.
- Returns:
- new_cube:
NDCube
The resolution-degraded cube.
- new_cube:
Notes
Rebining Algorithm Rebinning is achieved by reshaping the N-D array to a 2N-D array and applying the function over the odd-numbered axes. To demonstrate, consider the following example. Let’s say you have an array:
x = np.array([[0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1, 1], [0, 0, 1, 0, 0, 0]])
and you want to sum over 2x2 non-overlapping sub-arrays. This summing can be done by reshaping the array:
y = x.reshape(3,2,3,2)
and then summing over the 1st and third directions:
y2 = y.sum(axis=3).sum(axis=1)
which gives the expected array:
array([[0, 3, 2], [2, 0, 4], [1, 2, 2]])
Defining Custom Error Propagation To perform custom uncertainty propagation, a function must be provided via the propgate_uncertainty kwarg. This function must accept, although doesn’t have to use, the following args:
- uncertainty:
astropy.nddata.NDUncertainty
but notastropy.nddata.UnknownUncertainty
The uncertainties associated with the data.
- data: array-like
The data associated with the above uncertainties. Must have same shape as uncertainty.
- mask: array-like of
bool
orNone
Indicates whether any uncertainty elements should be ignored in propagation. True elements cause corresponding uncertainty elements to be ignored. False elements cause corresponding uncertainty elements to be propagated. Must have same shape as above. If None, no uncertainties are ignored.
All kwarg inputs to the rebin method are also passed on transparently to the propagation function. Hence additional inputs to the propagation function can be included as kwargs to
ndcube.NDCube.rebin()
.The shape of the uncertainty, data and mask inputs are such that the first dimension represents the pixels in a given bin whose data and uncertainties are aggregated by the rebin process. The shape of the remaining dimensions must be the same as the final rebinned data. A silly but informative example of a custom propagation function might be:
def my_propagate(uncertainty, data, mask, **kwargs): # As a silly example, propagate uncertainties by summing those in same bin. # Note not all args are used, but function must accept them. n_pixels_per_bin = data.shape[0] # 1st dimension of inputs gives pixels in bin. final_shape = data.shape[1:] # Trailing dims give shape of put rebinned data. # Propagate uncerts by adding them. new_uncert = numpy.zeros(final_shape) for i in range(n_pixels_per_bin): new_uncert += uncertainty.array[i] # Alternatively: new_uncerts = uncertainty.array.sum(axis=0) return type(uncertainty)(new_uncert) # Convert to original uncert type and return.
References
https://mail.scipy.org/pipermail/numpy-discussion/2010-July/051760.html
- reproject_to(target_wcs, algorithm='interpolation', shape_out=None, return_footprint=False, **reproject_args)¶
Reprojects the instance to the coordinates described by another WCS object.
- Parameters:
- target_wcs
astropy.wcs.wcsapi.BaseHighLevelWCS
,astropy.wcs.wcsapi.BaseLowLevelWCS
, or
astropy.io.fits.Header
The WCS object to which thendcube.NDCube
is to be reprojected.- algorithm: {‘interpolation’ | ‘adaptive’ | ‘exact’}
The algorithm to use for reprojecting. When set to “interpolation”
reproject_interp
is used, when set to “adaptive”reproject_adaptive
is used and when set to “exact”reproject_exact
is used.- shape_out: `tuple`, optional
The shape of the output data array. The ordering of the dimensions must follow NumPy ordering and not the WCS pixel shape. If not specified,
array_shape
attribute (if available) from the low level API of thetarget_wcs
is used.- return_footprint
bool
If
True
the footprint is returned in addition to the newNDCube
. Defaults toFalse
.- **reproject_args
All other arguments are passed through to the reproject function being called. The function being called depends on the
algorithm=
keyword argument, see that for more details.
- target_wcs
- Returns:
- reprojected_cube
ndcube.NDCube
A new resultant NDCube object, the supplied
target_wcs
will be the.wcs
attribute of the outputNDCube
.- footprint:
numpy.ndarray
Footprint of the input array in the output array. Values of 0 indicate no coverage or valid values in the input image, while values of 1 indicate valid values.
- reprojected_cube
Notes
This method doesn’t support handling of the
mask
,extra_coords
, anduncertainty
attributes yet. However,meta
andglobal_coords
are copied to the outputndcube.NDCube
.
- set_radial_velocity_to(radial_velocity)[source]¶
This sets the radial velocity of the spectrum to be
radial_velocity
without changing the values of thespectral_axis
.If you want to shift the
spectral_axis
based on this value, useshift_spectrum_to
.
- set_redshift_to(redshift)[source]¶
This sets the redshift of the spectrum to be
redshift
without changing the values of thespectral_axis
.If you want to shift the
spectral_axis
based on this value, useshift_spectrum_to
.
- shift_spectrum_to(*, redshift=None, radial_velocity=None)[source]¶
This shifts in-place the values of the
spectral_axis
, given either a redshift or radial velocity.If you do not want to change the
spectral_axis
, useset_redshift_to
orset_radial_velocity_to
.
- classmethod subtract(operand, operand2=None, **kwargs)¶
Performs subtraction by evaluating
self
-operand
.- Parameters:
- operand, operand2
NDData
-like instance If
operand2
isNone
or not given it will perform the operationself
-operand
. Ifoperand2
is given it will performoperand
-operand2
. If the method was called on a class rather than on the instanceoperand2
must be given.- propagate_uncertainties
bool
orNone
, optional If
None
the result will have no uncertainty. IfFalse
the result will have a copied version of the first operand that has an uncertainty. IfTrue
the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties areNDUncertainty
-like. Default isTrue
.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
None
was added as valid parameter value.- handle_maskcallable,
'first_found'
orNone
, optional If
None
the result will have no mask. If'first_found'
the result will have a copied version of the first operand that has a mask). If it is a callable then the specified callable must create the resultsmask
and if necessary provide a copy. Default isnumpy.logical_or
.New in version 1.2.
- handle_metacallable,
'first_found'
orNone
, optional If
None
the result will have no meta. If'first_found'
the result will have a copied version of the first operand that has a (not empty) meta. If it is a callable then the specified callable must create the resultsmeta
and if necessary provide a copy. Default isNone
.New in version 1.2.
- compare_wcscallable,
'first_found'
orNone
, optional If
None
the result will have no wcs and no comparison between the wcs of the operands is made. If'first_found'
the result will have a copied version of the first operand that has a wcs. If it is a callable then the specified callable must compare thewcs
. The resultingwcs
will be like ifFalse
was given otherwise it raises aValueError
if the comparison was not successful. Default is'first_found'
.New in version 1.2.
- uncertainty_correlationnumber or
ndarray
, optional The correlation between the two operands is used for correct error propagation for correlated data as given in: https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas Default is 0.
New in version 1.2.
- kwargs
Any other parameter that should be passed to the callables used.
- operand, operand2
- Returns:
- result
NDData
-like The resulting dataset
- result
Notes
If a
callable
is used formask
,wcs
ormeta
the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargs
and must start with"wcs_"
(for wcs callable) or"meta_"
(for meta callable). This startstring is removed before the callable is called."first_found"
can also be abbreviated with"ff"
.
- to(new_unit, **kwargs)¶
Convert instance to another unit.
Converts the data, uncertainty and unit and returns a new instance with other attributes unchanged.
- Parameters:
- new_unit: `astropy.units.Unit`
The unit to convert to.
- kwargs:
Passed to the unit conversion method, self.unit.to.
- Returns:
- :
NDCube
A new instance with the new unit and data and uncertainties scales accordingly.
- :
- with_spectral_unit(unit, velocity_convention=None, rest_value=None)¶
Returns a new spectrum with a different spectral axis unit.
- Parameters:
- unit
Unit
Any valid spectral unit: velocity, (wave)length, or frequency. Only vacuum units are supported.
- velocity_convention‘relativistic’, ‘radio’, or ‘optical’
The velocity convention to use for the output velocity axis. Required if the output type is velocity. This can be either one of the above strings, or an
astropy.units
equivalency.- rest_value
Quantity
A rest wavelength or frequency with appropriate units. Required if output type is velocity. The spectrum’s WCS should include this already if the input type is velocity, but the WCS’s rest wavelength/frequency can be overridden with this parameter.
- unit
- with_velocity_convention(velocity_convention)¶