hyperspy.roi module

Region of interests (ROIs).

ROIs operate on BaseSignal instances and include widgets for interactive operation.

The following 1D ROIs are available:

Point1DROI

Single element ROI of a 1D signal.

SpanROI

Interval ROI of a 1D signal.

The following 2D ROIs are available:

Point2DROI

Single element ROI of a 2D signal.

RectangularROI

Rectagular ROI of a 2D signal.

CircleROI

(Hollow) circular ROI of a 2D signal

Line2DROI

Line profile of a 2D signal with customisable width.

class hyperspy.roi.BaseInteractiveROI

Bases: hyperspy.roi.BaseROI

Base class for interactive ROIs, i.e. ROIs with widget interaction. The base class defines a lot of the common code for interacting with widgets, but inheritors need to implement the following functions:

_get_widget_type() _apply_roi2widget(widget) _set_from_widget(widget)

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_on_widget_change(widget)

Callback for widgets’ ‘changed’ event. Updates the internal state from the widget, and triggers events (excluding connections to the source widget).

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

_update_widgets(exclude=None)

Internal function for updating the associated widgets to the geometry contained in the ROI.

Parameters

exclude (set()) – A set of widgets to exclude from the update. Useful e.g. if a widget has triggered a change in the ROI: Then all widgets, excluding the one that was the source for the change, should be updated.

add_widget(signal, axes=None, widget=None, color='green', snap=True, **kwargs)

Add a widget to visually represent the ROI, and connect it so any changes in either are reflected in the other. Note that only one widget can be added per signal/axes combination.

Parameters
  • signal (Signal) – The signal to which the widget is added. This is used to determine which plot to add the widget to, and it supplies the axes_manager for the widget.

  • axes (specification of axes to use, default is None) –

    The axes argument specifies which axes the ROI will be applied on. The axes in the collection can be either of the following:

    • Anything that can index the provided axes_manager.

    • a tuple or list of:

      • DataAxis

      • anything that can index the provided axes_manager

    • None, it will check whether the widget can be added to the navigator, i.e. if dimensionality matches, and use it if possible, otherwise it will try the signal space. If none of the two attempts work, an error message will be raised.

  • widget (Widget or None (default)) – If specified, this is the widget that will be added. If None, the default widget will be used, as given by _get_widget_type().

  • color (Matplotlib color specifier (default: 'green')) – The color for the widget. Any format that matplotlib uses should be ok. This will not change the color for any widget passed with the ‘widget’ argument.

  • snap (bool, optional) – If True, the ROI will be snapped to the axes values. Default is True.

  • kwargs – All keyword arguments are passed to the widget constructor.

interactive(signal, navigation_signal='same', out=None, color='green', snap=True, **kwargs)

Creates an interactively sliced Signal (sliced by this ROI) via hyperspy.interactive.

Parameters
  • signal (Signal) – The source signal to slice.

  • navigation_signal (Signal, None or "same" (default)) – The signal the ROI will be added to, for navigation purposes only. Only the source signal will be sliced. If not None, it will automatically create a widget on navigation_signal. Passing “same” is identical to passing the same signal to ‘signal’ and ‘navigation_signal’, but is less ambigous, and allows “same” to be the default value.

  • out (Signal) – If not None, it will use ‘out’ as the output instead of returning a new Signal.

  • color (Matplotlib color specifier (default: 'green')) – The color for the widget. Any format that matplotlib uses should be ok. This will not change the color for any widget passed with the ‘widget’ argument.

  • snap (bool, optional) – If True, the ROI will be snapped to the axes values. Default is True.

  • **kwargs – All kwargs are passed to the roi __call__ method which is called interactively on any roi parameter change.

remove_widget(signal, render_figure=True)
Removing a widget from a signal consists of two tasks:
  1. Disconnect the interactive operations associated with this ROI and the specified signal signal.

  2. Removing the widget from the plot.

Parameters
  • signal (BaseSignal) – The signal from which the interactive operations will be disconnected.

  • render_figure (bool, optional) – If False, the figure will not be rendered after removing the widget in order to save redraw events. The default is True.

Returns

Return type

None.

update()

Function responsible for updating anything that depends on the ROI. It should be called by implementors whenever the ROI changes. This implementation updates the widgets associated with it, and triggers the changed event.

class hyperspy.roi.BasePointROI

Bases: hyperspy.roi.BaseInteractiveROI

Base ROI class for point ROIs, i.e. ROIs with a unit size in each of its dimensions.

Sets up events.changed event, and inits HasTraits.

class hyperspy.roi.BaseROI

Bases: traits.has_traits.HasTraits

Base class for all ROIs.

Provides some basic functionalities that are likely to be shared between all ROIs, and serve as a common type that can be checked for.

Sets up events.changed event, and inits HasTraits.

_get_ranges()

