Tutorial 3: Alignment and Coordinate Transforms

A self-contained lesson with synthetic hexagonal diffraction patterns and known subpixel beam drift. No microscope acquisition, preceding tutorial output, RosettaSciIO, or simulation tools are required. Use core 4Denoise plus a Jupyter/IPython kernel.

We will align a central disk, inspect its stored center/radius, block the direct beam, rotate Cartesian and polar patterns, reconstruct a Cartesian image, and save polar metadata. A marked input cell near the end lets you introduce real data later.

Teaching model, not an electron-scattering simulation: six Gaussian spots surround an artificial central disk. We translate the whole pattern, without changing orientation or introducing strain. Calibration, intensities, and drift are invented. Passing these checks does not establish experimental calibration or R/Q orientation.

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

Restart the kernel and run from top to bottom. These explicit NumPy and Matplotlib imports provide names in this notebook; imports inside 4Denoise do not supply them here. Generated files belong to a temporary directory removed in the final cell.

%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-03-')
work_dir = Path(workspace.name)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py

2. A drifting central disk and regular hexagon

The array has shape (8, 10, 80, 80), ordered (Ry, Rx, Ky, Kx). Each pattern contains a softened disk of radius 6 pixels and six spots at radius 22 pixels. A smooth, known (dy, dx) displacement moves the beam and spots together. The drift includes a nonzero mean offset and varies by scan position.

Absolute detector coordinates are (row, column) = (y, x), with rows increasing downward. Angles in this construction increase clockwise from the right. The random seed makes Poisson noise reproducible. Float32 storage allows interpolated intensities; these samples are not integer counts after alignment.

rng = np.random.default_rng(2027)
Ry, Rx, Ky, Kx = 8, 10, 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
drift_y = 1.0 + 1.8 * sy + 0.5 * np.sin(np.pi * sx)
drift_x = -1.2 + 1.6 * sx + 0.4 * np.cos(np.pi * sy)
true_centers = np.stack((cy + drift_y, cx + drift_x), axis=-1)
beam_radius_px, spot_radius_px = 6.0, 22.0
dy = yy - true_centers[..., 0, None, None]
dx = xx - true_centers[..., 1, None, None]
radius = np.hypot(dy, dx)
background_level = 2.0
expected_counts = background_level + 120 * (1 - np.tanh((radius - beam_radius_px) / 0.45)) / 2
angles = np.arange(6) * np.pi / 3
for angle in angles:
    expected_counts += 30 * np.exp(
        -((dy - spot_radius_px * np.sin(angle))**2
          + (dx - spot_radius_px * np.cos(angle))**2) / (2 * 1.3**2)
    )
synthetic_array = rng.poisson(expected_counts).astype(np.float32)
hexagon_offsets = np.column_stack((spot_radius_px * np.sin(angles),
                                   spot_radius_px * np.cos(angles)))
np.testing.assert_allclose(np.linalg.norm(hexagon_offsets, axis=1), spot_radius_px)
np.testing.assert_allclose(np.linalg.norm(np.roll(hexagon_offsets, -1, axis=0)
                                        - hexagon_offsets, 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: (8, 10, 80, 80) float32
Numerical size: 1.95 MiB

The illustrative calibration is 2 nm per scan row, 3 nm per scan column, and 0.25 mrad per diffraction pixel. A copy of this small input will check non-mutation; do not duplicate a multi-GB acquisition just for that check. We deliberately begin without a fitted beam center or R/Q calibration.

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': 2027,
                          'description': 'Translated disk and regular hexagonal spots'},
)
original_counts = data.array.copy()
assert data.center_beam_metadata is None and data.rq_calibration is None
contrast_power = 0.4
display_max = float(data.array.max())**contrast_power
print(data.metadata_summary())
Current data shape: (8, 10, 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

3. Measure the imposed motion independently

This small diagnostic computes an intensity centroid in a 12-pixel central neighborhood after subtracting the known synthetic background. It is independent of the template fit used below. The neighborhood contains every shifted disk and excludes the hexagonal spots. It is not a generally valid estimator or background model for microscope data.

First check the centroid against the analytical centers. The maps show imposed row/column motion in detector pixels, not specimen displacement. No private 4Denoise helper is used for this diagnostic.

def measure_synthetic_beam_centers(array, approximate_center):
    rows, cols = np.indices(array.shape[-2:])
    roi = np.hypot(rows - approximate_center[0], cols - approximate_center[1]) <= 12
    weights = np.maximum(array - background_level, 0) * roi
    mass = weights.sum(axis=(-2, -1))
    return np.stack(((weights * rows).sum(axis=(-2, -1)) / mass,
                     (weights * cols).sum(axis=(-2, -1)) / mass), axis=-1)

centers_before = measure_synthetic_beam_centers(data.array, (cy, cx))
truth_error = np.sqrt(np.mean(np.sum((centers_before - true_centers)**2, axis=-1)))
assert truth_error < 0.15
print('Measured versus imposed center RMSE: {:.3f} pixels'.format(truth_error))
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), constrained_layout=True)
for ax, values, label in zip(axes, (drift_y, drift_x), ('Imposed dy', 'Imposed dx')):
    im = ax.imshow(values, cmap='RdBu_r', vmin=-3.5, vmax=3.5)
    ax.set(title=label, xlabel='Scan column Rx', ylabel='Scan row Ry')
    fig.colorbar(im, ax=ax, label='Detector pixels')
