erlab.interactive.imagetool.viewer

Provides core functionality of ImageTool.

This module contains ImageSlicerArea which handles the core functionality of ImageTool, including the slicing and plotting of data.

Functions

link_slicer([func, indices, steps, color])

Sync decorated methods across multiple ImageSlicerArea instances.

record_history([method])

Log history before calling the decorated method.

suppress_history([method])

Ignore history changes made within the decorated method.

Classes

ColorMapState

A dictionary containing the colormap state of an ImageSlicerArea instance.

GuidelineState

A dictionary containing the state of rotation guidelines.

ImageSlicerArea(parent, data[, cmap, gamma, ...])

An interactive tool based on pyqtgraph for exploring 3D data.

ImageSlicerState

A dictionary containing the state of an ImageSlicerArea instance.

PlotItemState

A dictionary containing the state of a PlotItem instance.

SlicerLinkProxy(*slicers[, link_colors])

Internal class for handling linked ImageSlicerArea s.

class erlab.interactive.imagetool.viewer.ColorMapState[source]

Bases: TypedDict

A dictionary containing the colormap state of an ImageSlicerArea instance.

cmap: str | ColorMap
gamma: float
reverse: bool
high_contrast: bool
zero_centered: bool
levels_locked: bool
levels: NotRequired[tuple[float, float]]
class erlab.interactive.imagetool.viewer.GuidelineState[source]

Bases: TypedDict

A dictionary containing the state of rotation guidelines.

count: Literal[1, 2, 3]
angle: float
offset: tuple[float, float]
follow_cursor: bool
class erlab.interactive.imagetool.viewer.PlotItemState[source]

Bases: TypedDict

A dictionary containing the state of a PlotItem instance.

vb_aspect_locked: bool | float
vb_x_inverted: NotRequired[bool]
vb_y_inverted: NotRequired[bool]
vb_autorange: NotRequired[tuple[bool, bool]]
roi_states: NotRequired[list[dict[str, Any]]]
guideline_state: NotRequired[GuidelineState]
class erlab.interactive.imagetool.viewer.ImageSlicerState[source]

Bases: TypedDict

A dictionary containing the state of an ImageSlicerArea instance.

color: ColorMapState
slice: ArraySlicerState
current_cursor: int
manual_limits: dict[str, list[float]]
axis_inversions: typing.NotRequired[dict[str, bool]]
cursor_colors: list[str]
controls_visible: typing.NotRequired[bool]
file_path: typing.NotRequired[str | None]
load_func: typing.NotRequired[tuple[str, dict[str, typing.Any], _FileSelection] | None]
splitter_sizes: typing.NotRequired[list[list[int]]]
plotitem_states: typing.NotRequired[list[PlotItemState]]
erlab.interactive.imagetool.viewer.suppress_history(method=None)[source]

Ignore history changes made within the decorated method.

erlab.interactive.imagetool.viewer.record_history(method=None)[source]

Log history before calling the decorated method.

Sync decorated methods across multiple ImageSlicerArea instances.

Parameters:
  • func (Callable | None, default: None) – The method to sync across multiple instances of ImageSlicerArea.

  • indices (bool, default: False) – If True, the input argument named value given to func are interpreted as indices, and will be converted to appropriate values for other instances of ImageSlicerArea. The behavior of this conversion is determined by steps. If True, An input argument named axis of type integer must be present in the decorated method to determine the axis along which the index is to be changed.

  • steps (bool, default: False) – If False, considers value as an absolute index. If True, considers value as a relative value such as the number of steps or bins. See the implementation of SlicerLinkProxy for more information.

  • color (bool, default: False) – Boolean whether the decorated method is related to visualization, such as colormap control.

class erlab.interactive.imagetool.viewer.SlicerLinkProxy(*slicers, link_colors=True)[source]

Bases: object

Internal class for handling linked ImageSlicerArea s.

Parameters:
  • *slicers (ImageSlicerArea) – The slicers to link.

  • link_colors (bool, default: True) – Whether to sync color related changes, by default True.

property children: WeakSet
property num_children: int
add(slicer_area)[source]
remove(slicer_area)[source]
sync(source, funcname, arguments, indices, steps, color, transaction_id, keep_pending)[source]

Propagate changes across multiple ImageSlicerAreas.

This method is invoked every time a method decorated with link_slicer() in a linked ImageSlicerArea is called.

Parameters:
convert_args(source, target, args, indices, steps, transaction_id, keep_pending)[source]
static convert_index(source, target, axis, index, steps)[source]
class erlab.interactive.imagetool.viewer.ImageSlicerArea(parent, data, cmap=None, gamma=None, high_contrast=False, zero_centered=False, vmin=None, vmax=None, rad2deg=False, *, transpose=False, bench=False, state=None, file_path=None, load_func=None, auto_compute=True, image_cls=None, plotdata_cls=None, _in_manager=False)[source]

