milespy.spectra.Spectra
- class milespy.spectra.Spectra(*args, **kwargs)
Bases:
SpectrumClass for storing spectra in milespy.
This class inherits Spectrum from specutils, and can use all the methods of that class.
The main difference is how we use the meta dictionary. We assume that all the values stored in meta have the same lengths as the number of spectra. Thus, each value of each key univoquely refers to some information of a given spectra. The exact keys in this dictionary will depend on the model creating this object.
- Attributes:
array_axis_physical_typesReturns the WCS physical types that vary along each array axis.
- bin_edges
combined_wcsThe WCS transform for the NDCube, including the coordinates specified in
.extra_coords.data~numpy.ndarray - like
dimShape of the spectrum array excluding the spectral axis (e.g.
- dimensions
energyThe energy of the spectral axis as a ~astropy.units.Quantity in units of eV.
extra_coordsCoordinates not described by
NDCubeABC.wcswhich vary along one or more axes.fluxConverts the stored data and unit information into a quantity.
frequencyThe spectral_axis as a ~astropy.units.Quantity in units of GHz
global_coordsCoordinate metadata which applies to the whole cube.
maskany type : Mask for the dataset, if any.
- meta
npixNumber of spectral pixels (length of the spectral axis).
nspecTotal number of spectra (product of non-spectral dimensions).
photon_fluxThe flux density of photons as a ~astropy.units.Quantity, in units of
- plotter
propertiesList of metadata keys (e.g.
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_value
- shape
spectral_axisReturns the SpectralCoord object.
- spectral_axis_direction
- spectral_axis_index
spectral_wcsReturns the spectral axes of the WCS
uncertaintyany type : Uncertainty in the dataset, if any.
unit~astropy.units.Unit : 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
wavelengthThe spectral_axis as a ~astropy.units.Quantity in units of Angstroms
wcsany type : A world coordinate system (WCS) for the dataset, if any.
Methods
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.
convolve([lsf, lsf_wave])Convolve the spectra with a Gaussian kernel given by the line-spread function (LSF).
crop(*points[, wcs, keepdims])Crop using real world coordinates.
crop_by_values(*points[, units, wcs, keepdims])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.
line_strength(indeces)Compute line-strength (Lick/IDS) indices for the spectra.
magnitudes([filters, zeropoint])Compute magnitudes in the given filters (AB or Vega zeropoint).
mass_to_light(filters[, mass_in])Compute mass-to-light (M/L) ratios in the desired filters.
multiply(operand[, operand2])Performs multiplication by evaluating
self*operand.new_flux_unit(unit[, equivalencies, ...])plot([axes, plot_axes, axes_coordinates, ...])Visualize the ~ndcube.NDCube.
rebin(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
redshift_spectra([redshift])Return a copy with redshift and line-spread function (LSF) metadata updated.
reproject_to(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
resample(new_wave)Resample the spectra onto a new wavelength grid.
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.
squeeze([axis])Removes all axes with a length of 1.
subtract(operand[, operand2])Performs subtraction by evaluating
self-operand.to(new_unit, **kwargs)Convert instance to another unit.
tune_spectra([wave_lims, dwave, sampling, ...])Return a copy tuned to desired wavelength range, sampling, redshift, and LSF.
velocity_shift(v_los)Apply a line-of-sight velocity shift to the spectrum (Doppler shift).
with_flux_unit(unit[, equivalencies, ...])Returns a new spectrum with a different flux unit.
with_spectral_axis_and_flux_units(...[, ...])Perform
with_spectral_axis_unit()andwith_flux_unit()together.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[, ...])max
mean
median
min
read
sum
with_velocity_convention
write
- __init__(*args, **kwargs)
- classmethod add(operand, operand2=None, **kwargs)
Performs addition by evaluating
self+operand.- Parameters:
operand (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself+operand. Ifoperand2is given it will performoperand+operand2. If the method was called on a class rather than on the instanceoperand2must be given.operand2 (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself+operand. Ifoperand2is given it will performoperand+operand2. If the method was called on a class rather than on the instanceoperand2must be given.propagate_uncertainties (bool or
None, optional) –If
Nonethe result will have no uncertainty. IfFalsethe result will have a copied version of the first operand that has an uncertainty. IfTruethe result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default isTrue.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
Nonewas added as valid parameter value.handle_mask (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmaskand if necessary provide a copy. Default is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmetaand if necessary provide a copy. Default isNone.Added in version 1.2.
compare_wcs (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultingwcswill be like ifFalsewas given otherwise it raises aValueErrorif the comparison was not successful. Default is'first_found'.Added in version 1.2.
uncertainty_correlation (number or ~numpy.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.
Added in version 1.2.
- kwargs :
Any other parameter that should be passed to the callables used.
- Returns:
result – The resulting dataset
- Return type:
~astropy.nddata.NDData-like
Notes
If a
callableis used formask,wcsormetathe callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargsand 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".
- property array_axis_physical_types
Returns the WCS physical types that vary along each array axis.
Returns an iterable of tuples where each tuple corresponds to an array axis and holds strings denoting the WCS physical types associated with that array axis. Since multiple physical types can be associated with one array axis, tuples can be of different lengths. Likewise, as a single physical type can correspond to multiple array axes, the same physical type string can appear in multiple tuples.
The physical types returned by this property are drawn from the ~ndcube.NDCube.combined_wcs property so they include the coordinates contained in ~ndcube.NDCube.extra_coords.
- 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 <astropy.wcs.wcsapi.BaseWCSWrapper> 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_wcscombining both the WCS and extra coords. Default=self.wcs
- Returns:
axes_coords – An iterable of “high level” objects giving the real world coords for the axes requested by user. For example, a tuple of ~astropy.coordinates.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=Truein which case the length along each axis will be 1 greater than the number of pixels.- Return type:
iterable
Examples
>>> NDCube.axis_world_coords('lat', 'lon') >>> NDCube.axis_world_coords(2)
- 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 ~astropy.units.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 <astropy.wcs.wcsapi.BaseWCSWrapper> 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.wcsproperty.
- Returns:
axes_coords – 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=Truein which case the length along each axis will be 1 greater than the number of pixels.- Return type:
tuple of ~astropy.units.Quantity
Examples
>>> NDCube.axis_world_coords_values('lat', 'lon') >>> NDCube.axis_world_coords_values(2)
- collapse(method, axis=None)
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_typeis specified.If the collapse leaves the spectral axis unchanged, a ~specutils.Spectrum will be returned. Otherwise an ~astropy.units.Quantity array will be returned.
Note that these calculations are not currently uncertainty-aware, but do respect masks.
- Parameters:
method (str, 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.
axis (int, 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.
- Return type:
- property combined_wcs
The WCS transform for the NDCube, including the coordinates specified in
.extra_coords.This transform should implement the high level wcsapi, and have
pixel_n_dimequal to the number of array dimensions in the ~ndcube.NDCube. The number of world dimensions should be equal to the number of world dimensions inself.wcsand inself.extra_coordscombined.
- convolve(lsf=<Quantity 1. Angstrom>, lsf_wave=None)
Convolve the spectra with a Gaussian kernel given by the line-spread function (LSF).
The LSF is specified as FWHM (full width at half maximum) in wavelength. Convolution sigma is derived from the difference between target and current LSF. If target LSF is smaller than the current one, a very small sigma is used.
- crop(*points, wcs=None, keepdims=False)
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 ~astropy.coordinates.SkyCoord, ~astropy.coordinates.SpectralCoord, etc.
- Parameters:
points (iterable of iterables) –
Tuples of high level coordinate objects e.g. ~astropy.coordinates.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 ~astropy.wcs.wcsapi.BaseHighLevelWCS.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
.wcsproperty if not given. While any valid WCS could be used it is expected that either the.wcsor.extra_coordsproperties will be used.keepdims (bool, optional) – If False and if cropping results in length-1 dimensions, these are sliced away in output cube. If True, length-1 dimensions are kept. Default=False
- Return type:
~ndcube.ndcube.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] >>> point2 = [SkyCoord(0*u.deg, -6*u.deg, frame=frames.HeliographicStonyhurst), None] >>> NDCube.crop(point1, point2)
- crop_by_values(*points, units=None, wcs=None, keepdims=False)
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. ~astropy.units.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_valuesso 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 ~astropy.units.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
.wcsproperty if not given. While any valid WCS could be used it is expected that either the.wcsor.extra_coordsproperties will be used.keepdims (bool, optional) – If False and if cropping results in length-1 dimensions, these are sliced away in output cube. If True, length-1 dimensions are kept. Default=False
- Return type:
~ndcube.ndcube.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))
- property data
- ~numpy.ndarray - like
The stored dataset.
Notes
It is possible to set the
.dataattribute on a ~ndcube.NDCube with an array-like object of the same shape. However, this is really only intended for replacing the data with a different object representing the same physical data as no other properties of the cube will be changed, such as uncertainty or unit.
- property dim: tuple
Shape of the spectrum array excluding the spectral axis (e.g. (n_models,) or (ny, nx)).
- classmethod divide(operand, operand2=None, **kwargs)
Performs division by evaluating
self/operand.- Parameters:
operand (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself/operand. Ifoperand2is given it will performoperand/operand2. If the method was called on a class rather than on the instanceoperand2must be given.operand2 (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself/operand. Ifoperand2is given it will performoperand/operand2. If the method was called on a class rather than on the instanceoperand2must be given.propagate_uncertainties (bool or
None, optional) –If
Nonethe result will have no uncertainty. IfFalsethe result will have a copied version of the first operand that has an uncertainty. IfTruethe result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default isTrue.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
Nonewas added as valid parameter value.handle_mask (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmaskand if necessary provide a copy. Default is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmetaand if necessary provide a copy. Default isNone.Added in version 1.2.
compare_wcs (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultingwcswill be like ifFalsewas given otherwise it raises aValueErrorif the comparison was not successful. Default is'first_found'.Added in version 1.2.
uncertainty_correlation (number or ~numpy.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.
Added in version 1.2.
- kwargs :
Any other parameter that should be passed to the callables used.
- Returns:
result – The resulting dataset
- Return type:
~astropy.nddata.NDData-like
Notes
If a
callableis used formask,wcsormetathe callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargsand 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".
- property energy
The energy of the spectral axis as a ~astropy.units.Quantity in units of eV.
- 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.
- Returns:
result
- Return type:
ndcube.NDCubeSequence
- property extra_coords
Coordinates not described by
NDCubeABC.wcswhich vary along one or more axes.
- property flux
Converts the stored data and unit information into a quantity.
- Returns:
Spectral data as a quantity.
- Return type:
~astropy.units.Quantity
- property frequency
The spectral_axis as a ~astropy.units.Quantity in units of GHz
- property global_coords
Coordinate metadata which applies to the whole cube.
- line_strength(indeces)
Compute line-strength (Lick/IDS) indices for the spectra.
- Parameters:
indeces (list[LineStrengthIndex]) – Index definitions from
milespy.ls_indices.get_indices_from_database().- Returns:
Dictionary mapping index name to value (array or scalar per spectrum).
- Return type:
- magnitudes(filters=None, zeropoint='AB')
Compute magnitudes in the given filters (AB or Vega zeropoint).
- Parameters:
filters (list[Filter], optional) – Filters as provided by
milespy.filter.get_filters(). Default empty.zeropoint (str, optional) – ‘AB’ or ‘VEGA’.
- Returns:
Dictionary mapping filter name to magnitude (per spectrum).
- Return type:
- property mask
Mask for the dataset, if any.
Masks should follow the
numpyconvention that valid data points are marked byFalseand invalid ones withTrue.- Type:
any type
- mass_to_light(filters, mass_in='star+remn')
Compute mass-to-light (M/L) ratios in the desired filters.
Uses solar absolute magnitudes and the chosen mass component (total, stellar, remnant, star+remnant, or gas).
- Parameters:
filters (list[Filter]) – Filters as provided by
milespy.filter.get_filters().mass_in (str or list[str], optional) – Mass component: ‘total’, ‘star’, ‘remn’, ‘star+remn’, ‘gas’. If a list, returns a dict keyed by type.
- Returns:
Mass-to-light ratio per filter (and per mass type if mass_in is a list).
- Return type:
dict
- meta = None
- classmethod multiply(operand, operand2=None, **kwargs)
Performs multiplication by evaluating
self*operand.- Parameters:
operand (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself*operand. Ifoperand2is given it will performoperand*operand2. If the method was called on a class rather than on the instanceoperand2must be given.operand2 (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself*operand. Ifoperand2is given it will performoperand*operand2. If the method was called on a class rather than on the instanceoperand2must be given.propagate_uncertainties (bool or
None, optional) –If
Nonethe result will have no uncertainty. IfFalsethe result will have a copied version of the first operand that has an uncertainty. IfTruethe result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default isTrue.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
Nonewas added as valid parameter value.handle_mask (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmaskand if necessary provide a copy. Default is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmetaand if necessary provide a copy. Default isNone.Added in version 1.2.
compare_wcs (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultingwcswill be like ifFalsewas given otherwise it raises aValueErrorif the comparison was not successful. Default is'first_found'.Added in version 1.2.
uncertainty_correlation (number or ~numpy.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.
Added in version 1.2.
- kwargs :
Any other parameter that should be passed to the callables used.
- Returns:
result – The resulting dataset
- Return type:
~astropy.nddata.NDData-like
Notes
If a
callableis used formask,wcsormetathe callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargsand 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.
- property npix: int
Number of spectral pixels (length of the spectral axis).
- property nspec: int
Total number of spectra (product of non-spectral dimensions).
- property photon_flux
The flux density of photons as a ~astropy.units.Quantity, in units of photons per cm^2 per second per spectral_axis unit
- plot(axes=None, plot_axes=None, axes_coordinates=None, axes_units=None, data_unit=None, wcs=None, **kwargs)
Visualize the ~ndcube.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.unitif not given.wcs (astropy.wcs.wcsapi.BaseHighLevelWCS) – The WCS object to define the coordinates of the plot axes.
kwargs – Additional keyword arguments are given to the underlying plotting infrastructure which depends on the dimensionality of the data and whether 1 or 2 plot_axes are defined: - Animations: mpl_animators.ArrayAnimatorWCS - Static 2-D images: matplotlib.pyplot.imshow - Static 1-D line plots: matplotlib.pyplot.plot
- plotter = None
A ~ndcube.visualization.mpl_plotter.MatplotlibPlotter` instance providing visualization methods.
The type of this attribute can be changed to provide custom visualization functionality.
- property properties: list
List of metadata keys (e.g. age, metallicity) attached to each spectrum.
- property psf
Image representation of the PSF for the dataset.
Should be ndarray-like.
- property quantity
Unitful representation of the NDCube data.
- property radial_velocity
The radial velocity(s) of the objects represented by this spectrum. May be scalar (if this spectrum’s
fluxis 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.
- 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_shapeinput. 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_shape (array-like, astropy.units.Quantity) – 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. If provided as a ~astropy.units.Quantity the units have to be convertible to pixels. The sentinel value
-1can be passed for a dimension which sets the bin size equal to the number of pixels along that axis. This results in a pixel size of 1 for this axis in the output (e.g. sum along that axis). Please note thebin_shapefollows array axis (NumPy) ordering of the axes.operation (function) – 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 (~ndcube.utils.cube.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_uncertaintiesfunction.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 – The resolution-degraded cube.
- Return type:
~ndcube.NDCube
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.
- property redshift
The redshift(s) of the objects represented by this spectrum. May be scalar (if this spectrum’s
fluxis 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.
- redshift_spectra(redshift=None)
Return a copy with redshift and line-spread function (LSF) metadata updated.
Does not change the spectral axis or flux; only sets the redshift attribute and scales the LSF FWHM by 1/(1+z) for use in later processing.
- 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 the ndcube.NDCube is to be reprojected.
algorithm (str, optional) – The algorithm to use for reprojecting. When set to “interpolation” ~reproject.reproject_interp is used. When set to “adaptive” ~reproject.reproject_adaptive is used. When set to “exact” ~reproject.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, ~astropy.wcs.wcsapi.BaseLowLevelWCS.array_shape attribute (if available) from the low level API of the
target_wcsis used.return_footprint (bool) – If True the footprint is returned in addition to the new ~ndcube.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_cube (ndcube.NDCube) – A new resultant NDCube object, the supplied
target_wcswill be the.wcsattribute of the output ~ndcube.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.
See also
reproject.reproject_interp,reproject.reproject_adaptive,reproject.reproject_exactNotes
This method doesn’t support handling of the
mask,extra_coords, anduncertaintyattributes yet. However,metaandglobal_coordsare copied to the output ndcube.NDCube.
- resample(new_wave)
Resample the spectra onto a new wavelength grid.
Uses flux-conserving resampling via spectres. Values at bin centers are interpolated; boundaries may yield NaN.
- Parameters:
new_wave (Quantity) – New spectral axis (e.g. wavelength in u.AA); bin centers.
- Returns:
New instance with the resampled flux and spectral_axis.
- Return type:
Notes
Uses
spectres.spectres()[1]. Care at boundaries may cause NaN.[1]A. C. Carnall, “SpectRes: A Fast Spectral Resampling Tool in Python”, arXiv:1705.05165
- 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.
If you want to shift the spectral_axis based on this value, use shift_spectrum_to.
- set_redshift_to(redshift)
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)
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.
- property spectral_axis
Returns the SpectralCoord object.
- property spectral_wcs
Returns the spectral axes of the WCS
- squeeze(axis=None)
Removes all axes with a length of 1.
- Parameters:
axis (array-like, optional) – Specifies specific axes to be removed. If one of those axes has length larger than 1, an error is thrown. If not specified, all axes of length 1 get removed.
- Returns:
A new NDCube instance with the removed axes.
- Return type:
~ndcube.NDCube
- classmethod subtract(operand, operand2=None, **kwargs)
Performs subtraction by evaluating
self-operand.- Parameters:
operand (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself-operand. Ifoperand2is given it will performoperand-operand2. If the method was called on a class rather than on the instanceoperand2must be given.operand2 (NDData-like instance) – If
operand2isNoneor not given it will perform the operationself-operand. Ifoperand2is given it will performoperand-operand2. If the method was called on a class rather than on the instanceoperand2must be given.propagate_uncertainties (bool or
None, optional) –If
Nonethe result will have no uncertainty. IfFalsethe result will have a copied version of the first operand that has an uncertainty. IfTruethe result will have a correctly propagated uncertainty from the uncertainties of the operands but this assumes that the uncertainties are NDUncertainty-like. Default isTrue.Changed in version 1.2: This parameter must be given as keyword-parameter. Using it as positional parameter is deprecated.
Nonewas added as valid parameter value.handle_mask (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmaskand if necessary provide a copy. Default is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultsmetaand if necessary provide a copy. Default isNone.Added in version 1.2.
compare_wcs (callable,
'first_found'orNone, optional) –If
Nonethe 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 resultingwcswill be like ifFalsewas given otherwise it raises aValueErrorif the comparison was not successful. Default is'first_found'.Added in version 1.2.
uncertainty_correlation (number or ~numpy.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.
Added in version 1.2.
- kwargs :
Any other parameter that should be passed to the callables used.
- Returns:
result – The resulting dataset
- Return type:
~astropy.nddata.NDData-like
Notes
If a
callableis used formask,wcsormetathe callable must accept the corresponding attributes as first two parameters. If the callable also needs additional parameters these can be defined askwargsand 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:
A new instance with the new unit and data and uncertainties scales accordingly.
- Return type:
~ndcube.NDCube
- tune_spectra(wave_lims=None, dwave=None, sampling=None, redshift=None, lsf_flag=False, lsf_mode='FWHM', lsf_wave=None, lsf=None)
Return a copy tuned to desired wavelength range, sampling, redshift, and LSF.
- Parameters:
wave_lims (array-like, optional) – Wavelength limits in Ångström.
dwave (float, optional) – Wavelength step (Ångström).
sampling (str, optional) – ‘lin’ or ‘ln’ (log).
redshift (float, optional) – Desired redshift.
lsf_flag (bool, optional) – Whether to apply LSF (line-spread function) correction.
lsf_wave (Quantity, optional) – Wavelength vector for the output LSF.
lsf (Quantity, optional) – LSF FWHM (or velocity dispersion if lsf_mode=’VDISP’).
lsf_mode (str, optional) – ‘FWHM’ (wavelength) or ‘VDISP’ (km/s).
- Returns:
Tuned spectra (resampling/redshift may be no-ops; convolution applied if lsf given).
- Return type:
- property uncertainty
Uncertainty in the dataset, if any.
Should have an attribute
uncertainty_typethat defines what kind of uncertainty is stored, such as'std'for standard deviation or'var'for variance. A metaclass defining such an interface is ~astropy.nddata.NDUncertainty but isn’t mandatory.- Type:
any type
- property unit
Unit for the dataset, if any.
- Type:
~astropy.units.Unit
- property 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:
unit (str or Unit`) – The unit to convert the dispersion array to.
rest (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.
radial_velocity (redshift or) – If present, this shift is applied to the final output velocity to get into the rest frame of the object.
- Returns:
new_data – The converted dispersion array in the new dispersion space.
- Return type:
~astropy.units.Quantity
- property velocity_convention
Returns the velocity convention
- velocity_shift(v_los)
Apply a line-of-sight velocity shift to the spectrum (Doppler shift).
- property wavelength
The spectral_axis as a ~astropy.units.Quantity in units of Angstroms
- property wcs
A world coordinate system (WCS) for the dataset, if any.
- Type:
any type
- with_flux_unit(unit, equivalencies=None, suppress_conversion=False)
Returns a new spectrum with a different flux unit. If uncertainty is defined, it will be converted to ~astropy.nddata.StdDevUncertainty in the new unit.
- Parameters:
unit (str or ~astropy.units.Unit) – The unit to convert the flux array to.
equivalencies (list of equivalencies) – Custom equivalencies to apply to conversions. Set to spectral_density by default.
suppress_conversion (bool) – Set to True if updating the flux unit without converting data values. This is ignored for
uncertaintycomponent.
- Returns:
new_spec – A new spectrum with the converted flux array (and uncertainty, if applicable).
- Return type:
~specutils.Spectrum
- with_spectral_axis_and_flux_units(spectral_axis_unit, flux_unit, velocity_convention=None, rest_value=None, flux_equivalencies=None, suppress_flux_conversion=False)
Perform
with_spectral_axis_unit()andwith_flux_unit()together. See the respective methods for input and output definitions.- Returns:
new_spec – Spectrum in requested units.
- Return type:
~specutils.Spectrum
- with_spectral_axis_last()
Convenience method to return a new copy of the Spectrum with the spectral axis last.
- 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
WCSbased on the new spectral axis. The original WCS will be stored in theoriginal_wcsentry of the new object’smetadictionary.- 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.
- 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.