plt.show()
Measured versus imposed center RMSE: 0.058 pixels
Figure from the synthetic tutorial

4. Fit one representative disk, then align all patterns

Use method=’disk’ for the template workflow. Choose template=’negative_trench’ for a disk with a clear edge: the positive disk is surrounded by a negative ring. A plain ’disk’ template is another option. ’gaussian’ suits a peak-like/blob-like beam; method=’com’ suits a compact, isolated bright peak with a stable centroid. Templates are choices within the disk workflow, not separate alignment methods.

Here fit_radius=True searches candidate radii on the mean pattern. radius_range controls size candidates; search_radius controls translation, first around the supplied center and then around the fitted representative center for each pattern. These inputs are pixels, not mrad. Searching is local.

The mean is blurred by drift, so its best template radius need not equal the constructed radius. To use an independently chosen representative pattern, replace radius_operation=’mean’ with radius_reference_dp=data.get_dp(…) (or a matching 2D array). That parameter takes precedence and implies radius fitting.

Disk alignment crops each pattern and applies a residual subpixel shift, then returns a common canvas. enforce_square=True makes this canvas square. Unlike a pure translation on a fixed canvas, this can discard detector-edge data. Inspect the output shape. Currently alignment requires 4D input; a 3D stack must first be folded to a known scan grid.

aligned = data.alignment(
    method='disk', template='negative_trench',
    center=(cy, cx), r_center=6, search_radius=7,
    fit_radius=True, radius_range=(5, 7), radius_step=0.25,
    radius_operation='mean', iterations=1, enforce_square=True,
)
print('Before:', data.shape, 'After:', aligned.shape)
assert aligned.shape[:2] == (Ry, Rx)
assert aligned.shape[-2] == aligned.shape[-1]
np.testing.assert_array_equal(data.array, original_counts)
np.testing.assert_allclose(aligned.real_conv_factor, data.real_conv_factor)
np.testing.assert_allclose(aligned.real_origin, data.real_origin)
assert aligned.reciprocal_conv_factor == data.reciprocal_conv_factor
assert not np.shares_memory(aligned.array, data.array)
Selected negative_trench template reference from operation='mean': radius=6.5000, center=(40.0000, 38.0000) (score=0.8093).
Initial disk-center standard deviation (ky, kx): (1.2241, 1.0804)
Initial disk center (ky, kx): (40.4985, 38.2455)
Cropping diffraction patterns to common k-space shape (73, 73).
Final disk-center standard deviation (ky, kx): (0.0774, 0.0823)
Final disk center (ky, kx): (35.9993, 36.0033)
Before: (8, 10, 80, 80) After: (8, 10, 73, 73)
Template-matching negative_trench centers:   0%|          | 0/8 [00:00<?, ?it/s]
Template-matching negative_trench centers: 100%|██████████| 8/8 [00:00<00:00, 535.93it/s]
Cropping and affine-aligning disks:   0%|          | 0/8 [00:00<?, ?it/s]
Cropping and affine-aligning disks: 100%|██████████| 8/8 [00:00<00:00, 819.72it/s]
Template-matching negative_trench centers:   0%|          | 0/8 [00:00<?, ?it/s]
Template-matching negative_trench centers: 100%|██████████| 8/8 [00:00<00:00, 558.27it/s]

