Tutorial 2: Visualization and Virtual Detectors

A self-contained lesson with synthetic hexagonal diffraction patterns. This notebook needs only 4Denoise and an IPython/Jupyter kernel. It does not read Tutorial 1’s output or require a microscope dataset, RosettaSciIO, or simulation tools.

We will display diffraction patterns and a scan montage, build annular and displaced circular detectors, combine disks, supply Boolean and weighted masks, compare pixel/calibrated inputs, and customize returned real-space images. A marked input cell near the end is ready for a microscope dataset later.

Teaching model, not electron-scattering simulation: two artificial scan regions contain regular hexagons separated by a 30-degree clockwise rotation in detector-array coordinates. Their intensity variations are deliberately assigned. The resulting contrast is not evidence of phase, strain, crystalline fraction, or indexing confidence.

Note

Synthetic teaching data, not experimental validation. Code and figures below come from a validated fresh-kernel run.

Download the clean notebook or read the lesson overview.

1. Imports and a disposable workspace

Choose the environment where you installed the current 4Denoise source, restart the kernel, and run all cells. All files created here belong to a temporary tutorial directory. The final cell removes only that directory, not any microscope input.

%matplotlib inline
from pathlib import Path
import sys
import tempfile

import matplotlib.pyplot as plt
import numpy as np

import fourdenoise
from fourdenoise import HyperData

print('Python:', sys.executable)
print('4Denoise:', fourdenoise.__file__)
workspace = tempfile.TemporaryDirectory(prefix='4denoise-tutorial-02-')
work_dir = Path(workspace.name)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py

2. Build two hexagonal teaching regions

Our array has shape (16, 20, 80, 80): 320 diffraction patterns, each 80 by 80 pixels. The left scan half uses a zero-degree hexagon and the right half a 30-degree hexagon. Every pattern has a centered direct beam, six spots at the same radius, diffuse ring intensity, and Poisson counting noise.

A smooth spot-amplitude envelope and an opposing-spot imbalance create recognizable detector contrast. Unequal spot intensities are an assigned visualization target, not a crystallographic claim. The analytical coordinates below are known from construction; no peak detection or orientation matching has been performed.

rng = np.random.default_rng(2026)
Ry, Rx, Ky, Kx = 16, 20, 80, 80
scan_y, scan_x = np.mgrid[:Ry, :Rx]
sy, sx = 2 * scan_y / (Ry - 1) - 1, 2 * scan_x / (Rx - 1) - 1
yy, xx = np.mgrid[:Ky, :Kx]
cy, cx = (Ky - 1) / 2, (Kx - 1) / 2
distance_sq = (yy - cy)**2 + (xx - cx)**2

