7. Large-data processing

Keep diffraction pixels on disk while producing small, useful results. This independent lesson constructs reproducible synthetic hexagonal patterns directly in an HDF5 file, never a full 4D fixture in RAM. It demonstrates metadata inspection, owned single-pattern reads, bounded reductions, chunk iteration, virtual imaging, incremental peak files, and transforms saved directly to disk. The default example is deliberately small enough for a laptop and routine CI; it demonstrates an execution path, not a multi-GB RAM benchmark or physical scattering simulation.

The marked input cell can later select a real acquisition or saved simulation. Unlike Tutorials 1-6, this lesson is file-based: an existing array/HyperData is not silently copied, saved, or treated as lazy. Save such data deliberately first, then supply its file path. No full-source load() or eager HyperData(path) occurs in the workflow.

Restart the kernel and run all cells. Core dependencies plus a Jupyter kernel are sufficient for the native HDF5 default. RosettaSciIO is optional for supported lazy microscope readers. Generated files live in an owned temporary directory; the final cell closes figures and removes only those files.

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.

%matplotlib inline
import hashlib
import json
from pathlib import Path
import shutil
import sys
from tempfile import TemporaryDirectory
from time import perf_counter
import h5py
import matplotlib.pyplot as plt
import numpy as np
import fourdenoise as fd
from fourdenoise import HyperData, RealSpace

print('Python:', sys.executable)
print('4Denoise:', fd.__file__)
temporary_output = TemporaryDirectory(prefix='4denoise-tutorial-07-')
output_dir = Path(temporary_output.name)
timings = {}
written_paths = {}

def streaming_sha256(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as file:
        for piece in iter(lambda: file.read(1024 * 1024), b''):
            digest.update(piece)
    return digest.hexdigest()

def json_numeric(value):
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    raise TypeError('Unsupported manifest value: ' + type(value).__name__)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py

1. Construct a disk-backed teaching fixture

The scan is (12, 16), and each pattern is (64, 64), in (Ry, Rx, Ky, Kx) order. Two differently oriented hexagonal regions have varying spot amplitudes and small beam motion. Each generated pattern is quantized to uint16 counts and written immediately. Only detector-sized arrays are needed during construction. This is a toy signal/noise model, not an electron-scattering calculation.

HDF5 storage chunks are (1, 4, 64, 64). Storage chunks control physical reads/compression; the processing blocks requested later are a separate choice. A small slice can still cause a larger storage/reader chunk to be read. Generic HDF5 attributes below are descriptive only: 4Denoise does not infer calibration from arbitrarily named attributes, so we pass the illustrative calibration explicitly when opening this fixture.

synthetic_path = output_dir / 'synthetic_hexagons.hdf5'
synthetic_shape = (12, 16, 64, 64)
synthetic_calibration = dict(real_units='nm', real_conv_factor=(2.0, 3.0), real_origin=(10.0, 20.0),
                             reciprocal_units='1/angstrom', reciprocal_conv_factor=0.04)
rng = np.random.default_rng(2031)
yy, xx = np.ogrid[:64, :64]
with h5py.File(synthetic_path, 'x') as file:
    dataset = file.create_dataset('diffraction', shape=synthetic_shape, dtype='uint16',
                                  chunks=(1, 4, 64, 64), compression='gzip', compression_opts=1)
    file.attrs['description'] = 'Synthetic teaching fixture; not an original acquisition'
    for i, j in np.ndindex(synthetic_shape[:2]):
        center = np.array([31.5 + 0.3 * np.sin(i / 3), 31.5 + 0.3 * np.cos(j / 4)])
        angle = np.deg2rad(10 if j < 8 else 28)
        phi = angle + np.arange(6) * np.pi / 3
        positions = center + 18 * np.column_stack((np.sin(phi), np.cos(phi)))
        pattern = 2.0 + 80 * np.exp(-((yy - center[0])**2 + (xx - center[1])**2) / 8)
        for peak_index, (y, x) in enumerate(positions):
            amplitude = (35 + 25 * j / 15) * (0.8 + 0.08 * peak_index)
            pattern += amplitude * np.exp(-((yy - y)**2 + (xx - x)**2) / (2 * 1.1**2))
        dataset[i, j] = rng.poisson(pattern).astype(np.uint16)
print('Created:', synthetic_path.name, synthetic_shape, 'uint16')
print('Only one detector-sized synthetic pattern was generated at a time.')
Created: synthetic_hexagons.hdf5 (12, 16, 64, 64) uint16
Only one detector-sized synthetic pattern was generated at a time.

2. Select a file, not an eager copy

Leave microscope_path=None for the fixture. For external input, give a path and confirm the stored axis order is (Ry, Rx, Ky, Kx). Native sources support .npy, .h5/.hdf5/.hdf, and saved .4denoise. Generic HDF5 with multiple datasets needs microscope_options={‘hdf5_dataset’: ‘/path/to/data’}. Saved HyperData retains its own metadata. Bare .npy/generic HDF5 has no assumed calibration: supply verified unit/scale pairs explicitly, or remain in pixels.

For a supported microscope reader, set microscope_backend=’rosetta’ and choose reader/dataset/axis_order in microscope_options when needed. Install the optional rosetta extra first. Unsupported lazy readers raise instead of silently loading the acquisition eagerly. Reader availability is not validation of an original acquisition’s axes, calibration, beam center, or R/Q orientation.

External data requires an explicitly inspected analysis_annulus_px. Peak extraction and transform writing default to off for an external file; inspect its geometry, operation settings, output estimate, and free disk space before opting in. Tutorial outputs remain temporary even for external inputs. To keep results, deliberately choose persistent destinations in the relevant cells before running them.

input_data = None  # Intentionally unsupported here: save arrays/HyperData explicitly, then use a file.
input_origin = 'experimental'  # Or 'simulation'; a declaration, not verified provenance.
microscope_path = None
microscope_backend = 'native'
microscope_options = {}
microscope_calibration = {}
working_memory_mb = 16.0
max_scan_map_mb = 64.0  # Guard for each complete float64 scan map, not total process RAM.
chunk_shape = (3, 4)
analysis_annulus_px = None  # Synthetic: (12, 24); choose explicitly for external data.
transform_center_px = None  # Current center_px metadata if present; otherwise geometric midpoint.
scan_mask_input = None  # Peak extraction only; other operations cover the complete scan.
run_peak_detection = None  # None: synthetic only. True explicitly opts in for another file.
peak_options_input = None  # External peak extraction needs explicitly reviewed detector settings.
run_transforms = None  # None: synthetic only; creates several full disk outputs when True.

if input_data is not None:
    raise ValueError('This lesson is file-based. Save your array/HyperData deliberately, then set microscope_path.')
if input_origin not in ('experimental', 'simulation'):
    raise ValueError('input_origin must be experimental or simulation.')
if microscope_backend not in ('native', 'rosetta', 'auto'):
    raise ValueError('microscope_backend must be native, rosetta, or auto.')
is_synthetic = microscope_path is None
if is_synthetic:
    if microscope_options or microscope_calibration or microscope_backend != 'native':
        raise ValueError('Use default file options for the fixture, or select an external microscope_path.')
    source_path = synthetic_path
    open_options = dict(backend='native', **synthetic_calibration)
else:
    source_path = Path(microscope_path).expanduser()
    conflicts = set(microscope_options) & (set(microscope_calibration) | {'backend'})
    if conflicts:
        raise ValueError('Specify each reader/calibration option only once: ' + ', '.join(sorted(conflicts)))
    open_options = dict(backend=microscope_backend, **microscope_options, **microscope_calibration)
if not source_path.is_file():
    raise FileNotFoundError(source_path)
for name, value in (('working_memory_mb', working_memory_mb), ('max_scan_map_mb', max_scan_map_mb)):
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)) or not np.isfinite(value) or value <= 0:
        raise ValueError(name + ' must be positive and finite.')