5. Inspect the result, not just the fitted summary

center_beam_metadata describes the current aligned canvas. Its center_px is absolute (row, column), whereas center_calibrated is relative to the geometric diffraction origin with y upward and x rightward. The radius is stored both in pixels and calibrated units. Historical reference/initial-fit coordinates refer to the original canvas, not this one.

The independent centroid diagnostic below should show much less pattern-to-pattern spread after alignment. Its agreement is more informative than reusing only the same template estimator. Exact centers are not expected with noise, discrete templates, and interpolation. These tolerances are checks on this teaching fixture, not universal quality thresholds.

beam = aligned.center_beam_metadata
beam_center = np.asarray(beam['center_px'])
for key in ('center_px', 'radius_px', 'center_calibrated', 'radius_calibrated',
            'calibrated_units', 'shape', 'initial_std_fit_center_px', 'std_fit_center_px'):
    print(key + ':', beam[key])
assert tuple(beam['shape']) == aligned.shape[-2:]
np.testing.assert_allclose(beam['radius_calibrated'],
                           beam['radius_px'] * aligned.reciprocal_conv_factor)
midpoint = (np.asarray(aligned.shape[-2:]) - 1) / 2
expected_calibrated_center = (beam_center - midpoint) * (-0.25, 0.25)
np.testing.assert_allclose(beam['center_calibrated'], expected_calibrated_center)
centers_after = measure_synthetic_beam_centers(aligned.array, beam_center)
spread_before = centers_before.std(axis=(0, 1))
spread_after = centers_after.std(axis=(0, 1))
target_rmse = np.sqrt(np.mean(np.sum((centers_after - beam_center)**2, axis=-1)))
print('Independent center std (dy, dx), before:', spread_before, 'after:', spread_after)
print('After-alignment target RMSE: {:.3f} pixels'.format(target_rmse))
assert np.all(spread_after < 0.2) and np.all(spread_after < 0.2 * spread_before)
assert target_rmse < 0.3
fig, ax = plt.subplots(figsize=(5.5, 4.5), constrained_layout=True)
before_offset = (centers_before - centers_before.mean(axis=(0, 1))).reshape(-1, 2)
after_offset = (centers_after - beam_center).reshape(-1, 2)
ax.scatter(before_offset[:, 1], before_offset[:, 0], label='Before: relative to mean', s=18)
ax.scatter(after_offset[:, 1], after_offset[:, 0], label='After: relative to fitted center', s=18)
ax.set(xlabel='Column offset dx (pixels)', ylabel='Row offset dy (pixels)',
       title='Independent center measurement', aspect='equal')
ax.invert_yaxis()
ax.legend(fontsize=8)
ax.grid(alpha=0.25)
plt.show()
center_px: (35.99932343117105, 36.00332559254677)
radius_px: 6.5
center_calibrated: (0.00016914220723762696, 0.0008313981366931955)
radius_calibrated: 1.625
calibrated_units: mrad
shape: (73, 73)
initial_std_fit_center_px: (1.2240669131219355, 1.0804331392628996)
std_fit_center_px: (0.07742368029659212, 0.08230889516381484)
Independent center std (dy, dx), before: [1.20756892 1.04197473] after: [0.08392738 0.09434898]
After-alignment target RMSE: 0.126 pixels
Figure from the synthetic tutorial

The mean pattern should sharpen after removing the imposed motion. The two views use identical intensity limits and calibration, but the aligned field of view is smaller. A displayed power transform changes only the figure. coords overlays take absolute pixel (y, x) coordinates even when the axes are calibrated and y-up.

mean_before = data.get_dp(operation='mean')
mean_aligned = aligned.get_dp(operation='mean')
mean_before.show(title='Before alignment: mean', axis_units='calibrated',
                 power=contrast_power, logScale=False, vmin=0, vmax=display_max,
                 cmap='magma', scale_bar=2, figsize=(5.5, 4.5))
