Views and Results API

These objects retain the calibration or analysis context needed to interpret their arrays. Shape-changing methods generally return new objects; inspect the individual method contracts before relying on that behavior.

Real-space images

class fourdenoise.RealSpace(data, units=None, conv_factor=None, origin=(0.0, 0.0), quantity='Intensity', value_units=None)[source]

Container for a single 2D real-space image.

Parameters:
  • data (np.ndarray) – Two-dimensional real-space data.

  • units (str or None, optional) – Physical units associated with the real-space pixel spacing (for example 'nm' or 'Å').

  • conv_factor (float or (float, float) or None, optional) – Physical units per pixel. A scalar means equal (y, x) spacing; a pair supports rectangular scan pixels.

  • origin ((float, float), optional) – Physical (y, x) coordinate of pixel center (0, 0). Defaults to (0, 0) and is preserved through crop and resize.

  • quantity (str or None, optional) – Meaning and units of pixel values, used to label the colorbar.

  • value_units (str or None, optional) – Meaning and units of pixel values, used to label the colorbar.

__init__(data, units=None, conv_factor=None, origin=(0.0, 0.0), quantity='Intensity', value_units=None)[source]

Validate a 2D image and attach its optional spatial calibration.

Parameters:

units (str)

RealSpace.show(title='Real-Space Image', axes=True, grid=False, num_div=10, gridColor='black', vmin=None, vmax=None, figsize=(8, 8), aspect=None, cmap='gray', coords=None, axis_units='auto', *, ax=None, show=True, colorbar=None, colorbar_label=None, grid_color=None, grid_ticks=None, scale_bar=None, scale_bar_position='left', scale_bar_color='white', scale_bar_label=True, coords_units='pixels', y=None, x=None, percentiles=None, symmetric=False, **scatter_kwargs)[source]

Display the image on new or existing Matplotlib axes.

Parameters:
  • axis_units ({'auto', 'pixels', 'calibrated'}, optional) – Axis and scale-bar units. 'auto' uses calibration if available.

  • ax (matplotlib.axes.Axes or None, optional) – Existing axes for a subplot. If None, create a new figure.

  • show (bool, optional) – Call plt.show() when True. Set False when composing figures.

  • colorbar (bool or None, optional) – Draw a colorbar. None follows axes; an explicit value is independent of whether image axes are visible.

  • colorbar_label (str or None, optional) – Override the label from quantity and value_units.

  • coords (array-like, optional) – Scatter positions, with coords in (y, x) order. Supply either coords or both y and x. The default input is pixel indices even when displayed axes are calibrated.

  • y (array-like, optional) – Scatter positions, with coords in (y, x) order. Supply either coords or both y and x. The default input is pixel indices even when displayed axes are calibrated.

  • x (array-like, optional) – Scatter positions, with coords in (y, x) order. Supply either coords or both y and x. The default input is pixel indices even when displayed axes are calibrated.

  • coords_units ({'pixels', 'calibrated'}, optional) – Input coordinate system for scatter positions.

  • grid_color (optional) – Grid color and tick count (scalar or (y, x)). num_div and gridColor remain accepted for existing plotting calls.

  • grid_ticks (optional) – Grid color and tick count (scalar or (y, x)). num_div and gridColor remain accepted for existing plotting calls.

  • scale_bar (positive float or None, optional) – Length in the displayed axis units. Its location, color, and numeric label are controlled by the scale_bar_* arguments.

  • percentiles ((float, float) or None, optional) – Use these finite-data percentiles when vmin or vmax is omitted. Explicit limits take priority.

  • symmetric (bool, optional) – Use color limits symmetric around zero, useful for strain maps.

  • title (str)

  • axes (bool)

  • grid (bool)

  • gridColor (str)

  • cmap (str)

Returns:

The figure and image axes. The image is not modified.

Return type:

tuple[Figure, Axes]

RealSpace.set_scale(units, conv_factor)[source]

Attach scalar or (y, x) real-space calibration.

Parameters:

units (str)

RealSpace.crop(ylim=None, xlim=None, selection_units='pixels')[source]

Return a cropped image while retaining its physical origin.

ylim and xlim are indices or half-open (start, stop) ranges. Use selection_units='calibrated' for physical coordinates. Pixel selections are the default, even on calibrated images.

