hyperspy.axes module
- class hyperspy.axes.AxesManager(axes_list)
Bases:
HasTraits
Contains and manages the data axes.
It supports indexing, slicing, subscripting and iteration. As an iterator, iterate over the navigation coordinates returning the current indices. It can only be indexed and sliced to access the DataAxis objects that it contains. Standard indexing and slicing follows the “natural order” as in Signal, i.e. [nX, nY, …,sX, sY,…] where n indicates a navigation axis and s a signal axis. In addition, AxesManager supports indexing using complex numbers a + bj, where b can be one of 0, 1, 2 and 3 and a valid index. If b is 3, AxesManager is indexed using the order of the axes in the array. If b is 1(2), indexes only the navigation(signal) axes in the natural order. In addition AxesManager supports subscription using axis name.
- signal_axes, navigation_axes
Contain the corresponding DataAxis objects
- Type:
- coordinates, indices, iterpath
Examples
Create a spectrum with random data
>>> s = hs.signals.Signal1D(np.random.random((2,3,4,5))) >>> s.axes_manager <Axes manager, axes: (4, 3, 2|5)> Name | size | index | offset | scale | units ================ | ====== | ====== | ======= | ======= | ====== <undefined> | 4 | 0 | 0 | 1 | <undefined> <undefined> | 3 | 0 | 0 | 1 | <undefined> <undefined> | 2 | 0 | 0 | 1 | <undefined> ---------------- | ------ | ------ | ------- | ------- | ------ <undefined> | 5 | | 0 | 1 | <undefined> >>> s.axes_manager[0] <Unnamed 0th axis, size: 4, index: 0> >>> s.axes_manager[3j] <Unnamed 2nd axis, size: 2, index: 0> >>> s.axes_manager[1j] <Unnamed 0th axis, size: 4, index: 0> >>> s.axes_manager[2j] <Unnamed 3rd axis, size: 5> >>> s.axes_manager[1].name = "y" >>> s.axes_manager["y"] <y axis, size: 3, index: 0> >>> for i in s.axes_manager: ... print(i, s.axes_manager.indices) ... (0, 0, 0) (0, 0, 0) (1, 0, 0) (1, 0, 0) (2, 0, 0) (2, 0, 0) (3, 0, 0) (3, 0, 0) (0, 1, 0) (0, 1, 0) (1, 1, 0) (1, 1, 0) (2, 1, 0) (2, 1, 0) (3, 1, 0) (3, 1, 0) (0, 2, 0) (0, 2, 0) (1, 2, 0) (1, 2, 0) (2, 2, 0) (2, 2, 0) (3, 2, 0) (3, 2, 0) (0, 0, 1) (0, 0, 1) (1, 0, 1) (1, 0, 1) (2, 0, 1) (2, 0, 1) (3, 0, 1) (3, 0, 1) (0, 1, 1) (0, 1, 1) (1, 1, 1) (1, 1, 1) (2, 1, 1) (2, 1, 1) (3, 1, 1) (3, 1, 1) (0, 2, 1) (0, 2, 1) (1, 2, 1) (1, 2, 1) (2, 2, 1) (2, 2, 1) (3, 2, 1) (3, 2, 1)
- _get_data_slice(fill=None)
Return a tuple of slice objects to slice the data.
- _get_iterpath_size(masked_elements=0)
Attempts to get the iterpath size, returning None if it is unknown
- _remove_one_axis(axis)
Remove the given Axis.
- Raises:
ValueError – If the Axis is not present.
- _set_axis_attribute_values(attr, values)
Set the given attribute of all the axes to the given value(s)
- Parameters:
attr (string) – The DataAxis attribute to set.
values (any) – If iterable, it must have the same number of items as axes are in this AxesManager instance. If not iterable, the attribute of all the axes are set to the given value.
- _sort_axes()
Sort _axes to align them.
When the data are aligned with the axes the axes order in self._axes is [nav_n, nav_n-1, …, nav_0, sig_m, sig_m-1 …, sig_0]. This method sort the axes in this way. Warning: this doesn’t sort the data axes.
- property axes_are_aligned_with_data
Verify if the data axes are aligned with the signal axes.
When the data are aligned with the axes the axes order in self._axes is [nav_n, nav_n-1, …, nav_0, sig_m, sig_m-1 …, sig_0].
- Returns:
aligned
- Return type:
- convert_units(axes=None, units=None, same_units=True, factor=0.25)
Convert the scale and the units of the selected axes. If the unit of measure is not supported by the pint library, the scale and units are not changed.
- Parameters:
axes ({int | string | iterable of DataAxis | None}) – Default = None Convert to a convenient scale and units on the specified axis. If int, the axis can be specified using the index of the axis in axes_manager. If string, argument can be navigation or signal to select the navigation or signal axes. The axis name can also be provided. If None, convert all axes.
units ({list of string of the same length than axes | str | None}) – Default = None If list, the selected axes will be converted to the provided units. If str, the navigation or signal axes will be converted to the provided units. If None, the scale and the units are converted to the appropriate scale and units to avoid displaying scalebar with >3 digits or too small number. This can be tweaked by the factor argument.
same_units (bool) – If True, force to keep the same units if the units of the axes differs. It only applies for the same kind of axis, navigation or signal. By default the converted units of the first axis is used for all axes. If False, convert all axes individually.
factor (float (default: 0.25)) – ‘factor’ is an adjustable value used to determine the prefix of the units. The product factor * scale * size is passed to the pint to_compact method to determine the prefix.
Note
Requires a uniform axis.
- property coordinates
Get and set the current coordinates, if the navigation dimension is not 0. If the navigation dimension is 0, it raises AttributeError when attempting to set its value.
- create_axes(axes_list)
Given a list of either axes dictionaries or axes objects, these are added to the AxesManager. In case dictionaries defining the axes properties are passed, the DataAxis/UniformDataAxis/FunctionalDataAxis instances are first created.
The index of the axis in the array and in the _axes lists can be defined by the index_in_array keyword if given for all axes. Otherwise, it is defined by their index in the list.
See also
_append_axis
- gui(display=True, toolkit=None, **kwargs)
Display or return interactive GUI element if available.
- Parameters:
display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
Navigation sliders to control the index of the navigation axes.
- Parameters:
title (str) –
%s –
%s –
- property indices
Get and set the current indices, if the navigation dimension is not 0. If the navigation dimension is 0, it raises AttributeError when attempting to set its value.
- property iterpath
Sets the order of iterating through the indices in the navigation dimension. Can be either “flyback” or “serpentine”, or an iterable of navigation indices.
Set hotkeys for controlling the indices of the navigator plot
The navigation axes as a tuple.
The dimension of the navigation space.
The shape of the navigation space.
The size of the navigation space.
- remove(axes)
Remove one or more axes
- set_axis(axis, index_in_axes_manager)
Replace an axis of current signal with one given in argument.
- Parameters:
axis (BaseDataAxis axis to replace the current axis with) –
index_in_axes_manager (index of the axis in current signal to remplace) – with axis passed in argument
See also
_append_axis
- set_signal_dimension(value)
Set the dimension of the signal.
- Raises:
ValueError – If value if greater than the number of axes or is negative.
- property signal_axes
The signal axes as a tuple.
- property signal_dimension
The dimension of the signal space.
- property signal_shape
The shape of the signal space.
- property signal_size
The size of the signal space.
- switch_iterpath(iterpath=None)
Context manager to change iterpath. The original iterpath is restored when exiting the context.
- Parameters:
iterpath (str, optional) – The iterpath to use. The default is None.
- Yields:
None.
Examples
>>> s = hs.signals.Signal1D(np.arange(2*3*4).reshape([3, 2, 4])) >>> with s.axes_manager.switch_iterpath('serpentine'): >>> for indices in s.axes_manager: >>> print(indices)
- update_axes_attributes_from(axes, attributes=None)
Update the axes attributes to match those given.
The axes are matched by their index in the array. The purpose of this method is to update multiple axes triggering any_axis_changed only once.
- Parameters:
axes (iterable of DataAxis instances.) – The axes to copy the attributes from.
attributes (iterable of strings.) – The attributes to copy.
- class hyperspy.axes.BaseDataAxis(index_in_array=None, name=<undefined>, units=<undefined>, navigate=False, is_binned=False, **kwargs)
Bases:
HasTraits
Parent class defining common attributes for all DataAxis classes.
- Parameters:
name (str, optional) – Name string by which the axis can be accessed. <undefined> if not set.
units (str, optional) – String for the units of the axis vector. <undefined> if not set.
navigate (bool, optional) – True for a navigation axis. Default False (signal axis).
is_binned (bool, optional) – True if data along the axis is binned. Default False.
- _get_array_slices(slice_)
Returns a slice to slice the corresponding data axis.
- property _is_increasing_order
Determine if the axis has an increasing, decreasing order or no order at all.
- Returns:
True if order is increasing, False if order is decreasing, None
otherwise.
- _parse_value(value)
Convert the input to calibrated value if string, otherwise, return the same value.
- _parse_value_from_string(value)
Return calibrated value from a suitable string
- convert_to_uniform_axis()
Convert to an uniform axis.
- gui(display=True, toolkit=None, **kwargs)
Display or return interactive GUI element if available.
- Parameters:
display (bool) – If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.
toolkit (str, iterable of strings or None) – If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.
- update_from(axis, attributes)
Copy values of specified axes fields from the passed AxesManager.
- Parameters:
axis (BaseDataAxis) – The BaseDataAxis instance to use as a source for values.
attributes (iterable container of strings.) – The name of the attribute to update. If the attribute does not exist in either of the AxesManagers, an AttributeError will be raised.
- Return type:
A boolean indicating whether any changes were made.
- value2index(value, rounding=<built-in function round>)
Return the closest index/indices to the given value(s) if between the axis limits.
- Parameters:
value (number or numpy array) –
rounding (function) – Handling of values intermediate between two axis points: If rounding=round, use round-half-away-from-zero strategy to find closest value. If rounding=math.floor, round to the next lower value. If round=math.ceil, round to the next higher value.
- Returns:
index
- Return type:
integer or numpy array
- Raises:
ValueError – If value is out of bounds or contains out of bounds values (array). If value is NaN or contains NaN values (array).
- value_range_to_indices(v1, v2)
Convert the given range to index range.
When a value is out of the axis limits, the endpoint is used instead. v1 must be preceding v2 in the axis values
if the axis scale is positive, it means v1 < v2
if the axis scale is negative, it means v1 > v2
- class hyperspy.axes.DataAxis(index_in_array=None, name=<undefined>, units=<undefined>, navigate=False, is_binned=False, axis=[1], **kwargs)
Bases:
BaseDataAxis
DataAxis class for a non-uniform axis defined through an
axis
array.The most flexible type of axis, where the axis points are directly given by an array named
axis
. As this can be any array, the propertyis_uniform
is automatically set toFalse
.- Parameters:
axis (numpy array or list) – The array defining the axis points.
Examples
Sample dictionary for a DataAxis:
>>> dict0 = {'axis': np.arange(11)**2} >>> s = hs.signals.Signal1D(np.ones(12), axes=[dict0]) >>> s.axes_manager[0].get_axis_dictionary() {'_type': 'DataAxis', 'name': <undefined>, 'units': <undefined>, 'navigate': False, 'axis': array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100])}
- _slice_me(slice_)
Returns a slice to slice the corresponding data axis and set the axis accordingly.
- Parameters:
slice ({int, slice}) –
- Returns:
my_slice
- Return type:
- crop(start=None, end=None)
Crop the axis in place.
- Parameters:
start (int, float, or None) – The beginning of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.end (int, float, or None) – The end of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.
- update_axis()
Set the value of an axis. The axis values need to be ordered.
- Parameters:
axis (numpy array or list) –
- Raises:
ValueError if the axis values are not ordered. –
- update_from(axis, attributes=None)
Copy values of specified axes fields from the passed AxesManager.
- Parameters:
axis (DataAxis) – The DataAxis instance to use as a source for values.
attributes (iterable container of strings.) – The name of the attribute to update. If the attribute does not exist in either of the AxesManagers, an AttributeError will be raised. If None, units will be updated.
- Return type:
A boolean indicating whether any changes were made.
- class hyperspy.axes.FunctionalDataAxis(expression, x=None, index_in_array=None, name=<undefined>, units=<undefined>, navigate=False, size=<undefined>, is_binned=False, **parameters)
Bases:
BaseDataAxis
DataAxis class for a non-uniform axis defined through an
expression
.A FunctionalDataAxis is defined based on an
expression
that is evaluated to yield the axis points. The expression is a function defined as astring
using the SymPy text expression format. An example would beexpression = a / x + b
. Any variables in the expression, in this casea
andb
must be defined as additional attributes of the axis. The propertyis_uniform
is automatically set toFalse
.x
itself is an instance of BaseDataAxis. By default, it will be a UniformDataAxis withoffset = 0
andscale = 1
of the givensize
. However, it can also be initialized with customoffset
andscale
values. Alternatively, it can be a non-uniform DataAxis.- Parameters:
expression (str) – SymPy mathematical expression defining the axis.
x (BaseDataAxis) – Defines x-values at which expression is evaluated.
Examples
Sample dictionary for a FunctionalDataAxis:
>>> dict0 = {'expression': 'a / (x + 1) + b', 'a': 100, 'b': 10, 'size': 500} >>> s = hs.signals.Signal1D(np.ones(500), axes=[dict0]) >>> s.axes_manager[0].get_axis_dictionary() {'_type': 'FunctionalDataAxis', 'name': <undefined>, 'units': <undefined>, 'navigate': False, 'expression': 'a / (x + 1) + b', 'size': 500, 'x': {'_type': 'UniformDataAxis', 'name': <undefined>, 'units': <undefined>, 'navigate': <undefined>, 'size': 500, 'scale': 1.0, 'offset': 0.0}, 'a': 100, 'b': 10}
- _slice_me(slice_)
Returns a slice to slice the ‘x’ vector of the corresponding functional data axis and set the axis accordingly.
- convert_to_non_uniform_axis()
Convert to a non-uniform axis.
- crop(start=None, end=None)
Crop the axis in place.
- Parameters:
start (int, float, or None) – The beginning of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.end (int, float, or None) – The end of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.
- update_from(axis, attributes=None)
Copy values of specified axes fields from the passed AxesManager.
- Parameters:
axis (FunctionalDataAxis) – The FunctionalDataAxis instance to use as a source for values.
attributes (iterable container of strings or None.) – A list of the name of the attribute to update. If an attribute does not exist in either of the AxesManagers, an AttributeError will be raised. If None, the parameters of expression are updated.
- Return type:
A boolean indicating whether any changes were made.
- class hyperspy.axes.GeneratorLen(gen, length)
Bases:
object
Helper class for creating a generator-like object with a known length. Useful when giving a generator as input to the AxesManager iterpath, so that the length is known for the progressbar.
Found at: https://stackoverflow.com/questions/7460836/how-to-lengenerator/7460986
- Parameters:
gen (generator) – The Generator containing hyperspy navigation indices.
length (int) – The manually-specified length of the generator.
- class hyperspy.axes.UniformDataAxis(index_in_array=None, name=<undefined>, units=<undefined>, navigate=False, size=1, scale=1.0, offset=0.0, is_binned=False, **kwargs)
Bases:
BaseDataAxis
,UnitConversion
DataAxis class for a uniform axis defined through a
scale
, anoffset
and asize
.The most common type of axis. It is defined by the
offset
,scale
andsize
parameters, which determine the initial value, spacing and length of the axis, respectively. The actualaxis
array is automatically calculated from these three values. TheUniformDataAxis
is a special case of theFunctionalDataAxis
defined by the functionscale * x + offset
.- Parameters:
Examples
Sample dictionary for a UniformDataAxis:
>>> dict0 = {'offset': 300, 'scale': 1, 'size': 500} >>> s = hs.signals.Signal1D(np.ones(500), axes=[dict0]) >>> s.axes_manager[0].get_axis_dictionary() {'_type': 'UniformDataAxis', 'name': <undefined>, 'units': <undefined>, 'navigate': False, 'size': 500, 'scale': 1.0, 'offset': 300.0}
- _slice_me(_slice)
Returns a slice to slice the corresponding data axis and change the offset and scale of the UniformDataAxis accordingly.
- crop(start=None, end=None)
Crop the axis in place.
- Parameters:
start (int, float, or None) – The beginning of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.end (int, float, or None) – The end of the cropping interval. If type is
int
, the value is taken as the axis index. If type isfloat
the index is calculated using the axis calibration. If start/end isNone
the method crops from/to the low/high end of the axis.
- update_from(axis, attributes=None)
Copy values of specified axes fields from the passed AxesManager.
- Parameters:
axis (UniformDataAxis) – The UniformDataAxis instance to use as a source for values.
attributes (iterable container of strings or None) – The name of the attribute to update. If the attribute does not exist in either of the AxesManagers, an AttributeError will be raised. If None, scale, offset and units are updated.
- Return type:
A boolean indicating whether any changes were made.
- value2index(value, rounding=<built-in function round>)
Return the closest index/indices to the given value(s) if between the axis limits.
- Parameters:
value (number or string, or numpy array of number or string) – if string, should either be a calibrated unit like “20nm” or a relative slicing like “rel0.2”.
rounding (function) – Handling of values intermediate between two axis points: If rounding=round, use python’s standard round-half-to-even strategy to find closest value. If rounding=math.floor, round to the next lower value. If round=math.ceil, round to the next higher value.
- Returns:
index
- Return type:
integer or numpy array
- Raises:
ValueError – If value is out of bounds or contains out of bounds values (array). If value is NaN or contains NaN values (array). If value is incorrectly formatted str or contains incorrectly formatted str (array).
- hyperspy.axes._flyback_iter(shape)
Classic flyback scan pattern generator which yields indices in similar fashion to np.ndindex. Takes shape in hyperspy order, not numpy order.
- hyperspy.axes._serpentine_iter(shape)
Similar to np.ndindex, but yields indices in serpentine pattern, like snake game. Takes shape in hyperspy order, not numpy order.
Code by Stackoverflow user Paul Panzer, from https://stackoverflow.com/questions/57366966/
Note that the [::-1] reversing is necessary to iterate first along the x-direction on multidimensional navigators.
- hyperspy.axes.create_axis(**kwargs)
Creates a uniform, a non-uniform axis or a functional axis depending on the kwargs provided. If axis or expression are provided, a non-uniform or a functional axis is created, respectively. Otherwise a uniform axis is created, which can be defined by scale, size and offset.
Alternatively, the offset_index of the offset channel can be specified.
- Parameters:
- Return type:
A DataAxis, FunctionalDataAxis or a UniformDataAxis
- hyperspy.axes.generate_uniform_axis(offset, scale, size, offset_index=0)
Creates a uniform axis vector given the offset, scale and number of channels.
Alternatively, the offset_index of the offset channel can be specified.