mean_aligned.show(title='After alignment: mean', axis_units='calibrated',
                  coords=beam_center[None, :], marker='+', c='cyan', s=100,
                  power=contrast_power, logScale=False, vmin=0, vmax=display_max,
                  cmap='magma', scale_bar=2, figsize=(5.5, 4.5))
Figure from the synthetic tutorial Figure from the synthetic tutorial

6. Reuse the alignment beam metadata

block_direct_beam() uses the stored center and radius when omitted. We explicitly choose fill_value=0; the method default is 1. An explicit radius overrides metadata, and beam_units controls the units of explicit inputs. Below we verify that the calibrated radius gives the same mask.

This removes a chosen circular region, not a fitted background or all central-disk tails. The fitted 6.5-pixel radius is a template parameter, not a physical convergence semiangle measurement. Keep aligned unblocked for the subsequent transforms.

blocked, beam_mask = aligned.block_direct_beam(fill_value=0, return_mask=True)
blocked_calibrated, calibrated_mask = aligned.block_direct_beam(
    radius=beam['radius_calibrated'], beam_units='calibrated',
    fill_value=0, return_mask=True,
)
np.testing.assert_array_equal(beam_mask, calibrated_mask)
np.testing.assert_array_equal(blocked.array, blocked_calibrated.array)
assert np.all(blocked.array[..., beam_mask] == 0)
np.testing.assert_array_equal(blocked.array[..., ~beam_mask], aligned.array[..., ~beam_mask])
blocked.get_dp(operation='mean').show(
    title='Direct beam blocked from metadata', axis_units='auto',
    overlay_mask=beam_mask, overlay_color='green', overlay_alpha=0.2,
    power=contrast_power, logScale=False, vmin=0, vmax=display_max,
    cmap='magma', figsize=(5.5, 4.5),
)
Figure from the synthetic tutorial

7. Rotate Cartesian diffraction patterns

rotate_dps(24, units=’deg’, order=1) rotates all patterns counterclockwise using SciPy’s image convention. It accepts a 3D stack or a 4D scan, and Cartesian rotation expands the canvas. It rotates about the geometric image center, not an arbitrary stored off-center beam. Alignment has already placed this fixture’s beam very close to that midpoint. This differs from the center-aware R/Q calibration overlay tool.

Real-space scan calibration is unchanged; the reciprocal pixel spacing remains unchanged on the expanded Cartesian canvas. Rotating interpolates intensities. Rotating forward and backward is not an exact undo. This demonstration changes array data and is not a measurement or assignment of an R/Q calibration.

cartesian_rotated = aligned.rotate_dps(24, units='deg', order=1)
print('Cartesian canvas:', aligned.shape[-2:], '->', cartesian_rotated.shape[-2:])
assert cartesian_rotated.shape[:2] == aligned.shape[:2]
assert cartesian_rotated.reciprocal_conv_factor == aligned.reciprocal_conv_factor
np.testing.assert_allclose(cartesian_rotated.real_conv_factor, aligned.real_conv_factor)
assert cartesian_rotated.rq_calibration is None
cartesian_rotated.get_dp(operation='mean').show(
    title='Cartesian rotation: +24 degrees CCW', axis_units='auto',
    power=contrast_power, logScale=False, vmin=0, vmax=display_max,
    cmap='magma', scale_bar=2, figsize=(5.5, 4.5),
)
Cartesian canvas: (73, 73) -> (96, 96)
Rotating Diffraction Patterns:   0%|          | 0/80 [00:00<?, ?it/s]
Rotating Diffraction Patterns: 100%|██████████| 80/80 [00:00<00:00, 5144.57it/s]
Figure from the synthetic tutorial

8. Resample onto a polar grid

Unlike ReciprocalSpace.show(mode=’polar’), to_polar() transforms the stored samples and marks their geometry. The last two axes become (kr, ktheta). Pass the metadata center explicitly: the method otherwise uses the geometric image midpoint.

We sample radius 0 through 30 original detector pixels using 48 radial samples and 180 angular samples. At 0.25 mrad per original pixel, the radial extent is 7.5 mrad and each angular step is 2 degrees. Theta starts at the right and increases clockwise in detector-array coordinates. Only the chosen circle is retained; the original square’s corners are not included.