RealSpace.resize(shape, method='area', *, working_memory_mb=None)[source]

Resize the image and update pixel spacing and pixel-center origin.

method='area' computes area-weighted downsampling. 'linear' and 'nearest' also support upsampling. Pixel values are preserved in their original range; integer data may become floating point. Floating output retains its dtype. working_memory_mb budgets temporary buffers (default 256 MiB), excluding the source and full returned output. The same numerical engine is used by HyperData.

RealSpace.copy()[source]

Return an independent copy of this RealSpace object.

The image array and calibration metadata are copied so the returned object can be edited without changing this object.

Diffraction patterns

class fourdenoise.ReciprocalSpace(data, units=None, conv_factor=None, polar_metadata=None, center_beam_metadata=None, cepstral_metadata=None)[source]

Container for a single 2D reciprocal-space image or diffraction pattern.

Parameters:
  • data (np.ndarray) – Two-dimensional reciprocal-space data.

  • units (str or None, optional) – Physical units associated with the reciprocal-space pixel spacing (for example 'mrad' or 'A^-1').

  • conv_factor (float or None, optional) – Conversion factor from pixels to physical units, expressed as units / pixel. When omitted, plots default to pixel units.

  • polar_metadata (dict or None, optional) – Description of a (kr, ktheta) image produced by a polar transform.

  • center_beam_metadata (dict or None, optional) – Direct-beam center and radius information, when available.

  • cepstral_metadata (dict)

__init__(data, units=None, conv_factor=None, polar_metadata=None, center_beam_metadata=None, cepstral_metadata=None)[source]

Store the image and copy optional polar and direct-beam metadata.

Parameters:
  • units (str)

  • conv_factor (float)

  • polar_metadata (dict)

  • center_beam_metadata (dict)

  • cepstral_metadata (dict)

ReciprocalSpace.show(power=1, title='Diffraction Pattern', logScale=True, axes=True, vmin=None, vmax=None, figsize=(10, 10), aspect=None, cmap='turbo', coords=None, axis_units='auto', y=None, x=None, overlay_mask=None, overlay_color='green', overlay_alpha=0.3, mode='cartesian', grid=False, grid_ticks=None, radial_ticks=None, angular_ticks=None, grid_color='white', grid_alpha=0.35, scale_bar=None, scale_bar_position=None, scale_bar_color='white', scale_bar_label=True, **scatter_kwargs)[source]

Visualize the diffraction pattern stored in this ReciprocalSpace object.

The diffraction pattern is displayed with optional log-scaling and intensity exponentiation. Optionally, a set of (y, x) peak coordinates can be overlaid as a scatter plot on top of the image. mode='polar' draws a circular plot. Cartesian input is sampled within its largest centered circle for this display only; the stored array is unchanged. Angles increase clockwise from the right, matching array row order.

