Interactive (erlab.interactive)

Interactive tools based on Qt and pyqtgraph.

This module provides interactive tools for plotting and analyzing ARPES data. See the sidebar on the right for a list of available tools.

Commonly used tools are available directly in the erlab.interactive namespace, so regular users should not need to import the submodules directly.

Documentation of classes and functions in submodules mostly contain implementation details for advanced users who want to create new interactive tools. See Authoring interactive tools for a contributor-oriented walkthrough, and use the source code of erlab.interactive.utils and erlab.interactive.colors as the main reference implementations.

Modules

imagetool

Interactive visualization tool for multidimensional image-like data.

bzplot

colors

Functions for manipulating colors in Qt.

derivative

Interactive tool for visualizing dispersive data.

explorer

Quickly browse and load ARPES data files with a file manager-like interface.

fermiedge

kspace

Interactive momentum conversion tool.

utils

Various helper functions and extensions to Qt and pyqtgraph.

erlab.interactive.data_explorer(directory=None, loader_name=None, *, execute=None)[source]

Start the data explorer.

Data explorer is a tool to browse and load ARPES data files with a file manager-like interface. Data attributes of supported files can be quickly inspected, and can be loaded into ImageTool manager for further analysis.

The data explorer can be started from the command line as a standalone application with the following command:

python -m erlab.interactive.explorer

Also, it can be opened from the GUI by selecting “File” -> “Data Explorer” or by pressing Ctrl+E in ImageTool manager.

Parameters:
  • directory (str | PathLike | None, default: None) – Initial directory to display in the explorer.

  • loader_name (str | None, default: None) – Stable name of the loader to use. This can identify a registered loader or a built-in Data Explorer loader.

erlab.interactive.dtool(data, data_name=None, *, execute=None)[source]

Interactive tool for visualizing dispersive data.

This tool can also be accessed from the right-click context menu of an image plot in an ImageTool window.

Parameters:
  • data (DataArray) – Data to visualize. Must be a 2D DataArray with no NaN values.

  • data_name (str | None, default: None) – Name of the data variable in the generated code. If not provided, the name is automatically determined.

erlab.interactive.ftool(data, model=None, params=None, *, uncertainty=None, data_name=None, model_name=None, uncertainty_name=None, scale_covar=None, execute=None)[source]

Launch an interactive fitting tool.

The tool provides an interactive GUI for fitting 1D models to 1D or 2D data.

See the ftool reference for more information about the tool.

Parameters:
  • data (DataArray | Dataset) – The 1D or 2D data to fit. Also accepted is a fit result xarray.Dataset, from which the data to fit will be extracted. In this case, the tool will attempt to restore the fit state from the dataset.

  • model (Model | None, default: None) – The model to fit to the data. If None, MultiPeakModel will be used.

  • params (Parameters | dict[str, Any] | None, default: None) – Initial parameters for the fit. If None, parameters will be initialized from the model. If data is 2D, params can be a dictionary that is interpreted like the params argument of xarray.DataArray.xlm.modelfit().

  • uncertainty (DataArray | None, default: None) – Absolute standard uncertainty of data. It must align with and broadcast to data. Values must be finite and strictly positive wherever data is finite. The fit uses its reciprocal as the lmfit weights.

  • data_name (str, optional) – The name of the data variable, used in code generation. If None, an attempt will be made to infer the name from the calling context.

  • model_name (str, optional) – The name of the model variable, used in code generation. If None, an attempt will be made to infer the name from the calling context.

  • uncertainty_name (str, optional) – The name of the uncertainty variable, used in code generation. If None, an attempt will be made to infer the name from the calling context.

  • scale_covar (bool | None, default: None) – Whether lmfit scales the parameter covariance by reduced chi-square. If None, the default is True without uncertainty and False with uncertainty. A restored fit result keeps its saved setting when all results agree and the saved weighting is available.

erlab.interactive.goldtool(data, data_corr=None, *, data_name=None, execute=None, **kwargs)[source]

