Show4DSTEM#

Open in Colab

Show4DSTEM opens a 4D-STEM dataset with live virtual detectors: a bright-field / annular-dark-field aperture over the diffraction stack on one side, the resulting virtual image on the other. It accepts a NumPy array, a PyTorch tensor, a quantem Dataset4dstem, or the output of load(...).

This tutorial uses the public binned gold 4D-STEM dataset from bobleesj/quantem-data. show4dstem_gold(size="medium") returns a calibrated real-data preview by striding the gold_128_npy_bin8 scan to 64 by 64 positions with 24 by 24 detector frames, so the rendered documentation opens quickly while preserving uint16 detector counts. Use load_tutorial_show4dstem(scan_stride=1) for the full 128 by 128 scan.

Tip

Run this exact notebook with the Colab badge above, or View or download this notebook on GitHub. For finished results, use HTML and file export to export interactive HTML or share a trusted notebook with widget state.

import numpy as np

from quantem.widget import Show4DSTEM
from quantem.widget.datasets import show4dstem_gold

stem_dataset = show4dstem_gold(size="medium")
Source: gold_128_npy_bin8 from Hugging Face
Full stack: (128, 128, 24, 24) uint16
Preview: (64, 64, 24, 24), scan stride 2
Sampling: [4.   4.   3.68 3.68] ['A', 'A', 'mrad', 'mrad']
Processing: real-space 4x4 block average from gold_512_npy_bin8; detector remains bin8

Virtual detectors on real gold data#

Drag the bright-field disk across the diffraction pattern, or use the BF / ABF / ADF presets, and watch the virtual image update from the real binned 4D-STEM stack. The documentation view embeds the compact browser data payload so the widget remains interactive after the page is rendered.

Show4DSTEM(
    stem_dataset,
    offline=True,
    offline_dtype="uint16",
    save_state=True,
    precompute_virtual_images=False,
    show_fft=False,
)

Multi-panel screening#

Use view_mode="multiple" when the extra frame axis represents datasets, time points, scan regions, or acquisition repeats that should share one detector ROI. The diffraction panel stays the familiar Show4DSTEM control surface; the virtual-image side becomes a grid. Click a tile to make it the selected dataset, switch compare_dp_mode between "average" and "selected", and use the tile star/hide/reorder controls to curate the set for a later cell or export.

compare_max_panels is the visible page size. If there are more datasets than that, the multiple grid gets a Group control like Show2D/Show3D galleries. Keep compare_group_mode="paged" for page-by-page lazy loading, or switch to compare_group_mode="all" when you want one dense overview of all reduced virtual-image panels. All mode still computes lazy folder data in page-sized batches instead of keeping every raw 4D master resident.

The small example below splits the same real gold scan into eight calibrated regions so the tutorial remains light, but the API is the same for a folder with many real master files.

gold = stem_dataset.array
row_edges = np.linspace(0, gold.shape[0], 3, dtype=int)
col_edges = np.linspace(0, gold.shape[1], 5, dtype=int)

region_stack = np.stack(
    [
        gold[row_edges[row]:row_edges[row + 1], col_edges[col]:col_edges[col + 1]]
        for row in range(2)
        for col in range(4)
    ],
    axis=0,
).astype(gold.dtype, copy=False)

region_labels = [f"region {row + 1}-{col + 1}" for row in range(2) for col in range(4)]

multi = Show4DSTEM(
    region_stack,
    sampling=tuple(stem_dataset.sampling),
    units=tuple(stem_dataset.units),
    view_mode="multiple",
    compare_cols=4,
    compare_max_panels=4,
    compare_panel_gap_px=0,
    compare_dp_mode="average",
    frame_dim_label="Region",
    frame_labels=region_labels,
    offline=True,
    offline_dtype="uint16",
    save_state=True,
    precompute_virtual_images=False,
    show_fft=False,
)
multi

Real master-file folders on a workstation#

For large no-bin or multi-acquisition sessions, open completed *_master.h5 files directly from a folder and keep the comparison grid dense. Show4DSTEM.from_folder(...) paints the initial page first, then preloads every unhidden dataset across the selected GPUs when the exact shape/dtype footprint fits. Larger series stay full-resolution and lazy; the automatic policy never silently bins or narrows data. page_size controls how many datasets are shown and computed together, while columns controls the grid width.

Pass sampling and units when the file metadata does not contain physical scan or reciprocal-space calibration. Use pixel units when calibration is unknown rather than inventing mrad or angstrom values.

from quantem.widget import Show4DSTEM

viewer = Show4DSTEM.from_folder(
    "/data/session",
    gpus=[0, 1],
    det_bin=1,
    columns=5,
    page_size=5,
    preload_all_if_fits=True,
    compare_dp_mode="selected",
    warm_cache=True,
    watch=True,
)
viewer

# Optional programmatic paging. Page numbers are zero-based.
viewer.set_compare_page(1)
viewer.show_compare_all_groups()    # dense overview of every visible panel
viewer.show_compare_paged_groups()  # return to page-by-page browsing
viewer.preload_all_datasets()       # re-check after GPU memory changes
viewer.wait_for_dataset_preload(timeout=120)  # optional deterministic wait
viewer.compare_page_idx, viewer.compare_page_count

Use compare_dp_mode="average" to show the average diffraction pattern for the visible grid, or compare_dp_mode="selected" when clicking a panel should show that dataset’s diffraction pattern. The panel order, hidden panels, starred panels, and current page are stored on the widget and can be reused with state_dict() / load_state_dict().

When sharing the result, choose the export type based on what the recipient needs. export_kind="report" writes a compact static HTML report with PNG virtual-image pages and no raw 4D payload, which is the safe option for lazy folders and many datasets. export_kind="interactive" embeds the binned raw 4D data so the exported page can still be driven like a widget, but the file can be much larger. The GUI HTML menu shows report options first, then a size-sorted ladder of interactive raw-4D presets.

# Compact page-aware report for colleagues.
viewer.export_html(
    "show4dstem_report.html",
    export_kind="report",
    dataset_scope="unhidden",  # or "current_page", "starred", "all"
    scan_bin=2,                # real-space mean bin for smaller report PNGs
    det_bin=8,                 # detector mean bin for the representative DP
    dtype="uint8",
)

# Raw offline widget when the recipient needs interactive 4D data.
viewer.export_html(
    "show4dstem_interactive.html",
    export_kind="interactive",
    scan_bin=2,
    det_bin=4,
    dtype="uint8",
)