Show4DSTEM#

class quantem.widget.Show4DSTEM(**kwargs: Any)[source]#

Bases: AnyWidget

Fast interactive 4D-STEM viewer with advanced features.

Optimized for speed with binary transfer and pre-normalization. Works with NumPy and PyTorch arrays.

Parameters:
  • data (Dataset4dstem or array_like) – Dataset4dstem object (calibration auto-extracted), 4D array of shape (scan_rows, scan_cols, det_rows, det_cols), or 5D array of shape (n_frames, scan_rows, scan_cols, det_rows, det_cols) for time-series or tilt-series data.

  • scan_shape (tuple, optional) – If data is flattened (N, det_rows, det_cols), provide scan dimensions.

  • pixel_size (float, optional) – Pixel size in Å (real-space). Used for scale bar. Auto-extracted from Dataset4dstem if not provided.

  • k_pixel_size (float, optional) – Detector pixel size in mrad (k-space). Used for scale bar. Auto-extracted from Dataset4dstem if not provided.

  • center (tuple[float, float], optional) – (center_row, center_col) of the diffraction pattern in pixels. If not provided, defaults to detector center.

  • bf_radius (float, optional) – Bright field disk radius in pixels. If not provided, estimated as 1/8 of detector size.

  • precompute_virtual_images (bool, default True) – Precompute BF/ABF/LAADF/HAADF virtual images for preset switching.

  • frame_dim_label (str, optional) – Label for the frame dimension when 5D data is provided. Defaults to “Frame”. Common values: “Tilt”, “Time”, “Focus”.

  • disabled_tools (list of str, optional) – Tool groups to lock while still showing controls. Supported: "display", "histogram", "stats", "navigation", "playback", "view", "export", "roi", "profile", "fft", "virtual", "frame", "all".

  • disable_* (bool, optional) – Convenience flags mirroring disabled_tools for each tool group, plus disable_all.

  • hidden_tools (list of str, optional) – Tool groups to hide from the UI. Uses the same keys as disabled_tools.

  • hide_* (bool, optional) – Convenience flags mirroring disable_* for hidden_tools.

Examples

>>> # From Dataset4dstem (calibration auto-extracted)
>>> from quantem.core.io.file_readers import read_emdfile_to_4dstem
>>> dataset = read_emdfile_to_4dstem("data.h5")
>>> Show4DSTEM(dataset)
>>> # From raw array with manual calibration
>>> import numpy as np
>>> data = np.random.rand(64, 64, 128, 128)
>>> Show4DSTEM(data, pixel_size=2.39, k_pixel_size=0.46)
>>> # With raster animation
>>> widget = Show4DSTEM(dataset)
>>> widget.raster(step=2, interval_ms=50)
>>> # 5D time-series or tilt-series data
>>> data_5d = np.random.rand(20, 64, 64, 128, 128)  # 20 frames
>>> Show4DSTEM(data_5d, frame_dim_label="Tilt")

Key Methods

Show4DSTEM.set_image(data, scan_shape=None)[source]#

Replace the 4D-STEM data. Preserves all display and ROI settings.

Show4DSTEM.save_image(path: str | Path, view: str | None = None, position: tuple[int, int] | None = None, frame_idx: int | None = None, format: str | None = None, include_metadata: bool = True, metadata_path: str | Path | None = None, include_overlays: bool | None = None, include_scalebar: bool | None = None, restore_state: bool = True, dpi: int | None = None) Path[source]#

Save the current visualization as PNG or PDF.

Parameters:
  • path (str or pathlib.Path) – Output image path.

  • view (str, optional) – One of: “diffraction”, “virtual”, “fft”, “all”.

  • position (tuple[int, int], optional) – Temporary scan position override as (row, col) for this export.

  • frame_idx (int, optional) – Temporary frame index override for 5D data.

  • format (str, optional) – “png” or “pdf”. If omitted, inferred from file extension.

  • include_metadata (bool, default True) – If True, writes JSON metadata next to the image.

  • metadata_path (str or pathlib.Path, optional) – Override metadata JSON path.

  • include_overlays (bool, optional) – Draw ROI/profile/crosshair overlays on exported panels. Defaults to export_include_overlays.

  • include_scalebar (bool, optional) – Draw panel scale bars on exported panels. Defaults to export_include_scalebar.

  • restore_state (bool, default True) – If True, temporary position/frame overrides are reverted after export.

  • dpi (int, optional) – Export DPI metadata.