Interactive tool for correcting curved Fermi edges.

This tool can also be accessed from the right-click context menu of an image plot in an ImageTool window.

Parameters:
  • data (DataArray) – The data to perform Fermi edge fitting on. Must be a 2D DataArray with an ‘eV’ dimension.

  • data_corr (DataArray | None, default: None) – The data to correct with the edge. Defaults to data.

  • data_name (str | None, default: None) – Name of the data used in generating the code snipped copied to the clipboard. Overrides automatic detection.

  • **kwargs – Arguments passed onto erlab.interactive.utils.AnalysisWindow.

erlab.interactive.itool(data, *, link=False, link_colors=True, manager=None, replace=None, execute=None, **kwargs)[source]

Create and display ImageTool windows.

This tool can also be conveniently accessed with xarray.DataArray.qshow() and xarray.Dataset.qshow().

Parameters:
  • data (DataArray, Dataset, DataTree, numpy.ndarray, list of DataArray or list of numpy.ndarray) –

    The data to be displayed. Data can be provided as:

    • A xarray.DataArray with 2 to 4 dimensions

      The DataArray will be displayed in an ImageTool window. DataArrays with more than 4 non-singleton dimensions can be reduced interactively before opening.

    • A numpy array with 2 to 4 dimensions

      The array is converted to a DataArray with dimensions named dim_0, dim_1, and so on. No coordinate values, name, or attributes are added. Arrays with more than 4 non-singleton dimensions can be reduced interactively before opening.

    • A list of the above objects

      Multiple ImageTool windows will be created and displayed.

    • A xarray.Dataset

      If the Dataset contains multiple displayable DataArrays, ImageTool asks which variables to open. Data variables with less than 2 effective dimensions are ignored. Variables with more than 4 non-singleton dimensions can be reduced interactively before opening.

    • A xarray.DataTree

      Every leaf node will be parsed as a xarray.Dataset. If the DataTree contains multiple displayable DataArrays, ImageTool asks which variables to open, grouped by DataTree node path.

  • link (bool, default: False) – Whether to enable linking between multiple ImageTool windows when data is a sequence or a xarray.Dataset, by default False.

  • link_colors (bool, default: True) – Whether to link the color maps between multiple linked ImageTool windows, by default True. This argument has no effect if link is set to False.

  • manager (bool | int | None, default: None) –

    Whether to open the ImageTool window(s) using the ImageToolManager if it is running. An integer targets a specific 0-based manager index. If True, the current process default manager is used, or the only live manager if no default is set. If multiple managers are live and no default has been selected, an error is raised. If not provided, the manager will only be used if it is in the same process as the caller.

    Changed in version 3.4.0: Argument renamed from use_manager to manager.

    Changed in version 3.22.0: Integer manager indexes select a specific ImageTool Manager instance.

  • replace (Collection[int] | int | None, default: None) –

    When using the manager, this argument specifies which existing ImageTool windows should be replaced with the new data. If the manager is not used, this argument is ignored. replace can be set to:

    • None (default): no existing windows are replaced. New windows are created for the new data.

    • A single integer: this can be a valid existing index (replace that window), one greater than the current largest index (create a new window), or a negative index from the end (for example, -1 means the largest existing index).

    • A list of integers: each integer is interpreted as described above. The list length must match the number of windows data is expected to create.

    If this argument is used, the link, link_colors, and kwargs arguments are ignored, since no new windows are created.

  • execute (bool | None, default: None) –

    Whether to execute the Qt event loop and display the window, by default None. For more information, see erlab.interactive.utils.setup_qapp().

    This argument has no effect when the ImageTool window(s) are opened in the manager.

  • **kwargs – Additional keyword arguments passed to the underlying slicer area when a new ImageTool window is created. These arguments are ignored when replace is used. For the supported arguments, see the erlab.interactive.imagetool.viewer.ImageSlicerArea documentation.

Returns:

ImageTool or list of ImageTool or None – The created ImageTool window(s).