spot_radius_px = 22.0
angles = np.arange(6) * np.pi / 3
orientation_deg = np.where(scan_x < Rx // 2, 0.0, 30.0)
orientation = np.deg2rad(orientation_deg)
envelope = 0.75 + 0.35 * np.exp(-2 * (sx**2 + sy**2))
base = (
    0.1 + 120 * np.exp(-distance_sq / (2 * 2.3**2))
    + 0.8 * np.exp(-((np.sqrt(distance_sq) - spot_radius_px) / 5)**2)
)
expected_counts = np.broadcast_to(base, (Ry, Rx, Ky, Kx)).copy()
for angle in angles:
    center_y = cy + spot_radius_px * np.sin(angle + orientation)
    center_x = cx + spot_radius_px * np.cos(angle + orientation)
    gain = 1 + 0.5 * sy * np.cos(angle - np.pi / 3)
    spot = np.exp(
        -((yy - center_y[..., None, None])**2 + (xx - center_x[..., None, None])**2)
        / (2 * 1.3**2)
    )
    expected_counts += (28 * envelope * gain)[..., None, None] * spot
synthetic_array = rng.poisson(expected_counts).astype(np.uint16)

hexagon_0 = np.column_stack((cy + spot_radius_px * np.sin(angles),
                            cx + spot_radius_px * np.cos(angles)))
hexagon_30 = np.column_stack((cy + spot_radius_px * np.sin(angles + np.pi / 6),
                             cx + spot_radius_px * np.cos(angles + np.pi / 6)))
for centers in (hexagon_0, hexagon_30):
    np.testing.assert_allclose(np.linalg.norm(centers - (cy, cx), axis=1), spot_radius_px)
    np.testing.assert_allclose(np.linalg.norm(np.roll(centers, -1, axis=0) - centers, axis=1),
                               spot_radius_px)
print('Synthetic scan:', synthetic_array.shape, synthetic_array.dtype)
print('Numerical size: {:.2f} MiB'.format(synthetic_array.nbytes / 1024**2))
Synthetic scan: (16, 20, 80, 80) uint16
Numerical size: 3.91 MiB

The illustrative calibration is 2 nm per scan row, 3 nm per scan column, and 0.25 mrad per diffraction pixel. These numbers are invented. The central beam was constructed at the geometric subpixel midpoint (39.5, 39.5); we have not measured or fitted a beam center, and have not established R/Q orientation.

The small pixel snapshot below is only an example check that visualization leaves the input unchanged. Do not duplicate a multi-gigabyte acquisition merely to make such a check.

data = HyperData(
    synthetic_array, real_units='nm', real_conv_factor=(2.0, 3.0),
    real_origin=(0.0, 0.0), reciprocal_units='mrad', reciprocal_conv_factor=0.25,
    acquisition_metadata={'data_origin': 'synthetic', 'synthetic_seed': 2026,
                          'description': 'Two invented hexagonal teaching regions'},
)
original_counts = data.array.copy()
contrast_power = 0.4
display_max = float(data.array.max())**contrast_power
left_scan_mask = orientation_deg == 0
right_scan_mask = orientation_deg == 30
mean_0 = data.get_dp(mask=left_scan_mask, operation='mean', working_memory_mb=16)
mean_30 = data.get_dp(mask=right_scan_mask, operation='mean', working_memory_mb=16)
mean_dp = data.get_dp(operation='mean', working_memory_mb=16)
assert data.center_beam_metadata is None and data.rq_calibration is None

3. Diffraction views, overlays, and units

A get_dp(mask=…) mask selects scan positions and has shape (Ry, Rx). Later, virtual_image(mask=…) will use a detector mask of shape (Ky, Kx). They are different masks for different purposes.

Both plots below overlay the known synthetic spot positions in (y, x) pixel coordinates, even when the displayed axes are calibrated. axis_units controls labels and scale-bar units, not the input convention for coords. The 8-pixel bar and 2-mrad bar represent the same detector length.

Cartesian diffraction display axes are centered, with positive displayed y upward, in both unit modes. Pixel-labeled axes therefore show offsets, not absolute array row/column indices. Overlay coords still use absolute array coordinates. Alternatively supply y=coords[:, 0] and x=coords[:, 1]; do not combine both styles.

We use logScale=False and power=0.4 because genuine zeros are present. No clipping is needed. vmin and vmax refer to displayed values, here counts raised to the power 0.4. Display transforms do not change stored counts.

mean_0.show(
    title='Region A: pixel axes', coords=hexagon_0, c='cyan', marker='x', s=35,
    axis_units='pixels', scale_bar=8, scale_bar_color='white',
    grid=True, grid_ticks=(5, 5), grid_alpha=0.2,
    logScale=False, power=contrast_power, vmin=0, vmax=display_max,
    cmap='magma', figsize=(5.5, 4.5),
)
mean_30.show(
    title='Region B: calibrated axes', coords=hexagon_30, c='cyan', marker='x', s=35,
    axis_units='calibrated', scale_bar=2, scale_bar_color='white',
    grid=True, grid_ticks=(5, 5), grid_alpha=0.2,
    logScale=False, power=contrast_power, vmin=0, vmax=display_max,
    cmap='magma', figsize=(5.5, 4.5),
)
Figure from the synthetic tutorial Figure from the synthetic tutorial

4. Survey the scan with a montage

visualize(grid_shape=(3, 4)) combines neighboring scan positions into 12 displayed diffraction tiles. It does not select 12 original patterns. Area-weighted averaging also handles the non-integer 16-to-3 scan reduction. White padding separates tiles, and all tiles share the same intensity scale.

The outer montage axes describe scan position, not a single continuous detector coordinate. Detector axes repeat inside every tile. The source dataset is not resized in place. Note the option spelling: visualize(log_scale=…) versus ReciprocalSpace.show(logScale=…).

montage_fig, montage_ax = data.visualize(
    grid_shape=(3, 4), padding=5, reduction='mean',
    log_scale=False, power=contrast_power, vmin=0, vmax=display_max,
    axis_units='auto', cmap='magma', figsize=(10, 7), title='Binned scan montage',
)
assert data.shape == (Ry, Rx, Ky, Kx)
plt.close(montage_fig)
Figure from the synthetic tutorial

5. What a virtual detector calculates

At every scan position, a detector forms the sum of intensity times a fixed two-dimensional weight image. A Boolean mask has weights 0 or 1. Positive fractional weights soften the response; signed weights form differences. There is no automatic normalization by detector area or weight sum.

Choose exactly one detector definition: annulus=(inner, outer), radius plus centers, or mask. Returned RealSpace objects contain a 2D scan image and its calibration, not a modified diffraction dataset.

Here all virtual detectors operate on the original Cartesian data. Centered annuli use the geometric diffraction origin; arbitrary off-center regions should use disks or an explicit mask. An off-center experimental beam must not be assumed to coincide with that origin.

annulus_px = (18.0, 26.0)
annulus_mask = (distance_sq >= annulus_px[0]**2) & (distance_sq <= annulus_px[1]**2)
disk_radius_px = 4.0
spot_center_px = hexagon_0[1]
spot_mask = ((yy - spot_center_px[0])**2 + (xx - spot_center_px[1])**2) <= disk_radius_px**2

total_signal = data.virtual_image(mask=np.ones((Ky, Kx), dtype=bool), show=False)
central_disk = data.virtual_image(radius=6, centers=(cy, cx), detector_units='pixels', show=False)
annular = data.virtual_image(annulus=annulus_px, detector_units='pixels', show=False)
one_spot = data.virtual_image(
    radius=disk_radius_px, centers=spot_center_px, detector_units='pixels', show=False,
)

# Direct NumPy checks are deliberately limited to this small teaching fixture.
np.testing.assert_array_equal(annular.array, data.array[..., annulus_mask].sum(axis=-1, dtype=np.float64))
np.testing.assert_array_equal(one_spot.array, data.array[..., spot_mask].sum(axis=-1, dtype=np.float64))
assert annular.shape == data.scan_shape
np.testing.assert_allclose(annular.pixel_size, data.real_conv_factor)
print('Annular detector pixels:', int(annulus_mask.sum()))
print('One-spot detector pixels:', int(spot_mask.sum()))
Annular detector pixels: 1108
One-spot detector pixels: 52

The central disk is nearly uniform because we constructed a nearly constant central beam. The annulus collects both hexagonal regions, while the one-spot disk mostly selects the zero-degree region. This is detector-selection contrast, not an orientation-indexing result.

Each panel below has an independent color scale starting at zero. Compare the spatial variation and read the colorbars; equal colors across different panels do not mean equal counts. Scaling a nearly flat noisy image to its own minimum and maximum can exaggerate noise, so zero is a useful baseline here.

fig, axes = plt.subplots(2, 2, figsize=(11, 8), layout='constrained')
for ax, image, title in zip(
    axes.flat, (total_signal, central_disk, annular, one_spot),
    ('Total signal', 'Central disk', 'Annular signal', 'One spot'),
):
    image.show(
        ax=ax, show=False, axis_units='auto', grid_ticks=(5, 5),
        title=title, cmap='viridis', vmin=0, colorbar_label='Integrated counts',
    )
plt.show()
Figure from the synthetic tutorial

6. Preview the detector on a diffraction pattern

plot_mask=True overlays the detector on an unmasked mean pattern. The mean of this entire scan contains both artificial hexagons and therefore up to 12 spot locations. The green overlay below is 30% opaque, or 70% transparent.

show=False suppresses the virtual-image figure, not a requested detector preview. units controls preview-axis units; axis_units controls real-space image units; detector_units controls the numerical detector definition. mask_cmap, mask_power, and mask_log_scale customize the preview.

With return_detector=True, the second return value is the masked/weighted mean pattern, not the Boolean detector mask and not the unmasked preview.

preview_image, masked_mean = data.virtual_image(
    annulus=annulus_px, detector_units='pixels', units='calibrated',
    show=False, plot_mask=True, return_detector=True,
    ring_color='lime', ring_alpha=0.3,
    mask_cmap='magma', mask_log_scale=False, mask_power=contrast_power,
    mask_vmin=0, mask_vmax=display_max,
    mask_show_kwargs={'title': 'Annular detector', 'figsize': (6, 5), 'scale_bar': 2},
)
np.testing.assert_array_equal(preview_image.array, annular.array)
np.testing.assert_allclose(masked_mean.array, mean_dp.array * annulus_mask)
Figure from the synthetic tutorial

7. Pixel and calibrated detector definitions

On calibrated data the default detector_units=’auto’ interprets radii and positions in the stored reciprocal units. Explicit ’pixels’ is therefore important for pixel recipes. A 4-pixel radius is 1 mrad here.

Pixel disk centers are absolute (row, column) coordinates. Calibrated centers are relative to the geometric detector midpoint, with positive ky upward and positive kx rightward. The conversion below includes the y sign change. These conventions are separate from .show(coords=…), which accepts pixel overlay coordinates.

Changing displayed units should never move the physical detector. The checks below show that equivalent pixel and calibrated definitions produce the same virtual image.

scale = data.reciprocal_conv_factor
annular_calibrated = data.virtual_image(
    annulus=np.asarray(annulus_px) * scale, detector_units='calibrated', show=False,
)
annular_auto = data.virtual_image(annulus=np.asarray(annulus_px) * scale, show=False)
spot_center_calibrated = np.array(((cy - spot_center_px[0]) * scale,
                                   (spot_center_px[1] - cx) * scale))
spot_calibrated = data.virtual_image(
    radius=disk_radius_px * scale, centers=spot_center_calibrated,
    detector_units='calibrated', show=False,
)
np.testing.assert_array_equal(annular_calibrated.array, annular.array)
np.testing.assert_array_equal(annular_auto.array, annular.array)
np.testing.assert_array_equal(spot_calibrated.array, one_spot.array)
print('One detector center in pixels:', np.round(spot_center_px, 3))
print('The same center in mrad:', np.round(spot_center_calibrated, 3))
One detector center in pixels: [58.553 50.5  ]
The same center in mrad: [-4.763  2.75 ]

Two equal-radius disks can select the corresponding spot in each artificial region. For this comparison we use the same count limits on both images so the colors are directly comparable. A weak image may simply mean the chosen spot lies outside that detector, not that the sample is non-crystalline.

other_spot = data.virtual_image(
    radius=disk_radius_px, centers=hexagon_30[1], detector_units='pixels', show=False,
)
shared_max = max(one_spot.array.max(), other_spot.array.max())
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
for ax, image, title in zip(axes, (one_spot, other_spot), ('Region A detector', 'Region B detector')):
    image.show(
        ax=ax, show=False, axis_units='calibrated', title=title,
        cmap='magma', vmin=0, vmax=shared_max, grid_ticks=(5, 5),
        colorbar_label='Integrated counts',
    )
plt.show()
Figure from the synthetic tutorial

8. Multiple disks form a union

Supply one center or an (N, 2) center array, with one shared radius or one radius per center. Overlapping disks count a pixel once. They are a union, not a sum of independent detector weights. Duplicating a center therefore does not double the signal.

If you need an overlapping pixel to contribute twice, construct a numeric weight mask explicitly instead.

union_centers = hexagon_0[[0, 2, 4]]
union_image = data.virtual_image(
    radius=disk_radius_px, centers=union_centers, detector_units='pixels', show=False,
)
union_mask = np.logical_or.reduce([
    (yy - y)**2 + (xx - x)**2 <= disk_radius_px**2 for y, x in union_centers
])
union_from_mask = data.virtual_image(mask=union_mask, show=False)
duplicate_image = data.virtual_image(
    radius=disk_radius_px, centers=np.vstack((spot_center_px, spot_center_px)),
    detector_units='pixels', show=False,
)
np.testing.assert_array_equal(union_image.array, union_from_mask.array)
np.testing.assert_array_equal(duplicate_image.array, one_spot.array)
print('Multiple disks agree with their Boolean union; duplicate centers do not double-count.')
Multiple disks agree with their Boolean union; duplicate centers do not double-count.

9. Arbitrary Boolean and weighted masks

Any finite real-valued detector array of shape (Ky, Kx) can supply weights. A Boolean example below keeps only the right half of the annulus. A soft Gaussian detector gives fractional weights near a spot. A signed detector subtracts one opposing spot from the other.

A preview tint shows only the nonzero support, not weight magnitude or sign. Plot the weight image itself to understand a soft or signed detector. This matters especially for a Gaussian, whose nonzero support can cover the entire detector.

half_annulus_mask = annulus_mask & (xx >= cx)
half_annulus = data.virtual_image(mask=half_annulus_mask, show=False)
gaussian_weights = np.exp(-((yy - spot_center_px[0])**2 + (xx - spot_center_px[1])**2) / (2 * 4.0**2))
soft_image = data.virtual_image(mask=gaussian_weights, show=False)

opposite_center = hexagon_0[4]
opposite_mask = ((yy - opposite_center[0])**2 + (xx - opposite_center[1])**2) <= disk_radius_px**2
signed_weights = spot_mask.astype(float) - opposite_mask.astype(float)
difference_image = data.virtual_image(mask=signed_weights, show=False)
opposite_image = data.virtual_image(mask=opposite_mask, show=False)
np.testing.assert_allclose(difference_image.array, one_spot.array - opposite_image.array)
assert difference_image.array.min() < 0 < difference_image.array.max()

fig, axes = plt.subplots(1, 3, figsize=(12, 4), layout='constrained')
for ax, weights, title, cmap, low, high in zip(
    axes, (half_annulus_mask, gaussian_weights, signed_weights),
    ('Boolean support', 'Soft weights', 'Signed weights'),
    ('gray', 'viridis', 'RdBu_r'), (0, 0, -1), (1, 1, 1),
):
    im = ax.imshow(weights, cmap=cmap, vmin=low, vmax=high, origin='upper')
    ax.set(title=title, xlabel='Detector column (pixels)', ylabel='Detector row (pixels)')
    fig.colorbar(im, ax=ax, shrink=0.7, label='Weight')
plt.show()
Figure from the synthetic tutorial
fig, axes = plt.subplots(1, 3, figsize=(14, 4), layout='constrained')
half_annulus.show(
    ax=axes[0], show=False, title='Half annulus', cmap='viridis', vmin=0,
    axis_units='auto', grid_ticks=(5, 5), colorbar_label='Integrated counts',
)
soft_image.show(
    ax=axes[1], show=False, title='Soft detector', cmap='magma', vmin=0,
    axis_units='auto', grid_ticks=(5, 5), colorbar_label='Weighted counts',
)
difference_image.show(
    ax=axes[2], show=False, title='Opposing-spot difference', cmap='RdBu_r', symmetric=True,
    axis_units='auto', grid_ticks=(5, 5), colorbar_label='Count difference',
)
plt.show()
Figure from the synthetic tutorial

The signed image deliberately contains negative and positive values. Do not clip it to zero or use a logarithmic display. Symmetric limits center its diverging colormap at zero. The sign reflects our assigned opposing-spot imbalance; it is not automatically a strain, electric-field, or center-of-mass measurement.

A Gaussian-weighted sum and a hard-disk sum are different measurements: weights are not area-normalized. Dividing by a chosen weight sum would instead give a weighted mean and must be an explicit analysis choice.

10. Compose an axes-free image with an adjustable scale bar

The scale-bar length uses the displayed units. With calibrated scan axes below, 15 means 15 nm, not 15 pixels. Its color, position, and numeric label are independently controlled. Set scale_bar_label=False to keep only the bar. If you switch to axis_units=’pixels’, choose the length in scan pixels instead.

Returned RealSpace.show() figures/axes allow further Matplotlib customization and export. The explicit limits below control the image colors, not the underlying counts.

scale_bar_length = 15.0  # nm because axis_units is calibrated
image_fig, image_ax = annular.show(
    axis_units='calibrated', axes=False, show=False, colorbar=True,
    title='Annular virtual image', cmap='magma', vmin=0, vmax=annular.array.max(),
    scale_bar=scale_bar_length, scale_bar_position='left',
    scale_bar_color='white', scale_bar_label=True,
    colorbar_label='Integrated counts', figsize=(6, 4),
)
export_path = work_dir / 'annular-virtual-image.png'
image_fig.savefig(export_path, dpi=150, bbox_inches='tight')
assert export_path.is_file()
plt.show()
print('Temporary figure export:', export_path)
Figure from the synthetic tutorial
Temporary figure export: /tmp/4denoise-tutorial-02-1hk2_jwc/annular-virtual-image.png

11. Polar display is not a polar data transform

ReciprocalSpace.show(mode=’polar’) displays a circular radial/angular projection of a pattern. Radial rings and angular spokes have separate tick counts. Angles increase clockwise from the right in this image-array convention. The scale bar uses radial units and defaults to a lower-centered position in circular mode.

This preview samples the largest centered circle for display only. It does not change the diffraction array or set polar metadata. For a stored rectangular (kr, ktheta) dataset, use to_polar(); that coordinate transformation and interpolation belong in Tutorial 3.

mean_0.show(
    mode='polar', axis_units='calibrated', title='Circular polar preview',
    grid=True, radial_ticks=5, angular_ticks=12, grid_alpha=0.35,
    scale_bar=2.0, scale_bar_position='center', scale_bar_color='white',
    logScale=False, power=contrast_power, vmin=0, vmax=display_max,
    cmap='magma', figsize=(6, 6),
)
assert not data.is_polar and not mean_0.is_polar
np.testing.assert_array_equal(data.array, original_counts)
Figure from the synthetic tutorial

12. The same detector can read from disk

A read-only source supports the same virtual detector definition and returns a complete, owned 2D scan image. Saved metadata supplies its calibration. This example checks exact agreement with the in-memory annulus after source closure; it never calls source.load().

working_memory_mb budgets estimated temporary numerical arrays, not the returned scan image, all caches, metadata, or total process RAM. Global tensor methods are not made lazy by opening a source.

saved_path = data.save(work_dir / 'hexagonal-scan.4denoise', overwrite=True)
with HyperData.open(saved_path) as source:
    disk_image = source.virtual_image(
        annulus=annulus_px, detector_units='pixels', show=False, working_memory_mb=8,
    )
assert source.closed
np.testing.assert_array_equal(disk_image.array, annular.array)
np.testing.assert_allclose(disk_image.pixel_size, annular.pixel_size)
print('Disk-backed and in-memory detector sums agree exactly.')
Disk-backed and in-memory detector sums agree exactly.

13. Substitute experimental or simulation data later

Edit the configuration at the top of the next cell. With input_data=None and microscope_path=None, the example remains runnable. Earlier examples continue to use their known synthetic fixture; they never export your acquisition.

Alternatively set input_data to an existing HyperData or numerical array and label its input_origin as ’experimental’ or ’simulation’. Do not set a file path at the same time. HyperData is copied with its existing geometry; leave loader options and calibration overrides empty for it. A bare array is copied with only the calibration you explicitly supply. Convert simulator-specific objects to an array first and confirm (Ry, Rx, Ky, Kx). No analytical hexagon, orientation labels, or synthetic detector radius is applied to an external input.

For native NumPy, HDF5, MATLAB, raw, or saved HyperData files, choose ’native’ and verified loader options. This branch eagerly loads the input; use a read-only source instead for an acquisition too large for RAM. For supported optional readers, install .[rosetta], choose ’rosetta’, and provide a confirmed reader/dataset/axis order when necessary. The Rosetta branch explicitly caps full loading at 512 MiB.

Leave calibration overrides empty unless you have verified values. The invented nm/mrad scales and synthetic acquisition record are not copied onto a microscope file. Define your own annulus in pixels after inspecting the acquisition. No experimental detector radius, beam location, scan orientation, or crystallinity threshold is guessed for you.

input_data = None  # Later: an existing HyperData object or numerical array.
input_origin = 'experimental'  # Or 'simulation'; not an automatic physical interpretation.
microscope_path = None  # Later: Path('path/to/your/acquisition.hdf5')
microscope_backend = 'native'  # 'native' or 'rosetta'
microscope_options = {}  # e.g. {'hdf5_dataset': '/entry/data'} for native HDF5
microscope_calibration = {}  # Verified overrides only; no synthetic defaults.
microscope_annulus_px = None  # Later: an explicitly chosen (inner, outer) pixel pair.

if input_data is not None and microscope_path is not None:
    raise ValueError('Provide input_data or microscope_path, not both.')
if input_origin not in ('experimental', 'simulation'):
    raise ValueError('input_origin must be experimental or simulation.')
if input_data is not None:
    if microscope_options:
        raise ValueError('Loader options apply to file inputs, not input_data.')
    if isinstance(input_data, HyperData):
        if microscope_calibration:
            raise ValueError('Calibrate your HyperData before passing it as input_data.')
        selected_data = input_data.copy()
    else:
        selected_data = HyperData(np.array(input_data, copy=True), **microscope_calibration)
    selected_annulus_px = microscope_annulus_px
    print('Selected in-memory ' + input_origin + ' data.')
elif microscope_path is None:
    selected_data = data.copy()
    selected_annulus_px = annulus_px
    print('Selected the SYNTHETIC hexagonal example.')
elif microscope_backend == 'native':
    selected_data = HyperData(
        Path(microscope_path), **microscope_options, **microscope_calibration,
    )
    selected_annulus_px = microscope_annulus_px
elif microscope_backend == 'rosetta':
    with HyperData.open(
        Path(microscope_path), backend='rosetta',
        **microscope_options, **microscope_calibration,
    ) as microscope_source:
        selected_data = microscope_source.load(max_memory_mb=512, working_memory_mb=64)
    selected_annulus_px = microscope_annulus_px
else:
    raise ValueError('microscope_backend must be native or rosetta.')
print(selected_data.metadata_summary())
Selected the SYNTHETIC hexagonal example.
Current data shape: (16, 20, 80, 80)
Acquisition metadata (original acquisition, not current geometry):
Instrument settings are not a verified R/Q or pixel calibration; no calibration or rotation is inferred.
Current real-space calibration: (2.0, 3.0) 'nm' per pixel
Current reciprocal-space calibration: 0.25 'mrad' per pixel
Current R/Q calibration: None
selected_data.get_dp(operation='mean', working_memory_mb=16).show(
    axis_units='auto', title='Selected input: mean pattern',
    logScale=False, power=0.4, cmap='magma', figsize=(5.5, 4.5),
)
if selected_data.ndim == 4 and not selected_data.is_polar and not selected_data.is_cepstral:
    if selected_annulus_px is not None:
        selected_image = selected_data.virtual_image(
            annulus=selected_annulus_px, detector_units='pixels', show=False,
            working_memory_mb=16,
        )
        selected_image.show(
            axis_units='auto', title='Selected annular image', cmap='magma',
            grid_ticks=(5, 5), figsize=(6, 4),
        )
    else:
        print('Inspect the detector, then set microscope_annulus_px explicitly.')
else:
    print('This detector recipe expects a Cartesian 4D scan; confirm the input geometry first.')
Figure from the synthetic tutorial Figure from the synthetic tutorial

Takeaways and cleanup

  • Scan masks and detector masks have different shapes and roles.

  • Display units, detector-input units, and intensity transforms are independent controls.

  • A virtual detector produces an unnormalized weighted sum at each scan position.

  • Multiple disks form a union; numeric masks let you define other weighting rules.

  • Returned images support shared color limits, subplots, axes-free views, and calibrated scale bars.

  • Weak selected-spot contrast does not by itself establish low crystallinity.

  • A polar display and an actual polar coordinate transformation are different operations.

The final cell checks that the original synthetic counts are unchanged, closes figures, and removes only the owned tutorial directory. In-memory results remain usable. Save any figure you want to keep outside that directory before cleanup. Next in the series: alignment and coordinate transforms.

np.testing.assert_array_equal(data.array, original_counts)
plt.close('all')
workspace.cleanup()
assert not work_dir.exists()
print('Tutorial complete: detector checks passed, source counts unchanged, temporary files removed.')
Tutorial complete: detector checks passed, source counts unchanged, temporary files removed.