Tutorial 4: Denoising and Unfolding

An independently runnable lesson with noisy synthetic hexagonal diffraction patterns. Core 4Denoise and an IPython/Jupyter kernel suffice. The optional BM4D section needs the bm extra. No microscope data, earlier notebook output, or simulation package is required.

We compare per-pattern filtering with 3D unfolded-volume filtering, inspect traversal order and cropped-out positions, time individual calls, and plot a TensorLy convergence history. Expensive rank sweeps and BM4D are disabled by default.

Replaceable input: the configuration in section 3 accepts a file, an existing HyperData, or a numerical experimental/simulation array. All subsequent denoising uses that selected input. Synthetic reference-error checks run only for the default teaching data or an explicitly supplied reference. The model is not an electron-scattering simulation or evidence for a universally best denoiser.

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

Select the environment containing your current 4Denoise installation, restart the kernel, and run all cells. Only temporary tutorial output is saved; no source acquisition is overwritten. perf_counter_ns() provides a high-resolution monotonic timer expressed in nanoseconds, not a promise of nanosecond measurement accuracy.

%matplotlib inline
from pathlib import Path
from time import perf_counter_ns, get_clock_info
import sys
import tempfile

import matplotlib.pyplot as plt
import numpy as np
import fourdenoise
from fourdenoise import HyperData, plot_traversals

print('Python:', sys.executable)
print('4Denoise:', fourdenoise.__file__)
print('Timer resolution (seconds):', get_clock_info('perf_counter').resolution)
workspace = tempfile.TemporaryDirectory(prefix='4denoise-tutorial-04-')
work_dir = Path(workspace.name)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py
Timer resolution (seconds): 1e-09

At a glance: all available traversal paths

plot_traversals(method=’all’, …) is the built-in gallery of implemented traversal methods. The three-column overview below colors each path from start to finish and marks its endpoints. Change traversal_grid_shape, cmap, or linewidth to customize it.

The grid shape is a maximum preview size. Full-shape paths use every cell; compatible curves/meanders can use a smaller centered region. Panel titles report both used and maximum shapes, and gray areas are excluded. This illustrative 16-by-16 grid does not set the dataset shape or process any data; later examples use the selected dataset’s geometry. Aliases are not repeated, and the unimplemented Moore placeholder is not shown.

traversal_grid_shape = (16, 16)
gallery_fig, gallery_axes = plot_traversals(
    method='all', grid_shape=traversal_grid_shape, ncols=3,
    cmap='viridis', linewidth=1.4, show_grid=True, mark_endpoints=True, show=False,
)
gallery_fig.set_size_inches(11, 13)
plt.show()
Figure from the synthetic tutorial

2. Build a small clean reference and noisy observation

The default (10, 12, 48, 48) float32 array follows (Ry, Rx, Ky, Kx). The two scan halves contain regular hexagons separated by a 30-degree clockwise rotation in detector-array coordinates. Smoothly varying spot amplitude, a bright central Gaussian, and a constant background complete the model. There is an intentional sharp boundary between orientations: averaging across it can mix distinct patterns.

The reference contains expected intensities; the observation is a Poisson draw with seed 2028. The invented calibration is 2 and 3 nm per scan row/column and 0.25 mrad per detector pixel. This convenient low-complexity teaching model can favor tensor decompositions and must not be treated as a benchmark for real acquisitions. The synthetic construction always remains separate from external input.

rng = np.random.default_rng(2028)
Ry, Rx, Ky, Kx = 10, 12, 48, 48
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
orientation = np.where(scan_x < Rx // 2, 0.0, np.pi / 6)
envelope = 0.8 + 0.3 * np.exp(-2 * (sy**2 + sx**2))
base = 0.4 + 80 * np.exp(-((yy - cy)**2 + (xx - cx)**2) / (2 * 2.5**2))
clean_array = np.broadcast_to(base, (Ry, Rx, Ky, Kx)).copy()
spot_radius_px = 14.0
for angle in np.arange(6) * np.pi / 3:
    spot_y = cy + spot_radius_px * np.sin(angle + orientation)
    spot_x = cx + spot_radius_px * np.cos(angle + orientation)
    clean_array += (22 * envelope)[..., None, None] * np.exp(
        -((yy - spot_y[..., None, None])**2 + (xx - spot_x[..., None, None])**2) / (2 * 1.5**2)
    )
clean_array = clean_array.astype(np.float32)
synthetic_array = rng.poisson(clean_array).astype(np.float32)
synthetic_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': 2028,
                          'description': 'Poisson-noisy Gaussian spots in two hexagonal regions'},
)
print('Teaching fixture:', synthetic_data.shape, synthetic_data.array.dtype)
Teaching fixture: (10, 12, 48, 48) float32

3. Select synthetic, experimental, or simulation input here