Bases: QWidget

An interactive tool based on pyqtgraph for exploring 3D data.

Parameters:
  • parent (QWidget) – Parent widget.

  • data (DataArray or array-like) – Data to display. The data must have 2 to 4 dimensions.

  • cmap (str | ColorMap | None, default: None) – Default colormap of the data.

  • gamma (float, optional) – Default power law normalization of the colormap.

  • high_contrast (bool, default: False) – If True, the colormap is displayed in high contrast mode. This changes the behavior of the exponent scaling of the colormap. See erlab.plotting.colors for a detailed explanation of the difference.

  • zero_centered (bool, default: False) – If True, the normalization is applied symmetrically from the midpoint of the colormap.

  • vmin (float | None, default: None) – Minimum value of the colormap.

  • vmax (float | None, default: None) – Maximum value of the colormap.

  • rad2deg (bool | Iterable[str], default: False) – If True and data is not None, converts some known angle coordinates to degrees. If an iterable of strings is given, only the coordinates that correspond to the given strings are converted.

  • transpose (bool, default: False) – If True, the main image is transposed before being displayed.

  • bench (bool, default: False) – Prints the fps on Ctrl + drag for debugging purposes.

  • state (ImageSlicerState | None, default: None) – Initial state containing the settings and cursor position.

  • file_path (str | PathLike | None, default: None) – Path to the file from which the data was loaded. If given, the file path is used to set the window title and when reloading the data. To successfully reload the data, load_func must also be provided.

  • load_func (tuple[Callable[..., Any] | str, dict[str, Any], int | dict[str, Any] | FileDataSelection] | None, default: None) – 3-tuple containing the function, a dictionary of keyword arguments, and the selection of the data variable used when loading the data. The function is called when reloading the data. If using a data loader plugin, the function may be given as a string representing the loader name.

Signals:
  • sigDataChanged()

  • sigCurrentCursorChanged(index)

  • sigViewOptionChanged()

  • sigHistoryChanged()

  • sigWriteHistory()

  • sigCursorColorsChanged()

  • sigDataEdited() – Signal to track when the data has been modified by user actions.

  • sigSourceDataReplaced() – Signal emitted when the underlying source data is replaced or otherwise changed at the source level, such as file open, reload, manager-driven replacement, or in-place console edits.

  • sigPointValueChanged(value) – Signal emitted when the point value at the current cursor has been computed. Only emitted for dask-backed data.

  • sigCursorCountChanged(n_cursors) – Inherited from erlab.interactive.slicer.ArraySlicer.

  • sigIndexChanged(cursor, axes) – Inherited from erlab.interactive.slicer.ArraySlicer.

  • sigBinChanged(cursor, axes) – Inherited from erlab.interactive.slicer.ArraySlicer.

  • sigShapeChanged() – Inherited from erlab.interactive.slicer.ArraySlicer.

  • sigTwinChanged() – Inherited from erlab.interactive.slicer.ArraySlicer.

property provenance_spec: ToolProvenanceSpec | None

Canonical replay provenance for the current ImageTool data.

property COLORS: tuple[QColor, ...]

PySide6.QtGui.QColors for multiple cursors.

TWIN_COLORS: tuple[QColor, ...] = (<PyQt6.QtGui.QColor object>, <PyQt6.QtGui.QColor object>, <PyQt6.QtGui.QColor object>, <PyQt6.QtGui.QColor object>, <PyQt6.QtGui.QColor object>)

PySide6.QtGui.QColors for twin plots.

HORIZ_PAD: int = 45

Reserved space for the x axes in each plot.

VERT_PAD: int = 30

Reserved space for the y axes in each plot.

TICK_FONT_SIZE: float = 11.0

Font size of axis ticks in points.

property parent_title: str
property display_name: str

Generate a display name for the slicer.

Depending on the source of the data and the ‘name’ attribute of the underlying DataArray, the display name is generated differently.

If nothing can be inferred, an empty string is returned.

property colormap_properties: ColorMapState
property controls_visible: bool
property state: ImageSlicerState
property splitter_sizes: list[list[int]]
property is_linked: bool
property linked_slicers: WeakSet
property colormap: str | ColorMap
property levels_locked: bool
property levels: tuple[float, float]
property slices: tuple[ItoolPlotItem, ...]
property profiles: tuple[ItoolPlotItem, ...]
property main_image: ItoolPlotItem

Return the main PlotItem.

property images: tuple[ItoolPlotItem, ...]
property axes: tuple[ItoolPlotItem, ...]

Currently valid subset of self._plots.