Parameters:
  • power (float, optional) – Intensity exponent. If logScale is True, the displayed image is power * log(self.array). If logScale is False, the displayed image is self.array ** power. Default is 1.

  • title (str, optional) – Title for the diffraction pattern (used on the axes when axes=True).

  • logScale (bool, optional) – If True, use a logarithmic transform (log) of the data before exponentiation. If False, use a pure power-law transform.

  • axes (bool, optional) – If True, show axes, ticks, and a colorbar. If False, hide these; a requested grid or scale bar still appears.

  • vmin (float or None, optional) – Minimum intensity for color scaling. If None, it is inferred from the transformed data.

  • vmax (float or None, optional) – Maximum intensity for color scaling. If None, it is inferred from the transformed data.

  • figsize (tuple, optional) – Figure size passed to plt.figure(figsize=…).

  • aspect (float, str, or None, optional) – Aspect ratio for the displayed image. If not None, passed to ax.set_aspect(aspect) in rectangular mode. Circular polar mode keeps an equal aspect ratio.

  • cmap (str, optional) – Matplotlib colormap name for the image. Default is ‘turbo’.

  • coords (array-like of shape (N, 2), optional) – Optional array of peak coordinates to overlay as scatter points. Each row should be [y, x]. When provided, points are plotted at x = coords[:, 1] and y = coords[:, 0] on top of the image.

  • y (scalar or array-like, optional) – Alternative pixel coordinates for scatter points. Supply both, with the same number of values. Do not combine with coords.

  • x (scalar or array-like, optional) – Alternative pixel coordinates for scatter points. Supply both, with the same number of values. Do not combine with coords.

  • overlay_mask (ndarray of bool or None, optional) – A detector region to tint over the diffraction pattern. Must have the same shape as the image.

  • overlay_color (matplotlib color, optional) – Color used for overlay_mask.

  • overlay_alpha (float, optional) – Opacity of overlay_mask between 0 and 1.

  • axis_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for the displayed axes. 'auto' uses stored reciprocal-space calibration when available and otherwise falls back to pixels. For polar data, calibrated display uses kr in the source reciprocal units and ktheta in degrees. EWPC data uses cepstral cy/cx pixel axes and the recorded FFT zero, not diffraction units or the geometric image midpoint.

  • mode ({'cartesian', 'polar'}, optional) – 'cartesian' preserves the current rectangular display, including an angle-versus-radius view for stored polar data. 'polar' displays a circular radius/angle projection.

  • grid (bool, optional) – Draw coordinate grid lines. The grid also appears with axes=False.

  • grid_ticks (int or (int, int), optional) – Number of Cartesian/rectangular grid ticks, (y, x), including endpoints. A scalar applies to both axes. Defaults to 6 when grid=True. Not used in circular polar mode.

  • radial_ticks (int or None, optional) – Number of radial rings and angular spokes in circular polar mode. Defaults to 5 and 12 when grid=True. Not used in Cartesian mode.

  • angular_ticks (int or None, optional) – Number of radial rings and angular spokes in circular polar mode. Defaults to 5 and 12 when grid=True. Not used in Cartesian mode.

  • grid_color (matplotlib color, optional) – Grid-line color; defaults to white.

  • grid_alpha (float, optional) – Grid-line opacity between 0 and 1.

  • scale_bar (positive float or None, optional) – Scale-bar length in the displayed horizontal units for rectangular mode, or radial units for circular polar mode. Thus a rectangular view of stored polar data uses degrees. If None, no bar is drawn.

  • scale_bar_position ({'left', 'center', 'right'} or None, optional) – Horizontal placement. Defaults to left for rectangular mode and center for circular polar mode.

  • scale_bar_color (matplotlib color, optional) – Scale-bar and label color; defaults to white.

  • scale_bar_label (bool, optional) – If False, omit the numeric length and unit text.

  • **scatter_kwargs – Additional keyword arguments forwarded to plt.scatter(…) for the overlay points (e.g., c=’r’, s=20, marker=’x’, etc.).

Notes

  • The method assumes self.array is a 2D diffraction pattern.

  • For logScale=True, non-positive values in self.array will produce -inf or nan in the log; it is recommended to use background- subtracted and strictly positive data when using log scaling.

ReciprocalSpace.set_scale(units, conv_factor)[source]

Attach a reciprocal-space calibration to the diffraction pattern.

Parameters:
  • units (str) – Physical reciprocal-space units, for example 'mrad' or 'A^-1'.

  • conv_factor (float) – Conversion factor in units / pixel.

Returns:

The current object, updated in place.

Return type:

ReciprocalSpace

ReciprocalSpace.get_peaks(radius, min_distance, trench_width=1.0, kernel_amp=1.0, trench_amp=-0.5, threshold_abs=1.0, threshold_rel=None, r_range=None, n_fold=None, sym_mode='none', sym_tolerance_px=2.0, center_tolerance_px=2.0, orbit_min_fraction=0.5, reorder=False, center=None, return_details=False, *, _array=None)[source]

Detect peaks in a 2D diffraction pattern via template matching with a disk and a negative “trench” kernel, optionally restricted to an annular region [r_min, r_max] (to exclude, for example, the central beam and far-away, low-signal peaks).

Optionally, enforce n-fold rotational symmetry about the search center over the full Bragg peak array (recommended for centrosymmetric diffraction patterns with approximate n-fold symmetry).

Notes

  • It is recommended to use background-subtracted data and to have all diffraction patterns center-beam aligned.

  • When using n_fold symmetry, it is generally recommended to have a reasonably clean peak detection (thresholds, min_distance) so that orbits can be reliably inferred.

  • The template is mean-centered on its disk and trench. Non-finite pixels are replaced by the finite-image median for the FFT, and candidate centers whose template touches them are excluded. A pattern with no finite pixels raises ValueError.