Only this configuration needs changing to select a different dataset. Leave input_data=None and microscope_path=None for the default synthetic workflow. Otherwise supply exactly one of:

  • input_data: an existing HyperData object or a numerical 4D array, including a converted simulation result. HyperData is copied with its own metadata. A bare array gets only the calibration you explicitly supply. Convert simulator-specific objects first; no axes or physical units are guessed.

  • microscope_path: a native NumPy/HDF5/MAT/raw/saved-HyperData path with appropriate options, or an optional Rosetta reader. This variable can also name a saved simulation file. input_origin is only your descriptive label, not verified provenance.

Native loading and in-memory copying are eager. The 64-MiB input-size check below only prevents accidentally running this in-memory tutorial on a huge selected array; it is not a limit on total process RAM or on an eager file load. Use a chosen representative ROI or a read-only source for large acquisitions. The optional Rosetta full load has an explicit 64-MiB output cap.

Do not copy synthetic calibration onto real data. Leave overrides empty for an existing HyperData object; calibrate it separately first. If you have a clean simulation/reference, supply reference_input only after verifying the same grid, orientation, calibration, and intensity scale. Shape checks cannot establish scientific registration. Without it, reference errors are intentionally omitted.

The example parameters below are teaching starting points, not automatic tuning for a new acquisition. Inspect noise scale, saturation, beam motion, and spot widths before choosing parameters. Synthetic Poisson noise is not the Gaussian noise model assumed by BM4D.

input_data = None  # Existing HyperData or a numerical (Ry, Rx, Ky, Kx) array.
input_origin = 'experimental'  # Or 'simulation'; used only when supplying an external input.
microscope_path = None  # Also accepts a saved simulation file.
microscope_backend = 'native'  # Or 'rosetta' with the optional reader extra.
microscope_options = {}  # e.g. {'hdf5_dataset': '/entry/data'}.
microscope_calibration = {}  # Verified metadata only; no synthetic defaults.
reference_input = None  # Optional registered clean HyperData/array; never inferred for external data.
max_tutorial_input_mb = 64
comparison_annulus_px = None  # None uses the total detector; otherwise choose your own (r_min, r_max).
run_tensorly_demo = None  # None: run for synthetic data only; True explicitly opts in for other inputs.
run_rank_sweep = False
run_bm4d = False
bm4d_sigma_psd = None  # Required in the input intensity units if opting into BM4D.

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.')
is_synthetic = input_data is None and microscope_path is None
if input_data is not None:
    if microscope_options:
        raise ValueError('Loader options apply to file inputs, not input_data.')
    candidate_array = input_data.array if isinstance(input_data, HyperData) else np.asarray(input_data)
    if candidate_array.nbytes > max_tutorial_input_mb * 1024**2:
        raise MemoryError('Select a representative ROI before making an in-memory tutorial copy.')
    if isinstance(input_data, HyperData):
        if microscope_calibration:
            raise ValueError('Calibrate your HyperData before passing it as input_data.')
        data = input_data.copy()
    else:
        data = HyperData(np.array(input_data, copy=True), **microscope_calibration)
elif microscope_path is None:
    data = synthetic_data.copy()
elif microscope_backend == 'native':
    data = HyperData(Path(microscope_path), **microscope_options, **microscope_calibration)
elif microscope_backend == 'rosetta':
    with HyperData.open(Path(microscope_path), backend='rosetta',
                        **microscope_options, **microscope_calibration) as source:
        data = source.load(max_memory_mb=max_tutorial_input_mb, working_memory_mb=16)
else:
    raise ValueError('microscope_backend must be native or rosetta.')
if data.ndim != 4 or data.is_polar or data.is_cepstral:
    raise ValueError('This lesson requires a Cartesian 4D scan. Fold a known 3D scan grid first.')
if data.array.nbytes > max_tutorial_input_mb * 1024**2:
    raise MemoryError('Select a representative ROI or deliberately raise the tutorial input-size guard.')
if min(data.shape) < 2 or data.array.dtype.kind not in 'iuf' or not np.all(np.isfinite(data.array)):
    raise ValueError('Use a finite real numeric 4D array with at least two samples per axis.')
if reference_input is not None:
    reference_array = np.asarray(reference_input.array if isinstance(reference_input, HyperData)
                                 else reference_input)
elif is_synthetic:
    reference_array = clean_array
else:
    reference_array = None
if reference_array is not None:
    if reference_array.shape != data.shape or reference_array.dtype.kind not in 'iuf':
        raise ValueError('The reference must be a real numerical array matching the selected input shape.')
    if not np.all(np.isfinite(reference_array)):
        raise ValueError('The reference must contain only finite values.')
if run_tensorly_demo is None:
    run_tensorly_demo = is_synthetic
print('Selected origin:', 'synthetic' if is_synthetic else input_origin)
print('Reference errors available:', reference_array is not None)
print(data.metadata_summary())
Selected origin: synthetic
Reference errors available: True
Current data shape: (10, 12, 48, 48)
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

4. Understand the axes before filtering