Returns:

The written image path.

Return type:

pathlib.Path

Show4DSTEM.save_figure(path: str | Path, template: str = 'dp_vi_fft', position: tuple[int, int] | None = None, frame_idx: int | None = None, format: str | None = None, include_metadata: bool = True, metadata_path: str | Path | None = None, include_overlays: bool | None = None, include_scalebar: bool | None = None, restore_state: bool = True, dpi: int | None = None, title: str | None = None, annotations: dict[str, str] | None = None) Path[source]#
Show4DSTEM.save_sequence(output_dir: str | Path, mode: str = 'path', view: str | None = None, format: str | None = None, include_metadata: bool = True, include_overlays: bool | None = None, include_scalebar: bool | None = None, frame_idx: int | None = None, position: tuple[int, int] | None = None, path_points: list[tuple[int, int]] | None = None, raster_step: int = 1, raster_bidirectional: bool = False, frame_indices: list[int] | None = None, frame_range: tuple[int, int] | None = None, filename_prefix: str | None = None, manifest_name: str = 'save_sequence_manifest.json', restore_state: bool = True, dpi: int | None = None) Path[source]#

ROI

Show4DSTEM.roi_circle(radius: float | None = None) Self[source]#

Switch to circle ROI mode for virtual imaging.

In circle mode, the virtual image integrates over a circular region centered at the current ROI position (like a virtual bright field detector).

Parameters:

radius (float, optional) – Radius of the circle in pixels. If not provided, uses current value or defaults to half the BF radius.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget.roi_circle(20)  # 20px radius circle
>>> widget.roi_circle()    # Use default radius
Show4DSTEM.roi_square(half_size: float | None = None) Self[source]#

Switch to square ROI mode for virtual imaging.

In square mode, the virtual image integrates over a square region centered at the current ROI position.

Parameters:

half_size (float, optional) – Half-size of the square in pixels (distance from center to edge). A half_size of 15 creates a 30x30 pixel square. If not provided, uses current roi_radius value.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget.roi_square(15)  # 30x30 pixel square (half_size=15)
>>> widget.roi_square()    # Use default size
Show4DSTEM.roi_rect(width: float | None = None, height: float | None = None) Self[source]#

Set ROI mode to rectangular.

Parameters:
  • width (float, optional) – Width in pixels. If not provided, uses current roi_width.

  • height (float, optional) – Height in pixels. If not provided, uses current roi_height.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget.roi_rect(30, 20)  # 30px wide, 20px tall
>>> widget.roi_rect(40, 40)  # 40x40 rectangle
Show4DSTEM.roi_annular(inner_radius: float | None = None, outer_radius: float | None = None) Self[source]#

Set ROI mode to annular (donut-shaped) for ADF/HAADF imaging.

Parameters:
  • inner_radius (float, optional) – Inner radius in pixels. If not provided, uses current roi_radius_inner.

  • outer_radius (float, optional) – Outer radius in pixels. If not provided, uses current roi_radius.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget.roi_annular(20, 50)  # ADF: inner=20px, outer=50px
>>> widget.roi_annular(30, 80)  # HAADF: larger angles
Show4DSTEM.roi_point() Self[source]#

Switch to point ROI mode (single-pixel indexing).

In point mode, the virtual image shows intensity at the exact ROI position. This is the default mode.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Show4DSTEM.auto_detect_center(update_roi: bool = True) Self[source]#

Automatically detect BF disk center and radius using centroid.

This method analyzes the summed diffraction pattern to find the bright field disk center and estimate its radius. The detected values are applied to the widget’s calibration (center_row, center_col, bf_radius).

Parameters:

update_roi (bool, default True) – If True, also update ROI center and recompute cached virtual images. Set to False during __init__ when ROI is not yet initialized.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget = Show4DSTEM(data)
>>> widget.auto_detect_center()  # Auto-detect and apply