Parameters:
  • radius (float) – Radius of the positive disk (in pixels).

  • trench_width (float, optional) – Width of the negative surround ring (in pixels).

  • kernel_amp (float, optional) – Disk weight before the template is mean-centered.

  • trench_amp (float, optional) – Trench weight before mean-centering. Must be less than kernel_amp.

  • threshold_abs (float, optional) – Absolute correlation threshold for peak detection.

  • threshold_rel (float, optional) – Relative threshold in [0, 1], as a fraction of the maximum valid correlation. If both thresholds are supplied, the stricter one applies. With r_range, the maximum is measured in the annulus.

  • min_distance (int, optional) – Minimum number of pixels separating peaks (for suppression).

  • r_range (tuple (r_min, r_max), optional) – If provided, only search for peaks whose radial distance from the search center lies within [r_min, r_max] (in pixels).

  • center ((ky, kx) or None, optional) – Search center in pixels for the radial range and symmetry. Uses center_beam_metadata['center_px'] when available, otherwise the geometric midpoint. Explicit input takes precedence.

  • n_fold (int or None, optional) – Order of rotational symmetry to enforce (e.g., 4 for 4-fold, 6 for 6-fold). If None or < 2, no symmetry enforcement is applied.

  • sym_mode ({"none", "repair", "prune", "both"}, optional) – How to enforce n_fold symmetry. none leaves detected peaks unchanged; repair adds missing peaks in sufficiently complete orbits; prune keeps only sufficiently complete orbits; and both prunes incomplete orbits and repairs retained ones.

  • sym_tolerance_px (float, optional) – Maximum Euclidean distance (in pixels) between a detected peak and its ideal symmetric position for them to be considered the same. Repaired peaks closer than this to a measured or previously repaired peak are not added.

  • center_tolerance_px (float, optional) – Radial tolerance (in pixels) used to classify peaks as belonging to the central beam region, which is excluded from symmetry grouping and passed through unchanged (after de-duplication).

  • orbit_min_fraction (float, optional) – Minimum fraction of the n_fold orbit that must be present in the detected peaks for that orbit to be considered “real”. Orbits below this fraction are treated as noise and ignored in “prune” and “both” modes (and will not be repaired in “repair” mode).

  • return_details (bool, optional) – Return a PeakDetectionResult containing correlation scores and measured/synthetic labels instead of coordinates alone.

  • reorder (bool)

Returns:

  • coords ((M, 2) np.ndarray) – Array of (y, x) coordinates of detected peaks (possibly augmented and/or pruned by symmetry enforcement). If return_details is True, return a PeakDetectionResult instead.

  • by Adan J. Mireles

  • Applied Physics Graduate Program, Rice University

  • July 2025

Return type:

ndarray | PeakDetectionResult

ReciprocalSpace.get_centers(r, ref_coords, show=False, method='CoM')[source]

Refine reference-peak centers in this diffraction pattern.

r may be a scalar or one radius per reference peak. method selects center of mass, axis-aligned Gaussian, or rotated elliptical Gaussian fitting.

ReciprocalSpace.get_intensities(r, centers=None, ref_coords=None, method='CoM', compute_resBg=False, residual_frac=0.9, *, _array=None, **resBg_kwargs)[source]

Integrate Bragg intensities in circular windows around peak centers.

r may be one radius or one radius per peak. Windows are clipped to the detector boundaries; no pixels wrap around an image edge. When subtracting residual background, the correction uses the number of pixels actually included in each integration window. The private _array fast path requires supplied centers and does not support residual-background inference; it never changes this object’s array, calibration or detector state.

ReciprocalSpace.block_direct_beam(radius=None, center=None, beam_units='auto', fill_value=1, return_mask=False)[source]

Block the central/direct beam in this diffraction pattern.

The selected circular beam region is replaced with fill_value. Explicit radius and center values take precedence over stored center_beam_metadata from alignment. If radius is omitted, the method uses metadata and raises a helpful error if no stored direct- beam radius is available.