For a 4D scan, domain=’reciprocal’ selects the detector axes; domain=’real’ selects the scan axes. For a 3D array, methods act on that array directly. Setting unfold_domain on 4D data instead unfolds, processes the resulting whole lower-dimensional tensor, and folds it back automatically.

  • Real unfolding: (Ry*Rx, Ky, Kx), a stack of diffraction patterns.

  • Reciprocal unfolding: (Ky*Kx, Ry, Rx), a stack of scan images.

  • Both, row-major: (RyRx, KyKx), a 2D matrix, not a 3D volume.

The first filter axis of a 3D unfolded tensor follows traversal order. A (3, 1, 1) median mixes adjacent entries of that traversal without smoothing the other two axes. (3, 3, 3) additionally smooths those image axes. These widths count samples, not calibrated physical distances. A 1D traversal cannot preserve every neighbor relationship of the original 2D grid.

ry, rx, ky, kx = data.shape
expected_shapes = {'real': (ry * rx, ky, kx), 'reciprocal': (ky * kx, ry, rx),
                   'both': (ry * rx, ky * kx)}
for selected_domain in ('real', 'reciprocal', 'both'):
    traversal = 'row_major' if selected_domain == 'both' else 'serpentine'
    unfolded = data.unfold(domain=selected_domain, method=traversal)
    assert unfolded.shape == expected_shapes[selected_domain]
    restored = unfolded.unfold(undo=True)
    np.testing.assert_array_equal(restored.array, data.array)
    print(selected_domain + ':', data.shape, '->', unfolded.shape, '->', restored.shape)
unfolded = restored = None
print(data.denoise_info('median', print_info=False))
real: (10, 12, 48, 48) -> (120, 48, 48) -> (10, 12, 48, 48)
reciprocal: (10, 12, 48, 48) -> (2304, 10, 12) -> (10, 12, 48, 48)
both: (10, 12, 48, 48) -> (120, 2304) -> (10, 12, 48, 48)
{'method': 'median', 'full_signature': "median(target_data, window_size=5, mode='reflect', cval=0.0, origin=0, axes=None)", 'method_kwargs_signature': "median(window_size=5, mode='reflect', cval=0.0, origin=0, axes=None)", 'example_call': "my_dataset.denoise(method='median', window_size=5, mode='reflect', cval=0.0, origin=0, axes=None)", 'injected_data_parameter': 'target_data', 'required_parameters': [], 'optional_parameters': [{'name': 'window_size', 'kind': 'positional or keyword', 'required': False, 'default': 5, 'has_default': True, 'annotation': None}, {'name': 'mode', 'kind': 'positional or keyword', 'required': False, 'default': 'reflect', 'has_default': True, 'annotation': None}, {'name': 'cval', 'kind': 'positional or keyword', 'required': False, 'default': 0.0, 'has_default': True, 'annotation': None}, {'name': 'origin', 'kind': 'positional or keyword', 'required': False, 'default': 0, 'has_default': True, 'annotation': None}, {'name': 'axes', 'kind': 'positional or keyword', 'required': False, 'default': None, 'has_default': True, 'annotation': None}], 'parameters': [{'name': 'window_size', 'kind': 'positional or keyword', 'required': False, 'default': 5, 'has_default': True, 'annotation': None}, {'name': 'mode', 'kind': 'positional or keyword', 'required': False, 'default': 'reflect', 'has_default': True, 'annotation': None}, {'name': 'cval', 'kind': 'positional or keyword', 'required': False, 'default': 0.0, 'has_default': True, 'annotation': None}, {'name': 'origin', 'kind': 'positional or keyword', 'required': False, 'default': 0, 'has_default': True, 'annotation': None}, {'name': 'axes', 'kind': 'positional or keyword', 'required': False, 'default': None, 'has_default': True, 'annotation': None}], 'doc_summary': 'Apply an axis-aware median filter to an image or volume.', 'family': 'image filter', 'supported_input_ndim': (2, 3, 4), 'input_layout': 'image or tensor with selected axes', 'constraints': 'axes=None filters every axis, including a 3D stack axis. HyperData selects real or reciprocal axis pairs for 4D domain routing.', 'four_dimensional_routes': ("domain='real' or 'reciprocal': filter the selected axis pair", "unfold_domain='both': filter the resulting 2D matrix"), 'default_output': 'shape-preserving HyperData reconstruction; ndarray with return_array=True', 'optional_result_flags': (), 'output_caveat': '', 'docstring': "Apply an axis-aware median filter to an image or volume.\n\nThe median filter replaces each pixel value with the median value of its neighborhood,\neffectively removing salt-and-pepper noise while preserving edges.\n\nParameters\n----------\ntarget_data : ndarray\n    Image or volume to be denoised.\nwindow_size : int or tuple of int, optional\n    Window width for every filtered axis, or one width per axis.\nmode : str, optional\n    Boundary-extension mode passed to ``scipy.ndimage.median_filter``.\ncval : scalar, optional\n    Constant fill value used when ``mode='constant'``.\norigin : int or sequence, optional\n    Placement of the filter relative to each filtered pixel.\naxes : tuple of int or None, optional\n    Axes over which to apply the median. ``None`` filters every axis,\n    including the stack axis of unfolded 3D data. For 4D data,\n    ``HyperData.denoise`` supplies the selected real- or\n    reciprocal-space axes unless ``domain=None`` is requested.\n\nReturns\n-------\nndarray\n    Filtered data with the input shape and dtype.\n\nNotes\n-----\nThe median filter is particularly effective for removing salt-and-pepper noise.\nIt may be less effective for Gaussian noise."}