Line Profile

Show4DSTEM.set_profile(start: tuple, end: tuple) Self[source]#
Show4DSTEM.clear_profile() Self[source]#

Path Animation

Show4DSTEM.set_path(points: list[tuple[int, int]], interval_ms: int = 100, loop: bool = True, autoplay: bool = True) Self[source]#

Set a custom path of scan positions to animate through.

Parameters:
  • points (list[tuple[int, int]]) – List of (row, col) scan positions to visit.

  • interval_ms (int, default 100) – Time between frames in milliseconds.

  • loop (bool, default True) – Whether to loop when reaching end.

  • autoplay (bool, default True) – Start playing immediately.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Examples

>>> widget.set_path([(0, 0), (10, 10), (20, 20), (30, 30)])
>>> widget.set_path([(i, i) for i in range(48)], interval_ms=50)
Show4DSTEM.raster(step: int = 1, bidirectional: bool = False, interval_ms: int = 100, loop: bool = True) Self[source]#

Play a raster scan path (row by row, left to right).

This mimics real STEM scanning: left→right, step down, left→right, etc.

Parameters:
  • step (int, default 1) – Step size between positions.

  • bidirectional (bool, default False) – If True, use snake/boustrophedon pattern (alternating direction). If False (default), always scan left→right like real STEM.

  • interval_ms (int, default 100) – Time between frames in milliseconds.

  • loop (bool, default True) – Whether to loop when reaching the end.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Show4DSTEM.play() Self[source]#

Start playing the path animation.

Show4DSTEM.pause() Self[source]#

Pause the path animation.

Show4DSTEM.stop() Self[source]#

Stop and reset path animation to beginning.

Show4DSTEM.goto(index: int) Self[source]#

Jump to a specific index in the path.

Sparse / Adaptive Acquisition

Show4DSTEM.ingest_scan_point(row: int, col: int, dp: ndarray, frame_idx: int = 0, dose: float | None = None) Self[source]#

Ingest one scanned diffraction pattern into sparse acquisition state.

Parameters:
  • row (int) – Scan-space row index.

  • col (int) – Scan-space column index.

  • dp (array_like) – Diffraction pattern with shape (det_rows, det_cols).

  • frame_idx (int, default 0) – Frame index for 5D data.

  • dose (float, optional) – Dose contribution for this acquisition event. Defaults to 1.0.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Show4DSTEM.ingest_scan_block(rows: list[int] | ndarray, cols: list[int] | ndarray, dp_block: ndarray, frame_idx: int = 0) Self[source]#

Ingest multiple scanned diffraction patterns in one call.

Parameters:
  • rows (list[int] or np.ndarray) – Row indices for each pattern in dp_block.

  • cols (list[int] or np.ndarray) – Column indices for each pattern in dp_block.

  • dp_block (np.ndarray) – Diffraction stack with shape (n_points, det_rows, det_cols).

  • frame_idx (int, default 0) – Frame index for 5D data.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Show4DSTEM.get_sparse_state() dict[str, Any][source]#

Return sparse acquisition state for checkpointing or replay.

Returns:

Sparse state with sampling mask, sampled diffraction stack, sampled-point coordinates, and dose map.

Return type:

dict

Show4DSTEM.set_sparse_state(mask: ndarray, sampled_data: ndarray) Self[source]#

Restore sparse acquisition state from mask + sampled data.

Parameters:
  • mask (np.ndarray) – Boolean scan mask. Shape (scan_rows, scan_cols) for 4D, or (n_frames, scan_rows, scan_cols) for 5D.

  • sampled_data (np.ndarray) – Either compact stack (n_sampled, det_rows, det_cols) matching row-major mask order, or dense data aligned to mask: (scan_rows, scan_cols, det_rows, det_cols) for 4D, (n_frames, scan_rows, scan_cols, det_rows, det_cols) for 5D.

Returns:

Self for method chaining.

Return type:

Show4DSTEM

Show4DSTEM.propose_next_points(k: int, strategy: str = 'adaptive', budget: dict[str, Any] | None = None) list[tuple[int, int]][source]#

Propose next scan points from current sparse acquisition state.