Utility to get the value ranges that the ROI would select.

If the ROI is point base or is rectangluar in nature, these can be used to slice a signal. Extracted from _make_slices() to ease implementation in inherited ROIs.

_make_slices(axes_collection, axes, ranges=None)

Utility function to make a slice structure that will slice all the axes in ‘axes_collection’. The axes in the axes argument will be sliced by the ROI, all other axes with ‘slice(None)’. Alternatively, if ‘ranges’ is passed, axes[i] will be sliced with ‘ranges[i]’.

_parse_axes(axes, axes_manager)

Utility function to parse the ‘axes’ argument to a list of DataAxis.

Parameters
  • axes (specification of axes to use, default is None) –

    The axes argument specifies which axes the ROI will be applied on. The axes in the collection can be either of the following:

    • Anything that can index the provided axes_manager.

    • a tuple or list of:

      • DataAxis

      • anything that can index the provided axes_manager

    • None, it will check whether the widget can be added to the navigator, i.e. if dimensionality matches, and use it if possible, otherwise it will try the signal space. If none of the two attempts work, an error message will be raised.

  • axes_manager (AxesManager) – The AxesManager to use for parsing axes

Returns

Return type

tuple of DataAxis

is_valid()

Determine if the ROI is in a valid state.

This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.

update()

Function responsible for updating anything that depends on the ROI. It should be called by implementors whenever the ROI changes. The base implementation simply triggers the changed event.

class hyperspy.roi.CircleROI(cx=None, cy=None, r=None, r_inner=0)

Bases: hyperspy.roi.BaseInteractiveROI

Selects a circular or annular region in a 2D space. The coordinates of the center of the circle are stored in the ‘cx’ and ‘cy’ attributes. The radious in the r attribute. If an internal radius is defined using the r_inner attribute, then an annular region is selected instead. CircleROI can be used in place of a tuple containing (cx, cy, r), (cx, cy, r, r_inner) when r_inner is not None.

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

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.

is_valid()

Determine if the ROI is in a valid state.

This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.

class hyperspy.roi.Line2DROI(x1=None, y1=None, x2=None, y2=None, linewidth=0)

Bases: hyperspy.roi.BaseInteractiveROI

Selects a line of a given width in 2D space. The coordinates of the end points of the line are stored in the x1, y1, x2, y2 parameters. The length is available in the length parameter and the method angle computes the angle of the line with the axes.

Line2DROI can be used in place of a tuple containing the coordinates of the two end-points of the line and the linewdith (x1, y1, x2, y2, linewidth).

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

static _line_profile_coordinates(src, dst, linewidth=1)

Return the coordinates of the profile of an image along a scan line.

Parameters
  • src (2-tuple of numeric scalar (float or int)) – The start point of the scan line.

  • dst (2-tuple of numeric scalar (float or int)) – The end point of the scan line.

  • linewidth (int, optional) – Width of the scan, perpendicular to the line

Returns

coords – The coordinates of the profile along the scan line. The length of the profile is the ceil of the computed length of the scan line.

Return type

array, shape (2, N, C), float

Notes

This is a utility method meant to be used internally by skimage functions. The destination point is included in the profile, in contrast to standard numpy indexing.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

angle(axis='horizontal', units='degrees')

“Angle between ROI line and selected axis

Parameters
  • axis (str, {'horizontal', 'vertical'}, optional) – Select axis against which the angle of the ROI line is measured. ‘x’ is alias to ‘horizontal’ and ‘y’ is ‘vertical’ (Default: ‘horizontal’)

  • units (str, {'degrees', 'radians'}) – The angle units of the output (Default: ‘degrees’)

Returns

angle

Return type

float

Examples

>>> import hyperspy.api as hs
>>> hs.roi.Line2DROI(0., 0., 1., 2., 1)
>>> r.angle()
63.43494882292201
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.

static profile_line(img, src, dst, axes, linewidth=1, order=1, mode='constant', cval=0.0)

Return the intensity profile of an image measured along a scan line.

Parameters
  • img (numeric array, shape (M, N[, C])) – The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information).

  • src (2-tuple of numeric scalar (float or int)) – The start point of the scan line.

  • dst (2-tuple of numeric scalar (float or int)) – The end point of the scan line.

  • linewidth (int, optional) – Width of the scan, perpendicular to the line

  • order (int in {0, 1, 2, 3, 4, 5}, optional) – The order of the spline interpolation to compute image values at non-integer coordinates. 0 means nearest-neighbor interpolation.

  • mode (string, one of {'constant', 'nearest', 'reflect', 'wrap'},) – optional How to compute any values falling outside of the image.

  • cval (float, optional) – If mode is ‘constant’, what constant value to use outside the image.

Returns

return_value – The intensity profile along the scan line. The length of the profile is the ceil of the computed length of the scan line.