The radial sample centers include both endpoints: their spacing is r_max / (n_r - 1). The displayed radial extent is divided into n_r image bins, with width r_max / n_r. Metadata records both conventions; do not assume they are identical. Changing the output shape changes sampling, not the original physical radial extent.

polar = aligned.to_polar(
    center=tuple(beam_center), r_max=30, output_shape=(48, 180),
    order=1, clip=False, progress=False,
)
assert polar.is_polar and polar.shape == (Ry, Rx, 48, 180)
assert polar.reciprocal_units is None and polar.reciprocal_conv_factor is None
assert polar.center_beam_metadata is None
pm = polar.polar_metadata
np.testing.assert_allclose(pm['center'], beam_center)
np.testing.assert_allclose(pm['radius_display_range'], (0, 7.5))
np.testing.assert_allclose(pm['theta_step'], 2.0)
np.testing.assert_allclose(pm['radius_sample_step'], 7.5 / 47)
np.testing.assert_allclose(pm['radius_step'], 7.5 / 48)
np.testing.assert_allclose(polar.real_conv_factor, aligned.real_conv_factor)
np.testing.assert_allclose(polar.real_origin, aligned.real_origin)
for key in ('axis_order', 'cartesian_shape', 'radius_units', 'radius_display_range',
            'radius_sample_step', 'radius_step', 'theta_range', 'theta_step'):
    print(key + ':', pm[key])
polar.get_dp(operation='mean').show(
    title='Stored polar data: kr versus ktheta', axis_units='auto',
    power=contrast_power, logScale=False, vmin=0, vmax=display_max,
    cmap='magma', aspect='auto', figsize=(9, 4),
)
axis_order: ('radius', 'theta')
cartesian_shape: (73, 73)
radius_units: mrad
radius_display_range: (0.0, 7.5)
radius_sample_step: 0.1595744680851064
radius_step: 0.15625
theta_range: (0.0, 360.0)
theta_step: 2.0
Figure from the synthetic tutorial

9. Periodic rotation, including subpixel angles

For polar data, rotation is a wrapped shift of angular columns. Positive angles still mean counterclockwise, so they shift columns toward lower indices because stored theta increases clockwise. Here +24 degrees is exactly -12 columns. This integer shift uses an exact periodic roll; a 360-degree rotation leaves the array unchanged.

A +25-degree angle corresponds to -12.5 columns and uses interpolation with periodic boundaries. Samples crossing 0/360 re-enter on the opposite side. The profile isolates the spot ring, so six main peaks should shift together. Interpolated rotation, unlike an integer roll, need not invert exactly.

polar_rotated = polar.rotate_dps(24, order=1)
polar_fractional = polar.rotate_dps(25, order=1)
np.testing.assert_array_equal(polar_rotated.array, np.roll(polar.array, -12, axis=-1))
np.testing.assert_array_equal(polar_rotated.rotate_dps(-24).array, polar.array)
np.testing.assert_array_equal(polar.rotate_dps(360).array, polar.array)
assert polar_fractional.is_polar and polar_fractional.shape == polar.shape
r_samples = np.linspace(0, pm['r_max'], polar.shape[-2])
ring_rows = (r_samples >= 19) & (r_samples <= 25)
theta = np.arange(polar.shape[-1]) * pm['theta_step']
fig, ax = plt.subplots(figsize=(9, 3.5), constrained_layout=True)
for obj, label, style in ((polar, 'Original', '-'),
                          (polar_rotated, '+24 degrees (-12 columns)', '--'),
                          (polar_fractional, '+25 degrees (-12.5 columns)', ':')):
    profile = obj.array[..., ring_rows, :].mean(axis=(0, 1, 2))
    ax.plot(np.r_[theta, 360], np.r_[profile, profile[0]], style, label=label)
ax.set(xlim=(0, 360), xticks=np.arange(0, 361, 60), xlabel='ktheta (degrees)',
       ylabel='Mean spot-ring intensity', title='Periodic polar rotation')
ax.legend(fontsize=8)
ax.grid(alpha=0.25)
plt.show()
Figure from the synthetic tutorial

10. Virtual detectors follow polar metadata