if run_peak_detection is None:
    run_peak_detection = is_synthetic
if run_transforms is None:
    run_transforms = is_synthetic
if not isinstance(run_peak_detection, (bool, np.bool_)) or not isinstance(run_transforms, (bool, np.bool_)):
    raise ValueError('run_peak_detection and run_transforms must be booleans or None.')
input_stat = (source_path.stat().st_size, source_path.stat().st_mtime_ns)
print('Selected origin:', 'synthetic' if is_synthetic else input_origin)
print('Selected file:', source_path)
Selected origin: synthetic
Selected file: /tmp/4denoise-tutorial-07-4lex48ih/synthetic_hexagons.hdf5

3. Inspect metadata and memory implications before reading pixels

HyperData.open returns a context manager for a read-only DiffractionSource. Inspecting shape/dtype/nbytes/metadata does not materialize its diffraction tensor. There is no public source.array, and implicit NumPy conversion is rejected. HyperData(path) is still eager; these are different contracts.

nbytes describes the uncompressed numerical tensor, not compressed disk size or peak process RAM. A hypothetical 512 x 512 scan of 256 x 256 float32 patterns needs 64 GiB for pixels alone; calculating that size below does not allocate it. Returned scan maps, metadata, plotting, Python/allocator overhead, codec/HDF5/OS caches, and upstream reader workspaces can add memory outside an operation’s buffer budget. Rosetta’s declared reader chunk is reserved by supported operations, but does not cover every reader internal. For a small fixture, an automatic planner may fit the entire scan in one budgeted temporary block. The guarantee is bounded processing, not that every read is a tiny fraction of the file; no persistent eager full-source object is requested.

with HyperData.open(source_path, **open_options) as source:
    if source.ndim != 4 or min(source.shape) < 2 or source.dtype.kind not in 'iuf':
        raise ValueError('This lesson needs real numerical Cartesian 4D data with at least two samples per axis.')
    metadata = source.metadata
    if metadata.get('polar_metadata') is not None or metadata.get('cepstral_metadata') is not None:
        raise ValueError('Start this lesson with Cartesian detector data.')
    source_info = dict(shape=source.shape, dtype=str(source.dtype), nbytes=source.nbytes,
                       backend=source.backend, dataset=source.dataset_path, metadata=metadata,
                       reader_chunk_nbytes=source.reader_chunk_nbytes)
    ry, rx, ky, kx = source.shape
    if ry * rx * 8 > max_scan_map_mb * 1024**2:
        raise MemoryError('A single float64 scan map exceeds max_scan_map_mb; choose a deliberate workflow/budget.')
