← Back to “Processing sections & scripts”
Import — into the native HDF5 format
Bring a raw 4D-STEM dataset into 4d's HDF5 format and derive first-look images and statistics.
| # | Title | What it does |
|---|---|---|
| 10 | Import 4D STEM (flat-field only) | Imports a dataset from an HDF5 file, optionally applying flat-field (gain) and bad-pixel corrections, and writes a new BLOSC2-compressed HDF5 structured for downstream scripts. |
| 20 | Inspect a HDF5 file | Walks the original and 4d-style HDF5 files, reporting the shape, type, compression, and attributes of every dataset/group. |
| 30 | Get statistics from HDF5 file | Reports dimensions, data type, and statistics (min, max, mean, std) of a chosen dataset, and auto-detects the diffraction-disk geometry. |
| 50 | Scan Pattern into HDF5 file | Reads a scan pattern from a STAR file and writes the scan positions into the HDF5 file. |
| 70 | Get BF and DF image | Computes bright-field and dark-field virtual-detector images using the detector geometry and the stored scan pattern, and saves them into the HDF5 file. |
| 75 | Get PSF | Computes a point-spread function from the dark-field region by extracting and averaging isolated peaks. |
fd_stack (a 4d-convention stem_dataset HDF5):
10 creates fd_stack from the raw data →
20 inspects it →
30 computes statistics and auto-suggests the Ronchigram centre and BF/DF detector radii →
50 attaches the scan pattern (/positions/units) →
70 builds the BF/DF virtual images →
75 builds the PSF.
Scripts 70 and 75 need the scan positions from step 50, and use the detector geometry produced by step 30. Values a script computes are written back both into the fd_stack header group (as HDF5 attributes) and to the GUI (via the results file), and output images are registered for the Results panel.
Each script's ? help button (on its Manual section) opens the matching entry below.
10 — Import 4D STEM (flat-field only)
Purpose
The entry point of the Prepare workflow. It reads a raw 4D-STEM dataset from an HDF5 file, optionally applies flat-field (gain) and problematic/dead-pixel correction, always applies a hot-pixel threshold, and writes the result to a new, downstream-compatible HDF5 working file (fd_stack) in the 4d stem_dataset v2.0 format. The output is BLOSC2-compressed and is the file every later script operates on.
Parameters
| Parameter | Role |
|---|---|
import_rawstack | The raw input HDF5 file to import (may be only dark-subtracted). |
import_rawstack_original | Original input path, used as a fallback if the raw stack isn't found. |
fd_stack | The output working file. If blank, auto-named fd_<inputname>. |
perform_gaincorrection | Master switch (y/n): apply flat-field + bad-pixel correction on import. |
gainref | Flat-field gain reference (.npy/.tif) used when correction is on. |
problematic_pixel_array | Bad/dead-pixel mask (.npy) applied during correction. |
hot_pixel_threshold | Raw-count value above which a pixel is treated as hot and zeroed (always applied; 0 disables). |
comment | Free text; written to the output file's root comments attribute. |
import_gainref_original, import_problematic_pixel_array_original | Source paths of the reference/mask (bookkeeping). |
imagenumber, tempkeep | Standard-script scaffolding (image id, temp-file switch). |
Algorithm
- Re-registers the HDF5 BLOSC/BLOSC2 filter plugins against the actual
libhdf5(avoids a known HDF5 1.14 crash) before any compressed I/O. - Resolves the input file, auto-derives the
fd_stackname if empty, and captures source metadata to carry forward (root andheaderattributes, everything underpositions, and auxiliary detector datasets such asflatfield_mask,deadpixel_mask,vacuumProbe). - Locates the diffraction patterns (trying
/data/dpatterns,/entry/data/data, …) and loads them. - Hot-pixel thresholding: if the threshold > 0, all voxels above it are set to 0 and the count reported.
- Optional correction (only when enabled): loads the gain reference (float32) and bad-pixel mask (bool); if their shapes disagree the mask is dropped. Correction runs on GPU via
applyFlatfieldCorrection_GPU_batched, falling back to CPU on error; 4D stacks are reshaped to(N, qy, qx)for the call. - Writes the output HDF5 in
stem_datasetv2.0 form.
Results
Images: none.
Data written: a new fd_stack HDF5 file — root attrs (file_type='stem_dataset', format_version, time_created, comments); header group (with gain_corrected); data/dpatterns (corrected/cleaned stack, BLOSC2 lz4, per-pattern chunks) plus carried-over auxiliary datasets and masks; and the positions group if present. The results file records fd_stack and registers the input, output, gain reference, and mask images.
20 — Inspect a HDF5 file
Purpose
A diagnostic tool. It recursively walks the entire structure of both the 4d-style working file (fd_stack) and the original raw file, printing every group and dataset with its shape, dtype, compression/filter details, and all attributes. It optionally computes basic grey-value statistics and writes the structural metadata to the results file. It opens the files read-only and modifies nothing.
Parameters
| Parameter | Role |
|---|---|
compute_minmaxmean | Input (y/n): compute min/max/mean/std of each dataset (can be slow on large files). |
fd_stack, import_rawstack | The two files inspected (4d-style file first, then the original). |
comment | Free-text note. |
detectorX, detectorY, ProbePositions | Outputs — derived from the dataset shape. |
minValue, maxValue, meanValue, stddevValue | Outputs — filled from /data/dpatterns when statistics are enabled. |
RonchiCenterOffsetX, RonchiCenterOffsetY | Displayed only (not computed here). |
Algorithm
- Recursively explores the file: logs all attributes of each group; for each dataset prints shape, dtype and decoded compression, mapping HDF5 filter IDs (gzip, shuffle, lz4, blosc, blosc2 = id 32026) to names and options.
- If statistics are enabled, computes numpy min/max/mean/std per dataset; the values from
/data/dpatternsbecome the reported global statistics. - For any dataset with three or more dimensions, derives
ProbePositions,detectorX,detectorY. - Runs on
fd_stackfirst, then the original raw file.
Results
Images: none.
Data written: to the results file only — ProbePositions/detectorX/detectorY, a full set of attr_<path>_<name> lines capturing every attribute, statistics if enabled, and image registrations for the two files. The HDF5 files are not modified.
30 — Get statistics from HDF5 file
Purpose
Computes the core statistics and reference images for the working file and, crucially, auto-detects the diffraction-disk geometry. It reads the full pattern stack, computes min/max/mean/std, produces average / clipped-average / standard-deviation diffraction maps, locates the central bright-field disk to derive the Ronchigram centre and suggested BF/DF detector radii, and writes all of this back to the file and to the GUI. Running it first gives good detector-geometry defaults for scripts 70 and 75.
Parameters
| Parameter | Role |
|---|---|
showplot | Input (y/n): show the disk-finding overlay and the grey-value histogram interactively. |
fd_stack | The working HDF5 file (opened read-write). |
comment | Free-text note. |
DF_Inner, DF_Outer, BF_Outer | Suggested outputs — dark-field annulus and bright-field radii derived from the fitted disk. |
minValue, maxValue, meanValue, stddevValue | Outputs — computed grey-value statistics. |
detectorX, detectorY, ProbePositions, chunks | Outputs — read from the dataset. |
scantype, imagenumber, tempkeep | Display / scaffolding. |
Algorithm
- Opens
fd_stackread-write and locates the pattern dataset (dpatterns_blosc2/dpatterns/ …). - Resolves the shape (4D → scan-y, scan-x, detector-y, detector-x; 3D → positions, detector-y, detector-x), warns if the dataset exceeds ~8 GB, and loads it.
- Computes min/max/mean/std over the whole array.
- Computes the average diffraction pattern (mean over all positions), the standard-deviation pattern, and a contrast-clipped average.
- Runs
find_disk_centeron the average pattern to locate the central beam; from the disk centre and radius it derivesRonchiCenterOffsetX/Y(centre − half-size) and radiiDF_Inner = 1.1·r,DF_Outer ≈ 2·r(at leastDF_Inner+20),BF_Outer = 0.9·r. - Builds a log-scaled 256-bin grey-value histogram.
Results
Images: fd_average_map, fd_average_clipped_map, fd_std_map (each as .mrc + .png) and fd_grey_value_histogram.png; plus an interactive disk overlay if showplot=y.
Computed values written: into the fd_stack header — the statistics, centerX/centerY (the Ronchigram offsets), and DF_Inner/DF_Outer/BF_Outer; the same values and image registrations go to the results file / GUI.
50 — Scan Pattern into HDF5 file
Purpose
Attaches the probe scan pattern to the working file. It reads a scan pattern from a STAR file (system-wide, project-wide, or local), optionally prepends dummy positions, and writes the positions into fd_stack as /positions/units (which SHARP and downstream tools read), along with scan-mode and step-size metadata.
Parameters
| Parameter | Role |
|---|---|
starfile_choice | Which STAR file to use: System-wide, Project-wide, or Local. |
system_star_file, project_star_file, local_star_file | The candidate STAR-file paths; the one matching the choice is used. |
ProbePositionsInsertDummies | Number of dummy positions to prepend (when the camera triggered before the scan reached its first real position). |
scan_showplot | Input (y/n): plot the scan pattern. |
ProbePositionsPlot | How many positions to draw (0 = all); affects the plot only. |
scan_y_down | Whether the Y axis points down (affects the plot orientation). |
fd_stack | The working HDF5 file written into. |
ProbePositions | Output — number of positions read from the STAR file. |
comment | Free-text note. |
Algorithm
- Selects the STAR file per
starfile_choice. - Reads the scan pattern, obtaining the position list plus
ScanMode, step size, position count, and snake offset. - Optionally plots the pattern (honouring the plot count and Y direction).
- If a dummy count is set, prepends that many copies of the first position.
- Writes the positions into
fd_stackas/positions/units(in[Y, X]order), replacing any existing dataset. - Writes
ScanModeandstep_size_angstromsasheaderattributes.
Results
Images: an interactive scan-pattern plot only, if enabled (not saved to disk).
Data written: into fd_stack the /positions/units dataset and header attributes ScanMode and step_size_angstroms; the results file records the scan mode and step size and registers the file and STAR file.
70 — Get BF and DF image
Purpose
Forms virtual bright-field (BF) and dark-field (DF) STEM images from the 4D dataset. Using the Ronchigram centre and BF/DF detector radii, it integrates each diffraction pattern over a central disk (BF) and an annulus (DF), then maps those per-probe intensities onto a real-space image using the scan positions. It requires the scan positions written by script 50.
Parameters
| Parameter | Role |
|---|---|
RonchiCenterOffsetX, RonchiCenterOffsetY | Diffraction-pattern centre offsets (added to detector half-size to get the absolute centre). |
DF_Inner, DF_Outer | Inner/outer radii (pixels) of the dark-field annulus. |
BF_Outer | Displayed; internally the BF radius is derived as DF_Inner − 10 (min 5). |
DF_size | Output image size in pixels (default 2048). |
scan_y_down | When y, flips the Y scan coordinates. |
mask_showplot | Input (y/n): show the DF annulus and BF disk masks. |
fd_stack | The working HDF5 file (read for patterns, written for the maps). |
minValue…stddevValue, ProbePositions, chunks | Outputs — recomputed here. |
detectorX, detectorY, scantype, scanPatternSTAR, imagenumber, tempkeep, comment | Display / bookkeeping (scanPatternSTAR is used only for logging). |
Algorithm
- Verifies BLOSC2 with a write/read self-test.
- Loads the scan positions from
fd_stack(aborts if none); flips Y if requested. - Locates and loads the pattern dataset (reshaping 4D to
(N, qy, qx)) and computes statistics. - Builds the absolute Ronchigram centre and two masks: a DF annulus between
DF_InnerandDF_Outer, and a BF disk out toDF_Inner − 10. - Virtual-detector integration: for every probe position, sums
pattern × maskto get its DF and BF intensity. - Real-space mapping: builds a
DF_size × DF_sizegrid over the scan-coordinate range, estimates the probe spacing with a KD-tree, and interpolates the DF/BF values with a piecewise-cubic (Clough–Tocher) interpolator, filling points outside the convex hull with the nearest value. A multiprocessing nearest-position fallback is used if SciPy is unavailable. - Normalises each map for MRC and writes 400×400 PNG previews.
Results
Images: fd_DF_image and fd_BF_image (each .mrc + .png); an interactive mask display if enabled.
Data written: into fd_stack the datasets /data/df_map and /data/bf_map (float, gzip) plus header attributes (statistics, centre offsets, DF_Inner/DF_Outer, dataset info); the same values and the four image files are recorded to the results file.
75 — Get PSF
Purpose
Estimates the detector/probe point-spread function (PSF) from isolated diffraction spots in the dark-field region. It searches each diffraction pattern for isolated intensity peaks lying within the DF annulus, extracts small patches centred on those peaks, and averages them into a single PSF image — characterising how a point diffraction event is spread on the detector (useful for downstream deconvolution/reconstruction). It requires the scan positions written by script 50.
Parameters
The GUI parameter list is the same as Get BF and DF image. The parameters that actually drive the PSF are RonchiCenterOffsetX/Y, DF_Inner and DF_Outer (they define the annular region searched for peaks); scan_y_down flips the Y scan coordinates; fd_stack is the input/output file. DF_size, BF_Outer and mask_showplot are parsed but not used in the PSF path. The statistics, ProbePositions and chunks are recomputed outputs.
Algorithm
- Loads the scan positions from
fd_stack(aborts if absent); flips Y if requested. - Locates and loads the pattern dataset (reshaping 4D to
(N, qy, qx)) and computes statistics. - Builds the DF annular mask between
DF_InnerandDF_Outeraround the centre. - Peak search + patch extraction over all patterns: on GPU (PyTorch, CUDA/MPS) it masks each pattern, thresholds at 0.1× its masked maximum, does non-maximum suppression (minimum peak distance 8), and cuts 16×16 patches around surviving peaks, with half-precision and OOM-safe batching (gated by the
FD_GPU_PEAKSenvironment variable); the CPU fallback usesskimage'speak_local_maxwith the same settings in a thread pool. - Averages all 16×16 patches into the final PSF.
Results
Images: psf_darkfield.mrc (or .npy fallback) and psf_darkfield.png (normalised, upscaled to 400×400). If no peaks are found, no PSF is written.
Data written: into the fd_stack header the statistics, centre offsets, DF_Inner/DF_Outer and dataset info (the PSF image itself is saved only as MRC/PNG, not into the HDF5); the results file records the statistics and registers the PSF files.