If the window(s) are executed, the function will return None, since the event loop will prevent the function from returning until the window(s) are closed.

If the window(s) are not executed, for example while running in an IPython shell with %gui qt, the function will not block and return the ImageTool window(s) or a list of ImageTool windows depending on the input data.

The function will also return None if the windows are opened in the ImageToolManager.

Return type:

ImageTool | list[ImageTool] | None

Examples

>>> itool(data, cmap="gray", gamma=0.5)
>>> itool([data1, data2], link=True)
erlab.interactive.ktool(data, avec=None, rotate_bz=None, centering=None, *, cmap=None, gamma=None, data_name=None, initial_normal_emission=None, initial_delta=None, options_model=None, execute=None, _initial_delta_from_guideline=False)[source]

Interactive momentum conversion tool.

This tool can also be accessed with DataArray.kspace.interactive(), or from the View menu of an ImageTool window.

Parameters:
  • data (DataArray) – Data to convert. Currently supports constant energy slices (2D data with alpha and beta dimensions), 2D angle-energy cuts with alpha and eV dimensions and a fixed or assigned beta coordinate, and all 3D data that has eV and alpha dimensions, including maps and photon energy dependent data.

  • avec (array-like, optional) – Real-space lattice vectors as a 2x2 or 3x3 numpy array. If provided, the Brillouin zone boundary overlay will be calculated based on these vectors. If given as a 2x2 array, the third row and column will be assumed to be all 0. You can use utilities from erlab.lattice to construct these vectors.

  • rotate_bz (float | None, default: None) – Rotation angle for the Brillouin zone boundary overlay.

  • centering (Literal['P', 'A', 'B', 'C', 'F', 'I', 'R'] | None, default: None) – Optional centering type to convert the conventional unit cell into a primitive one. Must be one of "P" (primitive), "A", "B", "C", "I" (body-centered), "F" (face-centered), and "R" (rhombohedral).

  • cmap (str, optional) – Name of the colormap to use.

  • gamma (float | None, default: None) – Initial gamma value for the colormap.

  • data_name (str | None, default: None) – Name of the data variable in the generated code. If not provided, the name is automatically determined.

  • initial_normal_emission (tuple[float, float] | None, default: None) – Optional pair of (alpha, beta) values used once during initialization to seed the normal emission controls and derived angle offsets.

  • initial_delta (float | None, default: None) – Optional delta value to apply alongside initial_normal_emission.

erlab.interactive.meshtool(data, data_name=None, *, execute=None)[source]

Interactive tool for mesh removal.

This tool can also be accessed from the menu in ImageTool.

Parameters:
  • data (DataArray) – Data to extract the mesh from. The data dimensions must include ‘alpha’ and ‘eV’. All other dimensions are averaged over to extract the mesh pattern.

  • data_name (str | None, default: None) – Name of the data variable in the generated code. If not provided, the name is automatically determined.

erlab.interactive.ptable(*, hv=None, workfunction=None, max_harmonic=1, notation=None, execute=None)[source]

Open the periodic table window.

The periodic table provides an interactive reference for XPS-relevant elemental properties, including x-ray absorption edges, ground-state electron configurations, and photoionization cross sections.

See Periodic table for an overview of the features and user interface.

Parameters:
  • hv (float | None, default: None) – Optional photon energy in eV. When given, the inspector also shows kinetic energies and marks the photon energy on the cross-section plot.

  • workfunction (float | None, default: None) – Optional work function in eV used for converting an absorption edge to kinetic energy.

  • max_harmonic (int, default: 1) – Highest harmonic order to include when kinetic energies are shown. Harmonics are integer multiples of hv from 1 through max_harmonic.

  • notation (str | None, default: None) – Initial energy-level notation. When omitted, the most recently used notation is restored. Explicit values should be either "orbital" or "iupac".

  • execute (bool | None, default: None) – Passed through to erlab.interactive.utils.setup_qapp().

Notes

The periodic table combines several reference datasets.

erlab.interactive.restool(data, *, data_name=None, execute=None)[source]

