Tutorial 5: Peak Analysis and Braggness¶
An independently runnable lesson with synthetic hexagonal spots and diffuse rings. Core 4Denoise and a Jupyter/IPython kernel suffice; no microscope acquisition, simulation package, or preceding notebook output is needed.
We detect a variable number of peaks in each diffraction pattern, refine their positions, integrate intensities, examine threshold sensitivity, and map concentrated sharp contrast with get_braggness(). We also demonstrate reuse of alignment beam metadata, keep invalid scan positions distinct from zero-peak patterns, and export numerical results without pickle.
The input cell accepts experimental/simulation files, arrays, or existing HyperData. Known-position checks use the synthetic model only, unless you explicitly provide registered reference coordinates. Neither detected peak count nor Braggness is an absolute crystalline fraction, phase label, or orientation confidence. This model is a teaching illustration, not electron-scattering simulation.
Note
Synthetic teaching data, not experimental validation. Code and figures below come from a validated fresh-kernel run.
Download the clean notebook or read the lesson overview.
1. Imports and a disposable workspace¶
Restart the kernel and run from top to bottom. All generated output belongs to a temporary directory removed in the last cell. The matching and Gaussian calculations below are explicit diagnostics of the public API, not replacement peak-finding or strain-fitting algorithms.
%matplotlib inline
from pathlib import Path
import json
import sys
import tempfile
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import gaussian_filter
from scipy.optimize import linear_sum_assignment
import fourdenoise
from fourdenoise import HyperData, RealSpace
print('Python:', sys.executable)
print('4Denoise:', fourdenoise.__file__)
workspace = tempfile.TemporaryDirectory(prefix='4denoise-tutorial-05-')
work_dir = Path(workspace.name)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py
2. Build controlled spot-rich, weak-spot, and diffuse regions¶
The default float32 array is (10, 15, 64, 64), ordered (Ry, Rx, Ky, Kx). Its left third contains six strong Gaussian spots at radius 18 pixels; the middle third contains four weaker spots selected from a rotated hexagon; the right third has only a broad diffuse ring. Every pattern also has a centered Gaussian direct beam and uniform background. Poisson counting noise uses seed 2029.
The selected middle spots change with scan row, so the true peak count and identity need not be the same in every pattern. No symmetry repair will be used to invent missing spots. The labels describe assigned image features, not verified material phases. The invented calibration is 2/3 nm per scan row/column and 0.25 mrad per detector pixel. Analytical coordinates remain absolute (y, x) pixels.
rng = np.random.default_rng(2029)
Ry, Rx, Ky, Kx = 10, 15, 64, 64
scan_y, scan_x = np.mgrid[:Ry, :Rx]
sy = 2 * scan_y / (Ry - 1) - 1
yy, xx = np.mgrid[:Ky, :Kx]
cy, cx = (Ky - 1) / 2, (Kx - 1) / 2
rr = np.hypot(yy - cy, xx - cx)
region = scan_x // (Rx // 3)
orientation = np.where(region == 0, 0.1, np.pi / 6)
diffuse_gain = np.choose(region, (0.7, 1.5, 7.0))
spot_gain = np.choose(region, (38.0, 20.0, 0.0)) * (0.85 + 0.15 * np.cos(sy * np.pi))
expected_counts = (1.5 + 100 * np.exp(-rr**2 / (2 * 2.0**2))
+ diffuse_gain[..., None, None] * np.exp(-((rr - 18) / 3.5)**2))
synthetic_truth = [[[] for _ in range(Rx)] for _ in range(Ry)]
for k, angle in enumerate(np.arange(6) * np.pi / 3):
py = cy + 18 * np.sin(angle + orientation)
px = cx + 18 * np.cos(angle + orientation)
present = (region == 0) | ((region == 1) & ((k + scan_y) % 3 != 0))
expected_counts += (spot_gain * present)[..., None, None] * np.exp(
-((yy - py[..., None, None])**2 + (xx - px[..., None, None])**2) / (2 * 1.15**2))
for i, j in np.ndindex(Ry, Rx):
if present[i, j]:
synthetic_truth[i][j].append((py[i, j], px[i, j]))
synthetic_truth = [[np.asarray(coords, dtype=float).reshape(-1, 2)
for coords in row] for row in synthetic_truth]
synthetic_array = rng.poisson(expected_counts).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': 2029,
'description': 'Assigned hexagonal spots and diffuse teaching regions'},
)
truth_counts = np.array([[len(coords) for coords in row] for row in synthetic_truth])
assert set(np.unique(truth_counts)) == {0, 4, 6}
print('Teaching fixture:', synthetic_data.shape, synthetic_data.array.dtype)
Teaching fixture: (10, 15, 64, 64) float32
3. Select the input and analysis settings¶
Leave input_data=None and microscope_path=None for the synthetic run. Otherwise set exactly one: an existing HyperData/numerical array, or a file path. Convert simulator-specific objects to numerical arrays and confirm (Ry, Rx, Ky, Kx) first. Existing HyperData is copied with its metadata; a bare array receives only explicit calibration. No synthetic centers, radii, reference peaks, or units are assigned to external inputs.
Native files load eagerly. In-memory inputs are size-checked before copying; a 64-MiB guard cannot cap total RAM or prevent an earlier eager file load. The optional Rosetta branch has an explicit full-load budget. Select a representative input yourself or use read-only sources for larger acquisitions. input_origin is a descriptive label, not verified provenance.
For external data, explicitly set analysis_annulus_px after inspecting the detector. Review template width, threshold, integration/background radii, Gaussian width, and top-pixel count for that acquisition. Every radius, coordinate, separation, and sigma below is in detector pixels, regardless of calibration. A detection threshold is a template-correlation threshold, not integrated intensity.
scan_mask_input marks positions to evaluate. This lesson assumes finite, nonnegative detector intensities at evaluated positions and will not silently clip or repair them. A supplied reference-coordinate collection must use this exact detector geometry and absolute pixel coordinates. Without it, an external input has no known-position accuracy check.
input_data = None # Existing HyperData or numerical (Ry, Rx, Ky, Kx) array.
input_origin = 'experimental' # Or 'simulation'.
microscope_path = None
microscope_backend = 'native'
microscope_options = {}
microscope_calibration = {}
max_tutorial_input_mb = 64
analysis_annulus_px = None # Synthetic default: (12, 24); REQUIRED explicitly for external data.
analysis_center_px = None # None uses beam metadata when available, otherwise the image midpoint.
scan_mask_input = None # Optional boolean (Ry, Rx); True means evaluate.
reference_peaks_input = None # Optional nested [Ry][Rx] arrays of known (y, x) pixel positions.
peak_template_radius_px = 1.5
peak_min_distance_px = 4
peak_threshold_abs = 40.0
refinement_radius_px = 3.0
refinement_method = 'CoM'
integration_radius_px = 3.0
background_ring_px = (3.5, 5.0)
bragg_sigma_px = 2.0
bragg_top_pixels = 50
run_alignment_example = None # None: synthetic only; True opts in for another input.
alignment_radius_px = None # Synthetic default 7; explicitly supply for an external alignment example.
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 input before making a 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 min(data.shape) < 2 or data.array.dtype.kind not in 'iuf':
raise ValueError('Use real numerical data with at least two samples per axis.')
if data.array.nbytes > max_tutorial_input_mb * 1024**2:
raise MemoryError('Select a representative input or deliberately raise the tutorial size guard.')
reference_peaks = reference_peaks_input
if reference_peaks is None and is_synthetic:
reference_peaks = synthetic_truth
if run_alignment_example is None:
run_alignment_example = is_synthetic
if alignment_radius_px is None and is_synthetic:
alignment_radius_px = 7.0
print('Selected origin:', 'synthetic' if is_synthetic else input_origin)
print(data.metadata_summary())
Selected origin: synthetic
Current data shape: (10, 15, 64, 64)
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
The default synthetic scan deliberately skips one otherwise valid position, (0, 0), to demonstrate masking. False means not evaluated, not non-crystalline. External inputs are not given this artificial exclusion. All numerical diagnostics below use the selected input. Synthetic labels and assertions remain gated to the synthetic run.
Peak detection uses a disk-with-negative-trench template and finds local maxima of its correlation. No reference pattern or symmetry is needed. A later get_centers(ref_coords=…) call uses each pattern’s own detections as initial seeds; its parameter name does not require a common experimental reference pattern.
ry, rx, ky, kx = data.shape
if analysis_annulus_px is None:
if not is_synthetic:
raise ValueError('Inspect your input, then explicitly set analysis_annulus_px in detector 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.')
if not np.isscalar(peak_threshold_abs) or not np.isfinite(peak_threshold_abs) or peak_threshold_abs <= 0:
raise ValueError('Choose a positive finite absolute template-correlation threshold for this lesson.')
if scan_mask_input is None:
scan_mask = np.ones((ry, rx), dtype=bool)
if is_synthetic:
scan_mask[0, 0] = False
else:
scan_mask = np.asarray(scan_mask_input)
if scan_mask.shape != (ry, rx) or scan_mask.dtype.kind != 'b':
raise ValueError('scan_mask_input must be boolean with shape (Ry, Rx).')
scan_mask = scan_mask.copy()
if not scan_mask.any():
raise ValueError('Select at least one scan position to evaluate.')
for index in np.ndindex(ry, rx):
if scan_mask[index]:
pattern = data.array[index]
if not np.all(np.isfinite(pattern)) or np.any(pattern < 0):
raise ValueError('This lesson needs finite nonnegative evaluated patterns; review scan index ' + str(index))
if reference_peaks is not None:
if len(reference_peaks) != ry or any(len(row) != rx for row in reference_peaks):
raise ValueError('Reference coordinates must be nested [Ry][Rx] collections.')
reference_peaks = [[np.asarray(coords, dtype=float) for coords in row] for row in reference_peaks]
for row in reference_peaks:
for coords in row:
if coords.ndim != 2 or coords.shape[1] != 2 or not np.all(np.isfinite(coords)):
raise ValueError('Each reference entry must have finite shape (n_peaks, 2); use (0, 2) for no peaks.')
original_probe = data.array.ravel()[::max(1, data.array.size // 256)].copy()
peak_kwargs = dict(radius=peak_template_radius_px, min_distance=peak_min_distance_px,
threshold_abs=peak_threshold_abs, threshold_rel=None, r_range=tuple(bounds),
center=analysis_center_px, n_fold=None, sym_mode='none')
print('Evaluated positions:', int(scan_mask.sum()), 'Skipped:', int((~scan_mask).sum()))
print('Known reference coordinates available:', reference_peaks is not None)
Evaluated positions: 149 Skipped: 1
Known reference coordinates available: True
4. Inspect the input before detecting peaks¶
The montage averages scan bins and therefore can combine different patterns. It is a survey, not a peak-detection input. Detection below always uses each individual pattern. The assigned synthetic-region map is shown only for the synthetic run; it is not inferred segmentation.
if np.all(np.isfinite(data.array)) and np.all(data.array >= 0):
data.visualize(grid_shape=(min(3, ry), min(3, rx)), padding=2,
title='Input survey: averaged scan bins', power=0.4, log_scale=False, cmap='magma')
else:
data.get_dp(mask=scan_mask, operation='mean').show(
title='Mean of evaluated finite patterns only', power=0.4, logScale=False, cmap='magma')
print('Montage skipped because excluded positions contain nonfinite or negative data.')
if is_synthetic:
fig, ax = plt.subplots(figsize=(6, 3.2), constrained_layout=True)
im = ax.imshow(region, cmap=plt.colormaps['Set2'].resampled(3), vmin=-0.5, vmax=2.5)
ax.set(title='Assigned synthetic regions, not a measured phase map', xlabel='Scan column Rx', ylabel='Scan row Ry')
region_bar = fig.colorbar(im, ax=ax, ticks=[0, 1, 2])
region_bar.ax.set_yticklabels(['Strong spots', 'Weak spots', 'Diffuse ring'])
plt.show()
5. Independent detection and ragged results¶
HyperData.get_peaks(return_details=True) returns nested lists [Ry][Rx] of PeakDetectionResult. Each entry has coords with shape (n_peaks, 2), correlation scores, and a synthetic_mask identifying symmetry-generated rows. Here symmetry is disabled, so every returned coordinate is a measured detection, including any false positives. Detection coordinates are integer pixel positions.
Different patterns can have different lengths: this is a ragged collection, not one rectangular peak tensor. Keep the nested structure instead of forcing it into a regular NumPy array. False scan-mask entries are empty, but an evaluated pattern with no detected peaks is also empty; retain the scan mask to tell them apart. Correlation scores are not integrated intensities or calibrated probabilities.
For comparison, the read-only DiffractionSource.get_peaks() API returns a PeakScanResult or writes a numeric peak collection to disk. It is a separate return contract, useful for large acquisitions, not the return type of this HyperData call.
all_detections = data.get_peaks(**peak_kwargs, real_mask=scan_mask, return_details=True)
all_peak_coords = [[entry.coords for entry in row] for row in all_detections]
all_scores = [[entry.scores for entry in row] for row in all_detections]
peak_count_map = np.array([[len(coords) for coords in row] for row in all_peak_coords])
assert peak_count_map.shape == (ry, rx) and np.all(peak_count_map[~scan_mask] == 0)
for row in all_detections:
for entry in row:
assert entry.coords.shape == (len(entry.scores), 2)
assert not entry.synthetic_mask.any()
sample_index = tuple(np.unravel_index(np.argmax(np.where(scan_mask, peak_count_map, -1)), (ry, rx)))
print('Returned peak counts:', np.unique(peak_count_map[scan_mask]))
print('Overlay example scan index:', sample_index)
data.get_dp(*sample_index, selection_units='pixels').show(
title='Detected integer peak positions', coords=all_peak_coords[sample_index[0]][sample_index[1]],
c='cyan', marker='+', s=60, axis_units='auto', power=0.4, logScale=False, cmap='magma', figsize=(5.5, 4.5),
)
Returned peak counts: [0 1 2 3 4 6]
Overlay example scan index: (0, 1)
Detecting peaks: 0%| | 0/150 [00:00<?, ?it/s]
Detecting peaks: 100%|██████████| 150/150 [00:00<00:00, 3332.23it/s]
6. Refine each pattern’s own peak seeds¶
The ragged detections become the local seeds for get_centers(). CoM refinement is quick; Gaussian and elliptical-Gaussian fits are alternative refinement_method choices when their models suit the spots. A fitted center is not automatically accurate: background, overlap, saturation, and an incorrect seed can bias it. No common peak count or ordering across patterns is imposed.
Refined centers stay in absolute (y, x) pixels. That is also the convention for show(coords=…) and intensity integration, even with calibrated display axes. The optional printed calibrated coordinates below instead use y-up/x-right offsets about the geometric detector midpoint; an off-center search origin does not redefine that display frame.
all_centers = data.get_centers(r=refinement_radius_px, ref_coords=all_peak_coords,
method=refinement_method, real_mask=scan_mask)
for i, j in np.ndindex(ry, rx):
assert np.asarray(all_centers[i][j]).shape == (peak_count_map[i, j], 2)
sample_centers = np.asarray(all_centers[sample_index[0]][sample_index[1]])
print('First refined centers (absolute y, x pixels):', sample_centers[:3])
if data.reciprocal_conv_factor is not None and data.reciprocal_units is not None:
midpoint = (np.asarray((ky, kx)) - 1) / 2
calibrated_centers = (sample_centers - midpoint) * np.array([-1, 1]) * data.reciprocal_conv_factor
print('Corresponding displayed y-up/x-right coordinates:', calibrated_centers[:3], data.reciprocal_units)
data.get_dp(*sample_index, selection_units='pixels').show(
title='Refined subpixel peak positions', coords=sample_centers, c='cyan', marker='+', s=60,
axis_units='auto', power=0.4, logScale=False, cmap='magma', figsize=(5.5, 4.5),
)
First refined centers (absolute y, x pixels): [[29.83687943 13.66312057]
[15.12543554 24.12195122]
[16.8302583 41.9704797 ]]
Corresponding displayed y-up/x-right coordinates: [[ 0.41578014 -4.45921986]
[ 4.09364111 -1.8445122 ]
[ 3.66743542 2.61761993]] mrad
Computing centers (4D): 0%| | 0/10 [00:00<?, ?it/s]
Computing centers (4D): 100%|██████████| 10/10 [00:00<00:00, 761.19it/s]
7. Integrate intensities and audit one circular window¶
get_intensities(centers=…) sums original pixel values inside circles around the supplied refined centers. It returns a matching ragged collection. These are raw window sums including local background, not correlation scores, Gaussian amplitudes, or calibrated reciprocal-area integrals. Windows are clipped at detector boundaries. Their radius is in pixels.
The explicit NumPy calculation verifies one window. If integration circles overlap, their sums can double-count pixels; summing peak-window intensities is not a unique-area Bragg intensity fraction. Missing detections and a changed radius also change that sum.
all_intensities = data.get_intensities(r=integration_radius_px, centers=all_centers,
compute_resBg=False, real_mask=scan_mask)
for i, j in np.ndindex(ry, rx):
assert len(all_intensities[i][j]) == peak_count_map[i, j]
if len(sample_centers):
rows, cols = np.indices((ky, kx))
one_window = np.hypot(rows - sample_centers[0, 0], cols - sample_centers[0, 1]) <= integration_radius_px
expected_sum = data.array[sample_index][one_window].sum(dtype=np.float64)
np.testing.assert_allclose(all_intensities[sample_index[0]][sample_index[1]][0], expected_sum)
print('First raw peak-window sum:', expected_sum, 'from', int(one_window.sum()), 'pixels')
else:
print('No peaks detected: review template and threshold settings before integrating.')
First raw peak-window sum: 287.0 from 29 pixels
Row: 0%| | 0/10 [00:00<?, ?it/s]
Row: 100%|██████████| 10/10 [00:00<00:00, 724.07it/s]
8. Optional local-background correction, explicitly defined¶
Here we request the mean intensity in a ring around each peak, multiplied by the actual integration-window pixel count, and subtract all of that estimate with residual_frac=1. The API default fraction is 0.9; we override it deliberately. r_spots is the background ring’s inner/outer radius, not the detector-wide analysis annulus.
A nearby ring estimates background only if it avoids neighbors and represents the local background under the peak. A broad diffuse ring can violate that approximation. Corrected values can be negative and are not clipped here. This operation does not modify the diffraction data, peak detections, or subsequent Braggness input.
corrected_intensities = data.get_intensities(
r=integration_radius_px, centers=all_centers, real_mask=scan_mask,
compute_resBg=True, residual_frac=1.0, r_spots=background_ring_px, bg_method='rings',
)
if len(sample_centers):
values = np.asarray(all_intensities[sample_index[0]][sample_index[1]])
corrected = np.asarray(corrected_intensities[sample_index[0]][sample_index[1]])
fig, ax = plt.subplots(figsize=(7, 3.5), constrained_layout=True)
indices = np.arange(len(values))
ax.bar(indices - 0.18, values, width=0.36, label='Raw window sum')
ax.bar(indices + 0.18, corrected, width=0.36, label='Local-background corrected')
ax.set(xlabel='Peak index within this pattern only', ylabel='Integrated intensity',
title='Background model changes the measured intensity', xticks=indices)
ax.margins(y=0.25)
ax.legend(fontsize=8)
plt.show()
Row: 0%| | 0/10 [00:00<?, ?it/s]
Row: 100%|██████████| 10/10 [00:00<00:00, 324.64it/s]
9. Inspect threshold sensitivity instead of equating peaks with phase¶
The same pattern is detected at half, the chosen, and twice the correlation threshold. The synthetic comparison uses one weak-spot and one diffuse pattern; an external input uses the selected example pattern. Low thresholds can admit noise maxima, while high thresholds miss weak spots. These examples alter only detection settings, not the stored data.
The correlation itself is computed using FFT convolution internally, but we are not counting peaks in an FFT of the diffraction pattern or defining an FFT crystallinity index. Sixfold symmetry is deliberately disabled: the observation need not contain a complete hexagon, and repair would add assumed peaks rather than measured evidence.
threshold_examples = [(ry // 2, rx // 2), (ry // 2, rx - 2)] if is_synthetic else [sample_index]
threshold_values = peak_threshold_abs * np.array([0.5, 1.0, 2.0])
fig, axes = plt.subplots(len(threshold_examples), 3, figsize=(10, 3.2 * len(threshold_examples)),
squeeze=False, constrained_layout=True)
for row_index, scan_index in enumerate(threshold_examples):
dp = data.get_dp(*scan_index, selection_units='pixels')
shown = np.maximum(dp.array, 0)**0.4
for ax, threshold in zip(axes[row_index], threshold_values):
settings = {**peak_kwargs, 'threshold_abs': float(threshold)}
found = dp.get_peaks(**settings)
ax.imshow(shown, cmap='magma', vmin=0, vmax=float(shown.max()))
if len(found):
ax.scatter(found[:, 1], found[:, 0], c='cyan', marker='+', s=30)
ax.set(title='Threshold {:.0f}: {} peaks'.format(threshold, len(found)),
xlabel='Detector column (pixels)', ylabel='Detector row (pixels)')
fig.suptitle('Threshold sensitivity: weak spots and noise can both change the count')
plt.show()
dp = None
10. Check detected positions against known coordinates when available¶
For this well-separated synthetic fixture, we assign refined centers one-to-one to analytical coordinates by minimum distance, then accept pairs within one pixel. We compare integer and refined errors on those same pairs. Precision/recall summarize matches, unmatched detections, and missed reference peaks across evaluated positions. Empty patterns and variable counts are allowed.
This diagnostic is not indexing or a production strain matcher. A distance gate, ambiguous overlaps, poor registration, and reference completeness affect its interpretation. External data without explicitly supplied reference coordinates skip this section; a visually convincing overlay does not provide a numerical ground-truth error. Synthetic-only tolerances below validate this fixture, not a universal detection standard.
coarse_errors, refined_errors = [], []
if reference_peaks is not None:
matched = detected_total = reference_total = 0
for i, j in np.ndindex(ry, rx):
if not scan_mask[i, j]:
continue
actual, reference = np.asarray(all_centers[i][j]), reference_peaks[i][j]
detected_total += len(actual)
reference_total += len(reference)
if len(actual) and len(reference):
distances = np.linalg.norm(actual[:, None, :] - reference[None, :, :], axis=-1)
rows, cols = linear_sum_assignment(distances)
keep = distances[rows, cols] <= 1.0
rows, cols = rows[keep], cols[keep]
matched += len(rows)
refined_errors.extend(distances[rows, cols])
coarse_errors.extend(np.linalg.norm(all_peak_coords[i][j][rows] - reference[cols], axis=-1))
precision = matched / detected_total if detected_total else np.nan
recall = matched / reference_total if reference_total else np.nan
print('Reference matches:', matched, 'Detected:', detected_total, 'Reference:', reference_total)
print('Precision:', precision, 'Recall:', recall)
if refined_errors:
print('Mean paired localization error (pixels): integer={:.3f}, refined={:.3f}'.format(
np.mean(coarse_errors), np.mean(refined_errors)))
fig, ax = plt.subplots(figsize=(7, 3.5), constrained_layout=True)
bins = np.linspace(0, max(1.5, max(coarse_errors)), 25)
ax.hist(coarse_errors, bins=bins, alpha=0.6, label='Integer detections')
ax.hist(refined_errors, bins=bins, alpha=0.6, label='Refined centers, same pairs')
ax.set(xlabel='Distance from known coordinate (pixels)', ylabel='Matched peaks',
title='Localization diagnostics for accepted reference pairs')
ax.legend(fontsize=8)
plt.show()
if is_synthetic:
assert precision > 0.9 and recall > 0.9
assert np.mean(refined_errors) < np.mean(coarse_errors)
else:
print('No registered reference peaks: skipping known-position accuracy checks.')
Reference matches: 490 Detected: 494 Reference: 494
Precision: 0.9919028340080972 Recall: 0.9919028340080972
Mean paired localization error (pixels): integer=0.419, refined=0.205
11. Braggness: a separate, detection-free measurement¶
For each full diffraction pattern D, form the positive residual R = maximum(D - Gaussian(D), 0). Select an annulus, sum its bragg_top_pixels largest residuals, and divide by max(sum(D in that annulus), 1). The Gaussian acts on the complete detector before annulus selection; neighboring scan positions are never mixed.
This does not use the detected peak coordinates or their integrated intensities. It measures how concentrated the sharp positive contrast is for the chosen settings. The annulus uses inner <= radius < outer; its outer bound is exclusive, unlike some other detector APIs. Radii, center, and Gaussian sigma are pixels, even with reciprocal calibration. The score is dimensionless but is not guaranteed to be in [0, 1].
With center=None, current beam metadata is preferred, otherwise the subpixel image midpoint is used. An explicit center overrides metadata. We print the resolved center/source rather than silently assuming every acquisition is centered. Skipped patterns become NaN and invalid; nonfinite=’raise’ rejects nonfinite evaluated input, rather than repairing it.
braggness = data.get_braggness(
annulus=tuple(bounds), center=analysis_center_px, sigma=bragg_sigma_px,
top_pixels=bragg_top_pixels, denominator_floor=1.0, scan_mask=scan_mask,
nonfinite='raise', progress=False,
)
np.testing.assert_array_equal(braggness.valid_mask, scan_mask)
assert np.all(np.isnan(braggness.score[~scan_mask]))
assert braggness.score.shape == (ry, rx) and braggness.score.dtype == np.float32
print('Resolved center:', braggness.metadata['center'])
print('Center source:', braggness.metadata['center_source'])
print('Evaluated/skipped:', braggness.metadata['evaluated_patterns'], braggness.metadata['skipped_patterns'])
score_view = braggness.as_real_space()
assert score_view.units == data.real_units
np.testing.assert_allclose(score_view.origin, data.real_origin)
if data.real_conv_factor is not None:
np.testing.assert_allclose(score_view.conv_factor, data.real_conv_factor)
Resolved center: [31.5, 31.5]
Center source: image_center
Evaluated/skipped: 149 1
12. Audit the formula on one complete pattern¶
This explicit calculation uses the same full-pattern Gaussian and pixel convention to verify the scalar score. The last panel marks the selected brightest residual pixels, which need not coincide with every detected peak. The green circles mark the analysis annulus. Display power is only a visualization transform, not part of the score formula. No logarithm or FFT-derived peak count enters the score.
calculation_dtype = np.float32 if data.array.dtype.kind == 'f' and data.array.dtype.itemsize <= 4 else np.float64
pattern = np.asarray(data.array[sample_index], dtype=calculation_dtype)
smoothed = gaussian_filter(pattern, sigma=bragg_sigma_px, mode='reflect', truncate=4.0)
positive_residual = np.maximum(pattern - smoothed, 0)
resolved_center = np.asarray(braggness.metadata['center'])
rows, cols = np.indices((ky, kx))
distance = np.hypot(rows - resolved_center[0], cols - resolved_center[1])
annulus_mask = (distance >= bounds[0]) & (distance < bounds[1])
annular_coords = np.argwhere(annulus_mask)
residual_values = positive_residual[annulus_mask]
selected = np.argpartition(residual_values, len(residual_values) - bragg_top_pixels)[-bragg_top_pixels:]
top_coords = annular_coords[selected]
numerator = residual_values[selected].sum(dtype=np.float64)
denominator = max(pattern[annulus_mask].sum(dtype=np.float64), 1.0)
np.testing.assert_allclose(braggness.score[sample_index], numerator / denominator, rtol=2e-6)
print('Sharp-contrast numerator:', numerator, 'Annular denominator:', denominator)
fig, axes = plt.subplots(1, 3, figsize=(11, 3.6), constrained_layout=True)
display_max = float(pattern.max())**0.4
for ax, image, label in zip(axes, (pattern, smoothed, positive_residual),
('Original pattern', 'Full-pattern Gaussian', 'Positive residual + selected pixels')):
ax.imshow(image**0.4, cmap='magma', vmin=0, vmax=display_max)
for radius in bounds:
ax.add_patch(plt.Circle((resolved_center[1], resolved_center[0]), radius,
fill=False, color='lime', linewidth=0.8, alpha=0.6))
ax.set(title=label, xlabel='Detector column (pixels)', ylabel='Detector row (pixels)')
ax.title.set_fontsize(10)
axes[-1].scatter(top_coords[:, 1], top_coords[:, 0], s=6, c='cyan', alpha=0.7)
plt.show()
Sharp-contrast numerator: 636.6982817649841 Annular denominator: 3858.0
13. Three complementary real-space maps¶
Detected peaks: how many template maxima passed the selected threshold and separation rule. Peak-window sum: the sum of raw integration-window values for those detections, including background and possible overlapping-window double-counts. Braggness: concentrated sharp positive contrast measured directly from the original selected diffraction data, independently of detection.
Gray positions are skipped, not zero. A zero-peak evaluated pattern can still have diffuse signal and a nonzero Braggness score. Bright spots can indicate ordered scattering, but counts and sharp contrast also depend on orientation, thickness, exposure, noise, artifacts, saturation, and analysis choices. Do not label these maps as a measured crystalline volume fraction. The axes and optional scale bars come from the selected dataset’s real-space metadata, not invented external defaults.
peak_sum_map = np.array([[np.sum(values, dtype=np.float64) for values in row] for row in all_intensities])
count_view = RealSpace(np.where(scan_mask, peak_count_map, np.nan), units=data.real_units,
conv_factor=data.real_conv_factor, origin=data.real_origin, quantity='Detected peaks')
sum_view = RealSpace(np.where(scan_mask, peak_sum_map, np.nan), units=data.real_units,
conv_factor=data.real_conv_factor, origin=data.real_origin, quantity='Raw peak-window sum')
fig, axes = plt.subplots(1, 3, figsize=(13, 3.2), constrained_layout=True)
for ax, view, title, cmap_name in zip(axes, (count_view, sum_view, score_view),
('Detected peaks', 'Peak-window sum', 'Braggness'),
('cividis', 'magma', 'viridis')):
cmap = plt.colormaps[cmap_name].copy()
cmap.set_bad('0.8')
maximum = float(np.nanmax(view.array))
display_maximum = maximum if maximum > 0 else 1.0
view.show(ax=ax, show=False, title=title, cmap=cmap, vmin=0, vmax=display_maximum, axis_units='auto',
colorbar=False, grid_ticks=(4, 4))
fig.colorbar(ax.images[-1], ax=ax, label=view.quantity, shrink=0.7)
plt.show()
if is_synthetic:
for label in range(3):
selected_region = (region == label) & scan_mask
print('Assigned region', label, 'mean detected peaks:', peak_count_map[selected_region].mean(),
'mean Braggness:', braggness.score[selected_region].mean())
Assigned region 0 mean detected peaks: 6.0 mean Braggness: 0.1698239
Assigned region 1 mean detected peaks: 3.92 mean Braggness: 0.09500555
Assigned region 2 mean detected peaks: 0.08 mean Braggness: 0.04620047
14. Keep validity separate from a score threshold¶
If you experiment with a threshold or morphological segmentation later, keep the valid mask in every operation. The example below selects scores at or above their 75th percentile among valid positions only. Ties can select more than a quarter, including every position in a constant-score map. This arbitrary exploratory rule is not a calibrated material classification. Zero detections do not mark a position invalid.
valid_scores = braggness.score[braggness.valid_mask]
exploratory_threshold = np.percentile(valid_scores, 75)
high_score_mask = braggness.valid_mask & (braggness.score >= exploratory_threshold)
assert not high_score_mask[~scan_mask].any()
print('Valid positions with zero detections:', int(np.count_nonzero(scan_mask & (peak_count_map == 0))))
print('Exploratory 75th-percentile threshold:', exploratory_threshold)
print('Selected valid positions:', int(high_score_mask.sum()), '(not a crystalline fraction)')
# After any later morphological refinement, apply: refined_mask &= braggness.valid_mask
Valid positions with zero detections: 47
Exploratory 75th-percentile threshold: 0.15785765647888184
Selected valid positions: 38 (not a crystalline fraction)
15. Reuse an alignment center without modifying the original analysis¶
If your selected input already came from alignment(), the preceding detection and Braggness calls already used its stored center when analysis_center_px=None. This separate example produces an aligned copy and omits center when scoring it, verifying that the aligned object’s current metadata is used. It does not replace data or rerun the original known-coordinate comparisons on transformed positions.
The default synthetic Gaussian beam suits CoM alignment. For external data, this example is disabled unless explicitly enabled with an inspected alignment_radius_px; other beam shapes may require the disk/negative-trench/Gaussian workflows from Tutorial 3. All pixels must be finite for this full alignment call, including positions skipped by the analysis mask.
COM metadata records the chosen central window radius, not an independently fitted physical disk edge. Inspect it before using it as a blocking radius. block_direct_beam(fill_value=0) then uses that radius and center automatically; explicit inputs can override them. Braggness is evaluated on the unblocked aligned copy, not on its display-only blocked counterpart. Alignment resamples intensities, so the resulting score is a different measurement from the original data and need not be identical.
aligned_example = aligned_braggness = blocked_example = None
if run_alignment_example:
if alignment_radius_px is None:
raise ValueError('Set alignment_radius_px after inspecting your external central beam.')
if not np.all(np.isfinite(data.array)):
raise ValueError('This separate alignment example needs finite values in every diffraction pattern.')
aligned_example = data.alignment(method='com', r_center=alignment_radius_px,
center=tuple(resolved_center), iterations=1)
aligned_braggness = aligned_example.get_braggness(
annulus=tuple(bounds), sigma=bragg_sigma_px, top_pixels=bragg_top_pixels,
scan_mask=scan_mask, nonfinite='raise',
)
assert aligned_braggness.metadata['center_source'] == 'center_beam_metadata.center_px'
np.testing.assert_allclose(aligned_braggness.metadata['center'],
aligned_example.center_beam_metadata['center_px'])
print('Aligned center and source:', aligned_braggness.metadata['center'],
aligned_braggness.metadata['center_source'])
blocked_example = aligned_example.block_direct_beam(fill_value=0)
blocked_example.get_dp(*sample_index, selection_units='pixels').show(
title='Beam blocked using alignment metadata', axis_units='auto',
power=0.4, logScale=False, cmap='magma', figsize=(5.5, 4.5),
)
else:
print('Separate alignment demonstration disabled for this external input.')
Initial COM standard deviation (ky, kx): (0.0396, 0.0400)
Initial COM (ky, kx): (31.4982, 31.5010)
Processing 10 × 15 real-space positions. Iteration (1/1)...
Iteration 1 COM standard deviation (ky, kx): (0.0038, 0.0039)
Iteration 1 COM (ky, kx): (31.4999, 31.5002)
Final COM standard deviation (ky, kx): (0.0038, 0.0039)
Final COM (ky, kx): (31.4999, 31.5002)
Aligned center and source: [31.5, 31.5] center_beam_metadata.center_px
Alignment Progress: 0%| | 0/10 [00:00<?, ?it/s]
Alignment Progress: 100%|██████████| 10/10 [00:00<00:00, 1102.60it/s]
16. Export ragged results as numeric tables, not pickle¶
This small tutorial interchange file stores flat centers/intensities with per-pattern counts and row-major offsets, the scan mask, Braggness arrays, and JSON settings. allow_pickle=False can reload it. An offset pair retrieves one pattern’s variable-length entries. Coordinate units/order and spatial calibration are explicit. This NPZ is not a native HyperData file or the source API’s peak-file format.
For larger acquisitions, use DiffractionSource.get_peaks(destination=…) to write the package’s numeric peak collection directly, rather than building all these eager lists or concatenating them. The export here retains no diffraction-pattern copy and is removed with the tutorial’s temporary directory.
flat_counts = peak_count_map.ravel()
offsets = np.r_[0, np.cumsum(flat_counts, dtype=np.int64)]
flat_centers = np.concatenate([all_centers[i][j] for i, j in np.ndindex(ry, rx)], axis=0)
flat_intensities = np.concatenate([all_intensities[i][j] for i, j in np.ndindex(ry, rx)])
settings = {
'coordinate_order': 'y,x', 'coordinate_units': 'absolute detector pixels',
'peak_detection': {'radius_px': float(peak_template_radius_px),
'min_distance_px': int(peak_min_distance_px),
'threshold_abs': float(peak_threshold_abs), 'r_range_px': bounds.tolist(),
'center_argument_px': None if analysis_center_px is None else np.asarray(analysis_center_px).tolist(),
'symmetry': 'none'},
'refinement_radius_px': float(refinement_radius_px), 'refinement_method': refinement_method,
'integration_radius_px': float(integration_radius_px), 'intensities': 'raw circular-window sums',
'braggness': braggness.metadata, 'real_units': data.real_units,
'real_conv_factor': None if data.real_conv_factor is None else np.asarray(data.real_conv_factor).tolist(),
'real_origin': np.asarray(data.real_origin).tolist(),
'reciprocal_units': data.reciprocal_units,
'reciprocal_conv_factor': None if data.reciprocal_conv_factor is None else float(data.reciprocal_conv_factor),
}
export_path = work_dir / 'peak_analysis_results.npz'
np.savez_compressed(export_path, centers=flat_centers, intensities=flat_intensities,
counts=peak_count_map, offsets=offsets, scan_mask=scan_mask,
braggness=braggness.score, valid_mask=braggness.valid_mask,
settings_json=np.array(json.dumps(settings)))
with np.load(export_path, allow_pickle=False) as saved:
flat_index = np.ravel_multi_index(sample_index, (ry, rx))
start, stop = saved['offsets'][flat_index:flat_index + 2]
np.testing.assert_array_equal(saved['centers'][start:stop], sample_centers)
np.testing.assert_array_equal(saved['counts'], peak_count_map)
np.testing.assert_array_equal(saved['scan_mask'], scan_mask)
assert json.loads(str(saved['settings_json']))['coordinate_order'] == 'y,x'
print('Numeric ragged export round trip passed:', export_path.name)
Numeric ragged export round trip passed: peak_analysis_results.npz
17. Moving to your data¶
Select the input in section 3, confirm detector geometry and calibration, explicitly choose the analysis annulus, and review all detector/window settings. Existing alignment beam metadata is reused unless you provide an explicit center. A scalar center does not model scan-dependent beam drift; align or otherwise calibrate that drift before interpreting radial selection.
Keep peak detection, subpixel refinement, raw/background-corrected intensity, and Braggness separate. They answer different questions and respond differently to noise and exposure. Check overlays across strong, weak, diffuse, and problematic patterns; do not impose hexagonal symmetry on a mixed or unknown structure. Retain validity after thresholds or morphological operations.
Known-coordinate metrics are skipped for external data without an explicitly supplied registered reference. Default CI validates the generated fixture, not an original microscope acquisition or a physical crystalline fraction. See using your own data, peaks and strain, and Braggness. Continue with Tutorial 6: Strain mapping and R/Q calibration.
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)
aligned_example = aligned_braggness = blocked_example = None
plt.close('all')
workspace.cleanup()
print('Checks passed; selected input unchanged and temporary outputs removed.')
Checks passed; selected input unchanged and temporary outputs removed.