milespy.spectra.Spectra
- class milespy.spectra.Spectra(flux=None, spectral_axis=None, wcs=None, velocity_convention=None, rest_value=None, redshift=None, radial_velocity=None, bin_specification=None, **kwargs)
Bases:
Spectrum1D
Class for storing spectra in milespy.
This class inherits Spectrum1D 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_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
~numpy.ndarray - like
- dim
- dimensions
energy
The energy of the spectral axis as a ~astropy.units.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 ~astropy.units.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
dict-like : Additional meta information about the dataset.
- npix
- nspec
photon_flux
The flux density of photons as a ~astropy.units.Quantity, in units of
- plotter
- properties
psf
Image representation of the PSF for the dataset.
quantity
Unitful representation of the NDCube data.
radial_velocity
The radial velocity(s) of the objects represented by this spectrum.
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
~astropy.units.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 ~astropy.units.Quantity in units of Angstroms
wcs
any 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])Returns a convolved version of the spectra.
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)Returns the LS indices of the input spectra given a list of index definitions
magnitudes
([filters, zeropoint])Returns the magnitudes of the input spectra given a list of filters in a file
mass_to_light
(filters[, mass_in])Computes the mass-to-light ratios of models in the desired filters
multiply
(operand[, operand2])Performs multiplication by evaluating
self
*operand
.new_flux_unit
(unit[, equivalencies, ...])plot
(*args, **kwargs)A convenience function for the plotters default
plot()
method.rebin
(bin_shape[, operation, ...])Downsample array by combining contiguous pixels into bins.
redshift_spectra
([redshift])Returns a copy of the instance with a redshifted wavelength vector, spectra and LSF
reproject_to
(target_wcs[, algorithm, ...])Reprojects the instance to the coordinates described by another WCS object.
resample
(new_wave)Resample the spectra
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, ...])Returns the a tuned to desired input parameters
velocity_shift
(v_los)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.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__(flux=None, spectral_axis=None, wcs=None, velocity_convention=None, rest_value=None, redshift=None, radial_velocity=None, bin_specification=None, **kwargs)
- classmethod add(operand, operand2=None, **kwargs)
Performs addition by evaluating
self
+operand
.- Parameters:
operand (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.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 or
None
, 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 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.
None
was added as valid parameter value.handle_mask (callable,
'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 is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'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
.Added in version 1.2.
compare_wcs (callable,
'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'
.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
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"
.
- 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_wcs
combining 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=True
in 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.wcs
property.
- 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=True
in 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_type
is specified.If the collapse leaves the spectral axis unchanged, a ~specutils.Spectrum1D 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_dim
equal 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.wcs
and inself.extra_coords
combined.
- convolve(lsf=<Quantity 1. Angstrom>, lsf_wave=None)
Returns a convolved version of the spectra. It does the convolution using the FWHM given in the input line spread function (LSF).
Notes
If output LSF < input LSF the sigma used for the convolution is set to very small values.
- Parameters:
lsf (~astropy.units.Quantity) – Line spread function as a function of lsf_wave. This is the FWMH to be used in the convolution, thus, should be provide in units of wavelength. It accepts a scalar value, that is assumend constant for all wavelenghts.
lsf_wave (~astropy.units.Quantity) – Associated wavelenghts to the values of lsf.
- Returns:
Object instance with convolved spectra
- Return type:
- 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
.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.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_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 ~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
.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.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
.data
attribute 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.
- classmethod divide(operand, operand2=None, **kwargs)
Performs division by evaluating
self
/operand
.- Parameters:
operand (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.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 or
None
, 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 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.
None
was added as valid parameter value.handle_mask (callable,
'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 is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'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
.Added in version 1.2.
compare_wcs (callable,
'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'
.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
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"
.
- 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.wcs
which 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)
Returns the LS indices of the input spectra given a list of index definitions
- Parameters:
indeces (list[LineStrenghtIndex]) – Indeces as provided by
milespy.ls_indices.get()
- Returns:
Dictionary with output LS indices for each spectra for each index
- Return type:
LineStrengthDict
- magnitudes(filters=[], zeropoint='AB')
Returns the magnitudes of the input spectra given a list of filters in a file
- Parameters:
filters (list[Filter]) – Filters as provided by
milespy.filter.get()
zeropoint – Type of zero point. Valid inputs are AB/VEGA
- Returns:
Dictionary with output magnitudes for each spectra for each filter
- Return type:
- property mask
Mask for the dataset, if any.
Masks should follow the
numpy
convention that valid data points are marked byFalse
and invalid ones withTrue
.- Type:
any type
- mass_to_light(filters, mass_in='star+remn')
Computes the mass-to-light ratios of models in the desired filters
- Parameters:
filters (list[Filter]) – Filters as provided by the method ‘get_filters”
mass_in (str | list[str]) – What mass to take into account for the ML. It can be given as a list, so that it returns a dictionary for each type. Valid values are: total, star, remn, star+remn, gas
- Returns:
Dictionary with mass-to-light ratios for each SSP model and filter. If mass_in is a list, the first key is the type of ML.
- Return type:
dict
- meta
Additional meta information about the dataset.
- Type:
dict-like
- classmethod multiply(operand, operand2=None, **kwargs)
Performs multiplication by evaluating
self
*operand
.- Parameters:
operand (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.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 or
None
, 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 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.
None
was added as valid parameter value.handle_mask (callable,
'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 is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'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
.Added in version 1.2.
compare_wcs (callable,
'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'
.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
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)
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 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(*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 the ndcube.NDCube.plotter class is set to a differentPlotter
class.
- plotter = None
A ~.MatplotlibPlotter instance providing visualization methods.
The type of this attribute can be changed to provide custom visualization functionality.
- 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
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.
- 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_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
-1
can be passed for a dimension which means that no rebinning will occur along that dimension.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_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 – 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
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.
- redshift_spectra(redshift=None)
Returns a copy of the instance with a redshifted wavelength vector, spectra and LSF
- Parameters:
redshift – Desired redshift
- Returns:
Object instance with spectra redshifted and updated info
- Return type:
- 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 ({'interpolation' | 'adaptive' | 'exact'}) – The algorithm to use for reprojecting. When set to “interpolation” ~reproject.reproject_interp is used, when set to “adaptive” ~reproject.reproject_adaptive is used and 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_wcs
is 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_wcs
will be the.wcs
attribute 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_exact
Notes
This method doesn’t support handling of the
mask
,extra_coords
, anduncertainty
attributes yet. However,meta
andglobal_coords
are copied to the output ndcube.NDCube.
- resample(new_wave)
Resample the spectra
- Parameters:
new_wave (
Quantity
) – Spectral axis with the desired sampling for the spectra. These values are the positions of the bin centers.
Notes
This functions makes use of
spectres.spectres()
[1]. Care must be taken when resampling near the boundaries of the spectral axis, which can cause nan values.[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_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.
- 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
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.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 or
None
, 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 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.
None
was added as valid parameter value.handle_mask (callable,
'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 is numpy.logical_or.Added in version 1.2.
handle_meta (callable,
'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
.Added in version 1.2.
compare_wcs (callable,
'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'
.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
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:
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)
Returns the a tuned to desired input parameters
- Parameters:
wave_lims – Wavelength limits in Angstroms
dwave – Step in wavelength (in Angstroms)
sampling – Type of sampling of the spectra. Valid inputs are lin/ln. Default: lin
redshift – Desired redshift
lsf_flag – Boolean flag to do LSF correction
lsf_wave – Wavelength vector of output LSF
lsf – LSF vector
lsf_mode – FWHM/VDISP. First one in Angstroms. Second one in km/s
- Returns:
Object instance with tuned spectra and updated info
- Return type:
- property uncertainty
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 ~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
- 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
uncertainty
component.
- Returns:
new_spec – A new spectrum with the converted flux array (and uncertainty, if applicable).
- Return type:
~specutils.Spectrum1D
- 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.Spectrum1D
- 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 theoriginal_wcs
entry of the new object’smeta
dictionary.- 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.