Parameters:
  • radius (float or None, optional) – Direct-beam radius. Interpreted according to beam_units when provided explicitly.

  • center (array-like of two floats or None, optional) – Direct-beam center as (ky, kx). Pixel centers are array coordinates. Calibrated centers are reciprocal coordinates relative to the diffraction origin, with positive ky upward and positive kx to the right.

  • beam_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system for explicit radius and center. 'auto' uses this object’s calibration when available and otherwise falls back to pixels.

  • fill_value (scalar, optional) – Value assigned to blocked direct-beam pixels. Defaults to 1.

  • return_mask (bool, optional) – If True, return (blocked_pattern, beam_mask) where beam_mask is True for blocked pixels.

Returns:

New diffraction-pattern object with the direct beam blocked, optionally followed by the 2D beam mask.

Return type:

ReciprocalSpace or tuple

Notes

block_direct_beam is the preferred name. remove_center_beam is kept as an alias for older notebook wording.

ReciprocalSpace.inpaint_background(centers=None, radius=6, mask=None, method='biharmonic', split_into_regions=False)[source]

Estimate a local background by inpainting selected diffraction spots.

Circular regions centered at centers with radius radius are treated as spots to remove. An explicit Boolean mask can also be provided, and is combined with any circular regions. The missing regions are filled by inpaint_background to produce a smooth background estimate. The original diffraction pattern is not modified.

Parameters:
  • centers (array-like or None, optional) – One (ky, kx) center or a sequence of centers identifying spots to inpaint. Required when mask is not provided.

  • radius (float or array-like of floats, optional) – Radius, in pixels, around each center to inpaint. Defaults to 6.

  • mask (ndarray of bool or None, optional) – Explicit inpainting mask with the same shape as this diffraction pattern. True-valued pixels are inpainted.

  • method ({'biharmonic'}, optional) – Inpainting method. Currently only 'biharmonic' is implemented.

  • split_into_regions (bool, optional) – Passed to skimage.restoration.inpaint_biharmonic.

Returns:

New diffraction-pattern object containing the estimated background and preserved calibration/metadata.

Return type:

ReciprocalSpace

ReciprocalSpace.copy()[source]

Return an independent copy of this ReciprocalSpace object.

The image array, calibration, and polar metadata are copied so the returned object can be edited without changing this object.

Analysis results

class fourdenoise.BraggnessResult(score, valid_mask, metadata, real_units=None, real_conv_factor=None, real_origin=(0.0, 0.0))[source]

Concentrated sharp diffraction contrast from HyperData.get_braggness().

Parameters:
  • score (ndarray)

  • valid_mask (ndarray)

  • metadata (dict)

  • real_units (str | None)

  • real_conv_factor (float | tuple[float, float] | None)

  • real_origin (tuple[float, float])

score

Dimensionless float32 scores with the source scan_shape: scalar shape () for one pattern, (N,) for a stack, or (Ry, Rx) for a 4D scan. Skipped or invalid patterns contain NaN.

Type:

numpy.ndarray

valid_mask

Boolean array of the same shape; True means successfully evaluated. Geometric segmentation/refinement must retain this exclusion, e.g. refined_mask &= result.valid_mask.

Type:

numpy.ndarray

metadata

Small JSON-serializable calculation settings and evaluation counts. Contains no diffraction arrays or per-pattern intermediates.

Type:

dict

real_units, real_conv_factor, real_origin

Source scan calibration used by as_real_space().

The score is not a phase label, crystalline volume fraction, or orientation
confidence. Noise, intensity, detector geometry, and parameters affect it.
as_real_space()[source]

Return a 2D score map retaining source scan units, spacing, and origin.

Raises ValueError for a single pattern or 1D stack, whose 2D scan layout cannot be inferred. No scan or detector axes are transposed.

class fourdenoise.RQCalibration(rotation_deg=0.0, mirror_axis=None, source='manual')[source]

Orientation of scan directions in the detector frame.

Directions use Cartesian (x, y) components, with x right and y up in each image. matrix maps real to reciprocal components by first reflecting about mirror_axis (if any), then rotating counterclockwise by rotation_deg. Magnitudes keep their original units: this is an orientation change, not a conversion of lengths to inverse lengths.

Arrays retain their usual (y, x) index order. Image registration scale, translation and pivot are deliberately separate from this calibration. Instances are immutable and their matrix properties return fresh arrays.

Parameters:
  • rotation_deg (float)

  • mirror_axis (str | None)

  • source (str)

property matrix

Orthogonal 2x2 matrix mapping real to reciprocal directions.

property inverse_matrix