An annular detector on stored polar data selects a rectangular radial interval. theta_range=(330, 30) selects a sector wrapping across zero. With detector_units=’pixels’, the radial limits mean original Cartesian pixel distances, not row indices of the 48-row polar array. With calibrated inputs, the equivalent range is (4.5, 6.5) mrad.

These virtual images sum polar sample values. They do not automatically apply a radial Jacobian, angular quadrature, or flux conservation. Do not compare their absolute sums to a Cartesian annulus as if the grids had equal sampling area. The calibrated/pixel equivalence check below compares two selectors on the same polar grid only.

ring_image = polar.virtual_image(annulus=(18, 26), detector_units='pixels', show=False)
ring_calibrated = polar.virtual_image(annulus=(4.5, 6.5),
                                      detector_units='calibrated', show=False)
np.testing.assert_allclose(ring_image.array, ring_calibrated.array)
sector_image = polar.virtual_image(annulus=(18, 26), theta_range=(330, 30),
                                   detector_units='pixels', show=False)
assert np.all(sector_image.array <= ring_image.array)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.7), constrained_layout=True)
for ax, image, label in zip(axes, (ring_image, sector_image), ('Full ring', 'Wrapped sector')):
    image.show(ax=ax, show=False, title=label, axis_units='auto', cmap='viridis',
               colorbar=True, colorbar_label='Sum of polar samples', scale_bar=10,
               scale_bar_color='white', grid_ticks=(5, 5))
plt.show()
Figure from the synthetic tutorial

11. Return to Cartesian coordinates: reconstruction, not undo

to_cartesian(output_shape=’original’) reconstructs on the shape and center stored by to_polar(). Here that is the aligned canvas, not the earlier 80-by-80 acquisition canvas. Only radii up to 30 pixels were sampled. Corners and other unsupported positions receive fill_value=0.

Two interpolations, finite angular/radial sampling, and excluded corners prevent exact recovery. We compare mean patterns inside radius 29, away from the support edge; the error tolerance below is deliberately specific to this synthetic dataset. A correct shape and calibration do not imply identical pixel values. The inverse clears the polar flag, but does not recreate alignment beam metadata that the polar conversion cleared.

reconstructed = polar.to_cartesian(output_shape='original', order=1,
                                    fill_value=0, clip=False, progress=False)
assert not reconstructed.is_polar and reconstructed.shape == aligned.shape
assert reconstructed.center_beam_metadata is None
assert reconstructed.reciprocal_units == aligned.reciprocal_units
np.testing.assert_allclose(reconstructed.reciprocal_conv_factor, aligned.reciprocal_conv_factor)
rows, cols = np.indices(aligned.shape[-2:])
reconstruction_radius = np.hypot(rows - beam_center[0], cols - beam_center[1])
inside = reconstruction_radius <= 29
outside = reconstruction_radius > pm['r_max']
assert np.all(reconstructed.array[..., outside] == 0)
reference_mean = aligned.array.mean(axis=(0, 1))
reconstructed_mean = reconstructed.array.mean(axis=(0, 1))
difference = reconstructed_mean - reference_mean
relative_error = np.linalg.norm(difference[inside]) / np.linalg.norm(reference_mean[inside])
assert 0 < relative_error < 0.1
print('Mean-pattern relative L2 error inside radius 29: {:.2%}'.format(relative_error))
fig, axes = plt.subplots(1, 3, figsize=(12, 3.7), constrained_layout=True)
for ax, image, label in zip(axes[:2], (reference_mean, reconstructed_mean),
                            ('Aligned reference', 'Polar -> Cartesian')):
    ax.imshow(image**contrast_power, cmap='magma', vmin=0, vmax=display_max)
    ax.set(title=label, xlabel='Detector column (pixels)', ylabel='Detector row (pixels)')
shown_error = np.where(inside, np.abs(difference), np.nan)
im = axes[2].imshow(shown_error, cmap='inferno', vmin=0)
axes[2].set(title='Absolute error inside r <= 29', xlabel='Detector column (pixels)')
fig.colorbar(im, ax=axes[2], label='Intensity difference')
plt.show()
Mean-pattern relative L2 error inside radius 29: 3.72%
Figure from the synthetic tutorial

12. Choose a new Cartesian canvas