These previews use a bounded maximum grid so they remain readable on a large scan. Each panel title reports the actual compatible grid. A cropped Hilbert preview may visit a smaller centered square. A preview with reduced grid_shape is not the exact traversal used on a differently sized dataset. Full-shape row-major and serpentine paths retain all positions; row-major has long jumps between rows. Serpentine avoids those row-boundary jumps, but still cannot keep all 2D neighbors adjacent.

preview_shape = (min(ry, 16), min(rx, 16))
for method in ('row_major', 'serpentine', 'hilbert'):
    plot_traversals(method=method, grid_shape=preview_shape, cmap='viridis',
                    linewidth=1.8, show_grid=True, mark_endpoints=True)
Figure from the synthetic tutorial Figure from the synthetic tutorial Figure from the synthetic tutorial

5. Retain small diagnostics, not every full result

Each method below calls data.denoise() explicitly. We clear and overwrite denoised between runs. This diagnostic helper stores only one copied diffraction pattern, one small virtual image, and scalar metrics per method; it does not wrap or hide denoising. Copying the selected 2D pattern avoids retaining its parent 4D tensor through a NumPy view.

Timing brackets the denoise call only, including internal unfolding/refolding and any requested convergence plotting, not later diagnostics. Small single-run timings are not rigorous compute-only performance benchmarks. RMSE compares against an available clean reference in its intensity units. NRMSE divides that by the reference RMS. Without a registered clean reference, both are reported as unavailable, not estimated from the noisy input.

The default virtual image sums the full detector. Set comparison_annulus_px for a deliberately chosen detector instead; annuli use the geometric detector midpoint. No synthetic radius is assigned to external data. Median and TV filtering need not conserve integrated intensity or peak widths.

sample_y, sample_x = ry // 2, rx // 4
original_probe = data.array.ravel()[::max(1, data.array.size // 256)].copy()
records, dp_samples, virtual_images = [], {}, {}
detector_kwargs = ({'mask': np.ones((ky, kx), dtype=bool)} if comparison_annulus_px is None
                   else {'annulus': comparison_annulus_px, 'detector_units': 'pixels'})

def record_result(label, result, elapsed_ns=0, processed_mask=None):
    assert isinstance(result, HyperData) and result.shape == data.shape
    for attr in ('real_units', 'reciprocal_units'):
        assert getattr(result, attr) == getattr(data, attr)
    for attr in ('real_conv_factor', 'real_origin', 'reciprocal_conv_factor'):
        expected, actual = getattr(data, attr), getattr(result, attr)
        if expected is None:
            assert actual is None
        else:
            np.testing.assert_allclose(actual, expected)
    coverage = 1.0 if processed_mask is None else float(processed_mask.mean())
    rmse = nrmse = processed_rmse = np.nan
    if reference_array is not None:
        difference = result.array.astype(np.float64) - reference_array
        rmse = float(np.sqrt(np.mean(difference**2)))
        reference_rms = float(np.sqrt(np.mean(np.asarray(reference_array, dtype=np.float64)**2)))
        nrmse = rmse / reference_rms if reference_rms > 0 else np.nan
        if processed_mask is not None:
            processed_rmse = float(np.sqrt(np.mean(difference[processed_mask]**2)))
    records.append({'label': label, 'seconds': elapsed_ns / 1e9, 'rmse': rmse,
                    'nrmse': nrmse, 'processed_fraction': coverage, 'processed_rmse': processed_rmse})
    dp_samples[label] = result.get_dp(sample_y, sample_x, selection_units='pixels').array.copy()
    virtual_images[label] = result.virtual_image(**detector_kwargs, show=False)

record_result('Noisy input', data)
preview_dp = data.get_dp(sample_y, sample_x, selection_units='pixels')
preview_power = 1.0 if np.any(preview_dp.array < 0) else 0.4
preview_dp.show(
    title='Selected input: one diffraction pattern', axis_units='auto',
    power=preview_power, logScale=False, cmap='magma', figsize=(5.5, 4.5),
)
preview_dp = None
Figure from the synthetic tutorial

6. Filter individual diffraction patterns

This (3, 3) median applies to (Ky, Kx) only, never mixing scan positions. The equivalent whole-array call is domain=None, window_size=(1, 1, 3, 3). We check that equivalence here. For other 4D filtering, a four-entry window can specify each axis, but widths larger than one in scan axes will mix scan positions.

Filtering can suppress real narrow spots as well as noise. The median is especially appropriate for impulse noise; this Poisson example is a comparison, not a claim that a median is optimal for counting statistics.

denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='median', domain='reciprocal', window_size=(3, 3))
end_time = perf_counter_ns()
record_result('Median DP', denoised, end_time - start_time)
direct_4d = data.denoise(method='median', domain=None, window_size=(1, 1, 3, 3))
np.testing.assert_array_equal(direct_4d.array, denoised.array)
direct_4d = None

7. Mix neighboring patterns along a traversal

Both calls below use a (3, 1, 1) median on the full real-unfolded 3D stack. The first window width follows scan traversal, not ky. The only change between calls is row-major versus serpentine order. Results are automatically folded into the selected input’s original 4D shape with its calibration.

A traversal can mix distinct structures at a scan boundary. Serpentine makes consecutive entries physically adjacent, but a 3-entry window still crosses the deliberately introduced orientation boundary. Unfolding is a numerical representation, not proof of physical similarity.

denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='median', unfold_domain='real',
                        unfold_method='row_major', window_size=(3, 1, 1))