Orthogonal 2x2 matrix mapping reciprocal to real directions.

transform_vectors(vectors, direction='real_to_reciprocal')[source]

Transform Cartesian (..., 2) vectors without changing their units.

Use centered Cartesian components, not raw (row, column) peak indices. direction may also be 'reciprocal_to_real'.

to_dict()[source]

Return versioned, HDF5-serializable orientation metadata.

classmethod from_matrix(matrix, *, mirror_axis='x', source='manual')[source]

Describe an orthogonal real-to-reciprocal matrix, including reflection.

class fourdenoise.RQComparison(real_image, reciprocal_image, *, calibration=None, on_apply=None, layout='overlay', real_alpha=0.7, reciprocal_alpha=0.7, interactive=True, scale=None, translation=(0.0, 0.0), real_show_kwargs=None, reciprocal_show_kwargs=None, figsize=(12, 8), show=True, export_path='rq_alignment.png')[source]

Interactive result returned by fourdenoise.HyperData.compare_rq().

The real image is fixed. The diffraction image is mirrored, rotated, and scaled about center (a subpixel (y, x) pivot), then placed with that pivot at the real-image midpoint plus translation. Translation uses real-image (dy, dx) pixels; positive dy is downward. scale is real horizontal pixels per diffraction pixel. Known unequal scan pixel spacings are respected independently of the displayed tick units.

rotation_deg is the counterclockwise diffraction correction, Q to R. calibration reports its inverse, R to Q, including any reflection. Editing controls affects only the preview. Call apply or press Apply calibration to store the orientation in the owning HyperData object.

property parameters

Return a copy of the current preview settings.

property calibration

Current orientation as R-to-Q metadata, independent of preview scale/shift.

property image_matrix

3x3 forward map from diffraction (x, y, 1) pixels to reference pixels.

transform_points(coords)[source]

Map diffraction (y, x) pixel positions into reference pixel coordinates.

set_parameters(**parameters)[source]

Update preview settings atomically; the source data and calibration are unchanged.

reset()[source]

Restore the opening preview settings, without reverting an applied calibration.

apply()[source]

Store the current orientation on the owning dataset and return it.

export(filename, *, dpi=180, overwrite=False)[source]

Save the image panels without controls; an existing file requires overwrite=True.

close()[source]

Disconnect GUI callbacks and close the comparison figure.

class fourdenoise.PeakDetectionResult(coords, scores, synthetic_mask, orbit_ids)[source]

Peak coordinates and their origin, in matching row order.

scores are template-correlation values for measured peaks and NaN for symmetry-generated peaks. orbit_ids is -1 for peaks not assigned to a complete-enough rotational orbit (including central peaks).

Parameters:
  • coords (ndarray)

  • scores (ndarray)

  • synthetic_mask (ndarray)

  • orbit_ids (ndarray)

property observed_mask

Boolean mask selecting peaks actually detected in the pattern.

class fourdenoise.PeakScanResult(coords, scores, synthetic_mask, orbit_ids, processed_mask, metadata, intensities=None)[source]

Ragged peak arrays indexed by the original scan position.

coords, scores, synthetic_mask and orbit_ids are object arrays with shape (Ry, Rx) for a 4D scan or (N,) for a 3D stack. Each coords[index] has shape (n_peaks, 2), in (y, x) order. The other entries have matching row order. intensities has the same ragged structure when requested, otherwise None. These are raw circular-window sums, not template correlation scores or background-corrected estimates. Symmetry-generated rows have NaN scores/intensities and True synthetic_mask.

processed_mask distinguishes masked-out positions from evaluated patterns containing zero peaks. Masked-out entries are empty arrays. metadata records coordinate units/convention, pixel detection settings, resolved beam/search center, scan geometry and original source metadata. Calibrated coordinates are y-up/x-right about the geometric detector midpoint; choosing an off-center search origin does not shift this frame.

The result owns its arrays and remains usable after source closure. It is a peak collection, not a RealSpace image; peak_counts is a scan-shaped array suitable for plotting. Its size grows with the number of scan positions and peaks, independently of the temporary-workspace budget. For larger results, supply destination to DiffractionSource.get_peaks instead.

Parameters:
  • coords (ndarray)

  • scores (ndarray)

  • synthetic_mask (ndarray)

  • orbit_ids (ndarray)

  • processed_mask (ndarray)

  • metadata (dict)

  • intensities (ndarray | None)