The default inverse uses (2n_r, 2n_r), here 96 by 96, with the beam at the subpixel image center. An explicit output_shape=(80, 80) uses a different pixel spacing. The physical outer radius stays 7.5 mrad, so the default spacing is 7.5 / 48 mrad per pixel and the 80-by-80 spacing is 7.5 / 40. Extra output pixels do not recover new physical resolution or the original corners.

These two inverses use a new centered canvas; ’original’ instead retains the stored Cartesian pixel scale and original stored center. All return new objects.

default_cartesian = polar.to_cartesian(progress=False)
custom_cartesian = polar.to_cartesian(output_shape=(80, 80), progress=False)
assert default_cartesian.shape == (Ry, Rx, 96, 96)
assert custom_cartesian.shape == (Ry, Rx, 80, 80)
np.testing.assert_allclose(default_cartesian.reciprocal_conv_factor, 7.5 / 48)
np.testing.assert_allclose(custom_cartesian.reciprocal_conv_factor, 7.5 / 40)
for name, obj in (('Original canvas', reconstructed),
                  ('Default canvas', default_cartesian), ('Custom canvas', custom_cartesian)):
    print(name, obj.shape[-2:], obj.reciprocal_conv_factor, obj.reciprocal_units + '/pixel')
default_cartesian.get_dp(operation='mean').show(
    title='New 96 x 96 canvas: same radial extent', axis_units='auto',
    power=contrast_power, logScale=False, vmin=0, vmax=display_max,
    cmap='magma', scale_bar=2, figsize=(5.5, 4.5),
)
Original canvas (73, 73) 0.25 mrad/pixel
Default canvas (96, 96) 0.15625 mrad/pixel
Custom canvas (80, 80) 0.1875 mrad/pixel
Figure from the synthetic tutorial

13. Save the transformed geometry with the data

A NumPy array alone cannot tell a later session that its last axes mean radius/angle. Native .save() retains polar and scan metadata. Reloading the saved samples is exact; reconstructing their pre-polar source is not. We also save the aligned object to check its beam metadata survives. Files remain in this tutorial’s disposable directory.

polar_path = work_dir / 'polar_hexagons.4denoise'
aligned_path = work_dir / 'aligned_hexagons.4denoise'
polar.save(polar_path)
aligned.save(aligned_path)
reloaded_polar = HyperData(polar_path)
reloaded_aligned = HyperData(aligned_path)
assert reloaded_polar.is_polar and not reloaded_aligned.is_polar
np.testing.assert_array_equal(reloaded_polar.array, polar.array)
np.testing.assert_allclose(reloaded_polar.polar_metadata['center'], beam_center)
np.testing.assert_allclose(reloaded_polar.polar_metadata['theta_step'], pm['theta_step'])
np.testing.assert_allclose(reloaded_polar.real_conv_factor, data.real_conv_factor)
np.testing.assert_allclose(reloaded_aligned.center_beam_metadata['radius_px'], beam['radius_px'])
np.testing.assert_allclose(reloaded_aligned.center_beam_metadata['center_px'], beam_center)
print(reloaded_polar.metadata_summary())
Current data shape: (8, 10, 48, 180)
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: not set
Current R/Q calibration: None

14. Replaceable experimental/simulation input: disabled by default

Leave input_data=None and microscope_path=None for the checked synthetic run. Later, set a path and reader options, or pass an existing HyperData/numerical array as input_data and label its input_origin as ’experimental’ or ’simulation’. Do not set both inputs. HyperData is copied with its metadata; leave loader and calibration overrides empty for it. A bare array receives only supplied, verified calibration. Convert simulator-specific objects to numerical arrays and verify their axis order first. Earlier known-truth exercises remain synthetic; this separate branch does not run their truth assertions on an acquisition.

No synthetic units, radius, center, or R/Q calibration are assigned to an external input. Native loading and in-memory copies are eager; the optional Rosetta branch explicitly caps a full load at 512 MiB. For larger inputs, start with HyperData.open() and the large-data guide instead.

Inspect the preview before enabling alignment. To opt in, supply a verified approximate center, radius, local translation search, and a radius candidate range, all in pixels. This example intentionally requires those choices and a 4D scan. A mean can blur the disk, diffraction edges can be clipped, and anisotropic/noncircular beams may not suit a circular template. Review each acquisition separately. This branch is not validated by the default synthetic run.

