PySTEMLab

4D-STEM · EDS · electron PDF

Every probe position holds a diffraction pattern. PySTEMLab turns them into maps you can question.

PySTEMLab is an interactive environment for four-dimensional scanning transmission electron microscopy, developed at Ben-Gurion University of the Negev. It takes raw scans with simultaneous HAADF and EDS signals through centring, region selection, classification, nucleus detection and pair-distribution-function analysis, with every step inspected by eye and reproducible by script.

14
linked dashboards, from raw scan to G(r)
4
independent ways to classify a film, compared on one region
6
successive scans of a Ge–Sb–Te film read as a dose series
0–30 V
bias series of a second film, from amorphous to polycrystalline

Workflow

One project, seven steps, the same region throughout

A project holds the scans and their calibration once; every dashboard then works on the same region of interest, so classes, nuclei and PDFs from different methods can be compared probe position by probe position.

  1. Project managerEMD and MRC scans, detector calibration, EDS cube
  2. Shift & Maskcentre every pattern, mask the bright-field disc
  3. Region of interestdraw the analysis window once, used everywhere
  4. Virtual detectorbright-field, annular and max-intensity images, any pattern on click
  5. ClassifyI(q) phase mapping, PCA and SimCLR clustering, HAADF–EDS correlation
  6. Nucleus markerBragg-contrast detection, hand correction, grain segmentation
  7. PDF explorerAu-calibrated electron G(r) for every class

About PySTEMLab

Developed in the group of Yevgeny Rakita, Department of Materials Engineering, Ben-Gurion University of the Negev, Be'er Sheva, Israel. The code is available to reviewers on request: .

Results shown here

M. Kumar, K. Sobolev, A. Upcher and Y. Rakita, Nucleation at the GST–oxide interface and beam-driven ordering in amorphous Ge–Sb–Te: HAADF, EDS and electron pair distribution functions across a 4D-STEM dose series, arXiv preprint (2026).

Tour · recorded in the real software

PySTEMLab at work on a Ge–Sb–Te scan

Each clip is an unedited screen recording of PySTEMLab running on scan 0033 of the dose series (110 × 45 probe positions, 256 × 256 patterns, simultaneous HAADF and EDS). Buttons are pressed, the computation runs, and the results appear. Press play on any clip.

InspectClick anywhere on the scan to see the diffraction pattern recorded at that probe position: the Au cap at the top, the amorphous film, and Bragg spots where a nucleus sits.Full-size screenshot
Virtual DetectorAnnular virtual detectors on the full 256×256 patterns, with the azimuthal I(q) of the mean pattern showing the detector band.Full-size screenshot
Nucleus MarkerAutomatic Bragg-contrast detection outlines the crystalline nuclei (8 objects in this scan); the expert then adopts, merges or corrects them by hand.Full-size screenshot
Component AnalysisNon-negative matrix factorisation of all 4,950 patterns into five components, with their maps and basis patterns, in a few seconds.Full-size screenshot
Phase MappingAzimuthal I(q) of every pattern → PCA → 3D UMAP → clustering. Classes appear on the UMAP, on the scan and as mean EDS spectra.Full-size screenshot
Correlation ExplorerHAADF against summed EDS for every probe position, split into bands of equal HAADF intensity, each with its mean pattern and spectrum.Full-size screenshot
Cluster ExplorerWhole-pattern PCA → UMAP → spectral clustering into seven classes, linked to the scan map, mean I(q), EDS and class patterns.Full-size screenshot
PDF ExplorerElectron pair distribution functions G(r) of every class, from Au-calibrated mean patterns, with I(Q), S(Q) and F(Q).Full-size screenshot

Tutorial

Your first analysis, from raw scan to G(r)