Parameters:
  • k (int) – Maximum number of new points to propose.

  • strategy (str, default "adaptive") – Proposal strategy: "adaptive", "random", or "raster".

  • budget (dict, optional) – Optional constraints and strategy parameters. Supported keys: frame_idx, max_new_points, max_total_points, max_total_fraction, max_total_dose, dose_per_point, roi_mask, seed, min_spacing, step, local_window, dose_lambda, weights, bidirectional.

Returns:

Proposed (row, col) scan coordinates.

Return type:

list[tuple[int, int]]

Show4DSTEM.suggest_adaptive_path(coarse_step: int = 4, target_fraction: float = 0.25, min_spacing: int = 2, include_coarse: bool = True, coarse_bidirectional: bool = True, local_window: int = 5, dose_lambda: float = 0.25, weights: dict[str, float] | None = None, roi_mask: ndarray | None = None, update_widget_path: bool = True, interval_ms: int | None = None, loop: bool = False, autoplay: bool = False, return_maps: bool = False) dict[str, Any][source]#

Suggest a sparse adaptive scan path using coarse-to-fine utility ranking.

The planner computes utility from current virtual-image and diffraction statistics, then selects spatially distributed high-utility points.

Parameters:
  • coarse_step (int, default 4) – Spacing of the initial coarse grid.

  • target_fraction (float, default 0.25) – Target total sampled fraction of scan positions in (0, 1].

  • min_spacing (int, default 2) – Minimum pixel spacing between selected dense points.

  • include_coarse (bool, default True) – If True, include coarse-grid points in the returned path.

  • coarse_bidirectional (bool, default True) – Use snake ordering for coarse-grid traversal.

  • local_window (int, default 5) – Window size for local-std utility component.

  • dose_lambda (float, default 0.25) – Penalty weight for re-sampling coarse points.

  • weights (dict[str, float], optional) – Utility weights for keys: vi_gradient, vi_local_std, dp_variance.

  • roi_mask (np.ndarray, optional) – Optional boolean mask of shape scan_shape restricting dense picks.

  • update_widget_path (bool, default True) – If True, calls set_path(...) with the suggested path.

  • interval_ms (int, optional) – Path interval when update_widget_path=True.

  • loop (bool, default False) – Path looping behavior when update_widget_path=True.

  • autoplay (bool, default False) – Start playback immediately when update_widget_path=True.

  • return_maps (bool, default False) – If True, include utility component maps in the returned dict.

Returns:

Planning result with coarse points, dense points, and final path.

Return type:

dict

Show4DSTEM.evaluate_against_reference(reference: str | ndarray = 'full_raster', metrics: list[str] | None = None) dict[str, Any][source]#

Evaluate sparse-sampled reconstruction against a reference image.

Parameters:
  • reference (str or np.ndarray, default "full_raster") – Reference target. "full_raster" uses the current full dataset and current ROI integration settings. Arrays are also accepted (virtual image or full diffraction stack; see method docs).

  • metrics (list[str], optional) – Metric names to compute. Supported: "rmse", "nrmse", "mae", "psnr".

Returns:

Evaluation summary including sampled fraction and metric values.

Return type:

dict

Show4DSTEM.export_session_bundle(path: str | Path) Path[source]#

Export a reproducible session bundle for sparse/adaptive workflows.

The bundle includes widget state, sparse-state arrays, a current view image with metadata, and the reproducibility report.

Parameters:

path (str or pathlib.Path) – Output directory for bundle files.

Returns:

Path to the bundle manifest JSON.

Return type:

pathlib.Path

Presets

Show4DSTEM.apply_preset(name: str) Self[source]#
Show4DSTEM.save_preset(name: str, path: str | Path | None = None) dict[str, Any][source]#
Show4DSTEM.load_preset(name: str, path: str | Path | None = None, apply: bool = True) dict[str, Any][source]#

State Persistence

Show4DSTEM.state_dict()[source]#
Show4DSTEM.save(path: str)[source]#
Show4DSTEM.load_state_dict(state)[source]#
Show4DSTEM.summary()[source]#
Show4DSTEM.save_reproducibility_report(path: str | Path) Path[source]#