Interactive tool for precise resolution fitting of EDCs.

This tool can also be accessed from the right-click context menu of an image plot in an ImageTool window.

Parameters:
  • data (DataArray) – Data to visualize. Must be a 2D DataArray with an ‘eV’ dimension.

  • data_name (str | None, default: None) – Name of the data variable in the generated code. If not provided, the name is automatically determined.

Interactive-tool authoring API

The following protected members are extension points for interactive tools. Use them only when you implement a subclass of erlab.interactive.utils.ToolWindow.

ToolWindow.sigInfoChanged
ToolWindow.sigStateChanged
ToolWindow.sigDataChanged
ToolWindow._append_persistence_payload(ds)[source]

Append optional save-only payload that should not participate in history.

ToolWindow._restore_persistence_payload(ds)[source]

Restore optional payload saved by _append_persistence_payload().

ToolWindow._persistence_data_items()[source]

Return named data artifacts that belong to this saved tool window.

ToolWindow._restore_persistence_data_items(data_items, ds)[source]

Restore named data artifacts saved by _persistence_data_items().

ToolWindow._cancel_background_work(*, timeout_ms)[source]

Stop any running background work before mutating the tool state.

Subclasses should override this when updates from ImageTool must wait for worker shutdown before tearing down widgets or replacing internal state.

ToolWindow._run_or_defer_restore_work(callback, *, key=None, run_on_show=False)[source]

Run optional restore work now, or queue it while restore is deferred.

This is the default hook for subclass authors. Call it where restore-time work would otherwise deserialize, render, or recompute optional data. The callback is run immediately for normal standalone restores and queued during manager workspace restore. Set run_on_show=True when hidden tools can wait until the user shows the window. If the window closes first, its queued work is discarded without running.

The callback itself is normally the queue key, so repeated calls coalesce. Pass key only when another method must address the work by a stable handle, for example to preserve a raw persisted payload while saving.

ToolWindow._flush_restore_work(callback=None, *, key=None, run_on_show_only=False, skip=())[source]

Materialize queued work before returning data or serialized state.

ToolWindow already calls this before save, copy/provenance generation, output access, and show. Subclasses should call it only at narrower correctness boundaries they own, such as a property that returns a derived result. Use skip only when saving can preserve a still-deferred raw payload unchanged.

ToolWindow._discard_restore_work(callback=None, *, key=None)[source]

Drop queued restore work that has been superseded by fresher work.

Subclasses should call this sparingly, only when explicit recomputation has already produced the data that a queued restore callback would produce. This prevents stale restore-time previews or caches from running later.

final ToolWindow._write_state(*_args)[source]
ToolWindow._reset_history_stack()[source]
final ToolWindow._replace_last_state(*_args)[source]
ToolWindow._notify_data_changed()[source]

Notify manager-facing listeners that displayed tool data has changed.

ToolWindow._defer_source_refresh()[source]

Keep the current input transaction pending until explicit completion.

ToolWindow.validate_update_inputs(inputs)[source]

Validate or normalize the complete named input mapping.

ToolWindow.update_inputs(inputs)[source]

Apply a validated complete input mapping to the existing window.

ToolWindow._launch_output_imagetool(data, *, output_id)[source]

Open or refresh a manager-tracked child ImageTool for a declared output.

ToolWindow._launch_detached_output_imagetool(data, *, provenance_spec=None)[source]

Open a new unbound ImageTool from this tool.

Managed tools create a fresh independent top-level manager window with detached replay provenance when the caller provides it. Standalone tools create a fresh standalone ImageTool window. To use the tool’s detached-output provenance hook, call it explicitly and pass its result as provenance_spec.

These implementation classes provide examples for tool authors. Their public launcher functions remain the supported user interface.

class erlab.interactive.derivative.DerivativeTool(data, *, data_name=None)[source]

Bases: ToolWindow

DerivativeTool.result
class erlab.interactive.kspace.KspaceToolGUI(avec=None, rotate_bz=None, centering=None, cmap=None, gamma=None, options_model=None)[source]