The steps below follow one scan through PySTEMLab. Each dashboard is a page of the same application; the scan and the region chosen in the header apply to all of them.

  1. Create a project

    On the Projects page, click New Project. The wizard asks for a name, the scan files (Velox .emd with HAADF and EDS, and the 4D .mrc), and the calibration: diffraction-pattern size, beam centre, wavelength, pixel sizes and the EDS energy scale. Create Project writes everything into one project file, which every dashboard reads.

  2. Centre the patterns: Shift & Mask

    Pick a scan and click Apply Shift & Mask. The bright-field disc is found in every diffraction pattern, each pattern is shifted so the disc sits at the centre, and the disc can be masked. The result is saved once and used by all the other dashboards.

  3. Choose a region of interest

    Draw the part of the scan you want to analyse (box, lasso or polygon), click Save ROI, then Use as app region. From now on every dashboard works on that region, so results from different methods can be compared pixel by pixel.

  4. Look at the data: Virtual Detector

    Click Load Data, then move the inner and outer radius of the annular detector: the virtual image updates live. Select a region on the image to see its mean diffraction pattern and I(q).

    Virtual Detector: virtual image and diffraction pattern of the scan
  5. Classify the film

    In Phase Mapping, click Load Data, Run PCA and Run UMAP, then Apply Auto Cluster, or draw classes by hand with the lasso and Assign. Each class appears on the map with its mean EDS spectrum and diffraction pattern; Save Classes keeps them. Cluster Explorer and Correlation Explorer classify the same region in other ways.

    Phase Mapping: classes on the map and in the UMAP embedding
  6. Mark the nuclei

    In Nucleus Marker, click Load Scan and Detect to find crystalline nuclei from their Bragg spots. Adopt auto takes the proposal; Mark and Unmark correct it by hand. Save Mask makes the nuclei available to the other dashboards.

    Nucleus Marker: detected nuclei on the max-intensity image
  7. Pair distribution functions

    PDF Explorer turns the mean diffraction pattern of every class into I(Q), S(Q) and G(r), with the q scale calibrated on a reference ring. Pick the classes and click Compute I(Q) + PDF; overlay classes or scans to compare their local order.

    PDF Explorer: G(r) of several classes
  8. Export and keep the record

    Every dashboard exports its figures and data (PDF, PNG, .npz, CSV). Save session in the header writes every step you took, with its settings, so the analysis can be repeated.

The full user manual is available on request, like the code.

Try it · computed in your browser

A virtual detector on real 4D-STEM data

These are measured data, binned four-fold in each detector direction so they fit in a web page. Move over the map to see the diffraction pattern at each probe position, click to pin it, and drag the rings on the pattern to build your own annular detector. The image on the left is recomputed from thousands of patterns every time you move a ring. This is the same operation PySTEMLab's Virtual Detector dashboard performs on the full-resolution data.

Data set
Image

Loading…

Real space

Diffraction

Patterns on a logarithmic scale. The dark centre is the masked bright-field disc. Ring radii in scattering vector q, calibrated on the Au cap.

Live app

Use PySTEMLab itself

The full application runs on our lab workstation and is reachable from the web. It opens on the same Ge–Sb–Te data as the examples, so every dashboard can be tried with its own controls. Access is for permitted users only.

Command line · pystemlab

The whole analysis in one command, from raw scans to finished figures.

The dashboards are where a scan is understood: you look at the patterns, try settings and judge the classes by eye. Once the settings are right, the rest is repetition, the same buttons scan after scan. pystemlab is PySTEMLab in the terminal. You write the analysis once, as a short pipeline file, and it runs the dashboards' own code on every scan, from the raw 4D-STEM files to the exported maps and PDFs. It needs no browser, so it runs on the lab workstation over SSH or overnight on a server.

9 min
for a 5-scan bias series, raw MRC files to class maps, in one command
7 s
to centre and mask 22 500 diffraction patterns on a laptop GPU
10 → 1
button presses per scan, replaced by one command for the whole series
1
code path: the terminal runs the dashboards' own code, so the results match

Why a command line

Explore in the app, then let the terminal do the repetition

A 4D-STEM study is rarely one scan. A dose series, a bias series or a set of samples needs the same centring, the same regions and the same classification on every scan, with the same settings, so the results can be compared. By hand this is slow, and a setting that differs on one scan is easy to miss. The command line leaves the judgement in the app and gives the repetition to the computer.

Repeatable

The pipeline file is the analysis: every step and every setting in a few lines of text. Keep it with the project, run it again on new scans, send it to a colleague, or publish it with a paper.

Unattended

It runs scan by scan and logs every step. A scan that fails is reported and the run goes on with the next one; an interrupted run resumes where it stopped. Nobody has to sit at the screen.

The same results as the app

It is not a second implementation. The terminal drives the dashboards' own code, so a result made there is the result the app gives with the same options. Our tests check this: the same class labels, pixel for pixel.

Traceable

Every export, from the app or the terminal, is logged with the settings that made it. A figure made by hand in the app can be turned into a pipeline, or made again from its record and compared.

Where the time goes

The computing is the same; the waiting between steps disappears

The terminal computes no faster than the app, because it runs the same code. What it removes is the person between the steps. In the app, the pipeline used here is ten button presses per scan: centre the patterns; load the virtual detector and save its image; load the scan, compute I(q), run PCA, UMAP and the classification, and export the map twice. Each press waits for the step before it. With pystemlab the whole series is one command, and the time in between is yours.

