HyperData API¶
HyperData wraps a 2D image, 3D pattern stack, or 4D scan. The public
methods below are selected entry points, not an inventory of implementation
helpers. See the data model and task guides
before using a method on a new dataset.
- class fourdenoise.HyperData(data, real_units=None, real_conv_factor=None, reciprocal_units=None, reciprocal_conv_factor=None, polar_metadata=None, center_beam_metadata=None, hdf5_dataset=None, flip_axis=None, real_origin=None, clip_on_load=False, repair_nans=False, raw_shape=None, raw_dtype=<class 'numpy.float32'>, raw_order='C', raw_trim_meta=None, raw_trim_dims=(128, 128), mat_variable=None, rq_calibration=None, metadata_path='auto', acquisition_metadata=None, cepstral_metadata=None)[source]¶
Hold diffraction data and its real- and reciprocal-space calibration.
The final two axes are diffraction coordinates
(Ky, Kx). A 4D array has scan axes(Ry, Rx, Ky, Kx); a 3D array is a stack of patterns(N, Ky, Kx)whose original 2D scan layout is not assumed. A 2D array represents one image or pattern. Input may be an array or a supported data-file path. Methods provide loading, visualization, preprocessing, denoising, peak analysis, and strain maps.See
__init__()for file-format, calibration, and metadata options.- Parameters:
real_units (str)
real_conv_factor (float | tuple[float, float])
reciprocal_units (str)
reciprocal_conv_factor (float)
polar_metadata (dict)
center_beam_metadata (dict)
- __init__(data, real_units=None, real_conv_factor=None, reciprocal_units=None, reciprocal_conv_factor=None, polar_metadata=None, center_beam_metadata=None, hdf5_dataset=None, flip_axis=None, real_origin=None, clip_on_load=False, repair_nans=False, raw_shape=None, raw_dtype=<class 'numpy.float32'>, raw_order='C', raw_trim_meta=None, raw_trim_dims=(128, 128), mat_variable=None, rq_calibration=None, metadata_path='auto', acquisition_metadata=None, cepstral_metadata=None)[source]¶
Wrap an array or load a dataset with optional axis reversal.
flip_axisaccepts one axis or a sequence of axes to reverse. For 4D data, axes(0, 1, 2, 3)mean(Ry, Rx, Ky, Kx). For 3D data, axes(0, 1, 2)mean(pattern, Ky, Kx). Negative axes follow NumPy conventions. Flipping a NumPy array creates a view.real_conv_factormay be scalar or(y, x)units per pixel. Negative steps indicate axes reversed relative to physical coordinates.real_originis the calibrated coordinate of scan pixel(0, 0)and defaults to(0, 0).scan_shapecontains all leading (non-pattern) axes andpattern_shapecontains the last two axes.real_shapeis the 2D scan grid only for 4D data; a 3D stack hasscan_shape=(N,)andreal_shape=Nonebecause its scan geometry is unknown. For generic files,clip_on_loadreplaces values below 1 with 1 andrepair_nansreplaces NaN-containing patterns with neighbor averages. Both are opt-in; loading preserves the stored data by default. For.rawfiles,raw_shapespecifies the full stored shape;raw_dtypeandraw_orderspecify the binary layout. Explicitraw_shapedisables EMPAD metadata-row trimming by default. Setraw_trim_meta=Trueandraw_trim_dimsto request that crop. For MATLAB.matfiles,mat_variableselects a named numeric array; it is required when the file has multiple suitable arrays. Assigning a newarraylater refreshes the shape, dtype, and denoising engine; shape-dependent metadata is cleared when necessary.rq_calibrationis an optionalRQCalibrationor saved calibration dictionary describing real-to-detector orientation. Saved files restore it automatically; axis flips update its frame.metadata_path='auto'discovers recognized EMPAD XML sidecars in the same directory as a raw file. The XML must name that raw file; multiple matches raise an error rather than choosing silently. Pass an explicit XML path to select a sidecar, or None to disable external discovery. Explicit paths are relative to the working directory. Imported scan dimensions must match the loaded array (or the pattern count for a 3D stack); sidecars do not change raw layout or trimming. Malformed sidecars warn and are skipped in auto mode; explicit ones raise errors. Auto discovery does not search for XML beside NumPy or generic HDF5 files. Saved HyperData files restore embedded metadata even withmetadata_path=Noneand do not rediscover sidecars.acquisition_metadataoptionally supplies a descriptive dictionary for an array or overrides saved/imported acquisition information. It cannot be combined with an explicitmetadata_path. The record is deep-copied and describes the original acquisition, not the current cropped/resized geometry. It never sets pixel calibration orrq_calibration; explicit user calibrations remain authoritative.cepstral_metadataidentifies EWPC/Fourier-conjugate pattern axes and their zero pixel. Saved files restore it; it is not diffraction calibration and is mutually exclusive withpolar_metadata.- Parameters:
real_units (str)
real_conv_factor (float | tuple[float, float])
reciprocal_units (str)
reciprocal_conv_factor (float)
polar_metadata (dict)
center_beam_metadata (dict)
Loading and metadata¶
- HyperData.metadata_summary()[source]¶
Return a readable acquisition and current-calibration summary.
Use
print(data.metadata_summary())in a notebook. Missing fields remain unknown. The original acquisition scan shape and instrument settings are reported separately from the current data shape and user/verified calibration; no rotation or scale is inferred here. Original XML values and conversion provenance are available throughacquisition_metadata['raw_metadata']and['field_sources'].
- classmethod HyperData.open(filename, hdf5_dataset=None, *, real_units=None, real_conv_factor=None, reciprocal_units=None, reciprocal_conv_factor=None, real_origin=None, backend='auto', reader=None, dataset=None, axis_order=None, reader_kwargs=None)[source]¶
Open disk-backed data without loading the complete array into RAM.
Returns a context manager yielding a read-only
DiffractionSource. Supports nonempty 3D stacks and 4D scans in.npy,.h5,.hdf5,.hdfand saved.4denoisefiles. NumPy arrays are memory-mapped read-only; HDF5 arrays remain on disk. Other formats use the optional RosettaSciIO backend when a curated lazy reader is available. Object arrays and NumPy archives are not supported.backend='auto'prefers native NumPy/HDF5 readers for their formats. Setbackend='rosetta'or specifyreaderto use RosettaSciIO explicitly, including vendor-specific HDF5 formats.readeraccepts a registered plugin name, alias or module suffix, e.g.'emd'. Unsupported lazy readers never fall back to loading the full array. Install the optional backend withpip install -e ".[rosetta]".datasetselects a Rosetta result by zero-based index or unique title when several numeric 3D/4D arrays are returned. Other dimensions, including thumbnail images, are not selected automatically.axis_orderis a permutation of original array indices, ordered as(Ry, Rx, Ky, Kx)or(N, Ky, Kx). Default None infers that order only from unambiguous labels/navigation metadata; ambiguous axes raise an error rather than guessing.reader_kwargsforwards plugin-specific options, excluding managedfilenameandlazy. Writablemode/mmap_modevalues are rejected before opening.Uniform compatible real-space calibration and isotropic detector pixel-size magnitudes are imported. Unsupported/nonuniform calibration warns and retains pixel units; all original axes and metadata are archived in acquisition metadata. Detector offsets/signs do not define a beam center or R/Q calibration.
source.reader_metadatadecodes the archive;unpack_reader_metadata()works after a full load or saved-file reload, even without RosettaSciIO installed.Lazy Rosetta slices are computed synchronously, reserving the largest declared reader chunk before budgeting managed buffers. Inspect
source.reader_chunk_nbytes. A small returned selection may still read a whole upstream chunk; task graphs, codecs/caches and library overhead are not a process-RAM guarantee. Smaller pluginchunkscan be supplied inreader_kwargswhen supported.hdf5_datasetselects one array when generic HDF5 has several. Saved HyperData files restore calibration and acquisition/geometry metadata automatically. Generic HDF5 and NumPy files have no assumed calibration. Supply both units and conversion factor for each domain to set or override its calibration, and optionallyreal_origin. These overrides affect returned objects, never the source file. Reciprocal overrides update Cartesian beam calibration but are rejected for saved polar/cepstral data, whose transformed axes have separate coordinate metadata; omit overrides to preserve that metadata.Inspect
source.shape,dtype,nbytesandmetadatawithout reading pixels. Useget_dpfor patterns or bounded mean/std/min/max reductions,iter_chunksfor independent HyperData blocks, orloadto explicitly create a complete in-memory HyperData object. Large unfolding undo payloads are deferred until a fullload. Every returned pattern/block/full object remains usable after closing the source. Reads after closure fail rather than accessing dead handles.This API does not promise lazy execution of arbitrary HyperData methods. In particular, global tensor denoising still needs an explicit full load.
HyperData(filename)retains its existing eager behavior.Examples
>>> with HyperData.open('experiment.npy') as source: ... mean_dp = source.get_dp(operation='mean', working_memory_mb=64) ... for scan_slices, block in source.iter_chunks((8, 8)): ... process(block) >>> with HyperData.open('saved.4denoise') as source: ... data = source.load(max_memory_mb=4096)
- classmethod HyperData.open_hdf5(filename, hdf5_dataset=None)[source]¶
Open an HDF5 diffraction source using the shared disk-backed reader.
Accepts
.h5,.hdf5,.hdfand.4denoisepaths. This format-specific entry point uses the sameDiffractionSourceasopen(); use that method for NumPy files or explicit calibration overrides. Existing HDF5 streaming workflows continue to use this API.
- classmethod HyperData.to_polar_hdf5(source, destination, *, hdf5_dataset=None, chunk_shape=8, working_memory_mb=None, center=None, r_max=None, output_shape=None, order=1, fill_value=0.0, clip=False, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Transform HDF5 diffraction data to polar coordinates without a full output array.
Read scan blocks through
open_hdf5(), apply the same numerical transform asto_polar(), and write each result directly into a chunked HyperData HDF5 file.chunk_shapebounds the number of scan positions held in memory; it is a scalar or one value per scan axis.working_memory_mbfurther bounds numerical interpolation workspace (default 256 MiB). For NumPy/Rosetta sources and explicit calibration, open a source withHyperData.open(...)and callsource.to_polar(destination=...)inside the with block. The saved result can be opened withHyperData.open_hdf5for later bounded-memory access or loaded fully withHyperData(destination). The destination must differ from the source. Atomic output is the default so an incomplete transform is never published.Parameters shared with
to_polar()have the same pixel-coordinate and interpolation meanings.hdf5_datasetselects an array from a generic HDF5 file; saved HyperData files use/arrayautomatically.
- classmethod HyperData.resize_hdf5(source, destination, shape, domain, method='area', *, hdf5_dataset=None, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Resize HDF5 data directly to a metadata-preserving disk destination.
- Parameters:
source (str or pathlib.Path) – Input HDF5 file and distinct output file (.4denoise/.h5/.hdf5/.hdf). A destination without a suffix receives .4denoise. Generic HDF5 inputs have no assumed calibration; saved HyperData inputs retain their metadata with the same geometry updates as resize.
destination (str or pathlib.Path) – Input HDF5 file and distinct output file (.4denoise/.h5/.hdf5/.hdf). A destination without a suffix receives .4denoise. Generic HDF5 inputs have no assumed calibration; saved HyperData inputs retain their metadata with the same geometry updates as resize.
shape – Same selected-axis output sizes and numerical meanings as resize. Real-space fractional bins span global scan coordinates even when their source regions cross processing-block boundaries.
domain – Same selected-axis output sizes and numerical meanings as resize. Real-space fractional bins span global scan coordinates even when their source regions cross processing-block boundaries.
method – Same selected-axis output sizes and numerical meanings as resize. Real-space fractional bins span global scan coordinates even when their source regions cross processing-block boundaries.
hdf5_dataset (str or None, optional) – Dataset path for generic multi-dataset inputs.
working_memory_mb (float or None, optional) – Temporary-buffer budget in MiB (default 256). Source and output remain on disk. Allocator overhead and HDF5 caches are excluded.
compression (str or None, optional) – HDF5 compression filter, default gzip.
compression_opts (int or None, optional) – Compression options, default gzip level 4.
overwrite (bool, optional) – Permit replacement of an existing destination, default False.
atomic (bool, optional) – Default True writes a temporary sibling file and publishes only after completion. Failed atomic writes leave an existing output untouched. False explicitly permits a partial output on failure.
progress (bool, optional) – Display one output-pixel progress bar, default True.
- Returns:
Saved path. Use open_hdf5 for bounded access; HyperData(path) explicitly loads the entire output into RAM.
- Return type:
str
- classmethod HyperData.to_cartesian_hdf5(source, destination, *, hdf5_dataset=None, output_shape=None, center=None, order=1, fill_value=0.0, clip=False, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Convert saved polar data to Cartesian patterns without a full RAM output.
Shape, center, interpolation and fill meanings match to_cartesian. None uses (2*n_r, 2*n_r); ‘original’ uses the stored Cartesian canvas. Only current scan blocks and per-pattern coordinate workspaces are allocated. working_memory_mb budgets explicit temporary arrays in MiB (default 256); allocator overhead, metadata, HDF5 caches and the caller’s data are excluded. An insufficient one-pattern budget fails before transforming a probe. Saved calibration, scan origin and R/Q metadata are preserved; polar identity is removed from the result.
Returns the output path, not an eager HyperData object. The source must have saved polar metadata. Writes are atomic by default; replacing an existing destination requires overwrite=True. Source and destination must differ. Set progress=False to suppress the single outer bar.
- classmethod HyperData.remove_bg_hdf5(source, destination, background, *, hdf5_dataset=None, bg_frac=1, a_min=1, a_max=None, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Subtract a fixed 2D diffraction background into a bounded HDF5 output.
bg_frac and clipping limits match remove_bg. Background must be one ndarray or ReciprocalSpace with the source diffraction shape; it is not a scan-shaped stack. Global background estimation and residual peak inference are intentionally not chunked here: estimate the background explicitly first. This path acts independently per pattern and does not approximate global denoising or change fitting semantics.
working_memory_mb is a temporary-array MiB budget (default 256), not a process-RAM limit; caller-owned background, metadata and HDF5 caches are excluded. Current scan blocks are read, transformed, and discarded. All coordinate metadata is retained. Returns a saved path. Atomic publication is the default; overwrite=True permits replacement, and source/destination must differ. One optional outer progress bar is used.
- HyperData.save(filename, overwrite=False, compression='gzip', compression_opts=4, atomic=True)[source]¶
Save this HyperData object with its metadata.
The saved file can be loaded directly with
HyperData(filename). The recommended extension is.4denoise;.h5and.hdf5are also accepted.- Parameters:
filename (str or pathlib.Path) – Output filename. If no extension is supplied,
.4denoiseis appended.overwrite (bool, optional) – If False, raise an error when the output file already exists.
compression (str or None, optional) – HDF5 compression filter for array-like datasets. Default is
'gzip'. UseNoneto save without compression.compression_opts (int or None, optional) – Compression level/options passed to HDF5. For gzip, values usually range from 0 to 9.
atomic (bool, optional) – Write to a temporary file in the destination directory and publish it only after a complete save. This protects an existing file from partial writes, but temporarily requires space for both copies when overwriting. Set False to write directly as before.
- Returns:
The saved file path.
- Return type:
str
Examples
>>> data.save('experiment.4denoise') >>> loaded = HyperData('experiment.4denoise')
Disk-backed source¶
Obtain a read-only source inside with HyperData.open(path) as source:.
Source reductions return independent in-memory views; disk-output transforms
return saved paths, not full tensors. get_peaks returns a
fourdenoise.PeakScanResult unless a destination is supplied.
See the streaming tutorial and
I/O guide for ownership, memory budgets,
optional readers, and the distinction between acquisition records and active
calibration. Global tensor denoising is not implicitly streamed.
- class fourdenoise.DiffractionSource(dataset, hyperdata_type, reciprocal_type, *, metadata=None, backend, filename, dataset_path=None, close_callback, unfold_loader=None, real_type=None)[source]¶
Read-only, on-demand access to a nonempty 3D stack or 4D scan.
Obtain a source with
HyperData.open(...)inside awithblock. Shapes follow(N, Ky, Kx)or(Ry, Rx, Ky, Kx).get_dpanditer_chunksreturn independent in-memory objects;loadexplicitly loads the complete dataset. There is deliberately no publicarrayproperty or implicit NumPy conversion. This is disk-backed reading, not a promise that all analysis or denoising methods execute lazily.to_polar,to_cartesian,resizeand fixedremove_bgwrite directly to a distinct, metadata-preserving file and return its path. They borrow this source without closing it and never allocate a complete numerical output in RAM. Global tensor denoising is not implicitly chunked.metadatareturns a defensive copy of descriptive/calibration records. Large unfolding undo payloads are deferred untilloadand are not attached to partial chunks.has_unfold_metadatareports their presence without reading them. Generic HDF5 and NumPy files have no assumed calibration; provide calibration explicitly when opening them.The source owns its file handle or memory map. Closing it is idempotent, prevents further reads, and does not invalidate already returned objects. Shape, dtype and copied metadata remain inspectable after closing.
- property shape¶
Complete stored shape, available without reading pixels.
- property ndim¶
three for a stack, four for a scan.
- Type:
Number of array axes
- property dtype¶
Stored NumPy dtype, including its byte order.
- property nbytes¶
Uncompressed numerical-array size, excluding metadata and overhead.
- property scan_shape¶
Leading scan axes, without inventing a 2D layout for 3D stacks.
- property pattern_shape¶
Detector axes
(Ky, Kx).
- property real_shape¶
2D scan shape for 4D data; None for a 3D stack.
- property backend¶
'hdf5','numpy'or'rosetta'.- Type:
Storage backend
- property filename¶
Absolute source-file path.
- property dataset_path¶
HDF5 path, Rosetta result index label, or None for NumPy files.
- property reader_chunk_nbytes¶
Largest declared lazy reader chunk; zero for native direct slicing.
RosettaSciIO may read a complete Dask chunk even for a small selection. Its size is reserved separately from 4Denoise’s read/reduction buffers. Task graphs, compression/library workspaces and OS caches are not covered by this estimate or by a process-RAM guarantee.
- property reader_metadata¶
Independent decoded Rosetta axes/metadata, or None for other records.
- property metadata¶
Independent metadata copy, excluding deferred unfolding payloads.
- property has_unfold_metadata¶
Whether a full load can restore saved unfolding undo metadata.
- property closed¶
Whether the owned disk resource has been closed.
- DiffractionSource.get_dp(y=None, x=None, mask=None, operation=None, selection_units='pixels', *, working_memory_mb=None)[source]¶
Read a pattern or perform a bounded scan reduction on disk.
Accepts the same pixel/calibrated scan selections and masks as
HyperData.get_dp. Supported reductions are mean, std, min and max; random selection is supported too. Exact median is rejected because it is not bounded-memory.working_memory_mbbudgets reduction arrays, not OS caches or process RAM. The returned ReciprocalSpace owns its data, so edits never change the source file.
- DiffractionSource.virtual_image(annulus=None, *, radius=None, centers=None, mask=None, theta_range=None, detector_units='auto', axis_units='auto', vmin=None, vmax=None, grid=True, num_div=10, plot_mask=False, grid_color='black', axes=True, return_detector=False, title='Virtual Detector Image', units='auto', mask_cmap='turbo', mask_vmin=None, mask_vmax=None, mask_power=1, mask_log_scale=True, mask_show_kwargs=None, ring_color='green', ring_alpha=0.3, show=True, working_memory_mb=None)[source]¶
Integrate a virtual detector without loading the complete 4D scan.
Detector definitions, inclusive boundaries, units and display options are the same as
fourdenoise.HyperData.virtual_image(): specify exactly one ofannulus=(inner, outer),radiuswithcenters, or a real Boolean/signed/fractional detectormask. Overlapping disks count once. Polar data supports annuli, wrappedtheta_rangeor masks, but not Cartesian disks. Radii in polar pixel mode refer to original Cartesian-pixel distances, not row indices.detector_units='auto'uses reciprocal calibration if available; choose'pixels'explicitly for pixel radii/positions.axis_unitschooses real-space display units, whileunitschooses detector preview units. All other visualization options follow HyperData’s method, including the optional unmasked mean-pattern overlay.Return a fully owned
fourdenoise.RealSpaceimage with scan calibration, spacing and origin. It remains usable after the source closes. Withreturn_detector=True, also return the masked mean detector image (ReciprocalSpace, or polar HyperData). Mean patterns are accumulated in the same read pass only when requested by this option or plot_mask.working_memory_mbbudgets numerical input/work buffers (default 256 MiB), reserving one declared Rosetta reader chunk too. It excludes the returned scan-sized image, detector construction, metadata, library/OS caches and plotting; it is not a process-RAM limit. A budget too small for one pattern raises before pixel reads. Products and sums use at least float64 precision; source data/dtype is never modified. NaN/Inf propagate according to ordinary NumPy multiplication/sums. Complex amplitudes are rejected; supply real-valued intensities. 3D stacks are rejected because they have no defined 2D scan grid.Examples
>>> with HyperData.open('scan.hdf5') as source: ... image = source.virtual_image( ... annulus=(10, 35), detector_units='pixels', ... working_memory_mb=64, show=False, ... ) >>> image.show()
- DiffractionSource.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, real_mask=None, center=None, *, intensity_radius=None, coords_units='pixels', working_memory_mb=None, chunk_size=None, destination=None, overwrite=False, atomic=True, progress=True)[source]¶
Detect peaks in Cartesian patterns without loading the whole scan.
Detection options have the same pixel meanings as
fourdenoise.HyperData.get_peaks()and use its existing ReciprocalSpace kernel. Parameters are validated before pixel reads. One detector wrapper/template is reused, one progress bar is shown, and blocks are discarded before the next read. No center refinement, intensity normalization, background subtraction or alignment is implied. Center defaults to valid stored beam metadata, then the image midpoint.real_maskis a Boolean (Ry, Rx) selection for 4D scans; fully masked read blocks are skipped. Mixed blocks can contain unselected patterns, but the detector is never applied to them. 3D stacks retain (N,) indexing. Polar and cepstral data must be converted appropriately before use.- Returns:
Without destination, a ragged result with scan-shaped object arrays: coords[index] is (n_peaks, 2), in (y, x) order; scores, synthetic_mask and orbit_ids align with its rows. processed_mask distinguishes excluded scans from evaluated patterns having zero peaks. Metadata includes source calibration, resolved pixel center and detector settings. This owned result survives source closure. With destination, return the atomically published peak-file path instead; never retain a complete peak collection in RAM. Load it explicitly with PeakScanResult.load(path), or read selected numeric /starts, /counts and /coords/… slices with h5py. Peak files are distinct from saved HyperData arrays and use .h5/.hdf5/.hdf; no suffix appends .peaks.h5.
- Return type:
fourdenoise.PeakScanResult or str
- Parameters:
intensity_radius (float or None) – Optional positive integration radius in detector pixels. Sum raw circular windows in float64 about measured integer peak positions using the existing intensity kernel, clipped at image boundaries. None does not integrate intensities. Correlation scores are not integrated intensity. Symmetry-generated rows have NaN scores and intensities, not fabricated observations; inspect synthetic_mask.
coords_units ({'pixels', 'auto', 'calibrated'}) – Output coordinates only. Default pixels means array (y-down,x-right). Calibrated means reciprocal units, y-up/x-right about the geometric midpoint, not the fitted beam center. Auto uses calibration if available. Search/template/integration parameters remain pixels.
working_memory_mb (float or None) – Temporary-buffer budget, default 256 MiB. Reserve a declared Rosetta IO chunk plus conservative template/FFT/candidate/symmetry workspace and two raw read/copy buffers. Too small raises before pixel reads. Metadata, existing detector/library/OS caches, Python allocator overhead and retained result arrays are excluded; not a RAM limit. Symmetry options can require a substantially larger budget.
chunk_size (int or None) – Maximum patterns per read, additionally limited by the budget. 4D reads stay within one scan row; the complete source is not flattened.
destination (path or None) – Incremental numeric peak-file output. Atomic publication is default; overwrite=True permits replacement, atomic=False permits a partial file on failure. Source aliases are forbidden. This source stays open on success/failure and pixels/metadata are never modified.
progress (bool) – Show one optional scan-progress bar, default True.
Examples
>>> with HyperData.open('scan.h5') as source: ... peaks = source.get_peaks(3, 5, intensity_radius=3, progress=False) >>> counts = peaks.observed_peak_counts >>> positions = peaks.coords[0, 0]
- DiffractionSource.to_polar(center=None, r_max=None, output_shape=None, order=1, fill_value=0.0, clip=False, *, destination, working_memory_mb=None, chunk_shape=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Convert Cartesian patterns directly into a saved polar dataset.
center,r_max,output_shape,order,fill_valueandcliphave the same meanings asfourdenoise.HyperData.to_polar(). In particular center/radius are Cartesian pixels, and the default center is the subpixel image midpoint. No fitting or hidden alignment is performed. The saved data retains scan calibration/origin, acquisition and R/Q records; polar metadata replaces Cartesian detector geometry as in the in-memory method.destinationis a distinct .4denoise/.h5/.hdf5/.hdf path; no suffix adds .4denoise. Return its path, not an eager HyperData. Read each pattern once, with one optional progress bar.working_memory_mb(default 256 MiB) budgets numerical blocks/interpolation work plus one declared Rosetta reader chunk. Metadata, caches, allocator overhead, caller-owned arrays and plotting are excluded.chunk_shapecan further limit scan positions per block; the memory budget still wins.Atomic output is the default: failures preserve an existing file and remove the temporary sibling. Replacing a destination requires
overwrite=True.atomic=Falseallows incomplete output on error. The source stays open on success/failure and is never modified.
- DiffractionSource.to_cartesian(output_shape=None, center=None, order=1, fill_value=0.0, clip=False, *, destination, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Convert saved polar patterns directly into a Cartesian saved file.
Numerical/coordinate options match
fourdenoise.HyperData.to_cartesian(). None uses a square of side 2*n_r;output_shape='original'uses the stored Cartesian canvas/center. Missing cropped annuli/sectors stay filled and only a complete angular domain wraps. Valid polar metadata is required; plain NumPy or vendor pixels do not imply it. The output recalibrates Cartesian detector pixels from the radial scale and retains unchanged scan/acquisition/R/Q metadata.Destination, memory budget, compression, atomic publication and source ownership follow
to_polar(). Return a path, not a full RAM array.
- DiffractionSource.resize(shape, domain, method='area', *, destination, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Resize scan or detector axes into a saved file without seams.
Shape/domain/method follow
fourdenoise.HyperData.resize(): real-space resizing supports a 2D 4D scan or the leading axis of a 3D stack; reciprocal resizing changes the final two axes. Area mode downsamples; linear/nearest also upsample. Fractional bins and interpolation halos use global coordinates across processing blocks, not independent local resizes. Polar reciprocal resizing retains the correct sample origins, radial scale and angular periodicity.Geometry/calibration are updated identically to in-memory resize. Return a saved path. Memory/publication/compression controls and source ownership follow
to_polar(). The budget includes one declared Rosetta reader chunk plus tiled numerical work buffers. Unfolding undo payloads are not preserved by this geometry-changing operation.
- DiffractionSource.remove_bg(background, bg_frac=1, a_min=1, a_max=None, *, destination, working_memory_mb=None, compression='gzip', compression_opts=4, overwrite=False, atomic=True, progress=True)[source]¶
Subtract one fixed detector-sized background directly into a saved file.
backgroundis a 2D array or ReciprocalSpace matching pattern_shape.bg_fracand clipping limits matchfourdenoise.HyperData.remove_bg(); seta_min=Noneto disable lower clipping. No global background estimation, residual inference or denoising is approximated per block. Estimate any common background explicitly first. Coordinate/acquisition metadata is retained; partial-block unfolding undo data is omitted.Return a saved path. Destination, numerical memory budget, compression, atomic publication and source ownership follow
to_polar(). The caller’s background array is excluded from the budget and never changed.
- DiffractionSource.iter_chunks(chunk_shape=16, *, working_memory_mb=None)[source]¶
Yield
(scan_slices, HyperData)blocks with independent storage.chunk_shapeis a maximum number of scan positions per axis: one positive integer, a one-tuple for 3D, or a two-tuple for 4D.working_memory_mbdefaults to 256 MiB and may reduce those sizes. It budgets two numerical read/copy buffers, excluding metadata, OS/ HDF5 caches and chunks retained by the caller. Do not collect all chunks into a list when the full dataset is too large for RAM.Detector geometry is preserved and 4D scan origins are offset for each block. Unfolding undo metadata is deliberately absent from partial blocks. Iterator reads fail clearly after source closure.
- DiffractionSource.load(*, max_memory_mb=None, working_memory_mb=None)[source]¶
Explicitly load all pixels and saved metadata into HyperData.
The returned object owns independent, writable storage and remains usable after closing this source. Dtype, calibration, acquisition, R/Q, beam and transformed-coordinate metadata are preserved. Saved unfolding undo data is read only here and restored on the full object.
max_memory_mboptionally caps the full numerical output allocation; an insufficient cap raises MemoryError before any pixel reads. None permits that allocation, which may require many GiB.working_memory_mbseparately bounds temporary input blocks (default 256 MiB). Neither limit includes metadata/undo payloads, library caches, allocator overhead, or other caller-owned arrays.
- DiffractionSource.close()[source]¶
Close the owned resource once; returned data remains independent.
- fourdenoise.unpack_reader_metadata(acquisition_metadata)[source]¶
Return independent RosettaSciIO axes and metadata from an acquisition record.
Accept
data.acquisition_metadataorsource.metadata['acquisition_metadata']. Returns a dictionary withaxes,metadataandoriginal_metadata; returns None when the record has no RosettaSciIO archive. Vendor keys containing slashes, bytes, arrays and timestamps survive HyperData save/load without pickle. Source axis descriptions remain in original storage order; the acquisition record separately stores the appliedaxis_order.
Viewing and geometry¶
- HyperData.compare_rq(real_image, reciprocal_image, *, 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]¶
Compare a fixed real-space image with a movable diffraction image.
This manual calibration viewer is useful with a virtual STEM image and a corresponding defocused shadow image. Only the two 2D inputs are copied. Original images and the full dataset are never resampled. Use an interactive Matplotlib backend (
%matplotlib widgetwith ipympl in Jupyter, or Qt in Spyder) for the sliders and buttons.- Parameters:
real_image (RealSpace or 2D ndarray) – Fixed reference. An array matching the dataset’s 2D scan shape inherits its real-space calibration; other arrays use pixels.
reciprocal_image (ReciprocalSpace or 2D ndarray) – Cartesian diffraction/shadow image. Its own beam metadata takes precedence. A plain array matching
pattern_shapeinherits this dataset’s reciprocal calibration and beam metadata. The pivot iscenter_px, thenmean_fit_center_px, then a calibrated center converted to pixels, or finally((Ky-1)/2, (Kx-1)/2). Stale or malformed center metadata raises an error rather than being used.layout ({'overlay', 'side_by_side'}, optional) – Overlay both images or show the fixed reference and transformed diffraction image on separate axes in the same reference frame.
real_alpha (float, optional) – Independent image opacities in [0, 1]. GUI sliders control both.
reciprocal_alpha (float, optional) – Independent image opacities in [0, 1]. GUI sliders control both.
interactive (bool, optional) – Show rotation, opacity, scale, shift, mirror, reset, apply and export controls. Noninteractive viewers can still be updated programmatically with
viewer.set_parameters(...).scale (positive float or None, optional) – Real horizontal pixels per diffraction pixel. None fits the image inside the reference field. This registration scale does not change either object’s physical calibration. Unequal scan spacings are respected when rotating, even when tick labels use pixels.
translation ((float, float), optional) –
(dy, dx)real-image pixels relative to its geometric midpoint. The diffraction pivot is placed at that midpoint plus this shift.real_show_kwargs (dict or None, optional) – Display options:
cmap,vmin,vmax,power,logScale,percentiles,symmetric,titleandinterpolation. Diffraction display defaults to logScale=True; real display is linear. The real options additionally acceptaxis_units,axes,grid,scale_bar,scale_bar_color, andscale_bar_labelfor the shared reference frame.reciprocal_show_kwargs (dict or None, optional) – Display options:
cmap,vmin,vmax,power,logScale,percentiles,symmetric,titleandinterpolation. Diffraction display defaults to logScale=True; real display is linear. The real options additionally acceptaxis_units,axes,grid,scale_bar,scale_bar_color, andscale_bar_labelfor the shared reference frame.figsize ((float, float), optional) – Figure size in inches.
show (bool, optional) – Call Matplotlib show. Set False for scripted composition/testing.
export_path (path-like, optional) – Initial filename in the GUI’s editable export box.
- Returns:
Retain this object as
viewer. Itscalibrationis the inverse of the displayed diffraction correction, with reflection included. Apply calibration stores that orientation on this dataset. Scale, shift and opacity remain preview settings;data.save(...)persists the applied orientation along with the other metadata.- Return type:
Examples
>>> viewer = data.compare_rq(virtual_image, shadow_image) >>> viewer.set_parameters(rotation_deg=12.5, real_alpha=0.6) >>> calibration = viewer.apply()
- HyperData.set_rq_calibration(rotation_deg=None, mirror_axis=None, *, calibration=None)[source]¶
Store real-to-detector orientation without changing array values.
- Parameters:
rotation_deg (float or None, optional) – Counterclockwise real-to-detector angle in Cartesian image axes (x right, y up). None defaults to zero when no calibration is given.
mirror_axis ({None, 'x', 'y'}, optional) – Reflect about this real-frame axis before the rotation. Reflection about x negates the y component; reflection about y negates x.
calibration (RQCalibration or dict, optional) – Reuse a calibration or its saved dictionary instead of supplying an angle/reflection. For example,
calibration=viewer.calibration.
- Returns:
This object, with updated metadata. Assign
rq_calibration=Noneto clear it. Save/load and copy preserve the calibration.- Return type:
- HyperData.get_dp(y=None, x=None, mask=None, operation=None, selection_units='pixels', *, working_memory_mb=None)[source]¶
Select a diffraction pattern or reduce a 3D stack/4D scan.
- Parameters:
y (number, length-2 range, or None, optional) – Scan selections for 4D data. Ranges are half-open; omitted axes select the complete axis. Two scalar indices return one pattern directly. For a 3D stack, pass its integer index as y or x.
get_dp('mean')is shorthand foroperation='mean'.x (number, length-2 range, or None, optional) – Scan selections for 4D data. Ranges are half-open; omitted axes select the complete axis. Two scalar indices return one pattern directly. For a 3D stack, pass its integer index as y or x.
get_dp('mean')is shorthand foroperation='mean'.mask (array-like of bool, optional) – Boolean scan mask of shape
(Ry, Rx)for 4D data. Selects the patterns included in the reduction; takes precedence over y/x. Empty selections and non-Boolean masks are rejected.operation ({'mean', 'std', 'min', 'max', 'median', 'random'}, optional) – Defaults to mean. Mean/std/min/max process bounded scan blocks. Std is the population standard deviation (ddof=0). Median remains exact but may copy the full selected stack; it is not memory-bounded. Random selects one pattern within the selection.
selection_units ({'pixels', 'calibrated', 'auto'}, optional) – Units for y/x on a 4D scan. Defaults to pixels even when calibration exists, so
get_dp(i, j)continues to select scan indices.working_memory_mb (positive float or None, keyword-only, optional) – Temporary-array budget in MiB (1024**2 bytes) for mean/std/min/max; None uses 256 MiB automatically. Accounts conservatively for block reads, masked copies, dtype conversion and reduction buffers. The resident source, input mask, Python/NumPy overhead and file caches are not included: this is not a total-process RAM limit. A budget too small for one pattern and its buffers raises a clear error. Explicit budgets are unsupported for median/random. Single-pattern index selections avoid aggregation and do not allocate these buffers.
- Returns:
Pattern with preserved detector units, direct-beam information and polar/cepstral geometry. No source values or metadata are modified.
- Return type:
Notes
Mean and variance accumulate using at least float64 precision, while floating input retains its output dtype. Integer means/stds return float64 and min/max retain the input dtype. NaN/Inf propagation follows NumPy, not nan-aware filtering. Block summation can differ in the final floating-point digits from one whole-array reduction.
- Raises:
TypeError – For unexpected keywords or a non-Boolean mask. The scan-mask argument is
mask, notreal_mask.ValueError – For invalid operations, selections or working-memory budgets.
Examples
>>> mean_dp = data.get_dp(mask=cluster_mask, working_memory_mb=64) >>> std_dp = data.get_dp(operation='std', working_memory_mb=64)
- HyperData.virtual_image(annulus=None, *, radius=None, centers=None, mask=None, theta_range=None, detector_units='auto', axis_units='auto', vmin=None, vmax=None, grid=True, num_div=10, plot_mask=False, grid_color='black', axes=True, return_detector=False, title='Virtual Detector Image', units='auto', mask_cmap='turbo', mask_vmin=None, mask_vmax=None, mask_power=1, mask_log_scale=True, mask_show_kwargs=None, ring_color='green', ring_alpha=0.3, show=True, working_memory_mb=None)[source]¶
Form a real-space virtual image using a reciprocal-space detector.
Products and sums are evaluated blockwise in at least float64 precision without allocating a complete weighted tensor.
working_memory_mbbounds the numerical workspace (default 256 MiB); it excludes the returned scan image, detector construction, metadata, caches and plots. The source is never mutated, and NaN/Inf propagate as in NumPy sums. A mean detector is computed only for plot_mask or return_detector. Complex amplitudes are rejected; supply real-valued intensities.The detector type is inferred from exactly one of these specifications:
annulus=(inner_radius, outer_radius)for a centered annulus.radiusandcentersfor one or more Cartesian disks.maskfor an arbitrary Boolean or weighted detector.
- Parameters:
annulus (array-like of two floats or None, optional) – Inner and outer detector radii. Interpreted according to
detector_units. For Cartesian data the annulus is centered at the diffraction origin. For polar data it selects a radialkrinterval.radius (float or array-like of floats or None, optional) – Radius of each Cartesian circular detector. Interpreted according to
detector_units. A scalar is applied to every center; otherwise provide one radius per center.centers (array-like or None, optional) – One
(ky, kx)center or an(N, 2)array of centers. Multiple circles are combined as a union. Pixel centers are array coordinates. Calibrated centers are reciprocal coordinates relative to the diffraction origin, with positivekyupward and positivekxto the right. Only valid for Cartesian data.mask (ndarray or None, optional) – Arbitrary detector with shape matching the last two data axes. Boolean masks select pixels. Numeric masks act as detector weights and may contain positive, negative, or fractional values.
theta_range (array-like of two floats or None, optional) – Angular interval in degrees for a polar annular detector. A wrapped interval such as
(330, 30)is supported. This parameter is only valid withannuluson polar data.detector_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for
annulus,radius, andcenters.'auto'uses reciprocal calibration when available and otherwise falls back to pixels.axis_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for the displayed real-space virtual image axes.
'auto'uses real-space calibration when available and otherwise falls back to pixels.vmin (float or None, optional) – Display range passed to the real-space visualization.
vmax (float or None, optional) – Display range passed to the real-space visualization.
title (str, optional) – Title of the real-space virtual image.
grid (bool, optional) – Whether to overlay a scan grid on the virtual image.
num_div (int or tuple, optional) – Number of grid divisions along each real-space axis.
plot_mask (bool, optional) – If True, show the unmasked mean diffraction pattern with the detector region overlaid. For
annulus, the overlay is a ring.units ({'auto', 'pixels', 'calibrated'}, optional) – Axis units for the diffraction pattern shown by
plot_mask.'auto'uses the stored reciprocal-space calibration.mask_cmap (str, optional) – Diffraction-pattern colormap used by
plot_mask.mask_vmin (float or None, optional) – Display limits for the diffraction pattern shown by
plot_mask. These are independent of the virtual image’svminandvmax.mask_vmax (float or None, optional) – Display limits for the diffraction pattern shown by
plot_mask. These are independent of the virtual image’svminandvmax.mask_power (float, optional) – Intensity power passed to
ReciprocalSpace.show.mask_log_scale (bool, optional) – Whether the mean diffraction pattern uses logarithmic display.
mask_show_kwargs (dict or None, optional) – Additional
ReciprocalSpace.showoptions for the diffraction pattern, such asfigsize,aspect, andaxes.ring_color (matplotlib color, optional) – Color of the detector overlay. Defaults to green.
ring_alpha (float, optional) – Overlay opacity between 0 and 1. The default 0.3 is 70% transparent.
grid_color (str, optional) – Grid color for the real-space visualization.
axes (bool, optional) – Whether to show axes in the real-space visualization.
return_detector (bool, optional) – If True, also return the masked mean diffraction pattern.
show (bool, optional) – Display the virtual image when True. Set False to return a
RealSpaceimage without creating its figure.
- Returns:
The virtual image, optionally followed by the detector image. The detector image is
ReciprocalSpacefor Cartesian data andHyperDatawith polar metadata for polar data.- Return type:
RealSpace or tuple
Examples
>>> image = data.virtual_image(annulus=(10, 35), detector_units='pixels') >>> image = data.virtual_image(radius=5, centers=(62, 74), detector_units='pixels') >>> image = data.virtual_image( ... radius=[4, 5], ... centers=[(62, 74), (51, 43)], ... ) >>> image = data.virtual_image(mask=detector_weights)
- HyperData.visualize(grid_shape=None, padding=2, reduction='mean', power=1, title='Diffraction-Pattern Montage', log_scale=True, axes=True, vmin=None, vmax=None, figsize=None, aspect=None, cmap='turbo', axis_units='auto')[source]¶
Display a reduced 4D dataset as a two-dimensional diffraction montage.
Neighboring scan positions are combined into
grid_shapereal-space bins. Each resulting diffraction pattern is placed at the corresponding scan position in one image, separated by white padding. A shared intensity scale is used so brightness remains comparable across tiles.- Parameters:
grid_shape (tuple of int or None, optional) – Number of diffraction patterns to display as
(Ny, Nx). Values cannot exceed the corresponding real-space dimensions. By default, each dimension is 10 percent of its original size, rounded down, with a minimum of 1 and a maximum of 25.padding (int, optional) – Number of white display pixels between adjacent patterns.
reduction ({'mean', 'sum'}, optional) – How scan positions contributing to each displayed tile are combined.
'mean'uses area-weighted averaging.'sum'approximates an integrated diffraction pattern for each bin.power (float, optional) – Display parameter matching
ReciprocalSpace.show(). With logarithmic scaling the values arepower * log(intensity); otherwise they areintensity ** power.title (str, optional) – Figure title.
log_scale (bool, optional) – Apply logarithmic intensity scaling.
axes (bool, optional) – Show real-space scan-position axes and a shared colorbar.
vmin (float or None, optional) – Shared display limits after the intensity transformation.
vmax (float or None, optional) – Shared display limits after the intensity transformation.
figsize (tuple or None, optional) – Matplotlib figure size. It is inferred from the montage if omitted.
aspect (float, str, or None, optional) – Aspect ratio forwarded to the montage axes.
cmap (str, optional) – Matplotlib colormap used for every diffraction pattern.
axis_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for the displayed real-space scan axes and the per-tile reciprocal-space calibration note.
'auto'uses stored calibration when available and otherwise falls back to pixels.
- Returns:
(fig, ax)for further customization or saving.- Return type:
tuple
Notes
The outer axes describe real-space scan position. Reciprocal-space axes repeat inside every tile and cannot be represented by one continuous montage axis, so their calibration is reported in the title.
- HyperData.crop(ylim=None, xlim=None, kylim=None, kxlim=None, kshape=None, rshape=None, real_limit_units='auto', reciprocal_limit_units='auto')[source]¶
Crop a 4D dataset either in the real or the reciprocal domain, with optional subpixel cropping and enforced resizing in both k-space (kshape) and real space (rshape).
- Parameters:
ylim (int or tuple, optional) – Real-space vertical limits. Interpreted according to
real_limit_units.xlim (int or tuple, optional) – Real-space horizontal limits. Interpreted according to
real_limit_units.kylim (int or tuple of (float or int), optional) – Reciprocal-space vertical limits. Interpreted according to
reciprocal_limit_units. Pixel-space values can be floats for subpixel cropping. Calibrated reciprocal limits use coordinates relative to the diffraction origin, with positive ky upward.kxlim (int or tuple of (float or int), optional) – Reciprocal-space horizontal limits. Interpreted according to
reciprocal_limit_units. Pixel-space values can be floats for subpixel cropping. Calibrated reciprocal limits use coordinates relative to the diffraction origin, with positive kx to the right.kshape (tuple of (int, int), optional) – Shape (A, B) to resize cropped diffraction patterns to. If not provided, each requested window extent is rounded to the nearest integer, with a minimum of one pixel, rather than using the enclosing integer slice. Limits are half-open pixel-index bounds: output pixel j samples
start + (j + 0.5) * (stop - start) / output_size - 0.5. For example, a four-pixel window (1.2, 5.2) samples 1.2, 2.2, 3.2, 4.2 along that axis. Downsampling is anti-aliased. Interpolating integer data returns floating-point output so detector counts retain their original range and subpixel values.rshape (tuple of (int, int), optional) – Shape (Ny_out, Nx_out) for real-space resizing (generalized binning). When
rshapedivides the current real-space shape, block averaging is used. Otherwise, the scan axes are interpolated. Resampling integer data produces floating-point output so fractional counts are not truncated.real_limit_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for
ylimandxlim.'auto'uses stored real-space calibration when available and otherwise falls back to pixels. Calibrated limits account for the image’s real-space origin.reciprocal_limit_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system used for
kylimandkxlim.'auto'uses stored reciprocal-space calibration when available and otherwise falls back to pixels. For polar data, limits are radial/angular array indices; use'pixels'or'auto'. Crops update polar sample ranges and support; an angular sector is no longer a full periodic circle.
Examples
Crop with pixel limits:
>>> cropped = data.crop( ... ylim=(10, 40), ... xlim=(20, 60), ... kylim=(30, 90), ... kxlim=(28, 92), ... real_limit_units='pixels', ... reciprocal_limit_units='pixels', ... )
Crop using stored calibrated units:
>>> cropped = data.crop( ... ylim=(0.0, 5.0), ... xlim=(0.0, 5.0), ... kylim=(-0.6, 0.6), ... kxlim=(-0.6, 0.6), ... real_limit_units='calibrated', ... reciprocal_limit_units='calibrated', ... )
- HyperData.resize(shape, domain, method='area', *, working_memory_mb=None)[source]¶
Resize selected axes using memory-budgeted output tiles.
- Parameters:
shape (int or sequence of int) – Desired domain shape. A 4D scan uses a (y, x) pair in either domain; a 3D stack uses an integer for real-space stack length.
domain ({'real', 'reciprocal'}) – Axes to resize, without mixing the other domain.
method ({'area', 'linear', 'nearest'}, optional) – Area-weighted averaging supports downsampling. Linear and nearest also support upsampling. Fractional bins and interpolation halos are defined globally, not separately inside each tile.
working_memory_mb (float or None, optional) – Temporary-buffer budget in MiB; None selects 256 MiB. Includes source reads, conversion, interpolation/filtering and tile buffers. Resident input and the complete returned output, allocator overhead and file caches are excluded. Too-small budgets raise ValueError. Use resize_hdf5 for outputs too large to keep in RAM.
- Returns:
Independently stored data with updated coordinate metadata.
- Return type:
Notes
Floating/complex output retains the source dtype, with at least float64 accumulator precision. Integer/Boolean averaging or linear interpolation produces float64; nearest retains the original dtype. A completely unchanged resize makes one same-dtype independent output, without interpolating or promoting its values.
Real-space pixel spacing and pixel-center origin are updated. Polar interpolation preserves radial endpoints and full-circle periodicity; area averaging records shifted sample centers. Beam/cepstral geometry is updated, or invalidated when its shape no longer represents it. Resizing changes geometry and does not retain unfolding undo metadata.
- HyperData.to_polar(center=None, r_max=None, output_shape=None, order=1, fill_value=0.0, clip=False, progress=True)[source]¶
Remap each diffraction pattern from Cartesian
(ky, kx)to polar(radius, angle)coordinates.The default output samples the largest centered circle that fits inside the diffraction pattern. The radial size is
ceil(r_max)and the angular size isceil(2*pi*r_max), so angular sampling roughly matches the outer circumference. The returned object storespolar_metadataso downstream methods know that the last two axes arekrandktheta.kthetais displayed from 0 to 360 degrees, whilekris displayed in the original reciprocal units when calibration is available.- Parameters:
center (tuple of two floats, optional) – (y_center, x_center) in pixel coordinates. Defaults to the image midpoint.
r_max (float, optional) – Maximum sampled radius in pixels. Defaults to the largest centered circle that fits inside the diffraction pattern. If a larger radius is requested, out-of-bounds samples are filled with
fill_value.output_shape (tuple (n_r, n_theta), optional) – Desired shape of the output polar image. - n_r = number of radial samples - n_theta = number of angular samples Default:
(ceil(r_max), ceil(2*pi*r_max)).order (int, default=1) – The spline interpolation order for map_coordinates (0=nearest, 1=bilinear, 3=cubic, etc.). For integer input, interpolation returns floating-point data; nearest-neighbor sampling retains integer dtype.
fill_value (float, optional) – Value used for out-of-bounds samples if
r_maxextends beyond the input diffraction pattern.clip (bool, optional) – If True, apply
clip_values()to each transformed pattern. Defaults to False to preserve zeros and sub-unit intensities.progress (bool, optional) – If True, display a progress bar.
- Returns:
New object with shape
(B, n_r, n_theta)for 3D data or(Ry, Rx, n_r, n_theta)for 4D data.- Return type:
- HyperData.to_cartesian(output_shape=None, center=None, order=1, fill_value=0.0, clip=False, progress=True)[source]¶
Resample polar diffraction data back onto a Cartesian
(ky, kx)grid.This is an inverse resampling operation, not an exact undo of
to_polar(). Any Cartesian pixels outside the sampled polar support are filled withfill_value. After cropping, this includes missing inner radii and angular sectors. Stored sample origins and steps are used; a cropped sector is never treated as a full circle.- Parameters:
output_shape (tuple(int, int), 'original', or None, optional) – Cartesian diffraction shape
(Ky, Kx)to reconstruct. If None, use(2*n_r, 2*n_r), wheren_ris the polar radial axis size. This makes the polarkr_maxmap to a circle whose diameter is the output image width/height. Use'original'to reconstruct on the Cartesian shape stored byto_polar().center (tuple(float, float) or None, optional) – Cartesian center
(cy, cx)in the output image. If None, use the output midpoint. Withoutput_shape='original', use the stored original Cartesian center when available.order (int, optional) – Spline interpolation order passed to
map_coordinates(). For integer input, interpolation returns floating-point data; nearest-neighbor sampling retains integer dtype.fill_value (float, optional) – Value assigned outside the polar support or outside polar bounds.
clip (bool, optional) – If True, apply
clip_values()to each reconstructed pattern. Defaults to False to preserve zeros and sub-unit intensities.progress (bool, optional) – If True, display a progress bar.
- Returns:
New Cartesian HyperData object. The returned object is not marked polar. Its reciprocal calibration is computed from the polar
kr_maxand the selected Cartesian output radius, so the displayedkx/kyscale matches the polar radial scale.- Return type:
Preprocessing and denoising¶
- HyperData.clip(a_min=1, a_max=None, mask=None)[source]¶
Clip all or selected data values to the interval [a_min, a_max].
Values smaller than a_min are set to a_min; values larger than a_max are set to a_max. If a_min or a_max is None, clipping on that side is skipped. When
maskis provided, values outside the mask are copied without modification.- Parameters:
a_min (float or None, optional) – Lower bound for clipping. If None, no lower clipping is applied. Default is 1.
a_max (float or None, optional) – Upper bound for clipping. If None, no upper clipping is applied. Default is None.
mask (array-like of bool or data object, optional) – Region where clipping is applied. A full-shape mask selects individual values. For 4D data, a
(Ry, Rx)mask selects whole diffraction patterns and a(Ky, Kx)mask selects reciprocal pixels across every pattern. For 3D data, a(N,)mask selects complete patterns. Explicitly broadcastable masks are also accepted. If omitted, the complete array is clipped.
- Returns:
New HyperData instance with clipped data and preserved metadata.
- Return type:
Examples
Clip the complete dataset:
>>> clipped = data.clip(a_min=0, a_max=100)
Clip only selected scan positions in a 4D dataset:
>>> scan_mask = np.zeros(data.shape[:2], dtype=bool) >>> scan_mask[10:20, 15:25] = True >>> clipped = data.clip(a_min=1, mask=scan_mask)
Clip selected reciprocal-space pixels in every diffraction pattern:
>>> k_mask = np.zeros(data.shape[-2:], dtype=bool) >>> k_mask[30:90, 30:90] = True >>> clipped = data.clip(a_max=500, mask=k_mask)
Notes
This method does not mutate
self.array.
- HyperData.remove_bg(background, bg_frac=1, residual_bg_frac=0, a_min=1, a_max=None, **resBg_kwargs)[source]¶
Subtract a diffraction background and clip the resulting dataset.
- Parameters:
background (ndarray or ReciprocalSpace) – Background diffraction pattern matching the last two data axes.
bg_frac (float, optional) – The fraction of the background to be subtracted from the dataset. Must be between 0 and 1 (inclusive).
residual_bg_frac (float, optional) – Fraction of the per-pattern residual background to subtract.
a_min (float or None, optional) – Lower and upper clipping limits after subtraction.
a_min=1matchesclip(); seta_min=Noneto leave values unclipped.a_max (float or None, optional) – Lower and upper clipping limits after subtraction.
a_min=1matchesclip(); seta_min=Noneto leave values unclipped.**resBg_kwargs – Options passed to
get_residualBgwhen residual subtraction is used.
- Returns:
A new instance of HyperData with the background subtracted.
- Return type:
- Raises:
ValueError – If ‘bg_frac’ is not within the required range [0, 1] or ‘background’ is not of the same shape as the diffraction patterns.
- HyperData.alignment(r_center=5, iterations=1, center=None, method='com', search_radius=None, enforce_square=False, fit_radius=False, radius_range=None, radius_step=1, radius_operation='mean', radius_reference_dp=None, template='disk', trench_width=1.0, kernel_amp=1.0, trench_amp=-0.5, gaussian_sigma=None)[source]¶
Align the diffraction patterns through the Center of mass of the center beam
- Parameters:
r_center (float) – Radius of the central peak or disk in pixels.
iterations (int) – Number of alignment refinement passes. For
method='disk'ormethod='template', the first pass crops and aligns to a common output shape; additional passes re-fit the center on the aligned stack and apply residual subpixel shifts.center (tuple or None) – Approximate reference disk center
(ky, kx). Defaults to the geometric k-space center((ky - 1)/2, (kx - 1)/2). Whenfit_radius=Trueorradius_rangeis provided, this center is refined on the representative diffraction pattern before aligning individual diffraction patterns.method ({'com', 'disk', 'template'}) –
'com'uses the original center-of-mass workflow.'disk'or'template'uses circular template matching, centered cropping, and a final affine subpixel shift.template ({'disk', 'negative_trench', 'gaussian'}) – Template used by the template-matching workflow.
'disk'is the historical behavior: a filled circular disk, mean-subtracted and normalized.'negative_trench'uses a positive disk surrounded by a negative ring.'gaussian'uses a centered 2D Gaussian.search_radius (float or None) – Maximum disk-center translation, in pixels, around the current reference center. During reference fitting, the search is centered on
center. After the representative disk center is found, the same radius is centered on that fitted reference center for all per-pattern template matching. If None, the full diffraction pattern is searched. This is a translation search radius, not a radius-range search for the disk size.enforce_square (bool) – If True, force the disk-template output to satisfy
ky == kx.fit_radius (bool) – If True, estimate the best disk-template radius from a representative diffraction pattern before aligning all diffraction patterns.
radius_range (tuple or sequence or None) – Candidate radii used when
fit_radius=True. A two-value tuple is interpreted as(r_min, r_max)and sampled byradius_step. A longer sequence is used directly as the candidate radii. If None, a local radius search aroundr_centeris used.radius_step (float) – Step size for two-value
radius_rangesearches.radius_operation (str) – Operation passed to
get_dp(operation=...)to build the representative diffraction pattern used for radius fitting whenradius_reference_dpis not provided.radius_reference_dp (array-like or data object, optional) – Direct 2D diffraction pattern used as the representative pattern for disk-radius fitting. This can be a plain
ndarrayor an object with an.arrayattribute, such asReciprocalSpace. The shape must match the reciprocal-space shape(ky, kx). Providing this parameter implies radius fitting and bypassesradius_operationfor the reference pattern.trench_width (float) – Width of the negative ring used by
template='negative_trench'.kernel_amp (float) – Amplitude of the positive disk for
template='negative_trench'.trench_amp (float) – Amplitude of the surrounding trench for
template='negative_trench'. Negative values are usually useful.gaussian_sigma (float or None) – Standard deviation for
template='gaussian'. If None, defaults tor_center / 2for each tested radius.
Notes
method='com'is useful when the center beam is compact, bright, roughly isolated, and its center of mass is a stable estimate. Gaussian template matching is useful when the central beam is more peak-like or blobby than disk-like. Negative trench template matching is better when the central beam is disk-like with a clear edge, especially when the local background is sloped or slowly varying.
- HyperData.block_direct_beam(radius=None, center=None, beam_units='auto', fill_value=1, return_mask=False)[source]¶
Block the central/direct beam in every diffraction pattern.
This method masks a circular disk on the last two reciprocal-space axes and replaces the selected direct-beam pixels with
fill_value. It supports 3D stacks(N, Ky, Kx)and 4D-STEM datasets(Ry, Rx, Ky, Kx). The operation never mutatesself.array.- Parameters:
radius (float or None, optional) – Direct-beam radius. Explicit values take precedence over stored
center_beam_metadata. If omitted, the method usescenter_beam_metadata['radius_px']from alignment.center (array-like of two floats or None, optional) – Direct-beam center as
(ky, kx). Explicit values take precedence over metadata. If omitted, the method uses metadata when available and otherwise falls back to the geometric diffraction-pattern center.beam_units ({'auto', 'pixels', 'calibrated'}, optional) – Unit system for explicit
radiusandcenter.'auto'uses reciprocal-space calibration when available and otherwise falls back to pixels. Calibrated centers are reciprocal coordinates relative to the diffraction origin, with positivekyupward and positivekxto the right.fill_value (scalar, optional) – Value assigned to blocked direct-beam pixels. Defaults to 1.
return_mask (bool, optional) – If True, return
(blocked_data, beam_mask)wherebeam_maskis True for blocked pixels.
- Returns:
New HyperData object with direct-beam pixels blocked, optionally followed by the 2D beam mask.
- Return type:
HyperData or tuple
Notes
block_direct_beamis the preferred name.remove_center_beamis kept as an alias for older notebook wording.
- HyperData.unfold(domain='real', method='row_major', curve_shape_strategy='center_crop', preserve_excess=True, resize_side=None, resize_side_mode='nearest', resize_method='linear', preserve_original=False, undo=False, metadata=None, original_shape=None, return_metadata=False, plot_traversal=False, plot_kwargs=None, warn_on_crop=True)[source]¶
Unfold or restore a 4D-STEM tensor using explicit domain/method choices.
The tensor convention is
(Ry, Rx, Ky, Kx).domaincontrols which coordinate grid is unfolded, whilemethodcontrols the coordinate traversal or axis alignment strategy.- Parameters:
domain ({'real', 'reciprocal', 'both'}, optional) – Coordinate domain to unfold.
'real'produces a stack of diffraction patterns,'reciprocal'produces a stack of real-space images along the last axis, and'both'produces a 2D matrix.method (str, optional) – Traversal or axis-alignment method. Supported traversal methods are
'row_major','serpentine','spiral','diagonal_zigzag','hilbert','morton'/'z_order','peano','peano_meander','meander-4', and'meander-5'.'moore'is reserved and currently raisesNotImplementedError.coordinate_alignedis supported fordomain='real'anddomain='reciprocal'only.curve_shape_strategy ({'center_crop', 'resize'}, optional) – How compatible curve/block methods handle incompatible shapes.
'center_crop'unfolds the centered compatible square or block-meander rectangle.'resize'first resizes the selected traversal domain to a compatible square.meander-4andmeander-5currently support center-crop only.preserve_excess (bool, optional) – For center-crop curve methods, store cropped-out values in metadata so undo can reconstruct the original full tensor exactly. This consumes space proportional to the excluded data. Value-only operations on an unfolded object leave excluded values unchanged.
warn_on_crop (bool, optional) – Warn when center-cropping excludes coordinates from the unfolded tensor. The warning reports the selected region and whether undo can restore the excluded values. Set False for an intentional crop.
resize_side (int or None, optional) – Explicit compatible side length for resize mode. Hilbert, Morton, Z-order, and Moore require powers of 2; Peano requires powers of 3.
meander-4andmeander-5do not use this parameter.resize_side_mode ({'nearest', 'downsample', 'upsample'}, optional) – How to choose a compatible side when
resize_sideis omitted.resize_method ({'linear', 'nearest', 'area'}, optional) – Method passed to
resize()in resize mode.preserve_original (bool, optional) – For resize mode, store the original tensor in metadata so undo can reconstruct it exactly. This requires one full-tensor copy; otherwise undo returns the resized tensor. Shape-preserving operations share the stored read-only values rather than copying them again.
metadata['preserved_values_nbytes']reports their total size.undo (bool, optional) – If True, restore an unfolded object using
metadataor this object’s attachedunfold_metadata. If no metadata is available, row-major undo is supported usingoriginal_shapeor square-grid inference.metadata (dict or None, optional) – Metadata returned by a previous unfolding. Required for undo unless this object already has attached metadata, or the requested undo can be handled as row-major using
original_shape.original_shape (tuple or None, optional) – Shape used for metadata-less row-major undo. The full
(Ry, Rx, Ky, Kx)shape is always accepted. For 3Ddomain='real'stacks,(Ry, Rx)is also accepted and(Ky, Kx)is taken from the stack. For 3Ddomain='reciprocal'stacks,(Ky, Kx)is also accepted and(Ry, Rx)is taken from the stack.return_metadata (bool, optional) – If True, return
(result, metadata).plot_traversal (bool, optional) – Plot the selected traversal when unfolding. For
domain='both', show separate real- and reciprocal-space paths. Not available forundo=Trueormethod='coordinate_aligned'.plot_kwargs (dict or None, optional) – Options passed to
plot_traversals(), exceptmethod, which always matches this unfolding. By defaultgrid_shapeis the actual traversal grid (after any resize). Setgrid_shapefor a smaller preview; that figure may differ from the exact path used on the data. Other options includecmap,linewidth,show_grid,mark_endpoints,ncols, andshow.show=Falseleaves the figure open without displaying it.
- Returns:
New object containing the unfolded or restored data. The original object is not modified.
- Return type:
Examples
>>> original = np.arange(2*3*4*5).reshape(2, 3, 4, 5) >>> hd = HyperData(original) >>> unfolded, meta = hd.unfold(domain='real', ... method='hilbert', ... preserve_excess=True, ... return_metadata=True) >>> restored = unfolded.unfold(undo=True) >>> np.array_equal(restored.array, original) True >>> restored = HyperData(unfolded.array).unfold(undo=True, metadata=meta) >>> np.array_equal(restored.array, original) True >>> restored = HyperData(unfolded.array).unfold( ... undo=True, ... domain='real', ... original_shape=original.shape, ... ) >>> preview = hd.unfold( ... method='hilbert', plot_traversal=True, ... plot_kwargs={'grid_shape': (16, 16), 'cmap': 'viridis'}, ... )
- HyperData.reshape(*shape, order='C', return_array=False)[source]¶
Return a row-major reshaped copy of this dataset.
This is a thin HyperData wrapper around
numpy.reshape. It is useful when the data are already unfolded/folded in standard row-major order and the desired target shape is known directly.- Parameters:
*shape (int or tuple) – Target shape, either as separate dimensions or as one tuple. NumPy’s
-1inference is supported.order ({'C', 'F', 'A'}, optional) – Reshape order passed to
numpy.reshape. The default'C'is Python/NumPy row-major order.return_array (bool, optional) – If True, return the reshaped ndarray instead of a
HyperData.
Examples
>>> folded = HyperData(stack).reshape(Ry, Rx, Ky, Kx) >>> stack = HyperData(folded.array).reshape(Ry * Rx, Ky, Kx)
- HyperData.denoise(method, domain='reciprocal', unfold_domain=None, unfold_method='row_major', unfold_kwargs=None, return_array=False, convergence_plot=False, convergence_ax=None, convergence_show=True, **kwargs)[source]¶
Denoise this dataset and return a new
HyperDataobject.- Parameters:
method (str) – Name of a method available in
available_denoising_methods.domain ({'real', 'reciprocal'} or None, optional) – Coordinate domain used for denoising 4D data.
'real'selects axes 0 and 1, while'reciprocal'selects axes 2 and 3. Axis-aware methods such asmedianoperate on those axes in one whole-array call; methods that require individual 2D images remain slice-wise. Usedomain=Noneto apply a method directly to the whole array. For 2D and 3D data, methods are applied directly to the whole array regardless of domain.unfold_domain ({'real', 'reciprocal', 'both'} or None, optional) – Domain to unfold before denoising. If provided for 4D data, the data are unfolded, denoised as a whole lower-dimensional array, and then refolded automatically.
unfold_method (str, optional) – Traversal method passed to
unfold()during generic unfold-denoise-refold routing. A 3D volume filter treats the traversal index as one spatial axis, which cannot preserve every neighbor relationship of the original 2D coordinate grid.unfold_kwargs (dict or None, optional) – Additional keyword arguments passed to
unfold(), such ascurve_shape_strategyorpreserve_excess. A non-preserving crop or resize may return a smaller or resized 4D dataset; its calibration is updated for that geometry.preserve_original=Trueis not supported with resize here, because undo would discard the denoising result.return_array (bool, optional) – If True, return the denoised
ndarrayinstead of wrapping it in a newHyperDataobject.convergence_plot (bool, optional) – Plot the method’s reported per-iteration errors from this same denoising run. Requires a method with
return_errorssupport. Plotting does not change the default reconstruction-only return.convergence_ax (matplotlib.axes.Axes or None, optional) – Existing axes for the convergence plot. Only used when
convergence_plot=True.convergence_show (bool, optional) – Call
plt.show()for the convergence plot. Set False to compose or save the figure yourself throughconvergence_ax.**kwargs – Keyword arguments passed to the selected denoising method.
return_decomposition=Trueretains the method’s existing auxiliary return type for direct denoising. It is not supported with slice-wise 4D routing or automatic unfolding. For methods supportingreturn_errors=True, return(reconstruction, convergence_errors). Usedomain=Noneorunfold_domainfor 4D data; separate 2D slices do not have one shared convergence history. The plotted history is the selected method’s reported error, not a separately calculated residual; its definition may differ between methods. Tensor-Ring histories include iteration zero.
- Returns:
Denoised data. By default this is a new
HyperDataobject that preserves this object’s calibration metadata. Withreturn_errors=True, the first tuple element is the same reconstruction and the second is TensorLy’s error sequence.- Return type:
HyperData or ndarray, or tuple
Examples
>>> denoised = my_dataset.denoise( ... method='median', ... domain='reciprocal', ... window_size=3, ... ) >>> denoised = my_dataset.denoise( ... method='some_3d_method', ... unfold_domain='real', ... unfold_method='meander-4', ... ) >>> denoised = my_dataset.denoise( ... method='some_whole_array_method', ... domain=None, ... ) >>> denoised, errors = my_dataset.denoise( ... method='parafac', rank=5, return_errors=True, ... ) >>> denoised = my_dataset.denoise( ... method='parafac', rank=5, convergence_plot=True, ... )
- HyperData.denoise_info(method=None, include_doc=True, print_info=True)[source]¶
Alias for
denoising_method_info().
- HyperData.rank_scree(method, ranks, domain='reciprocal', unfold_domain=None, unfold_method='row_major', unfold_kwargs=None, metric='relative_error', plot=True, ax=None, log_y=False, show=True, progress=True, return_reconstructions=False, error_chunk_elements=1000000, **kwargs)[source]¶
Run a rank sweep and plot final reconstruction quality for each rank.
This method performs one complete denoising/decomposition run per rank. It is therefore much more expensive than a convergence plot from one denoise call.
ranksmay be arange, tuple, list, NumPy array, or any iterable of positive numeric rank values. Nested rank values, such as[(2, 2, 2), (4, 4, 4)]for Tucker-style rank specifications, are also accepted. When unfolding is requested, the input is unfolded once for the whole sweep. For reversible traversals, errors are measured in unfolded order without constructing full refolded arrays unlessreturn_reconstructions=True. For a cropped or resized traversal, fit quality is measured on the tensor actually denoised, not on untouched excess pixels or the original pre-resize tensor.- Parameters:
method (str) – Name of a denoising method that accepts a
rankargument.ranks (iterable) – Rank values to evaluate. Examples:
range(1, 31),[1, 2, 4, 8],np.array([5, 10, 20]).domain ({'real', 'reciprocal'} or None, optional) – Passed to
denoise().unfold_domain ({'real', 'reciprocal', 'both'} or None, optional) – Passed to
denoise().unfold_method (str, optional) – Passed to
denoise().unfold_kwargs (dict or None, optional) – Additional unfolding arguments passed to
denoise(). Resize traversals must usepreserve_original=Falseso undo returns the processed resized tensor rather than the saved input.metric ({'relative_error', 'residual_norm', 'fit'}, optional) – Quantity to plot on the y-axis.
plot (bool, optional) – If True, create a Matplotlib scree/elbow plot.
ax (matplotlib.axes.Axes or None, optional) – Existing axes for plotting. If None, a new figure is created.
log_y (bool, optional) – If True, use a logarithmic y-axis.
show (bool, optional) – If True, call
plt.show()after plotting.progress (bool, optional) – If True, show a progress bar over ranks.
return_reconstructions (bool, optional) – If True, include each reconstructed array in the returned results. This intentionally retains one full array per rank in memory.
error_chunk_elements (int, optional) – Maximum elements per block when computing reconstruction norms. Defaults to one million; lower this to reduce temporary memory.
**kwargs – Keyword arguments passed to
denoise()for every rank.
- Returns:
Dictionary containing ranks, residual norms, relative errors, fit, and plotting objects.
- Return type:
dict
Peak and strain analysis¶
- HyperData.get_braggness(annulus=(18.0, 50.0), *, center=None, sigma=2.0, top_pixels=50, denominator_floor=1.0, scan_mask=None, nonfinite='raise', progress=False)[source]¶
Measure concentrated sharp diffraction contrast, one pattern at a time.
Gaussian-filter each complete diffraction pattern D, then form
R = maximum(D - Gaussian(D), 0). Sum the largesttop_pixelsvalues of R inside the annulus and divide bymax(sum(D inside the annulus), denominator_floor). The Gaussian uses SciPymode='reflect'andtruncate=4.0and never mixes scan positions. This is not an FFT or a count of detected Bragg peaks.- Parameters:
annulus (pair of float, default (18, 50)) – Inner and outer radii in Cartesian detector pixels, selecting
inner <= radius < outer. Inner must be nonnegative and outer strictly greater. These bounds differ fromvirtual_image.center (pair of float or None) – Explicit array pixel coordinates
(ky, kx)override metadata. None usescenter_beam_metadata['center_px']from alignment, thenmean_fit_center_px, thencenter_calibratedconverted to pixels using its stored or current reciprocal calibration. Without a stored center, use the subpixel image center((Ky-1)/2, (Kx-1)/2). Stale/malformed metadata raises an error. Setcenter=(64, 64)explicitly to reproduce the 128x128 raw 4D-TOMO notebook calculation (not the image center 63.5).sigma (float, default 2) – Positive finite Gaussian width in detector pixels.
top_pixels (int, default 50) – Positive count, no greater than the selected annulus pixel count.
denominator_floor (float, default 1) – Positive finite lower bound on integrated annulus intensity.
scan_mask (boolean array or None) – Shape must equal
scan_shape. True means evaluate; False yields NaN and invalid status without reading/checking that pattern. For one 2D pattern, a scalar boolean has the required shape().nonfinite ({'raise', 'omit'}, default 'raise') – Raise with the scan index if any pixel in an evaluated pattern is nonfinite; omit invalidates the entire pattern. Numerical overflow during calculation follows the same policy. No values are repaired.
progress (bool, default False) – Display one progress bar over scan positions.
- Returns:
Float32 score and boolean validity arrays of shape
scan_shape; small metadata records settings, center source, dtype policy, and diagnostic counts. For 4D data,result.as_real_space()retains scan calibration.- Return type:
Notes
Supports real numeric 2D, 3D, and 4D Cartesian arrays. Complex, boolean, object, and polar data are rejected. Float16 is promoted to float32; float32 filtering/subtraction remains float32. Integer and other float inputs use float64; extended precision is reduced to float64. Both sums accumulate in float64, and output scores are float32. Integer values above float64’s exact-integer range may lose precision on conversion.
The current supplied array is used without flipping, aligning, clipping, repairing, or mutating it or its metadata/backing file. Only per-pattern temporaries and a detector-sized mask are allocated, even for trimmed or flipped noncontiguous memmaps. The reference 4D-TOMO calculation uses stored, unflipped, unaligned intensities; aligned/flipped input is a different measurement, particularly for an off-subpixel center.
Noise can increase sharp contrast. Counts, denominator flooring, annulus geometry, Gaussian width, and selected-pixel count affect comparability. This dimensionless index is not necessarily restricted to [0, 1] and does not establish phase, crystalline volume fraction, or orientation confidence. Use additional evidence for those interpretations.
- HyperData.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, real_mask=None, center=None, return_details=False)[source]¶
Detect peaks independently in every diffraction pattern.
This dataset-level method applies
ReciprocalSpace.get_peaks()to each diffraction pattern without requiring reference coordinates. Because the number of detected peaks may differ between patterns, the result is returned as a ragged collection of(n_peaks, 2)arrays.- Parameters:
radius (float) – Radius, in reciprocal-space pixels, of the positive disk in the peak-detection template.
min_distance (int) – Minimum pixel separation between detected peaks.
trench_width (float, optional) – Width of the negative ring surrounding the positive template.
kernel_amp (float, optional) – Amplitude of the positive disk in the template.
trench_amp (float, optional) – Amplitude of the negative surrounding trench.
threshold_abs (float or None, optional) – Absolute correlation threshold. Set to None to use
threshold_relinstead.threshold_rel (float or None, optional) – Correlation threshold relative to the maximum correlation.
r_range (tuple or None, optional) – Radial search interval
(r_min, r_max)in pixels.n_fold (int or None, optional) – Rotational-symmetry order used by the underlying peak detector.
sym_mode ({'none', 'repair', 'prune', 'both'}, optional) – Rotational-symmetry handling mode.
sym_tolerance_px (float, optional) – Matching tolerance for symmetry-related peaks, in pixels.
center_tolerance_px (float, optional) – Radius used to identify central peaks, in pixels.
orbit_min_fraction (float, optional) – Minimum detected fraction required for a symmetry orbit.
reorder (bool, optional) – If True, reorder detected peaks into symmetry-related shells when supported by
n_fold.real_mask (ndarray of bool or None, optional) – For 4D data, only detect peaks where this
(Ry, Rx)mask is True. Masked-out positions contain empty(0, 2)arrays. This parameter is not supported for 3D data.center ((ky, kx) or None, optional) – Reciprocal-space search center in pixels. If omitted, use valid center-beam metadata and then the pattern midpoint. This center controls both the radial search and symmetry grouping.
return_details (bool, optional) – If True, return
PeakDetectionResultentries with correlation scores and measured/synthetic provenance.
- Returns:
peaks – For 4D data, a nested list shaped
[Ry][Rx]. For 3D data, a list shaped[N]. Every entry is an integer array with shape(n_peaks, 2)containing(y, x)peak coordinates, or aPeakDetectionResultwhenreturn_details=True.- Return type:
list
Notes
Use
get_centers()afterward when the detected coordinates should be refined independently within each diffraction pattern.
- HyperData.get_centers(r, ref_coords, method='CoM', real_mask=None)[source]¶
Compute Bragg spot centers for each diffraction pattern.
Supports both 4D (Ny×Nx×C×D) and 3D (B×C×D) HyperData.
- Parameters:
r (float) – Radius (in pixels) of the local window used by the center-finding algorithm in each diffaction pattern.
ref_coords (array-like or nested list) – For 4D array input, shape
(n_peaks, 2)supplies shared peaks. For a 4D ragged list,ref_coords[i][j]holds the peaks at scan position(i, j). For 3D array input, shape(n_peaks, 2)supplies shared peaks; a 3D ragged list usesref_coords[i]for patterni.method ({'CoM', 'gaussian', 'elliptical_gaussian'}, optional) – Local center-refinement method for each diffraction pattern.
real_mask (ndarray[bool] or None, optional) – Only used for 4D datasets. Boolean mask of shape (Ny, Nx) defining which real-space positions have centers computed. False positions are skipped and filled with zeros, retaining the peak count for array or ragged input. A 3D stack does not accept
real_mask.
- Returns:
centers – Fixed-peak input returns
(Ny, Nx, n_peaks, 2)for 4D or(B, n_peaks, 2)for 3D. Ragged input returns a matching nested list of per-pattern coordinate arrays.- Return type:
ndarray or list
- HyperData.get_intensities(r=6, centers=None, ref_coords=None, method='CoM', compute_resBg=False, residual_frac=0.9, real_mask=None, **resBg_kwargs)[source]¶
Extract Bragg peak intensities from each diffraction pattern slice.
Supports both 4D (Ny×Nx×C×D) and 3D (B×C×D) HyperData.
- Parameters:
r (float, optional) – Integration radius in pixels.
centers (array-like or list, optional) – Fixed-peak arrays have shape
(Ny, Nx, n_peaks, 2)for 4D or(B, n_peaks, 2)for 3D. Ragged input holds a coordinate array per pattern, nested by scan row for 4D. If None, centers are refined fromref_coordswithin each diffraction pattern before its intensities are integrated.ref_coords (array-like or nested list, optional) – Reference peak coordinates used when centers is None. See get_centers for allowed formats.
method ({'CoM', 'gaussian', 'elliptical_gaussian'}, optional) – Center-finding method used if centers is None.
compute_resBg (bool, optional) – If True, subtract the estimated residual background from each integrated peak using its actual number of included pixels.
residual_frac (float, optional) – Fraction of the estimated background to subtract per included pixel.
real_mask (ndarray[bool] or None, optional) – Only used for 4D datasets. Boolean mask of shape (Ny, Nx) defining which real-space positions have intensities computed. False positions are skipped and filled with zeros, retaining the peak count for array or ragged input. A 3D stack does not accept
real_mask.**resBg_kwargs – Additional keyword arguments forwarded to dp.get_intensities(…).
- Returns:
all_ints – Fixed-peak input returns
(Ny, Nx, n_peaks)for 4D or(B, n_peaks)for 3D. Ragged input returns a matching list of per-pattern intensity arrays.- Return type:
np.ndarray or list
- HyperData.get_strains(centers=None, ref_centers=None, ang=0, g_vector=None, r_CoM=None, r_inner=None, r_outer=None, intensity_array=None, intensity_percentile=None, intensity_clip='both', real_mask=None, ewpc=False, match_peaks='auto', fit_translation=False, min_peak_pairs=2, return_transform=False, center=None, peak_units='pixels', max_condition_number=100000000.0, reject_peak_outliers=False, outlier_threshold=3.5, outlier_min_peak_pairs=None, outlier_min_peak_fraction=None, outlier_max_iterations=2, outlier_space='radial_angular', outlier_method='auto_mixture', outlier_bic_delta=0.0, *, output_frame='reciprocal', match_radius=None, initial_rotation=None, initial_transform=None, initial_translation=None, ambiguity_ratio=None)[source]¶
Calculate strain and rotation maps from Bragg peak centers.
This method fits the best 2D linear transform from reference peak coordinates to measured peak coordinates at each diffraction pattern, then extracts strain from the polar stretch matrix. Peak sets are not required to have the same size or order. By default, reference and measured peaks are paired by a one-to-one, neighborhood-gated spatial assignment before fitting. Unrelated peaks may remain unmatched; centroids of unequal peak sets are not assumed to be comparable.
Peak coordinates and diagnostic fitted matrices use
(ky, kx)order. For default reciprocal output atang=0, the stretch matrixUgiveseyy = 1 - U[0, 0]andexx = 1 - U[1, 1]. Map indices retain the input scan order(Ry, Rx). The named result components (and tuple unpacking order) remainexx, eyy, exy, erot. Real-frame output converts the fitted transform using stored R/Q calibration before extracting the Cartesian tensor.Matching options¶
match_radiusbounds pair distances in the supplied peak units; None uses 45% of the median nearest-reference-peak separation.initial_rotationis a Cartesian counterclockwise angle in degrees, scalar or scan-shaped.initial_transforminstead accepts a global or scan-shaped (2, 2) reference-to-measured matrix in (ky, kx) order. These mutually exclusive guesses select candidates only; fitting estimates the full transform and retains its rotation. Optionalinitial_translationuses (ky, kx) units and requiresfit_translation=True. Without it, translation consensus is sought without relying on peak-set centroids.ambiguity_ratiobetween zero and one optionally rejects pairs whose distance is too close to that of a competing candidate (smaller is stricter). The default retains pairs while reporting their geometric confidence margins. Explicitmatch_peaks='hungarian'allows unrestricted assignment if no match_radius is supplied;'ordered'trusts supplied pairing.'auto'and'nearest'use the neighborhood gate.- param centers:
Measured peak centers. Common fixed-size shape is
(Ry, Rx, n_peaks, 2), with each coordinate in(ky, kx)order. Nested lists may be used when each diffraction pattern has a different number of peaks.- type centers:
ndarray or nested list, optional
- param ref_centers:
Reference peak centers. Supported forms are a global
(n_ref_peaks, 2)array or a local reference with the same scan layout ascenters.- type ref_centers:
ndarray or nested list, optional
- param ang:
In-plane angle in degrees used to rotate the reporting basis of the fitted strain tensor, not the scan image. At the default 0,
exxfollows kx andeyyfollows ky; these directions need not coincide with the real-space scan axes. A 90-degree basis rotation exchangesexxandeyyand reversesexywithout moving scan pixels or changing the fitted local rotation. Determine this angle from the acquisition’s coordinate frames; it is not inferred from the strain map. This manual correction applies only tooutput_frame='reciprocal'. A nonzero value with real-frame output raises an error to prevent two corrections.- type ang:
float, optional
- param output_frame:
Reporting directions for the strain tensor. The default
'reciprocal'retains the existing detector-basis calculation and ignores stored R/Q calibration.'real'requiresself.rq_calibrationand automatically uses its rotation and optional reflection. R/Q directions are Cartesian (x right, y up); pixel peaks (y down) and calibrated peaks (ky up) are converted accordingly. Real-frame components formI - U;erotis positive counterclockwise and reflections are handled through the full basis matrix. Map pixels and peak-fit diagnostics remain in their original coordinates. Recorded acquisition scan rotation is not used as a substitute for R/Q calibration.- type output_frame:
{‘reciprocal’, ‘real’}, keyword-only, optional
- param g_vector:
Retained for compatibility with older calls. The least-squares implementation uses all matched peaks rather than selecting a hexagonal g-vector pair.
- type g_vector:
optional
- param r_CoM:
Radius passed to
get_centerswhen measured centers are not supplied.- type r_CoM:
float, optional
- param intensity_array:
Optional peak weights. If supplied, weights are matched to measured peaks and used in the least-squares fit. Each local weight vector must match either all measured peaks or their finite subset.
- type intensity_array:
ndarray or nested list, optional
- param intensity_percentile:
If supplied with
intensity_array, discard measured peaks with local outlier intensities before matching and fitting. With the defaultintensity_clip='both', the percentile is split evenly between tails, sointensity_percentile=10removes the lowest 5% and highest 5% of finite measured peaks in each diffraction pattern.- type intensity_percentile:
float or None, optional
- param intensity_clip:
Which intensity tail(s) to clip when
intensity_percentileis supplied.'lower'clips only weak peaks,'upper'clips only bright outliers, and'both'clips both tails.- type intensity_clip:
{‘both’, ‘lower’, ‘upper’}, optional
- param real_mask:
Only used for 4D scan-shaped centers. Boolean mask of shape
(Ry, Rx)defining which real-space positions should have strain computed. Masked-out positions remain NaN in strain/transform maps and have zero match counts.- type real_mask:
ndarray[bool] or None, optional
- param ewpc:
If True, invert the fitted reciprocal-space transform before extracting strain.
- type ewpc:
bool, optional
- param match_peaks:
'auto'(the default) and'nearest'use one-to-one spatial neighborhood-gated assignment regardless of count or input order. Initial guesses can align candidate coordinates before matching. ‘hungarian’ is unrestricted unless match_radius is supplied. Use'ordered'only when corresponding peaks are already at matching indices in both inputs, including after intensity filtering.- type match_peaks:
{‘auto’, ‘ordered’, ‘nearest’, ‘hungarian’}, optional
- param fit_translation:
If True, fit and remove an additional translation term after subtracting
centerso detector shifts are not interpreted as strain.- type fit_translation:
bool, optional
- param min_peak_pairs:
Minimum number of matched peak pairs required to fit a transform. With
fit_translation=True, at least three non-collinear pairs are required even if this value is smaller.- type min_peak_pairs:
int, optional
- param return_transform:
If True, attach detailed transform and peak-rejection diagnostics to the result. For existing tuple-style code, these remain the fifth item when unpacking or indexing the result.
- type return_transform:
bool, optional
- param center:
Reciprocal-space origin
(ky, kx)about which peak displacements are measured before fitting strain. If None, this defaults to currentcenter_beam_metadata['center_px']when available, falling back to mean-fit or calibrated-center metadata. If that metadata is unavailable, it falls back to the finite mean coordinate ofref_centerswhen a reference is supplied, or to the finite absolute mean coordinate of all peaks incenterswhenref_centersis None.- type center:
array-like of shape (2,) or None, optional
- param peak_units:
Units of supplied
centers,ref_centers, and explicitcenter. Pixel(ky, kx)coordinates are the default. Calibrated reciprocal(ky, kx)coordinates use positive ky upward and require stored reciprocal calibration. If the beam center comes from pixel metadata, it is converted automatically. Automatic center finding is pixel-only.- type peak_units:
{‘pixels’, ‘calibrated’}, optional
- param max_condition_number:
Reject peak configurations whose weighted reference design matrix exceeds this condition number. Such patterns remain NaN in the strain maps rather than producing unstable strain estimates.
- type max_condition_number:
float, optional
- param reject_peak_outliers:
If True, reject matched measured peaks that are poorly explained by the fitted strain transform. Rejection is performed after an initial transform fit and before the final strain fit.
- type reject_peak_outliers:
bool, optional
- param outlier_threshold:
Robust z-score threshold used only when
outlier_method='robust_zscore'. Withoutlier_space='radial_angular', radial and angular residual z-scores are combined as a Euclidean score.- type outlier_threshold:
float, optional
- param outlier_min_peak_pairs:
Minimum number of matched peak pairs required to attempt outlier rejection and the minimum number of pairs that must remain after rejection. If rejecting a candidate set would leave fewer pairs, only the most extreme candidates are rejected. The default of 4 lets a six-peak pattern drop up to two outlier peaks while keeping enough peaks for a stable 2D transform fit. Mutually exclusive with
outlier_min_peak_fraction.- type outlier_min_peak_pairs:
int or None, optional
- param outlier_min_peak_fraction:
Alternative to
outlier_min_peak_pairs. If supplied, the local outlier minimum isceil(fraction * n_reference_peaks)for each diffraction pattern, with a floor of 2 pairs. For example,0.5requires half the local reference peak count to remain.- type outlier_min_peak_fraction:
float or None, optional
- param outlier_max_iterations:
Maximum number of initial-fit/reject cycles before the final fit.
- type outlier_max_iterations:
int, optional
- param outlier_space:
Residual coordinate system used for robust z-score outlier detection. The
'radial_angular'mode resolves residuals into radial and tangential components relative tocenterand normalizes by peak radius.- type outlier_space:
{‘radial_angular’, ‘cartesian’, ‘distance’}, optional
- param outlier_method:
Peak-rejection strategy.
'auto_mixture'fits the strain transform first, models the post-fit residual distances as either one population or two populations using BIC, and rejects the high-residual population only when the two-population model is preferred.'robust_zscore'usesoutlier_threshold.- type outlier_method:
{‘auto_mixture’, ‘robust_zscore’}, optional
- param outlier_bic_delta:
Extra BIC margin required before the automatic mixture method accepts a two-population residual model. The default
0uses the standard BIC preference. Larger values make automatic rejection more conservative.- type outlier_bic_delta:
float, optional
- returns:
Named strain and rotation maps, fit-quality maps, optional diagnostics, real-space scan calibration, and reporting-frame metadata.
result.rq_calibrationis the calibration used for real output, andresult.output_basis_matrixrecords the basis transform. Diagnostic transforms and translations remain in the supplied peak-coordinate frame. Strains are dimensionless; rotation is in radians. The result also supports four-value unpacking and indexed access used by older notebooks.- rtype:
StrainResult
Examples
>>> result = data.get_strains(centers=measured, ref_centers=reference) >>> exx_image = result.as_real_space('exx') >>> fit_error = result.relative_fit_rmse >>> exx, eyy, exy, erot = result >>> real_result = data.get_strains( ... centers=measured, ref_centers=reference, output_frame='real', ... ) # Requires data.set_rq_calibration(...) first.
- HyperData.get_clusters(n_PCAcomponents=None, n_clusters=None, r_centerBeam=None, std_Threshold=0.2, power=1, clustering_method='k-means', plotStdMask=False, plotScree=False, plotClusterMap=False, plot3dClusterMap=False, filter_size=None, cluster_cmap=None, filter_iterations=1, outer_ring=None, polar=None, split_disconnected=False, *, detector_units='pixels', detector_mask=None, intensity_transform='log', normalize='none', pca_fit_samples=None, random_state=0, batch_size=None, return_diagnostics=False, include_mean_dps=False, split_connectivity=2, max_plot_points=10000, n_components=None, fit_samples=None, reduction_method='pca', feature_weighting='hard', soft_weight_scale=None, gmm_covariance_type='diag', hdbscan_min_cluster_size=20, hdbscan_min_samples=None, nmf_epochs=3)[source]¶
Cluster a 4D scan from weighted detector pixels and reduced features.
The return value is a
(Ry, Rx)integer label array. Setreturn_diagnostics=Truefor(labels, details). No intermediate arrays or model are retained on this object.- Parameters:
n_components (int or None) – Number of PCA or NMF components. Use this name for new calls;
n_PCAcomponentsremains accepted by existing notebooks.n_clusters (int or None) – Requested cluster count. Must be None for HDBSCAN, which selects its own number of clusters and may label outliers as -1.
r_centerBeam (float or None) – Inner exclusion radius and optional outer limit.
Nonemeans no inner/outer limit. Values usedetector_units.outer_ring (float or None) – Inner exclusion radius and optional outer limit.
Nonemeans no inner/outer limit. Values usedetector_units.detector_units ({'pixels', 'auto', 'calibrated'}) – Units for both radii. Pixels remain the default for existing notebook calls. On polar data, pixels mean source Cartesian diffraction pixels, not radial row indices.
detector_mask (ndarray of bool or None) – Optional
(Ky, Kx)or(Kr, Ktheta)mask intersected with the radial selection.std_Threshold (float) – With
feature_weighting='hard', keep pixels whose transformed- data standard deviation is at least this fraction of the maximum.feature_weighting ({'hard', 'soft', 'none'}) – Hard uses the previous Boolean threshold. Soft retains every varying pixel in the detector selection and assigns weight
std / (std + soft_weight_scale). None retains all selected pixels with unit weight. Physical exclusions still use the harddetector_maskand radial limits.soft_weight_scale (positive float or None) – Scale in transformed-data standard-deviation units. None uses the 75th percentile of positive pixel deviations, avoiding dependence on a single unusually variable detector pixel. Only for soft mode.
intensity_transform ({'log', 'log1p', 'sqrt', 'raw'}) – Transform nonnegative detector intensities before feature selection and decomposition.
'log'useslog(max(I, 1));'raw'leaves intensities unchanged. Negative inputs are clipped to zero.power (positive float) – Exponent applied after
intensity_transform. Thuspower=2genuinely emphasizes higher transformed intensities. Useintensity_transform='raw', power=2for squared raw counts.normalize ({'none', 'total'}) –
'total'divides each pattern by its mean nonnegative signal over the radial detector region before transforming it. This removes overall brightness variation but preserves relative spots.reduction_method ({'pca', 'nmf'}) – PCA uses incremental fitting. NMF uses mini-batch nonnegative factorization and can expose its detector components in diagnostics.
plotScreeapplies only to PCA.nmf_epochs (positive int) – Number of shuffled training passes for NMF. More passes may improve the factorization but read the data more times.
clustering_method ({'k-means', 'mini-batch-k-means', 'hierarchical',) – ‘gaussian-mixture’, ‘hdbscan’} Mini-batch k-means is useful for large scans. Hierarchical clustering remains limited to 5000 patterns due to quadratic RAM. Gaussian mixtures provide probabilistic assignments; HDBSCAN finds variable-density groups but may take longer on large scans.
gmm_covariance_type ({'diag', 'spherical', 'tied', 'full'}) – Gaussian-mixture covariance model. Diagonal is the less costly default for high-dimensional PCA or NMF scores.
hdbscan_min_cluster_size (int or None) – HDBSCAN density controls. The former defaults to 20; None for the latter lets HDBSCAN use its own default.
hdbscan_min_samples (int or None) – HDBSCAN density controls. The former defaults to 20; None for the latter lets HDBSCAN use its own default.
fit_samples (int, float in (0, 1], or None) – Number or fraction of randomly sampled patterns used to fit the reducer.
pca_fit_samplesis accepted for existing notebooks. Every pattern is still transformed and clustered. None fits all.random_state (int or None) – Seed for sampling, NMF, and clustering; 0 is reproducible.
batch_size (int or None) – Patterns per data batch. None chooses a bounded size automatically.
filter_size (odd positive int or None) – Opt-in categorical majority-filter window; None disables smoothing.
filter_iterations (nonnegative int) – Number of majority-filter passes when
filter_sizeis set.split_disconnected (bool) – Give disconnected islands distinct labels after smoothing.
split_connectivity ({1, 2}) – 4- or 8-connected neighborhoods for splitting; 8 is the default.
plotStdMask (bool) – Optional plots, disabled by default to avoid accumulating notebook outputs.
max_plot_pointscaps the 3D scatter size.plotScree (bool) – Optional plots, disabled by default to avoid accumulating notebook outputs.
max_plot_pointscaps the 3D scatter size.plotClusterMap (bool) – Optional plots, disabled by default to avoid accumulating notebook outputs.
max_plot_pointscaps the 3D scatter size.plot3dClusterMap (bool) – Optional plots, disabled by default to avoid accumulating notebook outputs.
max_plot_pointscaps the 3D scatter size.cluster_cmap (str or None) – Cluster-map colormap; defaults to
'gnuplot'.polar (bool or None) – Optional consistency check for existing calls. Geometry always follows
self.is_polarand its metadata.return_diagnostics (bool) – Also return selected detector pixels, feature weights, cluster sizes, and method settings. NMF components are in weighted feature space. Gaussian-mixture confidence is before spatial filtering.
include_mean_dps (bool) – With diagnostics, also compute raw mean diffraction patterns for the final clusters. This requires another pass over the 4D data.
Notes
Soft weights multiply detector intensities by
sqrt(weight)before decomposition, so squared Euclidean distances weight each pixel byweight. PCA and k-means remain the defaults for existing calls.