Bases: ToolWindow

class erlab.interactive.kspace.KspaceTool(data, avec=None, rotate_bz=None, centering=None, *, cmap=None, gamma=None, data_name=None, initial_normal_emission=None, initial_delta=None, options_model=None, _input_coordinates=None, _input_coordinate_edited_names=(), _configuration=None)[source]

Bases: KspaceToolGUI

class erlab.interactive.fermiedge.GoldTool(data, data_corr=None, *, data_name=None, **kwargs)[source]

Bases: AnalysisWindow

Interactive gold edge fitting.

Parameters:
  • data (DataArray) – The data to perform Fermi edge fitting on.

  • data_corr (DataArray | None, default: None) – The data to correct with the edge. Defaults to data.

  • data_name (str | None, default: None) – Name of the data used in generating the code snipped copied to the clipboard. Overrides automatic detection.

  • execute – Whether to execute the tool immediately.

  • **kwargs – Arguments passed onto erlab.interactive.utils.AnalysisWindow.

Signals:
  • sigProgressUpdated(int) – Signal used to update the progress bar.

  • sigAbortFitting() – Signal used to abort the fitting, emitted when the cancel button is clicked.

  • sigUpdated() – Signal emitted when all fitting steps are finished and plots are updated.

GoldTool.validate_update_inputs(inputs)[source]
GoldTool.update_inputs(inputs)[source]
class erlab.interactive.fermiedge.ResolutionTool(data, *, data_name=None)[source]

Bases: ToolWindow

class erlab.interactive._mesh.MeshTool(data, *, data_name=None)[source]

Bases: ToolWindow

class erlab.interactive._fit1d.Fit1DTool(data, model=None, params=None, *, uncertainty=None, data_name=None, model_name=None, uncertainty_name=None, scale_covar=None)[source]

Bases: ToolWindow

GUI for selecting initial parameters and bounds for 1D curve fitting.

Parameters:
  • model (Model | None, default: None) – The lmfit model to fit. If None, uses MultiPeakModel, and displays options for model initialization.

  • data (DataArray) – The 1D data to fit.

  • data_name (str | None, default: None) – Optional display name for the dataset.

Signals:

sigFitFinished(lmfit.Parameters) – Emitted after a successful fit with the latest parameters.

class erlab.interactive._fit2d.Fit2DTool(data, model=None, params=None, *, uncertainty=None, data_name=None, model_name=None, uncertainty_name=None, scale_covar=None)[source]

Bases: Fit1DTool

Interactive tool for fitting 1D curves to images.

class erlab.interactive._fit2d.Fit2DTool.Output(*values)

Bases: StrEnum

PARAMETER_VALUES = 'fit2d.param_plot.values'
PARAMETER_VALUES_FOR_WEIGHTED_FIT = 'fit2d.param_plot.values_for_weighted_fit'
PARAMETER_STDERR = 'fit2d.param_plot.stderr'
Fit2DTool._show_dataarray_in_itool(data, *, output_id=None)[source]
class erlab.interactive.imagetool.plot_items.ItoolPlotItem(slicer_area, display_axis, axis_enabled, image=False, image_cls=None, plotdata_cls=None, **item_kw)[source]

Bases: PlotItem

A subclass of pyqtgraph.PlotItem used in ImageTool.

This class tracks axes and cursors for the data displayed in the plot, and provides context menu actions for interacting with the data.

ItoolPlotItem.make_tool_source_spec(*, transpose=False, squeeze=False)[source]

Return a source spec for the current plot selection.

The spec contains qsel, isel, and sel operations for the current parent data. Copied code, derivation display, manager refresh, and saved workspaces use this form directly.

Parameters:
  • transpose (bool, default: False) – Whether to append a transpose step for the opened tool.

  • squeeze (bool, default: False) – Whether to append a squeeze step for singleton dimensions.

Returns:

ToolProvenanceSpec – Source spec for the current parent data.

Return type:

ToolProvenanceSpec