Measured runGe–Sb–Te film, bias series 0–30 V: 5 scans of 150 × 150 probe positions with 256 × 256 px patterns, 15 GB of raw 4D MRC files. A laptop with an NVIDIA RTX 4060 (8 GB) and 32 CPU threads. Times from the run's own log.
ScanBiasShift & Mask Virtual detectorPhase mappingScan total
00170 V6.6 s3.2 s93.3 s103 s
00365 V7.4 s2.8 s82.9 s93 s
004010 V6.9 s3.0 s102.2 s112 s
004715 V7.1 s2.7 s108.4 s118 s
005330 V6.9 s2.9 s114.5 s124 s
All 50–30 V35 s15 s501 s9 min 11 s

Creating the project, which copies the 15 GB of raw files, took 7 s, and checking the pipeline 3 s. The run took 9 min 13 s from start to finish, including starting Python and loading the code. Most of it is the robust two-stage classification of Phase Mapping, which runs on the CPU. In the app the same steps take the same computing time, plus the time to press each button once the step before it has finished, on every scan.

A real session

From a folder of raw files to the results

This is the run measured above, as the terminal showed it, with repeated lines shortened where marked and the warnings of third-party libraries left out. new creates the project from the raw files, info shows what is done for each scan, check reads the pipeline for mistakes and run does the work. Play the session replays it, with the long steps shortened.