Return type

array

Examples

>>> x = np.array([[1, 1, 1, 2, 2, 2]])
>>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)])
>>> img
array([[0, 0, 0, 0, 0, 0],
       [1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [1, 1, 1, 2, 2, 2],
       [0, 0, 0, 0, 0, 0]])
>>> profile_line(img, (2, 1), (2, 4))
array([ 1.,  1.,  2.,  2.])

Notes

The destination point is included in the profile, in contrast to standard numpy indexing. Requires uniform navigation axes.

class hyperspy.roi.Point1DROI(value=None)

Bases: hyperspy.roi.BasePointROI

Selects a single point in a 1D space. The coordinate of the point in the 1D space is stored in the ‘value’ trait.

Point1DROI can be used in place of a tuple containing the value of value.

Example

>>> roi = hs.roi.Point1DROI(0.5)
>>> value, = roi
>>> print(value)
0.5

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_ranges()

Utility to get the value ranges that the ROI would select.

If the ROI is point base or is rectangluar in nature, these can be used to slice a signal. Extracted from _make_slices() to ease implementation in inherited ROIs.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

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.

class hyperspy.roi.Point2DROI(x=None, y=None)

Bases: hyperspy.roi.BasePointROI

Selects a single point in a 2D space. The coordinates of the point in the 2D space are stored in the traits ‘x’ and ‘y’.

Point2DROI can be used in place of a tuple containing the coordinates of the point (x, y).

Example

>>> roi = hs.roi.Point2DROI(3, 5)
>>> x, y = roi
>>> print(x, y)
3 5

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_ranges()

Utility to get the value ranges that the ROI would select.

If the ROI is point base or is rectangluar in nature, these can be used to slice a signal. Extracted from _make_slices() to ease implementation in inherited ROIs.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

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.

class hyperspy.roi.RectangularROI(left=None, top=None, right=None, bottom=None)

Bases: hyperspy.roi.BaseInteractiveROI

Selects a range in a 2D space. The coordinates of the range in the 2D space are stored in the traits ‘left’, ‘right’, ‘top’ and ‘bottom’. Convenience properties ‘x’, ‘y’, ‘width’ and ‘height’ are also available, but cannot be used for initialization.

RectangularROI can be used in place of a tuple containing (left, right, top, bottom).

Example

>>> roi = hs.roi.RectangularROI(left=0, right=10, top=20, bottom=20.5)
>>> left, right, top, bottom = roi
>>> print(left, right, top, bottom)
0 10 20 20.5

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_ranges()

Utility to get the value ranges that the ROI would select.

If the ROI is point base or is rectangluar in nature, these can be used to slice a signal. Extracted from _make_slices() to ease implementation in inherited ROIs.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

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.

property height

Returns / sets the height of the ROI

is_valid()

Determine if the ROI is in a valid state.

This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.

property width

Returns / sets the width of the ROI

property x

Returns / sets the x coordinate of the ROI without changing its width

property y

Returns / sets the y coordinate of the ROI without changing its height

class hyperspy.roi.SpanROI(left=None, right=None)

Bases: hyperspy.roi.BaseInteractiveROI

Selects a range in a 1D space. The coordinates of the range in the 1D space are stored in the traits ‘left’ and ‘right’.

SpanROI can be used in place of a tuple containing the left and right values.

Example

>>> roi = hs.roi.SpanROI(-3, 5)
>>> left, right = roi
>>> print(left, right)
3 5

Sets up events.changed event, and inits HasTraits.

_apply_roi2widget(widget)

This function is responsible for applying the ROI geometry to the widget. When this function is called, the widget’s events are already suppressed, so this should not be necessary for _apply_roi2widget to handle.

_get_ranges()

Utility to get the value ranges that the ROI would select.

If the ROI is point base or is rectangluar in nature, these can be used to slice a signal. Extracted from _make_slices() to ease implementation in inherited ROIs.

_get_widget_type(axes, signal)

Get the type of a widget that can represent the ROI on the given axes and signal.

_set_default_values(signal, axes=None)

When the ROI is called interactively with Undefined parameters, use these values instead.

_set_from_widget(widget)

Sets the internal representation of the ROI from the passed widget, without doing anything to events.

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.

is_valid()

Determine if the ROI is in a valid state.

This is typically determined by all the coordinates being defined, and that the values makes sense relative to each other.

hyperspy.roi._get_central_half_limits_of_axis(ax)

Return indices of the central half of a DataAxis

hyperspy.roi._get_mpl_ax(plot, axes)

Returns MPL Axes that contains the axes.

The space of the first DataAxis in axes will be used to determine which plot’s matplotlib Axes to return.

Parameters
  • plot (MPL_HyperExplorer) – The explorer that contains the navigation and signal plots.

  • axes (collection of DataAxis) – The axes to infer from.