print('Shape:', source_info['shape'], 'dtype:', source_info['dtype'], 'backend:', source_info['backend'])
print('Dataset:', source_info['dataset'], 'Uncompressed pixels (MiB):', source_info['nbytes'] / 1024**2)
print('Declared upstream reader chunk (MiB):', source_info['reader_chunk_nbytes'] / 1024**2)
print('Real calibration:', metadata.get('real_units'), metadata.get('real_conv_factor'), metadata.get('real_origin'))
print('Reciprocal calibration:', metadata.get('reciprocal_units'), metadata.get('reciprocal_conv_factor'))
print('Hypothetical 512x512x256x256 float32 pixels (GiB):', 512 * 512 * 256 * 256 * 4 / 1024**3)
assert source.closed
input_checksum = streaming_sha256(source_path) if is_synthetic else None
Shape: (12, 16, 64, 64) dtype: uint16 backend: hdf5
Dataset: /diffraction Uncompressed pixels (MiB): 1.5
Declared upstream reader chunk (MiB): 0.0
Real calibration: nm (2.0, 3.0) (10.0, 20.0)
Reciprocal calibration: 1/angstrom 0.04
Hypothetical 512x512x256x256 float32 pixels (GiB): 64.0
if analysis_annulus_px is None:
    if not is_synthetic:
        raise ValueError('Inspect your external detector, then explicitly set analysis_annulus_px in pixels.')
    analysis_annulus_px = (12.0, 24.0)
bounds = np.asarray(analysis_annulus_px, dtype=float)
if bounds.shape != (2,) or not np.all(np.isfinite(bounds)) or not 0 <= bounds[0] < bounds[1]:
    raise ValueError('analysis_annulus_px must satisfy 0 <= inner < outer.')
beam = metadata.get('center_beam_metadata') or {}
if transform_center_px is None:
    if 'center_px' in beam:
        if tuple(beam.get('shape', (ky, kx))) != (ky, kx):
            raise ValueError('Stored beam metadata has a stale shape; verify it before processing.')
        transform_center_px = beam['center_px']
        center_source = 'current beam center_px metadata'
    else:
        transform_center_px = ((ky - 1) / 2, (kx - 1) / 2)
        center_source = 'geometric midpoint; no fitted center_px was assumed'
else:
    center_source = 'explicit pixel center'
transform_center_px = np.asarray(transform_center_px, dtype=float)
if transform_center_px.shape != (2,) or not np.all(np.isfinite(transform_center_px)):
    raise ValueError('transform_center_px must be a finite (y, x) pixel pair.')
if np.any(transform_center_px < 0) or np.any(transform_center_px > np.array([ky - 1, kx - 1])):
    raise ValueError('Choose a center inside the detector for this lesson.')
detector_y, detector_x = np.ogrid[:ky, :kx]
detector_radius = np.hypot(detector_y - transform_center_px[0], detector_x - transform_center_px[1])
detector_mask = (detector_radius >= bounds[0]) & (detector_radius <= bounds[1])
if not detector_mask.any():
    raise ValueError('The selected annular detector contains no pixels.')
if scan_mask_input is None:
    peak_scan_mask = np.ones((ry, rx), dtype=bool)
    if is_synthetic:
        peak_scan_mask[0, 0] = False
else:
    peak_scan_mask = np.asarray(scan_mask_input)
    if peak_scan_mask.shape != (ry, rx) or peak_scan_mask.dtype.kind != 'b':
        raise ValueError('scan_mask_input must be boolean with shape (Ry, Rx).')
    peak_scan_mask = peak_scan_mask.copy()
if run_peak_detection and not peak_scan_mask.any():
    raise ValueError('Choose at least one peak-extraction scan position.')
if peak_options_input is None:
    if run_peak_detection and not is_synthetic:
        raise ValueError('External peak extraction needs explicit peak_options_input.')
    peak_options = dict(radius=1.5, min_distance=5, threshold_abs=40, threshold_rel=None,
                        r_range=(12, 24), intensity_radius=3, n_fold=None, sym_mode='none') if is_synthetic else {}
else:
    peak_options = dict(peak_options_input)
    managed = {'destination', 'working_memory_mb', 'progress', 'real_mask', 'overwrite', 'atomic', 'coords_units', 'chunk_size', 'center'}
    if set(peak_options) & managed:
        raise ValueError('Keep output/budget/coverage/center options in the lesson cells, not peak_options_input.')
    if not {'radius', 'min_distance'} <= peak_options.keys() or not any(peak_options.get(key) is not None for key in ('threshold_abs', 'threshold_rel')):
        raise ValueError('Review radius, min_distance, and an explicit detection threshold.')
