Axes#

BaseDataAxis([index_in_array, name, units, ...])

Parent class defining common attributes for all DataAxis classes.

DataAxis([index_in_array, name, units, ...])

DataAxis class for a non-uniform axis defined through an axis array.

FunctionalDataAxis(expression[, x, ...])

DataAxis class for a non-uniform axis defined through an expression.

UniformDataAxis([index_in_array, name, ...])

DataAxis class for a uniform axis defined through a scale, an offset and a size.

AxesManager(axes_list)

Contains and manages the data axes.

UnitConversion([units, scale, offset])

Parent class containing unit conversion functionalities of Uniform Axis.

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.

Attributes:
signal_axes, navigation_axeslist

Contain the corresponding DataAxis objects

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 |       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)
(3, 1, 0) (3, 1, 0)
(2, 1, 0) (2, 1, 0)
(1, 1, 0) (1, 1, 0)
(0, 1, 0) (0, 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)
(3, 2, 1) (3, 2, 1)
(2, 2, 1) (2, 2, 1)
(1, 2, 1) (1, 2, 1)
(0, 2, 1) (0, 2, 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)
(3, 0, 1) (3, 0, 1)
(2, 0, 1) (2, 0, 1)
(1, 0, 1) (1, 0, 1)
(0, 0, 1) (0, 0, 1)
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:
alignedbool
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:
axesint, str, iterable of DataAxis or 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.

unitslist of str, str or None, default None

If list, the selected axes will be converted to the provided units. If string, 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_unitsbool

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 unit of the first axis is used for all axes. If False, convert all axes individually.

factorfloat (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.

Notes

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

Parameters:
axes_listlist of dict

The list of axes to create.

gui(display=True, toolkit=None, **kwargs)#

Display or return interactive GUI element if available.

Parameters:
displaybool

If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

toolkitstr, iterable of str 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.

gui_navigation_sliders(title='', display=True, toolkit=None)#

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.

key_navigator(event)#

Set hotkeys for controlling the indices of the navigator plot

property navigation_axes#

The navigation axes as a TupleSA.

A TupleSA object is a tuple with a set method to easily set the attributes of its items.

property navigation_dimension#

The dimension of the navigation space.

property navigation_extent#

The low and high values of the navigation axes.

property navigation_shape#

The shape of the navigation space.

property navigation_size#

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:
axisBaseDataAxis

The axis to replace the current axis with.

index_in_axes_managerint

The index of the axis in current signal to replace with the axis passed in argument.

property signal_axes#

The signal axes as a TupleSA.

A TupleSA object is a tuple with a set method to easily set the attributes of its items.

property signal_dimension#

The dimension of the signal space.

property signal_extent#

The low and high values of the signal axes.

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:
iterpathstr, 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)
(0, 0)
(1, 0)
(1, 1)
(0, 1)
(0, 2)
(1, 2)
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 :class:`~hyperspy.axes.DataAxis`.

The axes to copy the attributes from.

attributes: iterable of strings.

The attributes to copy.

class hyperspy.axes.BaseDataAxis(index_in_array=None, name=None, units=None, navigate=False, is_binned=False, **kwargs)#

Bases: HasTraits

Parent class defining common attributes for all DataAxis classes.

Parameters:
namestr, optional

Name string by which the axis can be accessed. <undefined> if not set.

unitsstr, optional

String for the units of the axis vector. <undefined> if not set.

navigatebool, optional

True for a navigation axis. Default False (signal axis).

is_binnedbool, optional

True if data along the axis is binned. Default False.

convert_to_uniform_axis(keep_bounds=True, log_scale_error=True)#

Convert to an uniform axis.

Parameters:
keep_boundsbool

If True, the first and last value of the axis will not be changed. The new scale is calculated by substracting the last value by the first value and dividing by the number of intervals. If False, the scale and offset are calculated using numpy.polynomial.polynomial.Polynomial.fit(), which minimises the scale difference over the whole axis range but the bounds of the axis can change (in some cases quite significantly, in particular when the interval width is changing continuously). Default is True.

log_scale_errorbool

If True, the maximum scale error will be logged as INFO. Default is True.

Notes

The function only converts the axis type and doesn’t interpolate the data itself - see interpolate_on_axis() to interpolate data on a uniform axis.

Examples

Using keep_bounds=True (default):

>>> s = hs.data.luminescence_signal(uniform=False)
>>> print(s.axes_manager)
<Axes manager, axes: (|1024)>
            Name |   size |  index |  offset |   scale |  units
================ | ====== | ====== | ======= | ======= | ======
---------------- | ------ | ------ | ------- | ------- | ------
          Energy |   1024 |      0 | non-uniform axis |     eV
>>> s.axes_manager[-1].convert_to_uniform_axis(keep_bounds=True)
>>> print(s.axes_manager)
<Axes manager, axes: (|1024)>
            Name |   size |  index |  offset |   scale |  units
================ | ====== | ====== | ======= | ======= | ======
---------------- | ------ | ------ | ------- | ------- | ------
          Energy |   1024 |      0 |     1.6 |  0.0039 |     eV

Using keep_bounds=False:

>>> s = hs.data.luminescence_signal(uniform=False)
>>> print(s.axes_manager)
<Axes manager, axes: (|1024)>
            Name |   size |  index |  offset |   scale |  units
================ | ====== | ====== | ======= | ======= | ======
---------------- | ------ | ------ | ------- | ------- | ------
          Energy |   1024 |      0 | non-uniform axis |     eV
