Tutorial 1: Loading and Calibration¶
A runnable introduction using synthetic data. No microscope file, simulation package, or RosettaSciIO installation is required. Use the Python environment in which you installed 4Denoise, then run all cells from a fresh kernel.
You will inspect array shapes, load NumPy/HDF5/MATLAB/raw files, assign units, select pixels versus physical scan coordinates, save metadata, and read a dataset without loading every diffraction pattern. A clearly marked cell near the end lets you substitute a microscope acquisition later.
The diffraction-like fixture is a teaching illustration, not a physical electron-scattering simulation. Its scales and acquisition settings are invented. Successful checks here validate this example’s data handling, not a microscope’s calibration.
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. Check the environment¶
Install the editable package and a notebook kernel in your chosen environment. The repository’s notebook extra is one option; docs-test supplies the lightweight notebook-execution dependencies used in CI. The imports below are explicit because importing a package does not put its internal NumPy or Matplotlib names into your notebook.
Check the interpreter and module path if an updated method appears to be missing. Restart the kernel after changing environments or updating class definitions.
%matplotlib inline
from pathlib import Path
import sys
import tempfile
import h5py
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import savemat
import fourdenoise
from fourdenoise import HyperData
print('Python:', sys.executable)
print('4Denoise:', fourdenoise.__file__)
print('Working directory:', Path.cwd())
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py
Working directory: /home/runner/work/4Denoise/4Denoise/tutorials
2. Create a small, repeatable dataset¶
All generated files go into an owned temporary directory, not alongside your research files. The final cell removes only this directory. Re-running a file-writing cell replaces only its own tutorial file. To keep a useful result, save it separately before cleanup.
The convention is (Ry, Rx, Ky, Kx): scan rows and columns followed by diffraction rows and columns. Here, (8, 10, 64, 64) means 80 diffraction patterns, each containing 64 by 64 pixels.
workspace = tempfile.TemporaryDirectory(prefix='4denoise-tutorial-01-')
work_dir = Path(workspace.name)
print('Temporary tutorial files:', work_dir)
Temporary tutorial files: /tmp/4denoise-tutorial-01-kk1jgad_
rng = np.random.default_rng(42)
Ry, Rx, Ky, Kx = 8, 10, 64, 64
scan_y, scan_x = np.mgrid[:Ry, :Rx]
ky, kx = np.mgrid[:Ky, :Kx]
cy, cx = (Ky - 1) / 2, (Kx - 1) / 2
pattern = 35 * np.exp(-((ky - cy)**2 + (kx - cx)**2) / (2 * 2.3**2))
for dy, dx in ((0, 18), (0, -18), (16, 9), (-16, -9), (16, -9), (-16, 9)):
pattern += 20 * np.exp(
-((ky - cy - dy)**2 + (kx - cx - dx)**2) / (2 * 1.3**2)
)
modulation = 0.7 + 0.6 * scan_x / (Rx - 1) + 0.1 * np.sin(scan_y)
expected_counts = 0.08 + modulation[..., None, None] * pattern
example_array = rng.poisson(expected_counts).astype(np.uint16)
assert example_array.shape == (8, 10, 64, 64)
assert example_array.min() == 0
print('Shape:', example_array.shape, '| dtype:', example_array.dtype)
print('Array size: {:.2f} MiB'.format(example_array.nbytes / 1024**2))
Shape: (8, 10, 64, 64) | dtype: uint16
Array size: 0.62 MiB
3. Wrap the array and declare calibration¶
Conversion factors are units per pixel, not pixels per unit. A scalar real-space factor describes equal scan steps; a pair gives (y, x) steps. In this example they are 2 nm and 3 nm, and scan pixel (0, 0) is at (10, -5) nm. The reciprocal factor is an isotropic 0.25 mrad per detector pixel.
These illustrative values change coordinate interpretation, not the stored intensities. Choose inverse-length units instead when those are your actual calibrated detector units; changing the label alone does not convert mrad into inverse angstroms.
acquisition_metadata describes the original experiment. It is separate from current geometry: a recorded scan rotation does not establish the real-space/diffraction-space (R/Q) relationship or set a beam center.
example_calibration = dict(
real_units='nm', real_conv_factor=(2.0, 3.0), real_origin=(10.0, -5.0),
reciprocal_units='mrad', reciprocal_conv_factor=0.25,
)
example_acquisition = dict(
data_origin='synthetic', synthetic_seed=42, scan_shape=(Ry, Rx),
scan_rotation_deg=12.0, description='Invented tutorial acquisition',
)
data = HyperData(
example_array, **example_calibration,
acquisition_metadata=example_acquisition,
)
assert data.scan_shape == (Ry, Rx)
assert data.pattern_shape == (Ky, Kx)
assert data.rq_calibration is None
assert data.center_beam_metadata is None
print(data.metadata_summary())
Current data shape: (8, 10, 64, 64)
Acquisition metadata (original acquisition, not current geometry):
Acquired scan shape (Ry, Rx): (8, 10)
Recorded scan rotation: 12 deg
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. Separate selection units from display units¶
get_dp(i, j) selects scan indices: its default is selection_units=’pixels’, even on calibrated data. selection_units=’calibrated’ instead uses physical scan coordinates. selection_units=’auto’ uses calibration when available.
A returned ReciprocalSpace pattern inherits detector calibration. Its axis_units controls display only: ’pixels’, ’calibrated’, or ’auto’. The default ’auto’ uses calibration if present. Calibrated Cartesian diffraction axes are centered and y-up; array indices are y-down. Pixel scaling alone does not determine the direct-beam position or R/Q orientation.
i, j = 2, 3
dy, dx = data.real_conv_factor
y0, x0 = data.real_origin
physical_y, physical_x = y0 + i * dy, x0 + j * dx
dp_pixels = data.get_dp(i, j, selection_units='pixels')
dp_physical = data.get_dp(
physical_y, physical_x, selection_units='calibrated',
)
np.testing.assert_array_equal(dp_pixels.array, dp_physical.array)
np.testing.assert_array_equal(dp_pixels.array, example_array[i, j])
print('Scan index:', (i, j), '-> position:', (physical_y, physical_x), 'nm')
print('Detector pixel scale:', dp_pixels.conv_factor, dp_pixels.units, 'per pixel')
Scan index: (2, 3) -> position: (14.0, 4.0) nm
Detector pixel scale: 0.25 mrad per pixel
dp_pixels.show(
axis_units='pixels', title='Detector pixels',
logScale=False, power=0.4, cmap='magma', figsize=(5, 4),
)
dp_pixels.show(
axis_units='calibrated', title='Calibrated detector axes',
logScale=False, power=0.4, cmap='magma', figsize=(5, 4),
)
np.testing.assert_array_equal(dp_pixels.array, example_array[i, j])
For a quick scan-axis check, integrate the complete detector. The resulting RealSpace image inherits the unequal scan steps and origin. This image is total recorded signal, not a crystalline fraction. Tutorial 2 will explore detector shapes and plotting controls.
Both plots above use a display-only power transform to reveal weak spots; no clipping, denoising, or rescaling of stored counts occurred.
scan_image = data.virtual_image(
mask=np.ones(data.pattern_shape, dtype=bool),
detector_units='pixels', show=False,
)
scan_image.show(
axis_units='calibrated', title='Calibrated scan', grid_ticks=(5, 6),
cmap='gray', figsize=(6, 4), colorbar_label='Integrated counts',
)
(<Figure size 600x400 with 2 Axes>,
<Axes: title={'center': 'Calibrated scan'}, xlabel='x (nm)', ylabel='y (nm)'>)
5. Load native file formats without changing values¶
We now export only the small synthetic array to several formats. Ordinary NumPy and generic HDF5/MATLAB/raw files do not automatically carry 4Denoise calibration. Declaring units on an earlier in-memory object does not make those units appear in a plain array export.
Format |
Selection/layout information |
|---|---|
NumPy |
One stored array, including its shape and dtype |
Generic HDF5 |
Use |
MATLAB |
Use |
Binary |
Supply the verified stored shape, dtype/byte order, and C/F storage order |
The tutorial raw file is little-endian unsigned 16-bit, C order, with no metadata rows. Do not copy those assumptions to a microscope acquisition. Explicit raw shape avoids legacy EMPAD row trimming; metadata_path=None disables unrelated sidecar discovery for this fixture.
npy_path = work_dir / 'example.npy'
h5_path = work_dir / 'example.hdf5'
mat_path = work_dir / 'example.mat'
raw_path = work_dir / 'example.raw'
np.save(npy_path, example_array)
with h5py.File(h5_path, 'w') as file:
file.create_dataset('/entry/diffraction', data=example_array, chunks=(1, 1, Ky, Kx))
savemat(mat_path, {'diffraction': example_array})
example_array.astype('<u2').tofile(raw_path)
print('Created four small fixtures in:', work_dir)
Created four small fixtures in: /tmp/4denoise-tutorial-01-kk1jgad_
loaded_examples = {
'NumPy': HyperData(npy_path),
'HDF5': HyperData(h5_path), # one dataset: selected automatically
'MATLAB': HyperData(mat_path, mat_variable='diffraction'),
'raw': HyperData(
raw_path, raw_shape=example_array.shape, raw_dtype='<u2', raw_order='C',
metadata_path=None,
),
}
for name, loaded in loaded_examples.items():
np.testing.assert_array_equal(loaded.array, example_array)
assert loaded.array.dtype == example_array.dtype
assert loaded.real_units is None and loaded.reciprocal_units is None
print(name, loaded.shape, loaded.dtype, '| stored zeros preserved')
NumPy (8, 10, 64, 64) uint16 | stored zeros preserved
HDF5 (8, 10, 64, 64) uint16 | stored zeros preserved
MATLAB (8, 10, 64, 64) uint16 | stored zeros preserved
raw (8, 10, 64, 64) uint16 | stored zeros preserved
Multiple HDF5 datasets are not interchangeable¶
A file can contain diffraction pixels, reference stacks, thumbnails, and other arrays. When more than one candidate exists, 4Denoise reports paths and shapes instead of silently selecting one. This cell deliberately triggers and handles that expected error, then selects the full scan explicitly.
An HDF5 dataset’s shape does not prove which dimensions are physical y and x. Confirm storage conventions before reordering axes. Native HDF5 loading also does not interpret arbitrary vendor attributes as calibration.
multi_path = work_dir / 'multiple-datasets.h5'
with h5py.File(multi_path, 'w') as file:
file.create_dataset('/entry/diffraction', data=example_array)
file.create_dataset('/entry/reference_stack', data=example_array[0])
try:
HyperData(multi_path)
except ValueError as error:
print('Expected ambiguity report:')
print(error)
else:
raise AssertionError('Multiple HDF5 datasets should require a selection.')
selected = HyperData(multi_path, hdf5_dataset='/entry/diffraction')
np.testing.assert_array_equal(selected.array, example_array)
Expected ambiguity report:
2 numeric multidimensional datasets were found in '/tmp/4denoise-tutorial-01-kk1jgad_/multiple-datasets.h5'. Select one with HyperData(filename, hdf5_dataset='/path/to/dataset').
Candidate datasets:
/entry/diffraction: shape=(8, 10, 64, 64), ndim=4, dtype=uint16
/entry/reference_stack: shape=(10, 64, 64), ndim=3, dtype=uint16
Loading is not preprocessing¶
Default generic loading preserves genuine zeros and does not repair NaN-containing patterns. clip_on_load=True explicitly replaces values below 1 with 1; it is not a scientific requirement. The following comparison changes only the newly loaded object, not the file. NaN repair is a separate, opt-in repair_nans operation and should be chosen deliberately.
clipped_on_load = HyperData(npy_path, clip_on_load=True)
np.testing.assert_array_equal(clipped_on_load.array, np.maximum(example_array, 1))
np.testing.assert_array_equal(HyperData(npy_path).array, example_array)
print('Default load minimum:', loaded_examples['NumPy'].array.min())
print('Explicitly clipped load minimum:', clipped_on_load.array.min())
Default load minimum: 0
Explicitly clipped load minimum: 1
6. Save pixels and metadata together¶
Use .save() for a metadata-preserving 4Denoise file; the recommended suffix is .4denoise. This HDF5-based format is distinct from a plain array export. Supported current geometry, original acquisition records, and stored R/Q/beam/polar information survive when present.
Default saves are atomic, and existing destinations require explicit replacement. Here overwrite=True makes this cell repeatable only for our own temporary tutorial output. Atomic replacement needs disk space for the old and new files. None of these operations establishes an R/Q calibration from the invented 12-degree scan setting.
saved_path = Path(data.save(work_dir / 'calibrated.4denoise', overwrite=True))
restored = HyperData(saved_path)
np.testing.assert_array_equal(restored.array, example_array)
assert restored.dtype == data.dtype
assert restored.real_units == data.real_units
np.testing.assert_allclose(restored.real_conv_factor, data.real_conv_factor)
np.testing.assert_allclose(restored.real_origin, data.real_origin)
assert restored.reciprocal_units == data.reciprocal_units
assert restored.reciprocal_conv_factor == data.reciprocal_conv_factor
assert restored.acquisition_metadata == data.acquisition_metadata
assert restored.rq_calibration is None
print('Saved and restored pixels, dtype, calibration, origin, and acquisition record.')
Saved and restored pixels, dtype, calibration, origin, and acquisition record.
Wrapping a NumPy array does not promise a deep copy. Use .copy() when you need independently editable pixels and metadata. Calibration changes describe coordinates; copying describes ownership. They are different concerns.
independent = restored.copy()
assert not np.shares_memory(independent.array, restored.array)
assert independent.acquisition_metadata is not restored.acquisition_metadata
np.testing.assert_array_equal(independent.array, restored.array)
print('copy() owns independent data and metadata.')
copy() owns independent data and metadata.
7. Recognize a 3D stack without guessing its scan geometry¶
A stack (N, Ky, Kx) is valid HyperData. Its scan_shape is (N,) and real_shape is None: the package cannot know a missing two-dimensional raster.
We can fold this example because we know how we flattened it: C-order traversal of an 8 by 10 grid. A matching pixel count alone does not prove that an experimental stack has this layout. Reshaping is not interpolation, beam alignment, or recovery of unknown scan ordering. More advanced traversals belong in the unfolding tutorial.
stack = HyperData(example_array.reshape(Ry * Rx, Ky, Kx))
assert stack.scan_shape == (Ry * Rx,)
assert stack.real_shape is None
np.testing.assert_array_equal(stack.get_dp(13).array, example_array.reshape(-1, Ky, Kx)[13])
folded = stack.reshape(Ry, Rx, Ky, Kx)
np.testing.assert_array_equal(folded.array, example_array)
print('Stack:', stack.shape, '| known-layout fold:', folded.shape)
print('Reshaping an uncalibrated stack does not invent a physical calibration.')
Stack: (80, 64, 64) | known-layout fold: (8, 10, 64, 64)
Reshaping an uncalibrated stack does not invent a physical calibration.
8. Choose eager loading or a read-only source¶
HyperData(path) loads all selected pixels into RAM. HyperData.open(path) instead owns a read-only source for native NumPy, HDF5, saved HyperData, or supported optional Rosetta readers. It has no public .array and does not silently convert into a full NumPy array.
Read while the source is open. Returned patterns and chunks own independent arrays and remain usable after closure. Saved calibration is restored on the source and inherited by returned objects. The following memory budget limits estimated temporary numerical buffers, not total process RAM; retained results, metadata, caches, and library overhead are additional.
Sources currently require a nonempty 3D stack or 4D scan. This is not a promise of lazy execution for every method or for global tensor decomposition.
with HyperData.open(saved_path) as source:
print('Disk-backed source:', source.shape, source.dtype, source.backend)
print('Full numerical size:', source.nbytes, 'bytes')
source_dp = source.get_dp(i, j, selection_units='pixels')
mean_dp = source.get_dp(operation='mean', working_memory_mb=8)
scan_slices, block = next(source.iter_chunks((2, 3), working_memory_mb=8))
print('First returned block:', scan_slices, block.shape)
assert source.reciprocal_conv_factor == data.reciprocal_conv_factor
assert source.closed
np.testing.assert_array_equal(source_dp.array, example_array[i, j])
np.testing.assert_allclose(mean_dp.array, example_array.mean(axis=(0, 1)))
np.testing.assert_array_equal(block.array, example_array[scan_slices])
print('The source is closed; its returned pattern, mean, and block still work.')
Disk-backed source: (8, 10, 64, 64) uint16 hdf5
Full numerical size: 655360 bytes
First returned block: (slice(0, 2, None), slice(0, 3, None)) (2, 3, 64, 64)
The source is closed; its returned pattern, mean, and block still work.
Full loading is an explicit choice. max_memory_mb caps the complete numerical output allocation, separately from the temporary-workspace budget; it does not cover every metadata or library allocation. This tiny example fits below 16 MiB. For multi-gigabyte acquisitions, keep the source open and request only the reductions, selections, or streamed operations you need.
with HyperData.open(saved_path) as source:
fully_loaded = source.load(max_memory_mb=16, working_memory_mb=8)
np.testing.assert_array_equal(fully_loaded.array, example_array)
assert fully_loaded.acquisition_metadata == example_acquisition
print('Explicit full load:', fully_loaded.shape)
Explicit full load: (8, 10, 64, 64)
9. Replace this input with experimental or simulation data later¶
Edit only the configuration at the top of the next cell. With both input_data=None and microscope_path=None, the notebook selects a copy of the calibrated synthetic example. Earlier format exercises always use their small synthetic fixture and never export your acquisition.
For an already loaded acquisition or simulation, set input_data to an existing HyperData or numerical array and choose input_origin=’experimental’ or ’simulation’. Use only one of input_data and microscope_path. A HyperData input is copied with its metadata; configure its calibration before passing it and leave loader/calibration overrides empty. A bare array is copied and gets only explicitly supplied calibration. Simulator objects should first be converted to a numerical array and their axes/units verified. These eager copies are not a streaming path.
For a native file, choose microscope_backend=’native’ and set an existing path. Options can include hdf5_dataset=’/entry/data’, mat_variable=’diffraction’, or the verified raw_shape, raw_dtype, and raw_order. Native construction eagerly loads the file; do not use that branch for an acquisition too large for RAM. Use a source as in section 8 instead.
For optional microscope readers, first install the rosetta extra in this interpreter and restart the kernel. Choose microscope_backend=’rosetta’; options may include a confirmed reader, dataset, axis_order, and plugin-specific reader_kwargs. This branch explicitly loads the selected dataset with a 512 MiB numerical-output cap. Keep it as a source instead if that is too small.
Leave microscope_calibration={} to retain any imported/saved calibration. Add verified unit/scale pairs only when needed. The synthetic nm/mrad scales, invented acquisition record, and 12-degree scan setting are deliberately not copied into a microscope dataset. Reader availability is not validation of your file’s axis conventions, beam center, or R/Q calibration.
input_data = None # Later: an existing HyperData object or numerical array.
input_origin = 'experimental' # Or 'simulation'; a descriptive label, not inferred metadata.
microscope_path = None # Later: Path('path/to/your/acquisition.hdf5')
microscope_backend = 'native' # 'native' or 'rosetta'
microscope_options = {} # e.g. {'hdf5_dataset': '/entry/data'} for native HDF5
microscope_calibration = {} # Leave empty unless you have verified overrides.
if input_data is not None and microscope_path is not None:
raise ValueError('Provide input_data or microscope_path, not both.')
if input_origin not in ('experimental', 'simulation'):
raise ValueError('input_origin must be experimental or simulation.')
if input_data is not None:
if microscope_options:
raise ValueError('Loader options apply to file inputs, not input_data.')
if isinstance(input_data, HyperData):
if microscope_calibration:
raise ValueError('Calibrate your HyperData before passing it as input_data.')
selected_data = input_data.copy()
else:
selected_data = HyperData(np.array(input_data, copy=True), **microscope_calibration)
print('Selected in-memory ' + input_origin + ' data.')
elif microscope_path is None:
selected_data = restored.copy()
print('Selected the SYNTHETIC teaching example; no microscope file was read.')
elif microscope_backend == 'native':
selected_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 microscope_source:
selected_data = microscope_source.load(max_memory_mb=512, working_memory_mb=64)
else:
raise ValueError('microscope_backend must be native or rosetta.')
print(selected_data.metadata_summary())
Selected the SYNTHETIC teaching example; no microscope file was read.
Current data shape: (8, 10, 64, 64)
Acquisition metadata (original acquisition, not current geometry):
Acquired scan shape (Ry, Rx): (8, 10)
Recorded scan rotation: 12 deg
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
Inspect a mean pattern before deciding that axis order or calibration is correct. axis_units=’auto’ shows stored calibration when available, otherwise pixels. This bounded reduction does not create a gathered copy of all selected diffraction patterns, but an eagerly loaded selected_data already occupies RAM.
For a newly introduced acquisition, compare shape, dtype/value range, representative patterns, scan ordering, units, and orientation with the microscope software or another trusted reference. A scan-rotation field is not an independently verified R/Q relationship.
selected_mean = selected_data.get_dp(operation='mean', working_memory_mb=16)
selected_mean.show(
axis_units='auto', title='Selected input: mean diffraction pattern',
logScale=False, power=0.4, cmap='magma', figsize=(5, 4),
)
Takeaways and cleanup¶
Array shape, storage order, coordinate calibration, and frame orientation are separate facts.
Native loading preserves counts by default; preprocessing is explicit.
Plain array exports and metadata-preserving
.4denoisesaves serve different purposes.A 3D stack does not supply a missing 2D scan layout.
Opening a source avoids an automatic full load; retained outputs still use memory.
Imported acquisition settings are descriptive unless their interpretation as active calibration is verified.
The next cell closes figures and removes only the temporary tutorial directory. In-memory objects remain usable. Save anything you wish to retain to a separate location first; the temporary file paths will no longer exist. This cleanup never targets microscope_path.
Next in the series: visualization and virtual detectors. The repository’s documentation also provides the data-model, I/O/calibration, and streaming guides.
plt.close('all')
workspace.cleanup()
assert not work_dir.exists()
print('Tutorial complete: all checks passed; temporary tutorial files removed.')
Tutorial complete: all checks passed; temporary tutorial files removed.