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 the flux have a shape with dimension greater than 1. The requirement is that the last dimension of flux match the length of the spectral_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, use SpectrumList. For more on this topic, see Overview of How Specutils Represents Spectra.

Parameters:
fluxQuantity

The flux data for this spectrum. This can be a simple Quantity, or an existing Spectrum1D or NDCube object.

spectral_axisQuantity or SpectralAxis

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.

wcsWCS or WCS

WCS information object that either has a spectral component or is only spectral.

velocity_convention{“relativistic”, “optical”, “radio”}

Convention used for velocity conversions.

rest_valueQuantity

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.

uncertaintyNDUncertainty

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.

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

Attributes Summary

array_axis_physical_types

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

bin_edges

combined_wcs

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

data

ndarray-like : The stored dataset.

dimensions

energy

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

extra_coords

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

flux

Converts the stored data and unit information into a quantity.

frequency

The spectral_axis as a Quantity in units of GHz

global_coords

Coordinate metadata which applies to the whole cube.

mask

any type : Mask for the dataset, if any.

meta

photon_flux

The flux density of photons as a Quantity, in units of photons per cm^2 per second per spectral_axis unit

plotter

A MatplotlibPlotter instance providing visualization methods.

psf

Image representation of the PSF for the dataset.

radial_velocity

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

read

Read and parse gridded N-dimensional data and return as an NDData-derived object.

redshift

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

rest_value

shape

spectral_axis

Returns the SpectralCoord object.

spectral_axis_direction

spectral_axis_unit

Deprecated since version v1.1.

spectral_wcs

Returns the spectral axes of the WCS

uncertainty

any type : Uncertainty in the dataset, if any.

unit

Unit : Unit for the dataset, if any.

velocity

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

velocity_convention

Returns the velocity convention

wavelength

The spectral_axis as a Quantity 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.

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

Deprecated since version v1.13.

plot([axes, plot_axes, axes_coordinates, ...])

Visualize the NDCube.

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

Downsample array by combining contiguous pixels into bins.

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

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

set_radial_velocity_to(radial_velocity)

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

set_redshift_to(redshift)

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

shift_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_flux_unit(unit[, equivalencies, ...])

Returns a new spectrum with a different flux unit

with_spectral_axis_unit(unit[, ...])

Returns a new spectrum with a different spectral axis unit.

with_spectral_unit(unit[, ...])

Deprecated since version v1.13.

with_velocity_convention(velocity_convention)

Attributes Documentation

array_axis_physical_types
bin_edges
combined_wcs
data

ndarray-like : The stored dataset.

dimensions
energy

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

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 a Quantity 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 by False and invalid ones with True.

meta = None
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:
outNDData subclass

NDData-basd object corresponding to file contents

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 is NDUncertainty but isn’t mandatory.

unit

Unit : Unit for the dataset, if any.

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 a Quantity 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, operand2NDData-like instance

If operand2 is None or not given it will perform the operation self + operand. If operand2 is given it will perform operand + operand2. If the method was called on a class rather than on the instance operand2 must be given.

propagate_uncertaintiesbool or None, optional

If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

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' or None, 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 results mask and if necessary provide a copy. Default is numpy.logical_or.

New in version 1.2.

handle_metacallable, 'first_found' or None, 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 results meta and if necessary provide a copy. Default is None.

New in version 1.2.

compare_wcscallable, 'first_found' or None, 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 the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError 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.

Returns:
resultNDData-like

The resulting dataset

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs 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, or self.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, unless pixel_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 returns Quantity 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, or self.combined_wcs, combing both the WCS and extra coords. Defaults to the .wcs property.

Returns:
axes_coords: tuple of Quantity

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.

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 an Quantity 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:
Spectrum1D or Quantity
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 from crop() 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 or Unit 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, operand2NDData-like instance

If operand2 is None or not given it will perform the operation self / operand. If operand2 is given it will perform operand / operand2. If the method was called on a class rather than on the instance operand2 must be given.

propagate_uncertaintiesbool or None, optional

If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

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' or None, 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 results mask and if necessary provide a copy. Default is numpy.logical_or.

New in version 1.2.

handle_metacallable, 'first_found' or None, 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 results meta and if necessary provide a copy. Default is None.

New in version 1.2.

compare_wcscallable, 'first_found' or None, 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 the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError 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.

Returns:
resultNDData-like

The resulting dataset

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs 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:
axisint