end_time = perf_counter_ns()
record_result('Median real: row-major', denoised, end_time - start_time)
denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='median', unfold_domain='real',
                        unfold_method='serpentine', window_size=(3, 1, 1))
end_time = perf_counter_ns()
record_result('Median real: serpentine', denoised, end_time - start_time)

8. Unfold the other domain

With unfold_domain=’reciprocal’, the 3D tensor is (Ky*Kx, Ry, Rx). Its first axis now follows detector positions. A (3, 1, 1) median mixes neighboring detector pixels along that path, not neighboring scan locations. A (3, 3, 3) window would also smooth the two scan-image axes. Do not carry a window specification across domains without reinterpreting it.

denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='median', unfold_domain='reciprocal',
                        unfold_method='serpentine', window_size=(3, 1, 1))
end_time = perf_counter_ns()
record_result('Median reciprocal: serpentine', denoised, end_time - start_time)

9. Apply volume methods to an unfolded tensor

Total variation (TV) and anisotropic diffusion process all three tensor axes here. TV weight and diffusion kappa are intensity-scale dependent; they are not automatically normalized for a new acquisition. These methods treat tensor axes as sample axes, not physically equivalent nm/mrad coordinates. gamma controls diffusion step size; niter and max_num_iter control iteration limits.

The current wrappers do not return an iteration-error history for TV or diffusion, so convergence_plot=True is not available for them. Do not confuse their iteration limit with a measured convergence curve. The diffusion implementation has no-flux boundaries and should retain total intensity to numerical precision; median, TV, and low-rank fitting have different behavior.

denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='total_variation', unfold_domain='real',
                        unfold_method='serpentine', weight=1.0, max_num_iter=30, eps=1e-4)
end_time = perf_counter_ns()
record_result('TV real: serpentine', denoised, end_time - start_time)
denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(method='anisotropic_diffusion', unfold_domain='real',
                        unfold_method='serpentine', niter=5, kappa=10, gamma=0.1, option=2)
end_time = perf_counter_ns()
record_result('Diffusion real: serpentine', denoised, end_time - start_time)
np.testing.assert_allclose(denoised.array.sum(dtype=np.float64),
                           data.array.sum(dtype=np.float64), rtol=1e-5, atol=1e-3)

10. Make cropped-curve coverage explicit

Hilbert traverses a power-of-two square. On the default 10-by-12 scan, center-cropping keeps the central 8-by-8 region: rows [1:9], columns [2:10]. Only 64 of 120 positions enter the unfolded tensor. A warning explains the omission.

With preserve_excess=True, excluded values are saved in metadata, consuming additional memory. Unfolding then undoing without processing is exact. After denoising, folding restores those excluded positions unchanged, not denoised. Full original shape therefore does not mean full processing coverage. Use row-major/serpentine when every position must be processed.

The first plot shows the actual cropped scan region; an additional traversal preview is bounded to 16-by-16 for readability on an external scan. It can differ from a larger actual path. A fully compatible square scan has no excess. Resizing is an alternative representation change, not an exact inverse; it is not used in this comparison.

hilbert_unfolded, hilbert_meta = data.unfold(
    domain='real', method='hilbert', curve_shape_strategy='center_crop',
    preserve_excess=True, return_metadata=True, plot_traversal=True,
    plot_kwargs={'grid_shape': preview_shape, 'cmap': 'viridis', 'linewidth': 1.8},
)
np.testing.assert_array_equal(hilbert_unfolded.unfold(undo=True).array, data.array)
processed_mask = np.zeros((ry, rx), dtype=bool)
kept = hilbert_meta['kept_indices']
processed_mask[kept[:, 0], kept[:, 1]] = True
crop = hilbert_meta['crop_slices']
print('Actual crop:', crop, 'Kept:', len(kept), 'of', ry * rx)
print('Preserved excess storage (MiB):', hilbert_meta['preserved_values_nbytes'] / 1024**2)
if is_synthetic:
    assert crop == {'y': (1, 9), 'x': (2, 10)} and int(processed_mask.sum()) == 64