sample_index = (ry // 2, rx // 3)
r_max = float(min(transform_center_px[0], ky - 1 - transform_center_px[0],
                  transform_center_px[1], kx - 1 - transform_center_px[1]))
if run_transforms and r_max <= 0:
    raise ValueError('Polar conversion in this lesson needs a center strictly inside the detector.')
polar_shape = (max(2, min(32, int(np.floor(r_max)) + 1)), 180)
resized_pattern_shape = (max(1, ky // 2), max(1, kx // 2))
resized_scan_shape = (max(1, ry // 2), max(1, rx // 2))
print('Detector/polar center:', transform_center_px, 'Source:', center_source)
print('Peak extraction:', run_peak_detection, 'Disk transforms:', run_transforms)
Detector/polar center: [31.5 31.5] Source: geometric midpoint; no fitted center_px was assumed
Peak extraction: True Disk transforms: True

4. Owned views and bounded scan reductions

A single-pattern read returns an owned ReciprocalSpace object, not a live file view. Mean and standard-deviation reductions traverse the input in bounded buffers and return detector-sized arrays. The virtual image returns one complete scan-sized RealSpace map, which is intentionally retained in RAM. Exact median is not supported as a bounded source reduction.

The Boolean detector below is an explicit pixel annulus around our chosen center, including both radial boundaries. This avoids assuming that a fitted beam center equals the geometric midpoint. Display calibration does not change the mask’s pixel meaning. Each separate reduction can make another pass over disk; bounded memory does not mean zero I/O or a cached full tensor.

start = perf_counter()
with HyperData.open(source_path, **open_options) as source:
    sample_dp = source.get_dp(*sample_index, selection_units='pixels', working_memory_mb=working_memory_mb)
    mean_dp = source.get_dp(operation='mean', working_memory_mb=working_memory_mb)
    std_dp = source.get_dp(operation='std', working_memory_mb=working_memory_mb)
    virtual = source.virtual_image(mask=detector_mask, detector_units='pixels',
                                   working_memory_mb=working_memory_mb, show=False)
timings['reductions_and_virtual_image'] = perf_counter() - start
assert source.closed
try:
    source.get_dp(*sample_index)
except RuntimeError as error:
    print('Expected closed-source protection:', error)
else:
    raise AssertionError('Closed source unexpectedly allowed a read.')
if not np.all(np.isfinite(mean_dp.array)) or not np.all(np.isfinite(virtual.array)):
    raise ValueError('Nonfinite data propagated into results; choose an explicit repair/exclusion policy before interpreting them.')
mean_dp.show(title='Mean DP from disk-backed source', power=0.4 if mean_dp.array.min() >= 0 else 1,
             logScale=False, cmap='magma', figsize=(6, 5), overlay_mask=detector_mask)
virtual.show(title='Disk-backed annular virtual image', cmap='viridis', num_div=3, figsize=(7, 4))
print('Owned results remain usable after file closure; no explicit full-source load was requested.')
Expected closed-source protection: The diffraction source is closed; use it inside the with block.
Owned results remain usable after file closure; no explicit full-source load was requested.
Figure from the synthetic tutorial Figure from the synthetic tutorial

5. Iterate independent blocks without collecting them

iter_chunks yields (scan_slices, HyperData). The requested block is a maximum; working_memory_mb can reduce it. Slices refer to global scan coordinates, while a block’s real-space origin is offset appropriately. Do not write list(source.iter_chunks(…)) or retain every block in a results dictionary.

This custom example accumulates a detector-sized sum and two scan maps. Its detector integration uses einsum rather than an extra full-block floating product. The iterator budgets read/copy buffers, not arbitrary work you add inside the loop. Track your own buffers too. visited below is a small scan-sized verification array, not a diffraction tensor. A global CP/Tucker factorization or a neighborhood filter is not equivalent to independently denoising unrelated blocks; scan filters need halos, and global decompositions need a separate algorithm.

manual_virtual = np.empty((ry, rx), dtype=np.float64)
mean_signal = np.empty((ry, rx), dtype=np.float64)
visited = np.zeros((ry, rx), dtype=np.uint8)
dp_sum = np.zeros((ky, kx), dtype=np.float64)
largest_block_bytes = 0
block_count = 0
start = perf_counter()
with HyperData.open(source_path, **open_options) as source:
    spacing = np.broadcast_to(np.asarray(source.real_conv_factor if source.real_conv_factor is not None else 1.0), (2,))
    for scan_slices, block in source.iter_chunks(chunk_shape, working_memory_mb=working_memory_mb):
        largest_block_bytes = max(largest_block_bytes, block.array.nbytes)
        block_count += 1
        visited[scan_slices] += 1
        manual_virtual[scan_slices] = np.einsum('...ij,ij->...', block.array, detector_mask, dtype=np.float64)
        mean_signal[scan_slices] = block.array.mean(axis=(-2, -1), dtype=np.float64)
        dp_sum += block.array.sum(axis=(0, 1), dtype=np.float64)
        expected_origin = np.asarray(source.real_origin) + np.array([item.start for item in scan_slices]) * spacing
        np.testing.assert_allclose(block.real_origin, expected_origin)
        del block  # Do not retain processed diffraction blocks.
timings['custom_chunk_reductions'] = perf_counter() - start
np.testing.assert_array_equal(visited, 1)
np.testing.assert_allclose(manual_virtual, virtual.array, rtol=1e-12, atol=1e-8)
np.testing.assert_allclose(dp_sum / (ry * rx), mean_dp.array, rtol=1e-10, atol=1e-8)
print('Blocks:', block_count, 'Largest raw block (MiB):', largest_block_bytes / 1024**2)
print('Managed-buffer budget (MiB):', working_memory_mb, 'This is not a measured peak-RAM value.')
RealSpace(mean_signal, units=metadata.get('real_units'), conv_factor=metadata.get('real_conv_factor'),
          origin=metadata.get('real_origin', (0, 0)), quantity='Mean detector counts').show(
    title='Mean signal from scan blocks', cmap='magma', num_div=3, figsize=(7, 4))
Blocks: 16 Largest raw block (MiB): 0.09375
Managed-buffer budget (MiB): 16.0 This is not a measured peak-RAM value.
Figure from the synthetic tutorial
(<Figure size 700x400 with 2 Axes>,
 <Axes: title={'center': 'Mean signal from scan blocks'}, xlabel='x (nm)', ylabel='y (nm)'>)

6. Write peaks incrementally, not as a full ragged collection

Supplying destination to source.get_peaks writes numeric coordinate/score/intensity tables with per-scan starts/counts directly to a peak file. It returns a path, not a complete PeakScanResult. Coordinates are (y, x) pixels here. Template scores are not integrated intensities; intensity_radius requests raw circular sums, not background-corrected estimates or subpixel refinement.

The synthetic run excludes only peak extraction at (0, 0) to demonstrate processed_mask. Other reductions/transforms still process the complete scan. Both oriented synthetic regions have six spots, so a nearly uniform count map is expected even though their superimposed mean DP has more spot positions. Counts alone do not identify orientation or phase. Without destination, result memory grows with scan size and peak count. Even a peak file can become large; loading the whole collection later defeats selective access. External extraction requires both an explicit opt-in and reviewed peak_options_input. No symmetry repair is enabled by the fixture.

peak_path = None
if run_peak_detection:
    start = perf_counter()
    with HyperData.open(source_path, **open_options) as source:
        peak_path = source.get_peaks(**peak_options, center=transform_center_px,
                                     real_mask=peak_scan_mask, coords_units='pixels',
                                     destination=output_dir / 'peaks.h5', overwrite=False, atomic=True,
                                     working_memory_mb=working_memory_mb, chunk_size=4, progress=False)
    timings['incremental_peaks'] = perf_counter() - start
    written_paths['peaks'] = Path(peak_path)
    print('Peak file:', Path(peak_path).name, 'No complete peak collection materialized.')
else:
    print('Peak-file writing skipped. Review settings, then opt in explicitly for an external acquisition.')
Peak file: peaks.h5 No complete peak collection materialized.
if peak_path is not None:
    with h5py.File(peak_path, 'r') as file:
        peak_counts = file['counts'][()]  # Deliberately materialize only a scan-sized map.
        processed_mask = file['processed_mask'][()]
        start_row = int(file['starts'][sample_index])
        count = int(file['counts'][sample_index])
        selected_coords = file['coords'][start_row:start_row + count]
        selected_synthetic = file['synthetic_mask'][start_row:start_row + count]
        selected_scores = file['scores'][start_row:start_row + count]
        selected_intensities = file['intensities'][start_row:start_row + count] if 'intensities' in file else None
    np.testing.assert_array_equal(processed_mask, peak_scan_mask)
    count_image = np.where(processed_mask, peak_counts.astype(float), np.nan)
    RealSpace(count_image, units=metadata.get('real_units'), conv_factor=metadata.get('real_conv_factor'),
              origin=metadata.get('real_origin', (0, 0)), quantity='Detected peak count').show(
        title='Peak counts (gray: skipped)', cmap=plt.colormaps['cividis'].with_extremes(bad='0.75'),
        vmin=0, vmax=max(1, float(peak_counts[processed_mask].max())), num_div=3, figsize=(7, 4))
    sample_dp.show(coords=selected_coords[~selected_synthetic], title=f'Observed peaks at scan {sample_index}',
                   power=0.4 if sample_dp.array.min() >= 0 else 1, logScale=False, cmap='magma', figsize=(6, 5),
                   facecolors='none', edgecolors='lime', s=65)
    print('Selected peak rows:', count, 'Observed:', int((~selected_synthetic).sum()))
    print('Selected correlation scores:', selected_scores)
    print('Selected raw integrated intensities:', selected_intensities)
    if is_synthetic:
        assert not processed_mask[0, 0] and peak_counts[0, 0] == 0
        assert 4 <= len(selected_coords) <= 8
Figure from the synthetic tutorial Figure from the synthetic tutorial
Selected peak rows: 6 Observed: 6
Selected correlation scores: [168.         167.57142857 147.85714286 144.42857143 125.35714286
 119.35714286]
Selected raw integrated intensities: [420. 427. 380. 390. 366. 333.]

7. Plan disk outputs before enabling full transforms

A small processing block does not make the output file small. The enabled transform sequence writes detector-resized, scan-resized, polar, and reconstructed Cartesian datasets. The estimates below assume float64 pixels as a conservative planning aid for these real inputs; they exclude metadata, temporary siblings, filesystem overhead, compression workspaces, peak tables, and any old outputs. Compression is not a guaranteed reduction. This is not a disk quota or a RAM measurement.

Atomic publication uses a temporary sibling and publishes each completed file separately. Replacement requires overwrite=True, which this lesson never sets. A complete multi-step pipeline is not one transaction: earlier successful outputs remain if a later stage fails. Use fresh destinations and enough disk space; avoid accidentally creating several acquisition-sized copies. External runs leave transforms disabled until you opt in.

estimated_output_bytes = {
    'detector_resized': ry * rx * int(np.prod(resized_pattern_shape)) * 8,
    'scan_resized': int(np.prod(resized_scan_shape)) * ky * kx * 8,
    'polar': ry * rx * int(np.prod(polar_shape)) * 8,
    'cartesian': ry * rx * ky * kx * 8,
}
for name, size in estimated_output_bytes.items():
    print(f'{name}: planned pixel allowance {size / 1024**2:.3f} MiB')
free_bytes = shutil.disk_usage(output_dir).free
print('Free space on output volume (GiB):', free_bytes / 1024**3)
print('Transforms enabled:', run_transforms)
if run_transforms and sum(estimated_output_bytes.values()) * 2 > free_bytes:
    raise OSError('Insufficient planning margin for these outputs and temporary siblings. Select another volume/workflow.')
detector_resized: planned pixel allowance 1.500 MiB
scan_resized: planned pixel allowance 1.500 MiB
polar: planned pixel allowance 8.438 MiB
cartesian: planned pixel allowance 6.000 MiB
Free space on output volume (GiB): 83.80264282226562
Transforms enabled: True

8. Resize globally into new files

source.resize writes a new saved HyperData without holding the full output tensor. It handles global area-bin boundaries instead of independently resizing arbitrary blocks, avoiding seam artifacts when sizes are not divisors. Scan and detector calibration are updated according to the changed pixel spacing. A scan pixel’s origin moves to the center of the new bin: grouping 2 x 2 scan pixels shifts the first output center by half an original pixel in each direction, while preserving the field’s pixel-edge extent. Area downsampling averages intensities; it does not preserve total counts as a sum over larger bins. Decide which convention your analysis needs.

We inspect one detector-resized pattern and compare it with the same operation on one owned in-memory pattern. The scan-resized file is inspected by metadata and a single read. Neither check materializes a full diffraction dataset.

single_pattern = HyperData(sample_dp.array[None], reciprocal_units=sample_dp.units,
                           reciprocal_conv_factor=sample_dp.conv_factor,
                           center_beam_metadata=sample_dp.center_beam_metadata)
if run_transforms:
    start = perf_counter()
    with HyperData.open(source_path, **open_options) as source:
        detector_resized_path = source.resize(resized_pattern_shape, domain='reciprocal', method='area',
                                              destination=output_dir / 'detector_resized.4denoise',
                                              working_memory_mb=working_memory_mb, progress=False)
        scan_resized_path = source.resize(resized_scan_shape, domain='real', method='area',
                                          destination=output_dir / 'scan_resized.4denoise',
                                          working_memory_mb=working_memory_mb, progress=False)
    timings['disk_resize_pair'] = perf_counter() - start
    written_paths.update(detector_resized=Path(detector_resized_path), scan_resized=Path(scan_resized_path))
    with HyperData.open(detector_resized_path) as source:
        assert source.shape == (ry, rx, *resized_pattern_shape)
        resized_dp = source.get_dp(*sample_index, working_memory_mb=working_memory_mb)
        np.testing.assert_allclose(resized_dp.array, single_pattern.resize(resized_pattern_shape, domain='reciprocal').array[0],
                                   rtol=1e-6, atol=1e-6)
        print('Detector resize calibration:', source.reciprocal_units, source.reciprocal_conv_factor)
    with HyperData.open(scan_resized_path) as source:
        assert source.shape == (*resized_scan_shape, ky, kx)
        print('Resized scan shape/spacing/origin:', source.scan_shape, source.real_conv_factor, source.real_origin)
        original_spacing = np.broadcast_to(np.asarray(metadata.get('real_conv_factor') if metadata.get('real_conv_factor') is not None else 1.0), (2,))
        resize_factors = np.array([ry, rx]) / np.array(resized_scan_shape)
        expected_origin = np.asarray(metadata.get('real_origin', (0, 0))) + 0.5 * (resize_factors - 1) * original_spacing
        np.testing.assert_allclose(source.real_origin, expected_origin)
    print('Both resize outputs remain on disk.')
Detector resize calibration: 1/angstrom 0.08
Resized scan shape/spacing/origin: (6, 8) (4.0, 6.0) (11.0, 21.5)
Both resize outputs remain on disk.

9. Transform to polar and back, directly on disk

The explicit center and r_max are Cartesian detector pixels. r_max is the largest inscribed radius around that chosen center, not necessarily half the detector width. to_polar itself does not automatically find a beam center; our settings cell selected it explicitly. The polar file carries radial/angular sampling metadata and unchanged scan calibration. The source’s Cartesian detector labels are not blindly attached to polar axes.

Reconstruction uses output_shape=’original’ to recover the original canvas shape, not original intensities. Resampling is lossy, and excluded corners cannot be recovered. We compare a single streamed polar pattern with the eager transform of that same single pattern, then show the Cartesian difference. Equality between implementations is not proof of an invertible physical transform. The polar plot uses aspect=’auto’: angular degrees and reciprocal radial units are not lengths on the same physical axis, so forcing an equal axis aspect would squash the plot.

if run_transforms:
    start = perf_counter()
    with HyperData.open(source_path, **open_options) as source:
        polar_path = source.to_polar(center=transform_center_px, r_max=r_max, output_shape=polar_shape,
                                     destination=output_dir / 'polar.4denoise',
                                     working_memory_mb=working_memory_mb, chunk_shape=(2, 3), progress=False)
    with HyperData.open(polar_path) as source:
        assert source.shape == (ry, rx, *polar_shape)
        assert source.metadata.get('polar_metadata') is not None
        polar_dp = source.get_dp(*sample_index, working_memory_mb=working_memory_mb)
        cartesian_path = source.to_cartesian(output_shape='original',
                                             destination=output_dir / 'cartesian.4denoise',
                                             working_memory_mb=working_memory_mb, progress=False)
    with HyperData.open(cartesian_path) as source:
        assert source.shape == (ry, rx, ky, kx)
        assert source.metadata.get('polar_metadata') is None
        cartesian_dp = source.get_dp(*sample_index, working_memory_mb=working_memory_mb)
        np.testing.assert_allclose(source.real_origin, metadata.get('real_origin', (0, 0)))
        assert source.real_units == metadata.get('real_units')
    timings['disk_polar_and_cartesian'] = perf_counter() - start
    written_paths.update(polar=Path(polar_path), cartesian=Path(cartesian_path))
    reference_polar = single_pattern.to_polar(center=transform_center_px, r_max=r_max,
                                               output_shape=polar_shape, progress=False)
    np.testing.assert_allclose(polar_dp.array, reference_polar.array[0], rtol=1e-6, atol=1e-6)
    polar_dp.show(title='Saved polar DP: radial and angular axes', power=0.4 if polar_dp.array.min() >= 0 else 1,
                  logScale=False, cmap='magma', figsize=(9, 4), aspect='auto')
    difference = cartesian_dp.array.astype(float) - sample_dp.array
    limit = max(float(np.percentile(np.abs(difference), 99)), 1e-6)
    fig, axes = plt.subplots(1, 3, figsize=(13, 4), constrained_layout=True)
    display_min = min(float(sample_dp.array.min()), float(cartesian_dp.array.min()))
    display_max = max(float(sample_dp.array.max()), float(cartesian_dp.array.max()))
    for ax, values, title in zip(axes[:2], (sample_dp.array, cartesian_dp.array), ('Original sample DP', 'Polar -> Cartesian sample DP')):
        im = ax.imshow(values, cmap='magma', vmin=display_min, vmax=display_max)
        ax.set(title=title, xlabel='kx pixel', ylabel='ky pixel')
        fig.colorbar(im, ax=ax, shrink=0.75, label='Intensity')
    im = axes[2].imshow(difference, cmap='RdBu_r', vmin=-limit, vmax=limit)
    axes[2].set(title='Reconstructed minus original', xlabel='kx pixel', ylabel='ky pixel')
    fig.colorbar(im, ax=axes[2], shrink=0.75, label='Intensity difference')
    plt.show()
    print('Full polar/Cartesian outputs stayed on disk; only single-pattern comparisons entered RAM.')
Figure from the synthetic tutorial Figure from the synthetic tutorial
Full polar/Cartesian outputs stayed on disk; only single-pattern comparisons entered RAM.

10. Protect existing outputs and distinguish budgets

The next synthetic-only check deliberately repeats a destination and confirms refusal without replacing the earlier result. It also verifies the complete small generated input by a streaming file hash; external multi-GB files are not reread merely for this demonstration. The source APIs are read-only, and every output path is distinct. File size/mtime checks alone are not a content checksum.

For a deliberate full load on a machine with enough RAM, the explicit API would be source.load(max_memory_mb=…, working_memory_mb=…). The first cap guards the full numerical allocation; the second budgets temporary reading buffers. Neither is a process-memory limit. This notebook never makes that full load. Similarly, PeakScanResult.load(path, max_memory_mb=…) loads the whole peak collection, not just the selected peak rows shown here.

An optional fixed-background operation is available as source.remove_bg(background, destination=…, a_min=None, …). It needs an independently justified detector-sized background; do not treat the mean DP, a constant, or each block’s mean as a universally correct background. Global tensor denoising and unrelated local blocks require separate planning.

if is_synthetic and run_transforms:
    existing_digest = streaming_sha256(detector_resized_path)
    with HyperData.open(source_path, **open_options) as source:
        try:
            source.resize(resized_pattern_shape, domain='reciprocal',
                          destination=detector_resized_path, working_memory_mb=working_memory_mb, progress=False)
        except FileExistsError:
            print('Expected: an existing output was not overwritten.')
        else:
            raise AssertionError('An existing destination was unexpectedly replaced.')
        assert not source.closed
    assert streaming_sha256(detector_resized_path) == existing_digest
if is_synthetic:
    assert streaming_sha256(source_path) == input_checksum
assert (source_path.stat().st_size, source_path.stat().st_mtime_ns) == input_stat
print('Input file size/mtime unchanged; all earlier source contexts are closed.')
Expected: an existing output was not overwritten.
Input file size/mtime unchanged; all earlier source contexts are closed.

11. Keep settings with results and inspect actual file sizes

The compact NPZ stores scan maps and the mean/std diffraction patterns, not all diffraction pixels. The JSON manifest records input path, selected dataset/backend, geometry, budgets, detector mask definition, enabled operations, and timings. Keep the original acquisition/calibration provenance separately; a source path and user-declared origin are not full scientific provenance. Native transform outputs retain the metadata supported by each geometry-changing operation, and the separate peak file records its own detector/source metadata.

The file sizes below are actual compressed disk sizes for this run, not numerical working memory. Several scan maps and detector arrays remain in RAM by design. Caches and the notebook’s displayed figures also consume memory; closing a source does not free results you intentionally retain, nor guarantee that the OS immediately releases cached pages.

manifest = {
    'data_origin': 'synthetic' if is_synthetic else input_origin, 'input_path': str(source_path.resolve()),
    'backend': source_info['backend'], 'dataset': source_info['dataset'], 'shape': list(source_info['shape']),
    'dtype': source_info['dtype'], 'uncompressed_input_bytes': source_info['nbytes'],
    'reader_chunk_nbytes': source_info['reader_chunk_nbytes'], 'working_memory_mb': working_memory_mb,
    'max_scan_map_mb': max_scan_map_mb, 'largest_observed_raw_block_bytes': largest_block_bytes,
    'real_units': metadata.get('real_units'), 'real_spacing': metadata.get('real_conv_factor'),
    'real_origin': metadata.get('real_origin', (0, 0)),
    'reciprocal_units': metadata.get('reciprocal_units'), 'reciprocal_spacing': metadata.get('reciprocal_conv_factor'),
    'annulus_pixels_inclusive': bounds.tolist(), 'center_px': transform_center_px.tolist(), 'center_source': center_source,
    'peak_extraction_enabled': bool(run_peak_detection), 'peak_parameters': peak_options,
    'peak_scan_mask_false_count': int((~peak_scan_mask).sum()), 'transforms_enabled': bool(run_transforms),
    'polar_shape': list(polar_shape), 'polar_r_max_pixels': r_max,
    'elapsed_seconds': timings, 'outputs': {name: str(path) for name, path in written_paths.items()},
}
(output_dir / 'manifest.json').write_text(json.dumps(manifest, indent=2, default=json_numeric), encoding='utf-8')
np.savez_compressed(output_dir / 'compact_maps.npz', virtual_image=virtual.array, mean_signal=mean_signal,
                    mean_dp=mean_dp.array, std_dp=std_dp.array)
for name, seconds in timings.items():
    print(f'{name}: {seconds:.3f} s')
for name, path in written_paths.items():
    print(f'{name}: actual file {path.stat().st_size / 1024**2:.3f} MiB')
with np.load(output_dir / 'compact_maps.npz', allow_pickle=False) as saved:
    np.testing.assert_array_equal(saved['virtual_image'], virtual.array)
print('Compact exports verified. All output paths are owned temporary files.')
reductions_and_virtual_image: 0.009 s
custom_chunk_reductions: 0.009 s
incremental_peaks: 0.487 s
disk_resize_pair: 0.031 s
disk_polar_and_cartesian: 0.198 s
peaks: actual file 0.062 MiB
detector_resized: actual file 0.227 MiB
scan_resized: actual file 0.239 MiB
polar: actual file 3.725 MiB
cartesian: actual file 2.113 MiB
Compact exports verified. All output paths are owned temporary files.

What to take to an original acquisition

  • Start with a verified file reader, dataset selection, axis order, and calibration. Native or Rosetta loading alone is not scientific validation.

  • Inspect metadata and size before choosing operations. File-based reads, working-buffer budgets, retained results, and actual process RAM are different quantities.

  • Use bounded reductions and explicit block iteration; do not collect blocks. Validate custom algorithms across block boundaries and budget their own temporaries.

  • Write large peak collections/transforms directly to distinct files, read selected peak-table rows, and retain processed masks. No peak count is automatically a crystalline fraction.

  • Reopen saved transforms to continue processing. Polar reconstruction is lossy even when the original canvas is restored. Do not independently chunk a global denoiser and call it equivalent.

  • Plan disk use, preserve settings/provenance, keep atomic defaults, and choose persistent outputs deliberately. External peak/transform stages require explicit opt-in here.

This completes the seven-notebook foundation. See using your own data, I/O and calibration, and the included experimental streaming example. Default CI validates this small generated workflow, not a true large-acquisition RAM benchmark or original vendor acquisition. The final cell removes only owned temporary files.

assert (source_path.stat().st_size, source_path.stat().st_mtime_ns) == input_stat
plt.close('all')
temporary_output.cleanup()
print('Finished. Disk resources closed; only owned temporary outputs removed.')
Finished. Disk resources closed; only owned temporary outputs removed.