property array_slicer: ArraySlicer
property n_cursors: int
property current_indices: list[int]
property current_values: list[float]
property current_values_uniform: list[float]
property data: DataArray
property undoable: bool
property redoable: bool
history_suppressed()[source]
history_group(timeout_ms=300)[source]
begin_history_group(timeout_ms=_HISTORY_GROUP_IDLE_TIMEOUT_MS)[source]
end_history_group()[source]
next_linked_history_transaction_id()[source]
begin_history_entry(transaction_id)[source]
finalize_history_entry(*, keep_pending=False)[source]
record_history_mutation(transaction_id, mutation, *, keep_pending=False)[source]
write_state()[source]
flush_history()[source]

Clear the undo and redo history.

undo()[source]

Undo the most recent action.

redo()[source]

Redo the most recently undone action.

history_states(*, finalize_pending=True)[source]
history_entry_changes(*, finalize_pending=True)[source]
go_to_history_index(index)[source]

Go to a specific index in the history.

Parameters:

index (int) – Index in the history to go to. 0 corresponds to the current state. Positive indices point to the future, while negative indices point to the past.

initialize_actions()[source]

Initialize QtWidgets.QAction instances.

edit_cursor_colors()[source]

Open a dialog to edit cursor colors.

refresh_actions_enabled()[source]

Refresh the enabled state of miscellaneous actions.

This slot is triggered from the parent widget when the menubar containing the actions is about to be shown.

connect_axes_signals()[source]
disconnect_axes_signals()[source]
connect_signals()[source]
get_current_index(axis)[source]
get_current_value(axis, uniform=False)[source]
get_axes_widget(index)[source]
get_axes(index)[source]
close_associated_windows()[source]
refresh_all(axes=None, only_plots=False)[source]
refresh_current(axes=None)[source]
refresh(cursor, axes=None)[source]
view_all()[source]
center_all_cursors()[source]
center_cursor()[source]
set_current_cursor(cursor, update=True)[source]
set_data(data, rad2deg=False, file_path=None, load_func=None, auto_compute=True, *, source_replaced=False)[source]

Set the data to be displayed.

Parameters:
  • data (DataArray | ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]) – The data to be displayed. If a xarray.DataArray is given, the dimensions and coordinates are used to determine the axes of the plots. If a xarray.Dataset is given, the first data variable is used. If a numpy.ndarray is given, it is converted to a xarray.DataArray with default dimensions.

  • rad2deg (bool | Iterable[str], default: False) – If True, converts coords along dimensions that have angle-like names to degrees. If an iterable of strings is given, coordinates for dimensions that correspond to the given strings are converted.

  • file_path (str | PathLike | None, default: None) – Path to the file from which the data was loaded. If given, the file path is used to set the window title and when reloading the data. To successfully reload the data, load_func must also be provided.

  • load_func (tuple[Callable[..., Any] | str, dict[str, Any], int | dict[str, Any] | FileDataSelection] | None, default: None) – 3-tuple containing the function, a dictionary of keyword arguments, and the selection of the data variable used when loading the data. The function is called when reloading the data. If using a data loader plugin, the function may be given as a string representing the loader name.

  • auto_compute (bool, default: True) – If True and the data is dask-backed, automatically compute the data if its size is below the threshold defined in options.

replace_source_data(data, rad2deg=False, file_path=None, load_func=None, auto_compute=True, *, emit_edited=False)[source]

Replace the underlying source data and notify bound child tools.

Parameters are the same as set_data(), with the addition of emit_edited to indicate that the replacement should also be treated as a user edit for watcher propagation.

property reloadable: bool

Check if the displayed data can be reloaded.

Direct file-backed windows reload from their stored loader. Detached file-rooted provenance reloads by replaying its self-contained code. Managed script-derived ImageTools reload through the manager from their recorded inputs.

Returns:

boolTrue if the data can be reloaded, False otherwise.

reload()[source]

Reload the displayed data from recorded source information.

Silently fails if the data cannot be reloaded. If an error occurs while reloading the data, a message is shown to the user.

See also

reloadable

update_values(values, update=True)[source]

Update only the values of the data.

The coords and shape of the data array are not changed.

Parameters:
  • values (ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | DataArray) – The new values to be set. If a xarray.DataArray is given, the dimensions must match the current data array. If a numpy.ndarray is given, the shape must match the current data array. Note that if the user has transposed the current data array, passing a numpy.ndarray with the original shape will fail.

  • update (bool, default: True) – If True, the plots are updated after setting the new values.

Note

This method only checks for matching dimension name and shape, and does not check for equal coordinate values.

displayed_provenance_spec(base_spec=None)[source]

Return provenance for the currently displayed data values.

apply_func(func, update=True, *, operation=None)[source]

Apply a function to the data.