>>> s.axes_manager[-1].convert_to_uniform_axis(keep_bounds=False)
>>> print(s.axes_manager)
<Axes manager, axes: (|1024)>
            Name |   size |  index |  offset |   scale |  units
================ | ====== | ====== | ======= | ======= | ======
---------------- | ------ | ------ | ------- | ------- | ------
          Energy |   1024 |      0 |     1.1 |  0.0033 |     eV
gui(display=True, toolkit=None, **kwargs)#

Display or return interactive GUI element if available.

Parameters:
displaybool

If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

toolkitstr, iterable of str 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:
axisBaseDataAxis

The instance to use as a source for values.

attributesiterable of str

The name of the attribute to update. If the attribute does not exist in either of the AxesManagers, an AttributeError will be raised.

Returns:
bool

True if any changes were made, otherwise False.

value2index(value, rounding=<built-in function round>)#

Return the closest index/indices to the given value(s) if between the axis limits.

Parameters:
valuefloat or numpy.ndarray
roundingcallable()

Handling of values 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 rounding=math.ceil, round to the next higher value.

Returns:
int 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

Parameters:
v1, v2float

The end points of the interval in the axis units.

Returns:
i2, i2float

The indices corresponding to the interval [v1, v2]

class hyperspy.axes.DataAxis(index_in_array=None, name=None, units=None, 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 property is_uniform is automatically set to False.

Parameters:
axisnumpy 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': None,
'units': None,
'navigate': False,
'is_binned': False,
'axis': array([  0,   1,   4,   9,  16,  25,  36,  49,  64,  81, 100])}
crop(start=None, end=None)#

Crop the axis in place.

Parameters:
startint, float, or None

The beginning of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None the method crops from/to the low/high end of the axis.

endint, float, or None

The end of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None 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.

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:
axisDataAxis

The instance to use as a source for values.

attributesiterable of str

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.

Returns:
bool

True if any changes were made, otherwise False.

class hyperspy.axes.FunctionalDataAxis(expression, x=None, index_in_array=None, name=None, units=None, navigate=False, size=1, 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 a string using the SymPy text expression format. An example would be expression = a / x + b. Any variables in the expression, in this case a and b must be defined as additional attributes of the axis. The property is_uniform is automatically set to False.

x itself is an instance of BaseDataAxis. By default, it will be a UniformDataAxis with offset = 0 and scale = 1 of the given size. However, it can also be initialized with custom offset and scale values. Alternatively, it can be a non-uniform DataAxis.

Parameters:
expression: str

SymPy mathematical expression defining the axis.

xBaseDataAxis

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': None,
'units': None,
'navigate': False,
'is_binned': False,
'expression': 'a / (x + 1) + b',
'size': 500,
'x': {'_type': 'UniformDataAxis',
  'name': None,
  'units': None,
  'navigate': False,
  'is_binned': False,
  'size': 500,
  'scale': 1.0,
  'offset': 0.0},
'a': 100,
'b': 10}
convert_to_non_uniform_axis()#

Convert to a non-uniform axis.

crop(start=None, end=None)#

Crop the axis in place.

Parameters:
startint, float, or None

The beginning of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None the method crops from/to the low/high end of the axis.

endint, float, or None

The end of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None 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:
axisFunctionalDataAxis

The instance to use as a source for values.

attributesiterable of str 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.

Returns
——-
A boolean indicating whether any changes were made.
class hyperspy.axes.UniformDataAxis(index_in_array=None, name=None, units=None, 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, an offset and a size.

The most common type of axis. It is defined by the offset, scale and size parameters, which determine the initial value, spacing and length of the axis, respectively. The actual axis array is automatically calculated from these three values. The UniformDataAxis is a special case of the FunctionalDataAxis defined by the function scale * x + offset.

Parameters:
offsetfloat

The first value of the axis vector.

scalefloat

The spacing between axis points.

sizeint

The number of points in the axis.

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}
crop(start=None, end=None)#

Crop the axis in place.

Parameters:
startint, float, or None

The beginning of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None the method crops from/to the low/high end of the axis.

endint, float, or None

The end of the cropping interval. If type is int, the value is taken as the axis index. If type is float the index is calculated using the axis calibration. If start/end is None 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:
axisUniformDataAxis

The UniformDataAxis instance to use as a source for values.

attributesiterable of str 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.

Returns
——-
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:
valuefloat, str, numpy.ndarray

If string, should either be a calibrated unit like “20nm” or a relative slicing like “rel0.2”.

roundingcallable()

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 rounding=math.ceil, round to the next higher value.

Returns:
int or numpy.ndarray
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).

class hyperspy.axes.UnitConversion(units=None, scale=1.0, offset=0.0)#

Bases: object

Parent class containing unit conversion functionalities of Uniform Axis.

Parameters:
offsetfloat

The first value of the axis vector.

scalefloat

The spacing between axis points.

sizeint

The number of points in the axis.

convert_to_units(units=None, inplace=True, factor=0.25)#

Convert the scale and the units of the current axis. If the unit of measure is not supported by the pint library, the scale and units are not modified.

Parameters:
units{str | None}

Default = None If str, the axis will be converted to the provided units. If “auto”, automatically determine the optimal units to avoid using too large or too small numbers. This can be tweaked by the factor argument.

inplacebool

If True, convert the axis in place. if False return the scale, offset and units.

factorfloat (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.