The array axis along which the data is to be changed.

Returns:
resultndcube.NDCubeSequence
max(**kwargs)[source]
mean(**kwargs)[source]
median(**kwargs)[source]
min(**kwargs)[source]
classmethod multiply(operand, operand2=None, **kwargs)

Performs multiplication by evaluating self * operand.

Parameters:
operand, operand2NDData-like instance

If operand2 is None or not given it will perform the operation self * operand. If operand2 is given it will perform operand * operand2. If the method was called on a class rather than on the instance operand2 must be given.

propagate_uncertaintiesbool or None, optional

If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

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' or None, 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 results mask and if necessary provide a copy. Default is numpy.logical_or.

New in version 1.2.

handle_metacallable, 'first_found' or None, 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 results meta and if necessary provide a copy. Default is None.

New in version 1.2.

compare_wcscallable, 'first_found' or None, 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 the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError 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.

Returns:
resultNDData-like

The resulting dataset

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs 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)

Deprecated since version v1.13: The new_flux_unit function is deprecated and may be removed in a future version. Use with_flux_unit instead.

plot(axes=None, plot_axes=None, axes_coordinates=None, axes_units=None, data_unit=None, wcs=None, **kwargs)

Visualize the NDCube.

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

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

plot_axes: `list`, optional

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

axes_unit: `list`, optional

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

axes_coordinates: `list`, optional

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

data_unit: `astropy.units.Unit`

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

wcs: `astropy.wcs.wcsapi.BaseHighLevelWCS`

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

kwargs

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

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 is None. Default is numpy.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 custom propagate_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.

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 not astropy.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 or None

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.
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_wcsastropy.wcs.wcsapi.BaseHighLevelWCS, astropy.wcs.wcsapi.BaseLowLevelWCS,

or astropy.io.fits.Header The WCS object to which the ndcube.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 the target_wcs is used.

return_footprintbool

If True the footprint is returned in addition to the new NDCube. Defaults to False.

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

Returns:
reprojected_cubendcube.NDCube

A new resultant NDCube object, the supplied target_wcs will be the .wcs attribute of the output NDCube.

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.

Notes

This method doesn’t support handling of the mask, extra_coords, and uncertainty attributes yet. However, meta and global_coords are copied to the output ndcube.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 the spectral_axis.

If you want to shift the spectral_axis based on this value, use shift_spectrum_to.

set_redshift_to(redshift)[source]

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

If you want to shift the spectral_axis based on this value, use shift_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, use set_redshift_to or set_radial_velocity_to.

classmethod subtract(operand, operand2=None, **kwargs)

Performs subtraction by evaluating self - operand.

Parameters:
operand, operand2NDData-like instance

If operand2 is None or not given it will perform the operation self - operand. If operand2 is given it will perform operand - operand2. If the method was called on a class rather than on the instance operand2 must be given.

propagate_uncertaintiesbool or None, optional

If None the result will have no uncertainty. If False the result will have a copied version of the first operand that has an uncertainty. If True the result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default is True.

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' or None, 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 results mask and if necessary provide a copy. Default is numpy.logical_or.

New in version 1.2.

handle_metacallable, 'first_found' or None, 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 results meta and if necessary provide a copy. Default is None.

New in version 1.2.

compare_wcscallable, 'first_found' or None, 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 the wcs. The resulting wcs will be like if False was given otherwise it raises a ValueError 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.

Returns:
resultNDData-like

The resulting dataset

Notes

If a callable is used for mask, wcs or meta the callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined as kwargs 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".

sum(**kwargs)[source]
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_flux_unit(unit, equivalencies=None, suppress_conversion=False)

Returns a new spectrum with a different flux unit

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.

Returns:
Spectrum1D

A new spectrum with the converted flux array

with_spectral_axis_unit(unit, velocity_convention=None, rest_value=None)

Returns a new spectrum with a different spectral axis unit. Note that this creates a new object using the converted spectral axis and thus drops the original WCS, if it existed, replacing it with a lookup-table WCS based on the new spectral axis. The original WCS will be stored in the original_wcs entry of the new object’s meta dictionary.

Parameters:
unitUnit

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_valueQuantity

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.

with_spectral_unit(unit, velocity_convention=None, rest_value=None)

Deprecated since version v1.13: The with_spectral_unit function is deprecated and may be removed in a future version. Use with_spectral_axis_unit instead.

with_velocity_convention(velocity_convention)