The function must accept the data as the first argument and return a new DataArray. The returned DataArray must have the same dimensions and coordinates as the original data.

This action is not recorded in the history, and the data is not affected. Only one function can be applied at a time.

Parameters:
  • func (Callable[[DataArray], DataArray] | None) – The function to apply to the data. if None, the data is restored.

  • update (bool, default: True) – If True, the plots are updated after setting the new values.

set_manual_limits(manual_limits)[source]

Set manual limits for the axes.

Replaces the current manual limits with the given limits dictionary and updates all child axes accordingly.

apply_axis_inversions()[source]
set_axis_inverted(dim, inverted)[source]
propagate_limit_change(axes)[source]

Propagate manual limits changes to all linked slicers.

Called when the limits of a child axes are changed by the user.

This method first propagates the limits to all linked slicers (if any), and then triggers the update of the manual limits for all other axes. This ensures that all plots share the same limits for a given dimension.

make_slice_dict()[source]

Create a dictionary of slices for current manual limits.

Returns:

dict – A dictionary mapping dimension names to slices.

Return type:

dict[Hashable, slice]

property watched_data_name: str | None

Get the name of the watched data variable.

Only applicable if in an ImageTool Manager and the data is linked to a watched variable in a notebook. Returns None if otherwise.

property data_chunked: bool

Check if the data is chunked (backed by dask).

Returns:

boolTrue if the data is chunked, False otherwise.

property data_file_backed: bool

Check if non-dask data is still lazily backed by a file.

property data_loadable: bool

Check if the data can be explicitly loaded into memory.

swap_axes(ax1, ax2)[source]
transpose_main_image()[source]
set_index(axis, value, update=True, cursor=None)[source]
step_index(axis, value, update=True, cursor=None)[source]
step_index_all(axis, value, update=True)[source]
set_value(axis, value, update=True, uniform=False, cursor=None)[source]
set_bin(axis, value, update=True, cursor=None)[source]
set_bin_all(axis, value, update=True)[source]
make_cursors(colors, *, update=True)[source]

Create cursors with the specified colors.

Used when restoring the state of the slicer. All existing cursors are removed.

add_cursor(color=None, *, update=True)[source]
remove_cursor(index, *, update=True)[source]
remove_current_cursor()[source]
toggle_cursor_visibility()[source]

Toggle the visibility of the cursor lines.

color_for_cursor(index)[source]

Pick a cursor color based on the index.

set_cursor_colors(colors)[source]

Set the colors of the cursors.

Parameters:

colors (Iterable[QColor]) – An iterable of colors to set for the cursors.

set_colormap(cmap=None, gamma=None, reverse=None, high_contrast=None, zero_centered=None, levels_locked=None, levels=None, update=True)[source]
refresh_colormap()[source]
lock_levels(lock)[source]
remove_from_manager()[source]

Remove this ImageTool from the manager, if it is in one.

add_tool_window(widget, update_title=True, transfer_to_manager=True)[source]

Save a reference to an additional window widget.

This is mainly used for handling tool windows such as goldtool and dtool.

The tool window is cleared from memory immediately when it is closed. Closing the main window will close all associated tool windows.

Only pass widgets that are not associated with a parent widget.

If the parent ImageTool is in the manager, the widget is transferred to the manager instead

Parameters:
  • widget (QWidget) – The widget to add.

  • update_title (bool, default: True) – If True, the window title is updated to include the parent title. If False, the window title is not changed.

  • transfer_to_manager (bool, default: True) – If True, the ownership of the widget is transferred to the manager if the parent ImageTool is in the manager. Use False for dialog windows that should not be managed by the manager.

open_in_ktool()[source]

Open the interactive momentum conversion tool.

open_in_meshtool()[source]

Open the interactive mesh removal tool.

adjust_layout(r=(1.2, 1.5, 3.0, 1.0))[source]

Determine the padding and aspect ratios.

Parameters:
  • horiz_pad – Reserved space for the x and y axes.

  • vert_pad – Reserved space for the x and y axes.

  • font_size – Font size of axis ticks in points.

  • r (tuple[float, float, float, float], default: (1.2, 1.5, 3.0, 1.0)) – 4 numbers that determine the aspect ratio of the layout. See notes.

Notes

Axes indices and layout parameters.

     ┌───────────┬───────────┐
r[0] │     1     │     6     │
     │           ├───────────┤
     ├───────────┤     3     │
r[1] │     4     ├───────────┤
     │           │     7     │
     │───────────┼───────┬───┤
     │           │       │   │
r[2] │     0     │   5   │ 2 │
     │           │       │   │
     └───────────┴───────┴───┘
      r[3] * r[2]
toggle_snap(value=None)[source]
changeEvent(evt)[source]