pystemlab · bias series
$ pystemlab new ~/raw/bias --name GST_bias --root ~/projects --material Ge-Sb-Te  read from 0017 - Area of interest - 0V bias.emd (Velox 3.22.1.3229 (format 15)): scan grid, scan step, beam energy, camera length, EDS calibration  not in the EMD (defaults or flags used): mapped elements, DP size, DP pixel size, beam centre  scan 0017: grid 150×150 (EMD (0017 - Area of interest - 0V bias.emd)) 4D MRC has 22500 patterns ✓  scan 0036: grid 150×150 (EMD (0036 - Area of interest - 5V bias.emd)) 4D MRC has 22500 patterns ✓  scan 0040: grid 150×150 (EMD (0040 - Area of interest - 10V bias.emd)) 4D MRC has 22500 patterns ✓  scan 0047: grid 150×150 (EMD (0047 - Area of interest - 15V bias.emd)) 4D MRC has 22500 patterns ✓  scan 0053: grid 150×150 (EMD (0053 - Area of interest - 30V bias.emd)) 4D MRC has 22500 patterns ✓  copying 0017 - Area of interest - 0V bias.emd (0.42 GB)  copying 0017 - Area of interest - 0V bias.mrc (2.97 GB)  copying 0036 - Area of interest - 5V bias.emd (0.42 GB)  copying 0036 - Area of interest - 5V bias.mrc (2.97 GB)  copying 0040 - Area of interest - 10V bias.emd (0.41 GB)  copying 0040 - Area of interest - 10V bias.mrc (2.97 GB)  copying 0047 - Area of interest - 15V bias.emd (0.40 GB)  copying 0047 - Area of interest - 15V bias.mrc (2.97 GB)  copying 0053 - Area of interest - 30V bias.emd (0.39 GB)  copying 0053 - Area of interest - 30V bias.mrc (2.97 GB)Created ~/projects/gst_bias/project.yaml$ pystemlab info ~/projects/gst_bias/project.yamlGST_bias: 5 scans · data ~/projects/gst_bias/data · analysis ~/projects/gst_bias/analysisscan   grid      raw 4D  zarr  nomask  caches  mask  ROIs                 last export0017   150×150   yes     -     -       0       -     -                    -0036   150×150   yes     -     -       0       -     -                    -0040   150×150   yes     -     -       0       -     -                    -0047   150×150   yes     -     -       0       -     -                    -0053   150×150   yes     -     -       0       -     -                    -$ pystemlab check bias_series.yamlOK: nothing to fix.$ pystemlab run bias_series.yaml09:29:55 scan 001709:29:55   [1] shift_mask09:29:55     Shift & Mask: apply on 22500 patterns …09:29:58       Shifting and masking: 2,400/22,50009:30:01       Shifting and masking: 22,500/22,50009:30:01       22500 patterns in 7 s on GPU (CuPy 13.6.0, NVIDIA GeForce RTX 4060 Laptop GPU, 8 GB); disc radius 4.7 px; 0 failed09:30:01       wrote ~/projects/gst_bias/data/shifted/0017_shifted.zarr09:30:01       wrote ~/projects/gst_bias/data/shifted/0017_shifted_centers.npz09:30:01       ok (6.6 s)09:30:01   [2] virtual_detector09:30:01     Virtual Detector: load_data …09:30:05       wrote analysis/data/virtual_images/vi_0017_maxpool.png09:30:05       ok (3.2 s)09:30:05   [3] phase_mapping09:30:07     Phase Mapping: load_data …09:30:15     Phase Mapping: compute_iq …09:30:17     Phase Mapping: run_pca …09:30:17     Phase Mapping: run_umap …09:30:32     Phase Mapping: run_auto …09:31:33     Phase Mapping: export npz …09:31:37     Phase Mapping: export pdf …09:31:38       wrote analysis/data/phase_mapping/phase_map_0017.npz09:31:38       wrote analysis/data/phase_mapping/phase_map_0017.pdf09:31:38       ok (93.3 s)   … scans 0036, 0040, 0047: the same three steps (shortened) …09:31:38 scan 003609:31:45       ok (7.4 s)09:31:48       ok (2.8 s)09:33:11       ok (82.9 s)09:33:11 scan 004009:33:18       ok (6.9 s)09:33:21       ok (3.0 s)09:35:03       ok (102.2 s)09:35:03 scan 004709:35:10       ok (7.1 s)09:35:13       ok (2.7 s)09:37:01       ok (108.4 s)09:37:01 scan 005309:37:01   [1] shift_mask09:37:01     Shift & Mask: apply on 22500 patterns …09:37:04       Shifting and masking: 2,400/22,50009:37:08       Shifting and masking: 22,500/22,50009:37:08       22500 patterns in 7 s on GPU (CuPy 13.6.0, NVIDIA GeForce RTX 4060 Laptop GPU, 8 GB); disc radius 4.4 px; 376 failed09:37:08       wrote ~/projects/gst_bias/data/shifted/0053_shifted.zarr09:37:08       wrote ~/projects/gst_bias/data/shifted/0053_shifted_centers.npz09:37:08       ok (6.9 s)09:37:08   [2] virtual_detector09:37:08     Virtual Detector: load_data …09:37:11       wrote analysis/data/virtual_images/vi_0053_maxpool.png09:37:11       ok (2.9 s)09:37:11   [3] phase_mapping09:37:11     Phase Mapping: load_data …09:37:19     Phase Mapping: compute_iq …09:37:22     Phase Mapping: run_pca …09:37:22     Phase Mapping: run_umap …09:37:28     Phase Mapping: run_auto …09:39:01     Phase Mapping: export npz …09:39:05     Phase Mapping: export pdf …09:39:06       wrote analysis/data/phase_mapping/phase_map_0053.npz09:39:06       wrote analysis/data/phase_mapping/phase_map_0053.pdf09:39:06       ok (114.5 s)15 steps, 0 failed. Run folder: ~/projects/gst_bias/analysis/data/runs/20261105_092955$ pystemlab info ~/projects/gst_bias/project.yamlGST_bias: 5 scans · data ~/projects/gst_bias/data · analysis ~/projects/gst_bias/analysisscan   grid      raw 4D  zarr  nomask  caches  mask  ROIs                 last export0017   150×150   yes     yes   -       4       -     -                    2026-11-05T09:31:38 phase_mapping phase_map_0017.pdf0036   150×150   yes     yes   -       4       -     -                    2026-11-05T09:33:11 phase_mapping phase_map_0036.pdf0040   150×150   yes     yes   -       4       -     -                    2026-11-05T09:35:03 phase_mapping phase_map_0040.pdf0047   150×150   yes     yes   -       4       -     -                    2026-11-05T09:37:01 phase_mapping phase_map_0047.pdf0053   150×150   yes     yes   -       4       -     -                    2026-11-05T09:39:06 phase_mapping phase_map_0053.pdf

The pipeline file

A few readable lines describe the whole analysis

A pipeline names the project, the scans and the steps in order. Each step is one dashboard with the settings you chose there; anything left out keeps its default. This is the complete file used for the run above.

bias_series.yaml
# Bias series 0–30 V: raw MRC files to class maps
project: ~/projects/gst_bias/project.yaml
scans: all
steps:
  - shift_mask:
      run: [apply]
  - virtual_detector:
      settings: {vi_mode: Max pool}
      export: [png]
  - phase_mapping:
      settings: {a_method: "Robust (two-stage)"}
      export: [npz, pdf]

Every option explained in the file

pystemlab template writes a pipeline with every option of every step. Above each option is the same help text as the ⓘ icon in the app; beside it are its default and every value it accepts. You delete what you don't need.

Checked before it runs

pystemlab check compares the file with the dashboards' options, so a typo is found in a second, not after an hour of computing:

$ pystemlab check bias_series.yaml
  ERROR step 2: virtual_detector.log_scale: 'maybe' is not one of [True, False]
  ERROR step 3: phase_mapping.a_method: 'Robust' is not one of ['KMeans', 'Spectral (RBF)', 'Spectral (kNN)', 'Robust (two-stage)']
  ERROR step 3: phase_mapping: unknown option 'a_kk'
3 error(s), 0 warning(s).
pystemlab template phase_mapping (excerpt)
  - phase_mapping:
      settings:
        # …
        # KMeans and Spectral cluster the UMAP embedding into k classes; Spectral (RBF) is refused when its dense pixels
        # x pixels matrix does not fit in memory. Robust (two-stage) works on the diffraction patterns, rare objects
        # first, and picks the number of classes.
        a_method: KMeans                         # default KMeans; one of: KMeans | Spectral (RBF) | Spectral (kNN) | Robust (two-stage)
        # Number of classes for KMeans and Spectral. Not used by Robust (two-stage).
        a_k: 5                                   # default 5; range 2 – 20
        # Pixels whose rare score (distance to the 10 most similar patterns) is above median + this x σ (σ = 1.4826 x
        # MAD) seed rare objects. Default 6; lower finds fainter objects, and more false ones.
        r_k_hi: 6.0                              # default 6.0; range 2.0 – 30.0
        # …

What it can do

Every dashboard, plus the steps around them

A pipeline can use any of these steps, in any order. Each runs on every scan, on the full scan or on a saved region, with the exports the dashboard offers.

StepWhat it doesExports
shift_maskFinds the bright-field disc in every raw pattern, centres it and masks it, on the GPU when there is one. A scan that already has its centred data is skipped unless you ask to redo it; a preview on 500 patterns checks the settings first.zarr, centres
roiSaves a region of interest: a rectangle, or a threshold on the virtual image (the film, not the vacuum).region
virtual_detectorAnnular, max-pool and mean-pool virtual images.npy, png
inspectA virtual image from a detector box, and the mean pattern with its I(q).npz, pdf
nucleus_markerFinds crystalline nuclei from their Bragg spots, or segments the grains of a polycrystalline film.mask, msa
phase_mappingI(q) profiles, PCA, UMAP and classification: KMeans, spectral clustering or the robust two-stage method.npz, pdf, msa
cluster_explorerClustering of PCA, NMF or SimCLR features of the patterns, with the EDS of each class.npz, pdf, msa
correlation_explorerClasses from bands of HAADF and summed EDS intensity.npz, pdf, msa
component_analysisNMF components of the diffraction patterns, streamed through the GPU for large scans.npz, pdf
pdf_explorerI(Q), S(Q) and the electron pair distribution function G(r) of each class.dat, report, figure
eds_quantEDS quantification of the classes of a step, Cliff–Lorimer with the project's k-factors.csv

One step, no file

Every dashboard is also a command of its own, for a quick result:

$ pystemlab phase-mapping project.yaml --scan 0053 --set a_k=7 --export pdf

From the app to the terminal

pystemlab list shows the exports made in the app; pystemlab recipe turns one into a pipeline, ready to run on every other scan.

Made again and compared

pystemlab rerun makes exports again from their recorded settings, in a separate folder, and compares the arrays with the originals.

Help on every command

--help lists a command's flags; on a dashboard command it also lists every setting with its default, its values and its explanation.

Safe to leave running

An overnight run cannot spoil a project

  • Results where the app expects them. Exports go into the project, so the dashboards open them the next morning. A file that would be replaced is first copied to previous/.
  • A sandbox when you want one. --out copies the project's inputs to another folder and writes everything there, leaving the project untouched.
  • Raw data are only read. new copies the raw files into the project, as the app's New Project wizard does, and never changes the originals.
  • A record of every run. Each run keeps its pipeline, a log and a report in runs/<time>/; --resume continues an interrupted run.
  • The same look as the app. Figures use the project's saved display settings: colour maps, contrast, scale bars and resolution.

Getting started

Four commands

  1. Install once

    Puts pystemlab on the path, using the Python environment that runs PySTEMLab.

    $ python pystemlab.py install
  2. Create a project from raw files

    Reads the Velox EMD files, links each scan's files by their number and copies them into a new project.

    $ pystemlab new /data/raw/bias --name "GST bias"
  3. Write the pipeline

    Start from the template, or from an export you made in the app, and check it.

    $ pystemlab template shift_mask phase_mapping > bias.yaml
    $ pystemlab check bias.yaml
  4. Run it

    On the workstation, over SSH or on a server. Open the dashboards when it has finished.

    $ pystemlab run bias.yaml

The command line is part of PySTEMLab. Like the application, its code and manual are available on request.