6. Strain mapping and R/Q calibration¶
Fit variable-length peak sets, inspect failures, and distinguish where a map pixel is from which directions its strain components describe. This independent lesson uses small, reproducible synthetic hexagonal diffraction patterns and known subpixel peak coordinates. It needs no microscope file or scattering simulator. The fixture tests coordinate conventions and fitting, not a physical material or an instrument calibration.
You will obtain detector-frame and verified real-frame strain, inspect matched peaks and residuals, compare weighted fits, check pixel/calibrated-coordinate equivalence, and export compact results with their frame metadata. A marked input cell can later accept an acquisition, simulation array, or existing HyperData, together with its own measured/reference peaks. Never reuse the synthetic reference, beam center, or R/Q calibration for experimental data.
Prerequisites: Tutorials 1, 3, and 5 are useful, but no files from them are required. Restart the kernel and run all cells. Default runs use core dependencies and a Jupyter kernel. Interactive R/Q calibration is explained separately and is not required for execution.
Note
Synthetic teaching data, not experimental validation. Code and figures below come from a validated fresh-kernel run.
Download the clean notebook or read the lesson overview.
%matplotlib inline
import hashlib
import json
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from time import perf_counter
import matplotlib.pyplot as plt
import numpy as np
import fourdenoise as fd
from fourdenoise import HyperData, RealSpace, RQCalibration
print('Python:', sys.executable)
print('4Denoise:', fd.__file__)
temporary_output = TemporaryDirectory(prefix='4denoise-tutorial-06-')
output_dir = Path(temporary_output.name)
Python: /opt/hostedtoolcache/Python/3.11.17/x64/bin/python
4Denoise: /home/runner/work/4Denoise/4Denoise/fourdenoise.py
1. Three coordinate conventions, kept separate¶
Data axes are (Ry, Rx, Ky, Kx). Supplied peak columns are always (ky, kx), never (x, y). Absolute pixel rows increase downward; calibrated ky increases upward. R/Q orientation matrices instead use Cartesian (x, y), x right and y up. The small matrix P below maps centered pixel (y, x) column vectors to Cartesian (x, y).
The known R/Q matrix G maps real-space directions into detector directions: optional real-frame reflection first, then a counterclockwise rotation. It does not convert lengths into inverse lengths. We deliberately choose 37 degrees and a reflection about x, rather than using a 90-degree correction to swap map names. A regular hexagon alone cannot determine a unique R/Q angle or handedness: this calibration is known because we constructed it.
get_strains fits a reference-to-measured reciprocal transform A, then uses its right polar decomposition A = R U. For real-frame output, the reported symmetric tensor is I - U, with rotation from R in radians. This is the package’s reciprocal-stretch strain convention, appropriate as a small-deformation approximation, not a claim that it equals a finite direct-lattice strain measure. The fixture is constructed using exactly this definition. No map is mean-centered or rotated to make it look correct.
rng = np.random.default_rng(2030)
synthetic_scan_shape = (8, 12)
synthetic_pattern_shape = (64, 64)
synthetic_center_px = np.array([31.2, 30.6]) # Deliberately subpixel and off-center.
synthetic_rq = RQCalibration(37.0, 'x', source='synthetic_known')
P = np.array([[0.0, 1.0], [-1.0, 0.0]])
G = synthetic_rq.matrix
def rotation_matrix(angle_rad):
c, s = np.cos(angle_rad), np.sin(angle_rad)
return np.array([[c, -s], [s, c]])
sy, sx = np.meshgrid(np.linspace(-1, 1, 8), np.linspace(-1, 1, 12), indexing='ij')
strain_truth = {
'exx': -0.018 * np.exp(-((np.abs(sx) - 0.6) / 0.28)**2),
'eyy': 0.012 * np.cos(np.pi * sy),
'exy': 0.004 * np.sin(np.pi * sx) * np.cos(np.pi * sy / 2),
'erot': np.deg2rad(1.5 * np.sin(np.pi * sx) + 0.5 * sy),
}
phi = np.arange(6) * np.pi / 3 + np.deg2rad(12)
reference_real_xy = 18 * np.column_stack((np.cos(phi), np.sin(phi)))
synthetic_reference = synthetic_center_px + reference_real_xy @ G.T @ P
synthetic_exact = np.empty((8, 12, 6, 2))
synthetic_measured = [[None for _ in range(12)] for _ in range(8)]
synthetic_intensities = [[None for _ in range(12)] for _ in range(8)]
synthetic_array = np.empty((8, 12, 64, 64), dtype=np.float32)
yy, xx = np.ogrid[:64, :64]
for index in np.ndindex(synthetic_scan_shape):
i, j = index
E = np.array([[strain_truth['exx'][index], strain_truth['exy'][index]],
[strain_truth['exy'][index], strain_truth['eyy'][index]]])
A_real = rotation_matrix(strain_truth['erot'][index]) @ (np.eye(2) - E)
shift_px = np.array([0.10 * sy[index], 0.08 * sx[index]])
positions = synthetic_center_px + reference_real_xy @ A_real.T @ G.T @ P + shift_px
synthetic_exact[index] = positions
keep = np.arange(6) != ((i + j) % 6) if (i + j) % 3 == 0 else np.ones(6, dtype=bool)
local = positions[keep].copy()
weights = np.linspace(25, 70, 6)[keep]
local += rng.normal(size=local.shape) * (0.018 * np.sqrt(70 / weights[:, None]))
if (i + 2 * j) % 7 == 0:
local = np.vstack((local, [4.0, 5.0])) # Unrelated, outside the matching gate.
weights = np.r_[weights, 3.0]
order = rng.permutation(len(local))
synthetic_measured[i][j], synthetic_intensities[i][j] = local[order], weights[order]
pattern = 1.5 + 100 * np.exp(-((yy - synthetic_center_px[0])**2 + (xx - synthetic_center_px[1])**2) / 8)
for (y, x), amplitude in zip(local, weights):
pattern += amplitude * np.exp(-((yy - y)**2 + (xx - x)**2) / (2 * 1.1**2))
synthetic_array[index] = np.clip(pattern + rng.normal(0, 0.12, (64, 64)), 0, None)
synthetic_measured[0][1] = synthetic_measured[0][1][:1] # Deliberately underdetermined input.
synthetic_intensities[0][1] = synthetic_intensities[0][1][:1]
synthetic_data = HyperData(synthetic_array, real_units='nm', real_conv_factor=(2.0, 3.0),
real_origin=(0.0, 0.0), reciprocal_units='inverse_angstrom',
reciprocal_conv_factor=0.04,
center_beam_metadata={'center_px': synthetic_center_px.tolist(),
'radius_px': 4.0, 'shape': (64, 64)})
print('Synthetic fixture:', synthetic_data.shape, 'No active R/Q calibration yet:', synthetic_data.rq_calibration)
Synthetic fixture: (8, 12, 64, 64) No active R/Q calibration yet: None
2. Replaceable data and peak inputs¶
Leave both data inputs None for the synthetic run. Otherwise select exactly one existing HyperData/numerical array or file. In-memory HyperData is copied with its own metadata; bare arrays receive only explicit calibration. Native loading is eager; the 64-MiB guard does not cap total RAM or prevent an earlier eager file load. Use read-only sources for large acquisitions.
For external data, supply measured_peaks_input as nested [Ry][Rx] arrays (n_i, 2), and reference_peaks_input as a global (n_ref, 2) array or a matching nested grid. Empty entries have shape (0, 2). Tutorial 5’s refined centers can be the measured input; its noisy measured peaks are not automatically an unstrained reference. A reference must represent the intended lattice state, phase, calibration, center, and orientation. Simulated peak units and handedness must first be reconciled with the measurement.
peak_units_input=’pixels’ means absolute downward-positive (y, x) detector pixels. ’calibrated’ means upward-positive (ky, kx) in the dataset’s reciprocal units. Do not mix these. strain_center_input=None uses existing beam metadata; this lesson requires an explicit center if external data has no beam metadata. Matching gates and translations use the same units as the peak coordinates. A coarse rotation guess guides matching but is not removed from the final fitted rotation. This lesson does not search a full symmetry/orientation domain.
Intensity weights are optional measured-peak integrated intensities, in each measured array’s exact order, not detector-template scores. They influence least squares but do not establish a statistical noise model. Keep the default intensity percentile None unless you intentionally want to discard tails. rq_verified is a user declaration, not an automatic validation. Only enable real-frame reporting after independently verifying the stored orientation or supplying verified values. Vendor scan-rotation metadata alone is insufficient.
input_data = None
input_origin = 'experimental' # Or 'simulation'.
microscope_path = None
microscope_backend = 'native'
microscope_options = {}
microscope_calibration = {}
max_tutorial_input_mb = 64
measured_peaks_input = None
reference_peaks_input = None
intensity_input = None
scan_mask_input = None
peak_units_input = 'pixels'
strain_center_input = None
match_radius_input = None # Synthetic: 1.5 pixels. External: None uses the library's spacing-based gate.
initial_rotation_input = None # Optional known Cartesian CCW degrees, scalar or scan-shaped.
intensity_percentile_input = None
rq_verified = False
verified_rq_angle_deg = None # None retains this input's existing orientation, if any.
verified_rq_mirror_axis = None
if input_data is not None and microscope_path is not None:
raise ValueError('Provide input_data or microscope_path, not both.')
if input_origin not in ('experimental', 'simulation'):
raise ValueError('input_origin must be experimental or simulation.')
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 (Ry, Rx, Ky, Kx) scan.')
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.')
print('Selected origin:', 'synthetic' if is_synthetic else input_origin)
print(data.metadata_summary())
Selected origin: synthetic
Current data shape: (8, 12, 64, 64)
Acquisition metadata: not available.
Current real-space calibration: (2.0, 3.0) 'nm' per pixel
Current reciprocal-space calibration: 0.04 'inverse_angstrom' per pixel
Current R/Q calibration: None
The next cell validates the scientific inputs separately from loading. The default fixture deliberately skips (0, 0) and supplies only one measured peak at (0, 1). The latter is an intentionally incomplete peak input, not evidence that the displayed pattern lacks other spots. It should fail to fit instead of returning zero strain. Missing/extra peaks elsewhere are left to the neighborhood-gated matcher. External inputs are not given either artificial exclusion.
ry, rx, ky, kx = data.shape
measured_peaks = measured_peaks_input if measured_peaks_input is not None else (synthetic_measured if is_synthetic else None)
reference_peaks = reference_peaks_input if reference_peaks_input is not None else (synthetic_reference if is_synthetic else None)
intensities = intensity_input if intensity_input is not None else (synthetic_intensities if is_synthetic else None)
if measured_peaks is None or reference_peaks is None:
raise ValueError('Supply measured_peaks_input and reference_peaks_input for your external data.')
def peak_collection(value, name, allow_global=False):
try:
candidate = np.asarray(value, dtype=float)
except (ValueError, TypeError):
candidate = None
if allow_global and candidate is not None and candidate.ndim == 2 and candidate.shape[1] == 2:
if not np.all(np.isfinite(candidate)) or len(candidate) < 3:
raise ValueError(name + ' needs at least three finite global reference peaks.')
return candidate.copy()
if len(value) != ry or any(len(row) != rx for row in value):
raise ValueError(name + ' must have a nested [Ry][Rx] layout.')
result = [[np.asarray(points, dtype=float).copy() for points in row] for row in value]
for row in result:
for points in row:
if points.ndim != 2 or points.shape[1] != 2 or not np.all(np.isfinite(points)):
raise ValueError(name + ' entries must be finite (n_peaks, 2); use (0, 2) for no peaks.')
return result
measured_peaks = peak_collection(measured_peaks, 'Measured peaks')
reference_peaks = peak_collection(reference_peaks, 'Reference peaks', allow_global=True)
if intensities is not None:
if len(intensities) != ry or any(len(row) != rx for row in intensities):
raise ValueError('Intensity weights must have a nested [Ry][Rx] layout.')
intensities = [[np.asarray(values, dtype=float).copy() for values in row] for row in intensities]
for i, j in np.ndindex(ry, rx):
values = intensities[i][j]
if (values.shape != (len(measured_peaks[i][j]),) or not np.all(np.isfinite(values))
or np.any(values < 0) or (values.size and not np.any(values > 0))):
raise ValueError('Intensity weights must match measured peaks and be finite, nonnegative, and not all zero.')
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.')
if peak_units_input not in ('pixels', 'calibrated'):
raise ValueError('peak_units_input must be pixels or calibrated.')
if peak_units_input == 'calibrated' and (data.reciprocal_units is None or data.reciprocal_conv_factor is None):
raise ValueError('Calibrated peak input requires verified reciprocal unit/scale metadata.')
if is_synthetic and peak_units_input != 'pixels':
raise ValueError('The built-in fixture supplies pixels; use the later calibrated-equivalence example instead.')
if strain_center_input is None and not data.center_beam_metadata:
raise ValueError('Supply strain_center_input or verified center_beam_metadata for this lesson.')
if not isinstance(rq_verified, (bool, np.bool_)):
raise ValueError('rq_verified must be an explicit boolean declaration.')
if verified_rq_angle_deg is not None and not rq_verified:
raise ValueError('Verify your R/Q calibration before supplying verified_rq_angle_deg.')
if verified_rq_mirror_axis is not None and verified_rq_angle_deg is None:
raise ValueError('Provide an explicit verified angle together with a new mirror setting.')
match_radius = 1.5 if is_synthetic and match_radius_input is None else match_radius_input
fit_options = dict(centers=measured_peaks, ref_centers=reference_peaks,
center=strain_center_input, peak_units=peak_units_input, real_mask=scan_mask,
match_peaks='auto', match_radius=match_radius, fit_translation=True, min_peak_pairs=3,
initial_rotation=initial_rotation_input, intensity_array=intensities,
intensity_percentile=intensity_percentile_input, return_transform=True)
original_pixels_digest = hashlib.sha256(data.array.tobytes()).hexdigest()
print('Requested scan positions:', int(scan_mask.sum()), 'Weighted fit:', intensities is not None)
Requested scan positions: 95 Weighted fit: True
if np.all(np.isfinite(data.array)) and np.all(data.array >= 0):
data.visualize(grid_shape=(min(2, ry), min(3, rx)), padding=0, power=0.4, figsize=(10, 7),
log_scale=False, cmap='magma', title='Selected input: averaged scan bins, not fitting inputs')
else:
print('Intensity preview skipped: nonfinite or negative intensities need an explicit display policy.')
print('Strain fitting below uses supplied peak coordinates, not the montage or a new detection pass.')
Strain fitting below uses supplied peak coordinates, not the montage or a new detection pass.
3. Fit in the detector frame first¶
Automatic matching makes a one-to-one assignment inside neighborhoods, allowing missing or extra peaks. It does not force every measured spot into the reference. The optional rotation guess is not a substitute for orientation matching when rotations are large or phases differ. Translation fitting avoids mistaking a beam shift for deformation and requires at least three non-collinear pairs. Reference degeneracy and insufficient matches remain invalid.
The beam center is omitted from this call when strain_center_input=None, so current alignment metadata supplies it. A center is an origin, not an R/Q calibration. Default detector components have exx along kx and eyy along ky. They are not automatically scan-direction components, even though the result arrays have shape (Ry, Rx).
start = perf_counter()
detector_result = data.get_strains(**fit_options, output_frame='reciprocal')
print(f'Detector fit: {perf_counter() - start:.3f} s')
print(detector_result)
print('Peak origin:', detector_result.peak_origin, 'Source:', detector_result.peak_origin_source)
print('Fit status counts:', dict(zip(*np.unique(detector_result.fit_status, return_counts=True))))
if not detector_result.valid_mask.any():
raise ValueError('No valid fits. Inspect units, reference state, center, initial rotation, and matching gate.')
assert detector_result.exx.shape == (ry, rx)
assert np.all(np.isnan(detector_result.exx[~detector_result.valid_mask]))
Detector fit: 0.086 s
StrainResult(shape=(8, 12), output_frame='reciprocal', real_units='nm', diagnostics=True)
Peak origin: (31.2, 30.6) Source: center_beam_metadata.center_px
Fit status counts: {'insufficient_peaks': 1, 'masked': 1, 'success': 94}
Computing strain matrices: 0%| | 0/8 [00:00<?, ?it/s]
Computing strain matrices: 100%|██████████| 8/8 [00:00<00:00, 95.12it/s]
4. Store a verified orientation, then request real-frame components¶
The synthetic calibration below is exact by construction. For an external input, nothing is installed unless you explicitly supply verified values; an existing calibration is used for real output only when rq_verified=True. Changing R/Q metadata changes reporting directions, not detector pixels or scan positions. No explicit 90-degree strain-basis rotation is needed.
set_rq_calibration(rotation_deg=…, mirror_axis=…) stores a real-to-detector orientation. Rotation is Cartesian counterclockwise; reflecting about x negates y before rotation. The viewer’s displayed correction is the inverse direction (detector to real), so reuse viewer.calibration or viewer.apply(), not a guessed sign conversion. Do not interpret the mean Bragg pattern and an unrelated virtual image as matching shadow images.
if is_synthetic:
data.set_rq_calibration(calibration=synthetic_rq)
use_real_frame = True
else:
if verified_rq_angle_deg is not None:
data.set_rq_calibration(rotation_deg=verified_rq_angle_deg, mirror_axis=verified_rq_mirror_axis)
use_real_frame = bool(rq_verified and data.rq_calibration is not None)
if rq_verified and data.rq_calibration is None:
raise ValueError('rq_verified=True also requires an existing or explicitly supplied R/Q calibration.')
print('Stored R/Q:', data.rq_calibration)
print('Real-frame reporting enabled:', use_real_frame)
if not use_real_frame:
print('Reporting detector components only. Verify/store R/Q orientation to enable the real-frame branch.')
Stored R/Q: RQCalibration(rotation_deg=37.0, mirror_axis='x', source='synthetic_known')
Real-frame reporting enabled: True
if use_real_frame:
directions = data.rq_calibration.transform_vectors(np.eye(2))
fig, ax = plt.subplots(figsize=(5, 5), constrained_layout=True)
ax.axhline(0, color='0.8', linewidth=0.8)
ax.axvline(0, color='0.8', linewidth=0.8)
for vector, label, color in zip(directions, ('real x in detector frame', 'real y in detector frame'), ('tab:blue', 'tab:orange')):
ax.quiver(0, 0, *vector, angles='xy', scale_units='xy', scale=1, color=color, label=label)
ax.set(xlim=(-1.3, 1.3), ylim=(-1.3, 1.3), aspect='equal',
xlabel='Detector Cartesian x (right)', ylabel='Detector Cartesian y (up)',
title='Stored orientation, not a calibration measurement')
ax.legend(loc='lower center', fontsize=8)
plt.show()
np.testing.assert_allclose(directions @ directions.T, np.eye(2), atol=1e-12)
real_result = None
if use_real_frame:
real_result = data.get_strains(**fit_options, output_frame='real')
np.testing.assert_array_equal(real_result.valid_mask, detector_result.valid_mask)
np.testing.assert_allclose(real_result.fit_rmse, detector_result.fit_rmse, equal_nan=True)
np.testing.assert_allclose(real_result.diagnostics['transforms'],
detector_result.diagnostics['transforms'], equal_nan=True)
assert real_result.rq_calibration == data.rq_calibration
print('Real output uses:', real_result.rq_calibration)
print('Centered input (ky, kx) -> reporting (x, y):')
print(real_result.output_basis_matrix)
result = real_result if real_result is not None else detector_result
print('Selected reporting frame:', result.output_frame)
Real output uses: RQCalibration(rotation_deg=37.0, mirror_axis='x', source='synthetic_known')
Centered input (ky, kx) -> reporting (x, y):
[[-0.60181502 0.79863551]
[ 0.79863551 0.60181502]]
Selected reporting frame: real
Computing strain matrices: 0%| | 0/8 [00:00<?, ?it/s]
Computing strain matrices: 100%|██████████| 8/8 [00:00<00:00, 97.21it/s]
5. Read the maps without changing their meaning¶
exx, eyy, and exy are dimensionless: multiply by 100 only when you want percent strain. erot is in radians; use np.rad2deg(result.erot) for degrees. Positive real-frame erot is Cartesian counterclockwise. Reflections can reverse the detector/real rotation sign.
as_real_space() provides calibrated scan axes and origins. It does not convert detector components into real components and does not rotate image pixels. The titles below state the selected reporting frame. Gray entries are invalid or skipped, never zero-filled. Symmetric color limits aid comparison but do not remove any mean strain.
signed_cmap = plt.colormaps['RdBu_r'].with_extremes(bad='0.75')
strain_limit = max(float(np.nanpercentile(np.abs(np.stack([result.exx, result.eyy, result.exy])), 99)), 1e-6)
fig, axes = plt.subplots(2, 2, figsize=(11, 7), constrained_layout=True)
for ax, component in zip(axes.flat, ('exx', 'eyy', 'exy', 'erot')):
image = result.as_real_space(component)
limit = strain_limit if component != 'erot' else max(float(np.nanmax(np.abs(result.erot))), 1e-6)
image.show(ax=ax, show=False, cmap=signed_cmap, vmin=-limit, vmax=limit, num_div=3,
title=f'{component}: {result.output_frame} directions', colorbar=True,
colorbar_label='radians' if component == 'erot' else 'dimensionless strain')
plt.show()
if real_result is not None:
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6), constrained_layout=True)
limit = max(np.nanmax(np.abs(detector_result.exx)), np.nanmax(np.abs(real_result.exx)), 1e-6)
for ax, fitted in zip(axes, (detector_result, real_result)):
fitted.as_real_space('exx').show(ax=ax, show=False, cmap=signed_cmap, vmin=-limit, vmax=limit, num_div=3,
title=f'exx in {fitted.output_frame} directions', colorbar=True,
colorbar_label='dimensionless strain')
plt.show()
print('Identical scan layout and residuals; different tensor reporting directions.')
Identical scan layout and residuals; different tensor reporting directions.
6. Diagnose fits before interpreting strain¶
fit_rmse is the weighted final peak-position residual in the supplied coordinate units. relative_fit_rmse divides it by the weighted RMS reference radius. Neither is a confidence probability, phase assignment, nor proof of a correct pairing. With too few peaks, even a small residual can be misleading. Inspect match counts, validity, fit status, conditioning, and representative overlays together. Missing peaks are not the same as outliers rejected after fitting. Outlier rejection is off here so this baseline remains transparent.
A False scan mask is ‘not evaluated’; an evaluated but underdetermined fit has a different status. The validity plot below can show invalid zeros because it is explicitly a Boolean indicator, not a strain map.
fig, axes = plt.subplots(1, 3, figsize=(14, 3.8), constrained_layout=True)
for ax, component, title, cmap in zip(axes,
('match_counts', 'relative_fit_rmse', 'valid_mask'),
('Retained pairs', 'Relative fit RMSE', 'Successful fit = 1'),
('viridis', 'magma', 'gray')):
result.as_real_space(component).show(ax=ax, show=False, title=title, cmap=cmap, colorbar=True, num_div=3)
plt.show()
print('Statuses:', dict(zip(*np.unique(result.fit_status, return_counts=True))))
print('Median valid condition number:', np.nanmedian(result.condition_numbers[result.valid_mask]))
if is_synthetic:
assert result.fit_status[0, 0] == 'masked'
assert not result.valid_mask[0, 1]
assert result.match_counts[0, 1] == 0 and np.isnan(result.exx[0, 1])
assert result.valid_mask.sum() == ry * rx - 2
Statuses: {'insufficient_peaks': 1, 'masked': 1, 'success': 94}
Median valid condition number: 1.1274886570516385
7. Inspect transformed-reference overlaps¶
Blue circles are measured peaks, orange crosses are the reference after the fitted reference-to-measured transform. Faint gray crosses show the original reference. Every reference point is displayed, including ones without a measured partner; unmatched measured spots can remain visible away from the fitted lattice. This overlay is in the original supplied detector peak coordinates, even when strain is reported in real directions. Diagnostic transforms and translations deliberately stay in that input frame.
The following three representative successful fits have equal axes aspect. Different peak counts and omitted partners need not be errors. On real data, also inspect failed/high-residual cases; a few attractive examples cannot validate the whole scan.
valid_indices = np.argwhere(result.valid_mask)
chosen = valid_indices[np.linspace(0, len(valid_indices) - 1, min(3, len(valid_indices)), dtype=int)]
fig, axes = plt.subplots(1, len(chosen), figsize=(5 * len(chosen), 4.6), squeeze=False, constrained_layout=True)
for ax, (i, j) in zip(axes.flat, chosen):
ref = reference_peaks if isinstance(reference_peaks, np.ndarray) else reference_peaks[i][j]
measured = measured_peaks[i][j]
origin = np.asarray(result.peak_origin)
fitted = origin + (ref - origin) @ result.diagnostics['transforms'][i, j].T + result.diagnostics['translations'][i, j]
ax.scatter(ref[:, 1], ref[:, 0], marker='x', color='0.75', s=25, label='Reference before fit')
ax.scatter(measured[:, 1], measured[:, 0], facecolors='none', edgecolors='tab:blue', s=65, label='Measured')
ax.scatter(fitted[:, 1], fitted[:, 0], marker='x', color='tab:orange', s=45, label='Transformed reference')
if peak_units_input == 'pixels':
ax.invert_yaxis()
ax.set(aspect='equal', xlabel=f'kx ({result.peak_units})', ylabel=f'ky ({result.peak_units})',
title=f'Scan ({i}, {j}): {result.match_counts[i, j]} pairs')
ax.legend(fontsize=8, loc='best')
plt.show()
8. Compare with known truth, only for the synthetic fixture¶
These checks never run against an unknown acquisition or your simulation. The first row is the assigned real-frame strain, the second row is the fitted value, and the last row is fitted minus assigned. Noise and missing peaks prevent exact recovery. The fixture tolerance is not an experimental uncertainty estimate. The two synthetic exclusions remain NaN in the fitted/error rows.
The target tensor is I - U in the real frame; it is not an atomistic direct-lattice deformation recovered from a physical scattering simulation. For a true finite direct-lattice strain measure, derive and document the appropriate inverse-transpose reciprocal/direct relationship and chosen strain definition before interpreting large deformations.
if is_synthetic:
fig, axes = plt.subplots(3, 3, figsize=(12, 9), constrained_layout=True)
for column, name in enumerate(('exx', 'eyy', 'exy')):
target = strain_truth[name]
fitted = getattr(real_result, name)
residual = fitted - target
for row, (values, label, limit) in enumerate(((target, 'Assigned', 0.02),
(fitted, 'Recovered', 0.02),
(residual, 'Difference', 0.003))):
RealSpace(values, units=data.real_units, conv_factor=data.real_conv_factor, origin=data.real_origin).show(
ax=axes[row, column], show=False, title=f'{label} {name}', cmap=signed_cmap, num_div=2,
vmin=-limit, vmax=limit, colorbar=True, colorbar_label='dimensionless')
rmse = np.sqrt(np.nanmean(residual**2))
print(f'{name}: known-truth RMSE = {rmse:.6f}')
assert rmse < 0.003
plt.show()
rotation_error_deg = np.rad2deg(real_result.erot - strain_truth['erot'])
print('Rotation RMSE (degrees):', np.sqrt(np.nanmean(rotation_error_deg**2)))
assert np.sqrt(np.nanmean(rotation_error_deg**2)) < 0.15
else:
print('Known-truth maps and assertions skipped: external inputs have no assigned strain truth here.')
exx: known-truth RMSE = 0.000812
eyy: known-truth RMSE = 0.000692
exy: known-truth RMSE = 0.000543
Rotation RMSE (degrees): 0.03375782760710891
9. Compare weighting without assuming it is always better¶
When weights are supplied, their measured-peak indices follow matching. With intensity_percentile=None, no intensity tail is discarded. An optional percentile is the percentage removed, not retained: for example 10 with the default both-tail policy removes the lowest 5% and highest 5% locally. A bright misidentified peak can bias a weighted fit, and intensity need not be proportional to inverse localization variance.
Below we compare against an unweighted fit using the same matching options, with percentile filtering disabled for that comparison. The synthetic bar plot measures strain error against assigned truth, not just a residual on noisy data. A single noise realization does not prove one weighting policy is universally best. External data report only fit statistics, without pretending to have ground truth.
if intensities is not None:
unweighted_options = {**fit_options, 'intensity_array': None, 'intensity_percentile': None}
unweighted = data.get_strains(**unweighted_options, output_frame=result.output_frame)
print('Median weighted/unweighted relative fit RMSE:',
np.nanmedian(result.relative_fit_rmse), np.nanmedian(unweighted.relative_fit_rmse))
print('These residuals use different weighting objectives and are not directly comparable likelihoods.')
if is_synthetic:
labels = ('exx', 'eyy', 'exy')
error_weighted = [np.sqrt(np.nanmean((getattr(result, name) - strain_truth[name])**2)) for name in labels]
error_unweighted = [np.sqrt(np.nanmean((getattr(unweighted, name) - strain_truth[name])**2)) for name in labels]
fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
positions = np.arange(3)
ax.bar(positions - 0.18, error_unweighted, width=0.36, label='Unweighted')
ax.bar(positions + 0.18, error_weighted, width=0.36, label='Intensity weighted')
ax.set(xticks=positions, xticklabels=labels, ylabel='Known-truth RMSE (dimensionless)', title='One synthetic noise realization')
ax.legend()
plt.show()
else:
print('No intensity weights supplied; baseline is already unweighted.')
Median weighted/unweighted relative fit RMSE: 0.001106153122346563 0.0011468182041665018
These residuals use different weighting objectives and are not directly comparable likelihoods.
Computing strain matrices: 0%| | 0/8 [00:00<?, ?it/s]
Computing strain matrices: 100%|██████████| 8/8 [00:00<00:00, 105.05it/s]
10. Exact coordinate and calibration checks¶
With noise removed and complete peaks, a separate synthetic-only fit must recover the assigned tensor and rotation to numerical precision. The translation term is retained, so this also checks that a detector shift is not reported as strain. A second fit converts both reference and measured peaks into isotropically calibrated reciprocal coordinates. The sign of ky reverses, but real-frame components must agree. Residual units change from pixels to reciprocal units. This pixel equivalence check is deliberately limited to the fixture’s isotropic detector spacing.
No synthetic truth check is applied to an external file. For anisotropic detector pixels, physical-coordinate fitting requires the actual axis spacings; a strain measured in raw pixel geometry need not equal one measured in physically scaled coordinates.
if is_synthetic:
exact = data.get_strains(centers=synthetic_exact, ref_centers=synthetic_reference,
fit_translation=True, match_peaks='auto', match_radius=1.5,
output_frame='real')
for name in ('exx', 'eyy', 'exy', 'erot'):
np.testing.assert_allclose(getattr(exact, name), strain_truth[name], atol=2e-12)
assert exact.valid_mask.all()
np.testing.assert_allclose(exact.peak_origin, synthetic_center_px)
geometric_center = (np.array(data.pattern_shape) - 1) / 2
scale = float(data.reciprocal_conv_factor)
def pixel_to_calibrated(points):
return (np.asarray(points) - geometric_center) * np.array([-scale, scale])
calibrated_measured = [[pixel_to_calibrated(points) for points in row] for row in measured_peaks]
calibrated = data.get_strains(**{**fit_options, 'centers': calibrated_measured,
'ref_centers': pixel_to_calibrated(reference_peaks),
'peak_units': 'calibrated', 'center': None,
'match_radius': match_radius * scale}, output_frame='real')
for name in ('exx', 'eyy', 'exy', 'erot', 'relative_fit_rmse'):
np.testing.assert_allclose(getattr(calibrated, name), getattr(real_result, name), atol=2e-12, equal_nan=True)
np.testing.assert_allclose(calibrated.fit_rmse, real_result.fit_rmse * scale, atol=2e-12, equal_nan=True)
print('Exact tensor/rotation recovery and pixel/calibrated equivalence passed.')
else:
print('Exact fixture checks skipped for external inputs.')
Exact tensor/rotation recovery and pixel/calibrated equivalence passed.
Computing strain matrices: 0%| | 0/8 [00:00<?, ?it/s]
Computing strain matrices: 100%|██████████| 8/8 [00:00<00:00, 104.97it/s]
Computing strain matrices: 0%| | 0/8 [00:00<?, ?it/s]
Computing strain matrices: 100%|██████████| 8/8 [00:00<00:00, 98.17it/s]
11. Optional interactive R/Q verification on a real acquisition¶
Use a real-space image and a corresponding defocused CBED shadow image of the same region, or another independently justified directional calibration. A synthetic Bragg hexagon alone cannot validate the acquisition orientation. With ipympl installed in the notebook environment, switch to an interactive backend in a separate cell:
%matplotlib widget
viewer = data.compare_rq(
real_image, shadow_image, layout='overlay',
real_alpha=0.6, reciprocal_alpha=0.6,
real_show_kwargs={'cmap': 'gray'},
reciprocal_show_kwargs={'cmap': 'magma', 'logScale': False},
)
# Inspect rotation, reflection, pivot, and registration before applying.
viewer.apply()
print(data.rq_calibration)
real_result = data.get_strains(**fit_options, output_frame='real')
The viewer rotates only the diffraction preview about its stored beam center, otherwise the subpixel image center. It offers independent opacity controls. Applying stores orientation, not the preview’s registration scale/shift or a resampled 4D array. The notebook above stays noninteractive for reproducibility; the snippet is intentionally not executed without your real image pair. Rerun the calibration/reporting cells with your verified settings, and save the resulting HyperData to retain the orientation. Do not use nonzero ang together with output_frame=’real’: that would attempt two basis corrections.
12. Export small results and preserve the dataset’s calibration¶
The numeric NPZ below stores maps, validity, statuses, fit quality, and JSON metadata without pickle. It is a tutorial export, not a native StrainResult save format; retain measured/reference peak inputs separately for a full re-fit. For acquisition-scale work, do not save another complete 4D copy merely to export a map. Here the selected input is deliberately small, so a native HyperData save/load also demonstrates retention of its beam center and R/Q orientation. All output paths are owned temporary files, never your original acquisition.
Frame metadata belongs with exported strain. A field called exx without its reporting frame, peak coordinate units, reference description, and scan calibration is not enough to interpret a scientific result.
export_metadata = {
'data_origin': 'synthetic' if is_synthetic else input_origin,
'strain_definition': 'I - right polar stretch of reciprocal reference-to-measured transform',
'output_frame': result.output_frame, 'rotation_units': 'radians', 'strain_units': 'dimensionless',
'peak_coordinate_order': 'ky,kx', 'peak_units': result.peak_units,
'peak_origin': list(result.peak_origin), 'peak_origin_source': result.peak_origin_source,
'scan_units': result.real_units, 'scan_spacing': data.real_conv_factor,
'scan_origin': list(result.real_origin), 'match_radius': match_radius,
'fit_translation': True, 'intensity_weighted': intensities is not None,
'intensity_percentile': intensity_percentile_input,
'reference_description': 'known synthetic unstrained hexagon' if is_synthetic else 'user-supplied; document source/state separately',
'rq_calibration_used': result.rq_calibration.to_dict() if result.rq_calibration is not None else None,
'rq_verification': 'known by construction' if is_synthetic else ('user-declared verified' if use_real_frame else 'not used for real output'),
}
export_path = output_dir / 'strain_maps.npz'
np.savez_compressed(export_path, exx=result.exx, eyy=result.eyy, exy=result.exy, erot=result.erot,
valid_mask=result.valid_mask, match_counts=result.match_counts, fit_status=result.fit_status,
fit_rmse=result.fit_rmse, relative_fit_rmse=result.relative_fit_rmse,
output_basis_matrix=result.output_basis_matrix, metadata_json=json.dumps(export_metadata))
with np.load(export_path, allow_pickle=False) as saved:
np.testing.assert_allclose(saved['exx'], result.exx, equal_nan=True)
assert json.loads(str(saved['metadata_json']))['output_frame'] == result.output_frame
native_path = output_dir / 'calibrated_input.4denoise'
data.save(native_path)
roundtrip = HyperData(native_path)
assert roundtrip.rq_calibration == data.rq_calibration
np.testing.assert_array_equal(roundtrip.array, data.array)
if data.center_beam_metadata is not None:
for key in ('center_px', 'mean_fit_center_px', 'center_calibrated'):
if key in data.center_beam_metadata:
np.testing.assert_allclose(roundtrip.center_beam_metadata[key], data.center_beam_metadata[key])
print('Verified temporary map export and native dataset metadata round trip.')
Verified temporary map export and native dataset metadata round trip.
What to take to your own data¶
Use measured and reference peaks in the same units, geometry, and stated lattice/orientation reference. Keep measured intensities attached to their own peaks.
Start with detector output, inspect statuses, retained pairs, residuals, and overlays. Large rotations require an independently justified initialization or orientation matching. Hexagonal symmetry can make multiple angles indistinguishable.
Use current alignment beam metadata or a verified explicit center. Beam alignment and R/Q orientation are different calibrations.
Request real-frame components only with verified R/Q orientation, including any reflection. Map positions stay (Ry, Rx); do not transpose maps or add an arbitrary 90-degree correction.
Preserve invalid values as NaN with a validity mask, retain reporting-frame metadata, and distinguish dimensionless strain from radians. Default CI validates this synthetic fixture, not a microscope acquisition.
See using your own data and peaks and strain. Continue with Tutorial 7: Large-data processing. The final cell removes only this lesson’s temporary files; change export paths deliberately before cleanup if you want persistent results.
assert hashlib.sha256(data.array.tobytes()).hexdigest() == original_pixels_digest
plt.close('all')
temporary_output.cleanup()
print('Finished. Input pixels unchanged; temporary outputs cleaned.')
Finished. Input pixels unchanged; temporary outputs cleaned.