input_data = None  # Existing HyperData or numerical array, including simulation output.
input_origin = 'experimental'  # Or 'simulation'.
microscope_path = None
microscope_backend = 'native'
microscope_options = {}
microscope_calibration = {}
run_microscope_alignment = False
microscope_center_px = None
microscope_disk_radius_px = None
microscope_radius_range_px = None
microscope_search_radius_px = None

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.')
        inspection_data = input_data.copy()
    else:
        inspection_data = HyperData(np.array(input_data, copy=True), **microscope_calibration)
    print('Selected in-memory ' + input_origin + ' data.')
elif microscope_path is None:
    inspection_data = data.copy()
    print('Using a copy of the unaligned synthetic input; microscope alignment is disabled.')
elif microscope_backend == 'native':
    inspection_data = HyperData(microscope_path, **microscope_options, **microscope_calibration)
elif microscope_backend == 'rosetta':
    with HyperData.open(microscope_path, backend='rosetta',
                        **microscope_options, **microscope_calibration) as source:
        print(source.metadata_summary())
        inspection_data = source.load(max_memory_mb=512, working_memory_mb=64)
else:
    raise ValueError('Choose microscope_backend as native or rosetta.')
print(inspection_data.metadata_summary())
Using a copy of the unaligned synthetic input; microscope alignment is disabled.
Current data shape: (8, 10, 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

This final preview uses your selected input’s own geometry. The optional alignment result gets a separate name so you retain the input. No polar conversion or R/Q correction is automatically applied to microscope data. If you later convert it, explicitly pass the fitted center_beam_metadata[‘center_px’] into to_polar(center=…), and choose an appropriate radius and sampling.

inspection_data.get_dp(operation='mean').show(
    title='Selected input: inspect before alignment', axis_units='auto',
    power=0.4, logScale=False, cmap='magma', figsize=(5.5, 4.5),
)
microscope_aligned = None
if (input_data is not None or microscope_path is not None) and run_microscope_alignment:
    if inspection_data.ndim != 4 or inspection_data.is_polar:
        raise ValueError('This alignment recipe needs a 4D Cartesian scan.')
    if any(value is None for value in (microscope_center_px, microscope_disk_radius_px,
                                       microscope_radius_range_px, microscope_search_radius_px)):
        raise ValueError('Set the center, disk radius, radius range, and translation search in pixels.')
    microscope_aligned = inspection_data.alignment(
        method='disk', template='negative_trench',
        center=microscope_center_px, r_center=microscope_disk_radius_px,
        search_radius=microscope_search_radius_px, fit_radius=True,
        radius_range=microscope_radius_range_px, radius_operation='mean',
        iterations=1, enforce_square=False,
    )
    print('Inspect fitted beam metadata:', microscope_aligned.center_beam_metadata)
Figure from the synthetic tutorial

15. What to remember

  • Alignment corrects translations, may crop the detector, and stores center/radius information for the resulting canvas. It does not determine orientation, strain, or R/Q rotation.

  • Check an alignment against independent diagnostics and representative patterns; a best-fit template radius is not necessarily the true beam radius.

  • Cartesian image rotation and clockwise stored theta have opposite signs. Integer polar shifts can be exactly reversible; interpolation and discarded support are not.

  • Polar geometry defines radial units, angular sampling, and supported data. A new Cartesian canvas changes pixel spacing while retaining the chosen physical radial extent.

  • Polar sample sums are not automatically flux-conserving Cartesian integrals. Save the metadata and keep the original acquisition.

Continue with Tutorial 4: Denoising and unfolding. See the data model, visualization guide, and streaming tutorial for geometry and bounded-memory workflows. The last cell checks the source once more and removes only files this notebook created.

np.testing.assert_array_equal(data.array, original_counts)
assert data.center_beam_metadata is None and data.rq_calibration is None
assert aligned.rq_calibration is None and polar.rq_calibration is None
plt.close('all')
workspace.cleanup()
print('Synthetic checks passed; original input unchanged; temporary files removed.')
Synthetic checks passed; original input unchanged; temporary files removed.