property scan_shape

Original leading scan-axis shape, without inventing a 2D layout.

property peak_counts

Scan-shaped counts of all returned peaks, including repaired rows.

property observed_peak_counts

Scan-shaped counts excluding symmetry-generated peaks.

classmethod PeakScanResult.load(filename, *, max_memory_mb=None)[source]

Explicitly load a saved peak collection, not the diffraction pixels.

File mode stores append-only numeric tables and per-scan starts/counts, not pickle or HDF5 variable-length object arrays. This loader validates schema, table lengths, ranges and scan indexing before exposing entries. max_memory_mb optionally caps stored numeric arrays and object pointer tables before reading them. Metadata, Python/NumPy object headers and allocator/library overhead are excluded; this is not a RAM guarantee. This operation materializes the whole collection. For selected entries, read /starts, /counts and the corresponding /coords/… slices with h5py.

PeakScanResult.copy()[source]

Return independent numerical arrays, ragged entries and metadata.

PeakDetectionResult describes one pattern’s detections. PeakScanResult contains scan-indexed ragged arrays and optional integrated intensities; it is not itself a fourdenoise.RealSpace image. A file produced by DiffractionSource.get_peaks(destination=...) uses a separate peak schema, not the saved diffraction-array format. See the peak guide for coordinates, provenance, masked entries, and selective numeric-table reads.

class fourdenoise.StrainResult(exx, eyy, exy, erot, fit_rmse, relative_fit_rmse, match_counts, initial_match_counts, outlier_counts, peak_origin, peak_origin_source, basis_angle_deg, ewpc, peak_units='pixels', real_units=None, real_conv_factor=None, real_origin=(0.0, 0.0), diagnostics=None, output_frame='reciprocal', rq_calibration=None, output_basis_matrix=None, fit_status=None, condition_numbers=None)[source]

Strain maps and fit quality from HyperData.get_strains().

exx, eyy, and exy are dimensionless; erot is in radians. fit_rmse is the final peak-position residual in the coordinate units supplied to get_strains. relative_fit_rmse divides it by the RMS reference-peak distance from peak_origin and is dimensionless. A low residual with only a few matched peaks does not establish a reliable fit; inspect match_counts and valid_mask too.

The maps use the source scan calibration only when their shape matches the source 4D scan. as_real_space is available for 2D maps. The result can also be indexed or unpacked like the historical four-array return; when return_transform=True, the diagnostics dictionary is item five.

output_frame='reciprocal' reports detector directions. Its default basis_angle_deg=0 assigns exx to kx and eyy to ky, preserving the input peak-coordinate shear/rotation conventions. The manual angle changes this reporting basis without moving scan pixels.

output_frame='real' uses the stored R/Q orientation to report a Cartesian real-space tensor (x right, y up). The strain tensor is I - U, with U the polar stretch in that frame; erot is positive counterclockwise. rq_calibration records the immutable calibration used, and output_basis_matrix maps centered input (ky, kx) vectors to reporting coordinates. basis_angle_deg is the manual angle only and is zero for real-frame output. Scan layout and fit errors are retained.

Parameters:
  • exx (ndarray)

  • eyy (ndarray)

  • exy (ndarray)

  • erot (ndarray)

  • fit_rmse (ndarray)

  • relative_fit_rmse (ndarray)

  • match_counts (ndarray)

  • initial_match_counts (ndarray)

  • outlier_counts (ndarray)

  • peak_origin (tuple[float, float])

  • peak_origin_source (str)

  • basis_angle_deg (float)

  • ewpc (bool)

  • peak_units (str)

  • real_units (str | None)

  • real_conv_factor (float | tuple[float, float] | None)

  • real_origin (tuple[float, float])

  • diagnostics (dict | None)

  • output_frame (str)

  • rq_calibration (RQCalibration | None)

  • output_basis_matrix (ndarray | None)

  • fit_status (ndarray | None)

  • condition_numbers (ndarray | None)

property valid_mask

Locations with a successful, finite strain fit.

as_real_space(component='exx')[source]

Return a 2D map with the source scan-axis calibration.

component may be a strain component, fit_rmse, relative_fit_rmse, a peak-count map, or valid_mask. This changes neither the scan layout nor the strain tensor basis.