fig, ax = plt.subplots(figsize=(5.5, 3.5), constrained_layout=True)
im = ax.imshow(processed_mask, cmap='Greys', vmin=0, vmax=1)
ax.set(title='Actual Hilbert coverage (black = processed)',
       xlabel='Scan column Rx', ylabel='Scan row Ry')
plt.show()
hilbert_unfolded = None
/tmp/ipykernel_2413/1331508364.py:1: UserWarning: Center-crop unfolding with method='hilbert' excludes coordinates from the unfolded tensor: real-space: 64/120 coordinates included (centered y[1:9], x[2:10]); 56 excluded. Excluded values are saved in metadata and restored unchanged by undo=True; operations on the unfolded tensor do not affect them.
  hilbert_unfolded, hilbert_meta = data.unfold(
Figure from the synthetic tutorial
Actual crop: {'y': (1, 9), 'x': (2, 10)} Kept: 64 of 120
Preserved excess storage (MiB): 0.4921875
Figure from the synthetic tutorial
denoised = None
start_time = perf_counter_ns()
denoised = data.denoise(
    method='median', unfold_domain='real', unfold_method='hilbert', window_size=(3, 1, 1),
    unfold_kwargs={'curve_shape_strategy': 'center_crop', 'preserve_excess': True},
)
end_time = perf_counter_ns()
np.testing.assert_array_equal(denoised.array[~processed_mask], data.array[~processed_mask])
record_result('Median real: Hilbert crop', denoised, end_time - start_time, processed_mask)
print('Excluded scan positions are restored unchanged:', int((~processed_mask).sum()))
Excluded scan positions are restored unchanged: 56
/home/runner/work/4Denoise/4Denoise/fourdenoise.py:4972: UserWarning: Center-crop unfolding with method='hilbert' excludes coordinates from the unfolded tensor: real-space: 64/120 coordinates included (centered y[1:9], x[2:10]); 56 excluded. Excluded values are saved in metadata and restored unchanged by undo=True; operations on the unfolded tensor do not affect them.
  unfolded, unfold_metadata = self.unfold(

11. One small TensorLy fit and its convergence history

The default synthetic run includes a rank-6 CP/PARAFAC fit with a short 20-iteration budget and reproducible random initialization. TensorLy is a core dependency. On an external input this section is disabled unless you set run_tensorly_demo=True; reassess rank, time, and full-tensor memory first.

convergence_plot=True plots errors returned from this same fit: it does not launch a second fit. With return_errors=True, the return is (HyperData, errors). The history describes reconstruction of the noisy input, not recovery of a clean reference. Lower fitting error, larger rank, or more iterations can eventually fit noise as well as signal. Error definitions differ across methods. This small budget demonstrates the API; it does not certify convergence or select an optimal rank.

convergence_errors = None
if run_tensorly_demo:
    denoised = None
    start_time = perf_counter_ns()
    denoised, convergence_errors = data.denoise(
        method='parafac', unfold_domain='real', unfold_method='serpentine',
        rank=6, init='random', random_state=42, n_iter_max=20, tol=1e-5,
        return_errors=True, convergence_plot=True,
    )
    end_time = perf_counter_ns()
    assert len(convergence_errors) > 0 and np.all(np.isfinite(convergence_errors))
    record_result('CP rank 6: serpentine', denoised, end_time - start_time)
    print('Reported iterations:', len(convergence_errors))
else:
    print('TensorLy demonstration skipped; explicitly opt in for your selected external data.')
Figure from the synthetic tutorial
Reported iterations: 20

12. Optional expensive extensions: disabled by default

A rank scree/elbow sweep performs a separate fit per rank, unlike the preceding convergence plot. The example accepts nonconsecutive ranks from a NumPy array; tuples/lists work too. Its errors are relative to the noisy tensor actually fitted. No clean reference is needed and no eigenvalue interpretation is implied. Keep return_reconstructions=False to avoid retaining a full output for every rank.

BM4D acts on a 3D volume, so we unfold the real grid and refold afterward. Install .[bm] in the active environment before enabling it. Supply an appropriate bm4d_sigma_psd in the current intensity units. The algorithm assumes a Gaussian noise model; the default Poisson fixture is not a calibrated BM4D benchmark. BM3D instead acts on 2D images. No optional package is installed by this notebook.

scree = None
if run_rank_sweep:
    scree = data.rank_scree(
        method='parafac', ranks=np.array([2, 4, 6]),
        unfold_domain='real', unfold_method='serpentine',
        init='random', random_state=42, n_iter_max=20, tol=1e-5,
        return_reconstructions=False, progress=False,
    )
    assert 'reconstructions' not in scree
    print('Fit tensor shape:', scree['comparison_shape'])
else:
    print('Rank sweep disabled: each selected rank requires another fit.')
Rank sweep disabled: each selected rank requires another fit.
if run_bm4d:
    if bm4d_sigma_psd is None or not np.isscalar(bm4d_sigma_psd) or bm4d_sigma_psd <= 0:
        raise ValueError('Set a positive bm4d_sigma_psd after reviewing the Gaussian noise model.')
    denoised = None
    start_time = perf_counter_ns()
    denoised = data.denoise(method='bm4d', unfold_domain='real',
                            unfold_method='serpentine', sigma_psd=bm4d_sigma_psd)
    end_time = perf_counter_ns()
    record_result('BM4D real: serpentine', denoised, end_time - start_time)
else:
    print('BM4D disabled: requires optional dependencies and an appropriate noise estimate.')
BM4D disabled: requires optional dependencies and an appropriate noise estimate.

13. Compare patterns and real-space images on shared scales

Every panel shows the same chosen scan coordinate, with one shared display transformation and intensity scale. Stored values are not clipped for visualization: signed power preserves possible negative fitted/background-corrected intensities. Only the displayed values are transformed. Diffraction axes use calibrated centered offsets when available, otherwise centered pixels, with displayed y upward.

For a cropped Hilbert traversal the chosen coordinate may lie outside its coverage on your own scan. Consult the coverage map and table. Shared-scale virtual images can reveal altered integrated signal or boundary smearing, but smoother appearance alone is not evidence of preserved peaks or improved strain estimates.

labels = list(dp_samples)
ncols, nrows = 3, int(np.ceil(len(labels) / 3))
pattern_samples = dp_samples
if reference_array is not None:
    pattern_samples = {'Clean reference': reference_array[sample_y, sample_x].copy(), **dp_samples}
pattern_labels = list(pattern_samples)
pattern_nrows = int(np.ceil(len(pattern_labels) / ncols))
power = 0.4
display_samples = {}
for label, values in pattern_samples.items():
    display_values = np.asarray(values, dtype=np.float64)
    display_samples[label] = np.sign(display_values) * np.abs(display_values)**power
low = min(0.0, min(float(values.min()) for values in display_samples.values()))
high = max(float(values.max()) for values in display_samples.values())
if low == high:
    high = low + 1
factor = data.reciprocal_conv_factor if data.reciprocal_conv_factor is not None else 1.0
units = data.reciprocal_units if data.reciprocal_units is not None else 'pixels'
extent = (-kx * factor / 2, kx * factor / 2, -ky * factor / 2, ky * factor / 2)
fig, axes = plt.subplots(pattern_nrows, ncols, figsize=(11, 3.2 * pattern_nrows), squeeze=False,
                         constrained_layout=True)
for ax, label in zip(axes.flat, pattern_labels):
    im = ax.imshow(display_samples[label], cmap='magma', vmin=low, vmax=high, extent=extent)
    ax.set(title=label, xlabel='kx (' + units + ')', ylabel='ky (' + units + ')')
    ax.title.set_fontsize(10)
for ax in list(axes.flat)[len(pattern_labels):]:
    ax.set_visible(False)
fig.suptitle('One diffraction pattern at scan (y, x) = ' + str((sample_y, sample_x)))
fig.colorbar(im, ax=list(axes.flat)[:len(pattern_labels)], label='Signed intensity power 0.4', shrink=0.75)
plt.show()
Figure from the synthetic tutorial
image_low = min(float(image.array.min()) for image in virtual_images.values())
image_high = max(float(image.array.max()) for image in virtual_images.values())
if image_low == image_high:
    image_high = image_low + 1
fig, axes = plt.subplots(nrows, ncols, figsize=(11, 2.6 * nrows), squeeze=False,
                         constrained_layout=True)
for ax, label in zip(axes.flat, labels):
    virtual_images[label].show(ax=ax, show=False, colorbar=False, title=label,
                               axis_units='auto', cmap='viridis', vmin=image_low,
                               vmax=image_high, grid_ticks=(4, 4))
    ax.title.set_fontsize(10)
for ax in list(axes.flat)[len(labels):]:
    ax.set_visible(False)
fig.colorbar(axes.flat[0].images[0], ax=list(axes.flat)[:len(labels)],
             label='Virtual-detector intensity sum', shrink=0.75)
fig.suptitle('Shared-scale virtual images; check the selected detector and coverage')
plt.show()
Figure from the synthetic tutorial

14. Read the quantitative comparison honestly

The table distinguishes full-tensor clean-reference error from processing coverage. The unfiltered noisy baseline has full available coverage, but has not been denoised. Hilbert’s full error includes untouched noisy excess positions; its processed-region RMSE concerns a different subset and should not be compared directly to a full-grid number. A single global RMSE can also be dominated by the central beam. In the synthetic example, even the low-error CP reconstruction can show directional artifacts around spots: compare it to the displayed clean reference and inspect peak shapes/downstream measurements, not just the score.

For external data without a registered clean reference, the table shows n/a and the reference-error plot is skipped. A residual or a lower CP fit error is not substituted for an unavailable true denoising error. These settings are not tuned, repeated benchmarks, physical uncertainty estimates, or an automatic method-selection rule.

print('{:<32} {:>14} {:>10} {:>10} {:>10} {:>12}'.format(
    'Method', 'HH:MM:SS.sss', 'RMSE', 'NRMSE', 'Coverage', 'Region RMSE'))
for row in records:
    seconds = row['seconds']
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    elapsed = '{:02d}:{:02d}:{:06.3f}'.format(hours, minutes, seconds % 60)
    values = [('{:.4f}'.format(row[key]) if np.isfinite(row[key]) else 'n/a')
              for key in ('rmse', 'nrmse', 'processed_rmse')]
    print('{:<32} {:>14} {:>10} {:>10} {:>9.1%} {:>12}'.format(
        row['label'], elapsed, values[0], values[1], row['processed_fraction'], values[2]))
if reference_array is not None:
    fig, ax = plt.subplots(figsize=(8.5, 4.5), constrained_layout=True)
    colors = ['tab:gray' if row['processed_fraction'] == 1 else 'tab:orange' for row in records]
    ax.barh([row['label'] for row in records], [row['rmse'] for row in records], color=colors)
    ax.invert_yaxis()
    ax.set(xlabel='RMSE against the supplied clean reference (intensity units)',
           title='Full-grid error; orange denotes partial processing coverage')
    plt.show()
else:
    print('No clean reference: skipping the reference-error plot.')
if is_synthetic:
    assert all(np.isfinite(row['rmse']) for row in records)
    assert next(row for row in records if row['label'] == 'Median DP')['rmse'] < records[0]['rmse']
Method                             HH:MM:SS.sss       RMSE      NRMSE   Coverage  Region RMSE
Noisy input                        00:00:00.000     1.5721     0.1973    100.0%          n/a
Median DP                          00:00:00.015     1.2287     0.1542    100.0%          n/a
Median real: row-major             00:00:00.006     1.1378     0.1428    100.0%          n/a
Median real: serpentine            00:00:00.006     1.1194     0.1405    100.0%          n/a
Median reciprocal: serpentine      00:00:00.011     1.3105     0.1644    100.0%          n/a
TV real: serpentine                00:00:00.027     1.1103     0.1393    100.0%          n/a
Diffusion real: serpentine         00:00:00.007     0.8856     0.1111    100.0%          n/a
Median real: Hilbert crop          00:00:00.005     1.3379     0.1679     53.3%       1.1038
CP rank 6: serpentine              00:00:00.063     0.3458     0.0434    100.0%          n/a
Figure from the synthetic tutorial

15. Save one result and retain the original input

denoised currently holds the last method that actually ran. Save that output with native metadata and check a numerical round trip. Earlier diagnostics retain only 2D summaries, not every 4D result. This remains an in-memory workflow: global tensor decomposition cannot be made bounded-memory simply by independently denoising arbitrary chunks.

The small sampled non-mutation check below is a sanity check, not a proof for every input pixel. For the default synthetic fixture we additionally check every pixel. The original supplied HyperData/array was copied in the selection cell. Keep your original acquisition and provenance regardless of visual improvement.

result_path = work_dir / 'last_denoised_result.4denoise'
denoised.save(result_path)
reloaded = HyperData(result_path)
np.testing.assert_array_equal(reloaded.array, denoised.array)
assert reloaded.real_units == data.real_units and reloaded.reciprocal_units == data.reciprocal_units
np.testing.assert_array_equal(data.array.ravel()[::max(1, data.array.size // 256)], original_probe)
if is_synthetic:
    np.testing.assert_array_equal(data.array, synthetic_array)
print('Saved and reloaded the last result; input checks passed.')
reloaded = None
Saved and reloaded the last result; input checks passed.

16. What to change when moving to your data

Start with the section 3 input cell. Confirm array order, calibration, registered reference availability, finite values, and memory size. Adapt filter widths/weights/noise estimates to your detector and specimen, compare representative weak/strong patterns and boundaries, and validate downstream peak/strain measurements. No implicit normalization, central-beam blocking, clipping, or center fitting is performed here.

Use full-shape traversals for full coverage, and read crop warnings when selecting a space-filling curve. Matrix/tensor decompositions depend mainly on factorization structure; spatial filters depend directly on adjacency along the traversal. A curve is not automatically a better ordering for every method.

The earlier tutorials retain small known-truth construction exercises, followed by their own experimental/simulation input branches. Their synthetic calibration, analytical spot positions, and truth assertions are not automatically transferred to a new acquisition. Notebook 4 instead places input selection before the common processing workflow. See using your own data and the denoising guide. Continue with Tutorial 5: Peak analysis and Braggness.

denoised = None
hilbert_meta = None
plt.close('all')
workspace.cleanup()
print('Tutorial complete; temporary outputs removed, source data not overwritten.')
Tutorial complete; temporary outputs removed, source data not overwritten.