API reference#
Sphinx builds this page from the docstrings of the installed package, so it cannot drift from the code. Everything below is public; anything not listed here is internal and may change without notice. The documentation build fails when a public module exports a name that this page does not show.
Package settings#
Set the process-wide numeric settings scatterem is tuned for. |
- scatterem.configure(*, matmul_precision: str | None = 'medium') dict[str, str | None]#
Set the process-wide numeric settings scatterem is tuned for.
Nothing is set at
import scatterem. Direct reconstructions, simulations and I/O run at whatever the process has – torch’s default"highest"unless the caller changes it. Call this to run them at TF32 speed.- Parameters:
matmul_precision ({"highest", "high", "medium"} or None, default "medium") – Passed to
torch.set_float32_matmul_precision()."medium"and"high"let float32 matmuls and convolutions run in TF32 on Ampere and later GPUs (and, for"medium", in bfloat16 through oneDNN on CPUs that support it): faster, with about three significant digits instead of seven."highest"is true float32.Noneleaves the setting untouched.- Returns:
The value every setting had before this call, keyed by parameter name, so
configure(**previous)restores them. A value isNonewhen torch could not report it (see Notes); passing that back sets nothing.- Return type:
dict of str to str or None
- Raises:
ValueError – If
matmul_precisionis not one of the three torch knows (torch itself only warns, and sets nothing).
Notes
Change the precision with this function or
torch.set_float32_matmul_precision(), never with the legacy flagtorch.backends.cuda.matmul.allow_tf32: torch (2.11) keeps three records of the precision, the flag rewrites two of them, and next to"medium"the third then makestorch.get_float32_matmul_precision()raise for the rest of the process – which some training frameworks call on every CUDA fit. A call here with a precision rewrites all three and repairs that state.Examples
>>> import torch >>> import scatterem >>> previous = scatterem.configure(matmul_precision="high") >>> torch.get_float32_matmul_precision() 'high' >>> _ = scatterem.configure(**previous)
Container#
An array plus the calibration needed to interpret its axes. |
|
A 4D STEM dataset with metadata for electron diffraction patterns. |
|
A virtual bright field 4D STEM dataset with metadata for electron diffraction patterns. |
|
A cheap view of |
- class scatterem.data.datasets.Dataset(array: Any, name: str, origin: NDArray | tuple | list | float | int, sampling: NDArray | tuple | list | float | int, units: list[str] | tuple | list, signal_units: str = 'arb. units', _token: object | None = None, device: device | str | None = None)#
An array plus the calibration needed to interpret its axes.
Each axis carries an origin, a pitch and a unit, so a position in the array can be turned into a physical coordinate without the caller tracking the conversion. Values have their own unit, separate from the axes’.
- Parameters:
array (array-like) – The data itself.
name (str) – Label used in reprs and figure titles.
origin (numpy.ndarray, tuple, list, float, or int) – Coordinate of index zero on each axis.
sampling (numpy.ndarray, tuple, list, float, or int) – Pitch per axis, in units.
signal_units (str, optional) – Unit of the stored values. Default is “arb. units”.
_token (object, optional) – Internal sentinel guarding direct construction; use
Dataset.from_array()instead of calling this constructor.device (torch.device or str or None, optional) –
Nonekeeps a torch tensor’s device; other inputs become CPU tensors.
- Variables:
array (torch.Tensor) – The values, as a tensor of any rank.
name (str) – Label used in reprs and figure titles.
origin (numpy.ndarray) – Coordinate of index zero on each axis.
sampling (numpy.ndarray) – Pitch per axis, in units.
signal_units (str) – Unit of the stored values.
- class scatterem.data.datasets.Dataset4DStem(array: Tensor | ndarray, name: str, origin: NDArray | tuple | list | float | int, sampling: NDArray | tuple | list | float | int, units: list[str] | tuple | list, signal_units: str = 'arb. units', meta: AcquisitionMetadata | None = None, transform_to_amplitudes: bool = False, astype_float32: bool = True, fourier_shift_dim: tuple | None = None, probe_index: int = 0, device: device | str | None = None, normalize: bool = True, clip_neg_values: bool = True, copy: bool = True, _token: object | None = None)#
A 4D STEM dataset with metadata for electron diffraction patterns.
- Parameters:
array (Tensor) – The 4D diffraction data, shaped
(scan_y, scan_x, det_y, det_x).name (str) – The name of the dataset.
origin (NDArray or tuple or list or float or int) – The per-axis origin, i.e. the pixel offset of the array’s zero index.
sampling (NDArray or tuple or list or float or int) – The per-axis physical sampling (scan step and detector pixel size).
units (list of str or tuple or list) – The per-axis physical units.
signal_units (str) – The units of the recorded signal.
meta (AcquisitionMetadata, optional) – Acquisition metadata (energy, semiconvergence angle, aberrations, and related quantities).
transform_to_amplitudes (bool) – Whether to take the square root of the array in place, converting recorded intensities to amplitudes.
astype_float32 (bool) – Whether to cast the array to
float32.fourier_shift_dim (tuple, optional) – Detector dims to
fftshifton construction: only to centre corner data.probe_index (int) – Index of the probe this dataset is associated with.
device (torch.device or str or None, optional) –
Nonekeeps a torch tensor’s device; other inputs become CPU.normalize (bool) – Whether to divide the array in place by the maximum mean diffraction pattern. Default is
True. This rescales the stored data: passnormalize=False(andclip_neg_values=False) whenever raw counts must survive byte-exact, e.g. for dose accounting or comparisons against another reader.clip_neg_values (bool) – Whether to clamp negative values to zero in place. Default is
True; see the note onnormalize.copy (bool) – Whether to clone the array before the in-place operations above run, so that the caller’s array is never mutated.
_token (object, optional) – Sentinel guarding direct construction; use
from_array()instead.
- Variables:
bright_field_mask_threshold (float) – Default bright-field mask level, 0.3.
FusedFullFieldConfigreads it when the caller omits the threshold; the other configs have their own default. The examples pass it to every config; set it per dataset.
- bright_field_radius_and_center(estimator: Literal['integral', 'rayfit'] = 'integral', *, edge_reach: float | None = None, arc_floor: float | None = None) PupilEstimate#
Return the radius and centre
(y, x)of the bright-field disk [pixel].Calls
scatterem.data.pupil_gauge.measure_pupil()on the mean diffraction pattern. The largest plausible radius is the default of that function (0.45 of the shorter detector side), or 1.0 for a dataset that is cropped to the bright field (is_bright_field).- Parameters:
estimator ({"integral", "rayfit"}) –
"integral"(default) for a complete disk."rayfit"for a disk with a missing sector or with a part outside the detector.edge_reach (float, optional) – Half-width of the edge band [pixel]; None: 2 (integral) or 10 (rayfit). A wide band reads a sloped disk top 4 % small (Gd2O3). Raise for soft edges.
arc_floor (float, optional) – Only for
"rayfit": the smallest fraction of the full circle that the accepted edge points must cover.
- Returns:
(rim_radius, rim_center): the radius [pixel] and the centre(y, x)[pixel] as a NumPy array of shape(2,).- Return type:
- Raises:
ValueError – If the mean pattern has no clear disk; see
measure_pupil().
- calibrate_reciprocal_from_bright_field(semiconvergence_angle: float | None = None, estimator: Literal['integral', 'rayfit'] = 'integral', *, edge_reach: float | None = None) float#
Calibrate the reciprocal-space pixel size
dkfrom the bright field.Sets
dk = alpha / rBF / wavelengthandself.sampling = (dr, dr, dk, dk)in place (the setter updatesself.meta.sampling).rBFcomes from the mean pattern of the whole detector (bright_field_radius_and_center()). A scratch crop (ascrop_brightfield_, sameedge_reach, no normalisation, so the array does not change) recentres the detector entries ofself.origin, setsself._radius_bright_fieldand refuses a disk near the detector edge.- Parameters:
semiconvergence_angle (float, optional) – Beam convergence semi-angle in radians. Defaults to
self.meta.semiconvergence_angle.estimator ({"integral", "rayfit"}) – The disk estimator; see
bright_field_radius_and_center().edge_reach (float, optional) – See
bright_field_radius_and_center().
- Returns:
The calibrated reciprocal-space sampling
dk.- Return type:
- classmethod from_array(array: Any, name: str | None = None, origin: NDArray | tuple | list | float | int | None = None, sampling: NDArray | tuple | list | float | int | None = None, units: list[str] | tuple | list | None = None, signal_units: str = 'arb. units', meta: AcquisitionMetadata | None = None, transform_to_amplitudes: bool = False, fourier_shift_dim: tuple | None = None, normalize: bool = True, clip_neg_values: bool = True, copy: bool = True, *, device: device | str | None = None, is_cropped: bool = False, out_of_core: bool = False, ooc_row_block: int = 8, g_residency: str = 'auto', energy: float | None = None, semiconvergence_angle: float | None = None, scan_step: float | tuple | list | NDArray | None = None, reciprocal_step: float | tuple | list | NDArray | None = None, rotation: float = 0.0, aberrations: Aberrations | None = None) Dataset4DStem#
Build a 4D-STEM dataset (scan y, scan x, detector y, detector x).
- Parameters:
array (Any) – The 4D cube: numpy array, tensor, h5py dataset or memory map.
name (str, optional) – Label. Default:
"4d dataset".origin (NDArray or tuple or list or float or int, optional) – Coordinate of index zero per axis. Default: 0, or the array centre on the physics path (see
energy).sampling (NDArray or tuple or list or float or int, optional) – Pitch per axis. Defaults to what
metadescribes (meta.sampling), else1.0per axis.units (list of str or tuple or list, optional) – Unit per axis. Default: the units of
meta, else"pixels".signal_units (str) – Unit of the values.
meta (AcquisitionMetadata, optional) – Acquisition metadata. Built internally from the physics-path parameters below when
Noneandenergyis given.transform_to_amplitudes (bool) – Whether to take the square root of the array in place, converting recorded intensities to amplitudes.
fourier_shift_dim (tuple, optional) – Detector dimensions to
fftshiftin place on construction.normalize (bool) – Whether to divide the array in place by the maximum mean diffraction pattern. Default is
True. This rescales the stored data: passnormalize=False(andclip_neg_values=False) whenever raw counts must survive byte-exact, e.g. for dose accounting or comparisons against another reader.clip_neg_values (bool) – Whether to clamp negative values to zero in place. Default is
True; see the note onnormalize.copy (bool) – Whether to clone the array before any in-place operations run, so that the caller’s array is never mutated.
device (torch.device or str or None, optional) –
Nonekeeps a torch tensor’s device; other inputs become CPU. Out-of-core: compute device for streamed slabs (None→ CPU).is_cropped (bool) – Whether the array is the result of a crop.
out_of_core (bool) – Keep the cube where it is and read it in pieces (a
MemmapSource); every read converts like the eager path. uint8, uint16 and float16 cubes stream in a fit.ooc_row_block (int) – Scan rows per read of pass 0 and
iter_scan_blocks(out-of-core only).g_residency (str) –
"gpu"|"vbf_gpu"|"cpu_pinned"|"auto"– where the streaming vBF provider keeps G (out-of-core only).energy (float, optional) – Beam energy in eV. Triggers the physics convenience path: when
metaisNoneandenergyis given, anAcquisitionMetadatais built internally (shape derived fromarray,sampling = (dr, dr, dk, dk)withdrfromscan_stepanddkfromreciprocal_step– both scalar or a length-2 pair,dkdefaulting to a(1.0, 1.0)placeholder to be calibrated later, e.g. viacalibrate_reciprocal_from_bright_field).origindefaults to the array center in this path when not given explicitly.semiconvergence_angle (float, optional) – Beam convergence semi-angle in radians, used by the physics path.
scan_step (float or tuple or list or NDArray, optional) – Real-space scan step, used by the physics path.
reciprocal_step (float or tuple or list or NDArray, optional) – Reciprocal-space pixel size, used by the physics path.
rotation (float) – Scan rotation in degrees, used by the physics path.
aberrations (Aberrations, optional) – Aberration coefficients, used by the physics path.
- Returns:
The container, with any unset axis metadata filled in from the array’s rank.
- Return type:
- classmethod load(path: str | Path, *, device: str | device = 'cpu')#
Read an instance of
cls(or of a subclass) frompath.- Parameters:
path (str or pathlib.Path) – A file written by
save().device (str or torch.device, optional) – Device every tensor field is placed on. Default
"cpu".
- Returns:
The object. When the file holds a subclass of
clsthat declares its own schema, an instance of that subclass.- Return type:
- Raises:
SerializationError – The file holds an unrelated class, a schema version this code cannot read, or a field list that does not match the class’s.
- save(path: str | Path, *, overwrite: bool = False) Path#
Write every declared field to one HDF5 file.
- Parameters:
path (str or pathlib.Path) – File to write. Missing parent directories are created.
overwrite (bool, optional) – Replace an existing file. Default
False, which refuses.
- Returns:
The path written.
- Return type:
- Raises:
SerializationError – If the file exists and
overwriteis false, or if a declared field cannot be written.
- class scatterem.data.datasets.DatasetVirtualBrightField4DStem(array: Tensor, name: str, origin: NDArray | tuple | list | float | int, sampling: NDArray | tuple | list | float | int, units: list[str] | tuple | list, parent_dataset: Dataset4DStem | None = None, diffraction_pattern_mean_normalized: torch.Tensor = tensor([]), bright_field_mask: torch.Tensor = tensor([]), bright_field_inds: torch.Tensor = tensor([]), bright_field_inds_centered: torch.Tensor = tensor([]), bright_field_inds_radial_order: torch.Tensor = tensor([]), bright_field_inds_ordered_by_radius: torch.Tensor = tensor([]), bright_field_inds_centered_ordered_by_radius: torch.Tensor = tensor([]), k: torch.Tensor = tensor([]), qx_1d: torch.Tensor = tensor([]), qy_1d: torch.Tensor = tensor([]), signal_units: str = 'arb. units', meta: AcquisitionMetadata | None = None, astype_float32: bool = True, fourier_shift_dim: tuple | None = None, probe_index: int = 0, device: torch.device | str | None = None, clip_neg_values: bool = True, _token: object | None = None)#
A virtual bright field 4D STEM dataset with metadata for electron diffraction patterns.
- Parameters:
array (torch.Tensor) – Gathered bright-field diffraction data, shape
(Ry, Rx, N_bf).name (str) – Dataset name.
origin (numpy.typing.NDArray or tuple or list or float or int) – Real-space origin.
sampling (numpy.typing.NDArray or tuple or list or float or int) – Real-space sampling (pixel size) per axis.
parent_dataset (Dataset4DStem or None, optional) – 4D-STEM dataset this virtual bright field was derived from.
diffraction_pattern_mean_normalized (torch.Tensor, optional) – Max-normalized mean CBED used to build the bright-field mask.
bright_field_mask (torch.Tensor, optional) – Boolean bright-field detector mask.
bright_field_inds (torch.Tensor, optional) – Detector pixel indices inside the bright-field mask.
bright_field_inds_centered (torch.Tensor, optional) –
bright_field_indscentered on their mean.bright_field_inds_radial_order (torch.Tensor, optional) – Permutation sorting
bright_field_indsby radius.bright_field_inds_ordered_by_radius (torch.Tensor, optional) –
bright_field_indssorted by radius.bright_field_inds_centered_ordered_by_radius (torch.Tensor, optional) –
bright_field_inds_centeredsorted by radius.k (torch.Tensor, optional) – Physical detector k-vectors of the bright-field pixels.
qx_1d (torch.Tensor, optional) – 1D Fourier frequencies along the scan x-axis.
qy_1d (torch.Tensor, optional) – 1D Fourier frequencies along the scan y-axis.
signal_units (str, optional) – Units of the signal values.
meta (AcquisitionMetadata or None, optional) – Acquisition metadata.
astype_float32 (bool, optional) – If True (default), cast the array to
float32.fourier_shift_dim (tuple, optional) – Dimensions to
ifftshift; unused here (always None fromfrom_4dstem_dataset()).probe_index (int, optional) – Probe index for multi-probe datasets.
device (torch.device or str or None, optional) –
Nonekeeps a torch tensor’s device; other inputs become CPU.clip_neg_values (bool, optional) – If True (default), clip negative array values to zero.
_token (object or None, optional) – Internal construction guard.
- scatterem.data.datasets.with_meta(dataset: D, meta: Any) D#
A cheap view of
datasetthat readsmetainstead of its own.The view is a shallow copy: it shares the measurement array and every other attribute with
dataset, so it costs one attribute dictionary. Onlymetadiffers, and the view starts with an empty virtual-bright- field cache, so aget_vbfon it builds a provider undermeta.datasetitself is not changed.Use it to reconstruct the same data with other metadata, for example two aberration fits:
view = with_meta(dataset, fit.applied_to(dataset.meta)) vbf = view.get_vbf(0.5)
scatterem.reconstruction.run()takesmeta=and does this for you.- Parameters:
- Returns:
The view, of the same type as
dataset.- Return type:
- Raises:
TypeError – If
datasethas nometaattribute or it cannot be set.
Running a reconstruction#
Run the reconstruction |
|
Base of every reconstruction result. |
|
Base of every reconstruction config. |
|
Where a |
|
Register the function |
- scatterem.reconstruction.run(data: Any, config: ReconstructionConfig[R], *, reuse: Mapping[str, Any] | None = None, meta: Any = None) R#
Run the reconstruction
configselects ondata.The family is chosen by
type(config)(the nearest registered class in its MRO).dataanddata.metaare never written to; outputs are placed ondata.deviceor, for a runner that departs from that rule (see the module docstring), whereprovenance.devicesays.To compare two aberration fits on one dataset, pass each fit’s metadata:
a = run(ds, config, meta=fit_a.applied_to(ds.meta)) b = run(ds, config, meta=fit_b.applied_to(ds.meta))
Memory: a direct-ptychography run frees its virtual bright field and its
Gstack when it returns, so a second run on one dataset peaks no higher than the first.- Parameters:
data (object) – The input the family expects (a dataset, a series, …).
config (ReconstructionConfig) – The family’s frozen config.
reuse (Mapping, optional) – Intermediate products from earlier runs, by the key the family documents (for example a virtual bright field). Nothing is reused unless it is passed here.
meta (object, optional) – Metadata to use instead of
data.meta. The runner gets awith_meta()view ofdata: it shares the array, starts with an empty vBF cache and leavesdataunchanged. The result’sprovenance.meta_overrideisTrue. A reused vBF ("vbf"/"vbf_cache") must have been built under thismeta, for examplewith_meta(data, meta).get_vbf(t).
- Returns:
The family’s result type, as
config’s type parameter declares.- Return type:
- Raises:
TypeError – If
configis not aReconstructionConfig, if no runner is registered for its type, or if the runner does not return aResult.ValueError – If
reuseholds a key the family does not accept, or, withmeta, a vBF provider built under other metadata.
- Warns:
UserWarning – If
datais 4D-STEM data whose reciprocal samplingdkis still the(1.0, 1.0)placeholder ofDataset4DStem.from_array.
- class scatterem.reconstruction.Result(*, provenance: Provenance, diagnostics: Mapping[str, ~typing.Any]=<factory>)#
Base of every reconstruction result.
A family’s result adds its named outputs as fields and implements
as_tuple(), which returns exactly what the family’s older function returned, so a caller can switch entry point without changing a number. Results compare by identity: their fields are tensors.- Parameters:
provenance (Provenance) – Where the result came from.
diagnostics (Mapping, optional) – Secondary outputs a family reports beside its named ones (read-only; empty by default).
- class scatterem.reconstruction.ReconstructionConfig#
Base of every reconstruction config.
A family subclasses it as a frozen dataclass whose fields and defaults are exactly the keyword arguments of the function it wraps, parameterised by its result type (
ReconstructionConfig[DirectPtychographyResult]) sorun()is typed per family, and sets the class attributemethod.
- class scatterem.reconstruction.Provenance(method: str, config: Mapping[str, Any], scatterem_version: str, input_name: str | None, meta: Any | None, device: device, meta_override: bool = False)#
Where a
Resultcame from.Deliberately free of a timestamp or git SHA: either would make two identical runs differ, and golden tests compare results field by field.
- Parameters:
method (str) – The reconstruction family, the config type’s
method.config (Mapping) – The fully resolved config, one entry per config field (read-only).
scatterem_version (str) –
scatterem.__version__at the time of the run.input_name (str or None) – The input’s
name, when it has a string one.meta (object or None) – A detached snapshot copy of the input’s
meta: later changes to the input’s metadata do not reach it, and it holds no autograd graph.device (torch.device) – The device the input lived on, where the outputs are placed.
meta_override (bool, optional) –
Truewhen the run read metadata other than the dataset’s own (run(..., meta=...)or awith_meta()view);metais then that metadata. DefaultFalse.
- scatterem.reconstruction.register_runner(config_type: type[ReconstructionConfig[Any]], *, reuse_keys: Iterable[str] = ()) Callable[[Callable[[Any, Any, Mapping[str, Any]], Result]], Callable[[Any, Any, Mapping[str, Any]], Result]]#
Register the function
run()calls forconfig_type.Used as a decorator in the module that implements the family. The runner is called as
runner(data, config, reuse), withreusea read-only mapping holding only keys fromreuse_keys.- Parameters:
config_type (type) – A
ReconstructionConfigsubclass that setsmethod.reuse_keys (sequence of str, optional) – The
reuse=keys this family accepts;run()rejects others.
- Returns:
A decorator that registers its argument and returns it unchanged.
- Return type:
callable
- Raises:
TypeError – If
config_typeis not aReconstructionConfigsubclass with a stringmethod.ValueError – If
config_typealready has a runner.
Direct ptychography and the aberration fit#
The aberration fit on a 4D-STEM dataset, run through |
|
Result of |
|
Single-side-band direct ptychography, run through |
|
Result of |
- class scatterem.reconstruction.ptychography.direct.AberrationFitConfig(correction_method: str = 'combined', fit_rotation: bool = False, target_percentage_nonzero_pixels: float = 0.75, n_batches: int = 25, registration_upsample_factor: int = 10, lowpass_fwhm_bright_field: float | None = None, bin_factors: tuple[int, ...] = (2, 1, 1), verbosity: int = 0, correct_order: int = 1, gradient_mask: tuple[bool, ...] | None = None, num_iterations: int = 10, lr: float = 20, bright_field_mask_threshold: float = 0.5, roi_shape: tuple[int, int] = (128, 128), roi_center: str | tuple[int, int] = 'center', upsample: int | str = 'nyquist', update_dataset: bool = True, n_center_indices: int = 25, phase_sign: Literal['preserve', 'positive', 'negative'] = 'preserve', sharpness_metric: str = 'sparsity', reg_weight: float = 0.05, alignment_method: str = 'reference', peak_selection: Literal['argmax', 'guided'] = 'argmax', init_method: Literal['closed_form', 'zeros'] = 'closed_form', use_com_rotation_prior: Literal['auto', 'off'] = 'auto', check_defocus_sign: bool = False)#
The aberration fit on a 4D-STEM dataset, run through
run().Fields are the keyword arguments of
scatterem.reconstruction.ptychography.direct.determine_aberrations(); see it for their meaning.update_datasetkeeps its old effect on the fit itself (whether it records the rotation, the defocus guess and the coefficients on the metadata, here reported inAberrationFitResult.meta_updates);run()writes nothing.datais aDataset4DStemor aDatasetVirtualBrightField4DStem.- Parameters:
correction_method (str) –
"combined","bright-field-shifts"or"autofocus".fit_rotation (bool) – Whether to fit the scan rotation.
target_percentage_nonzero_pixels (float) – Target percentage of nonzero pixels for the bright field.
n_batches (int) – Number of bright-field batches of the SSB images of the defocus sign check and the autofocus (TV) step; not used by the bright-field shift fit.
registration_upsample_factor (int) – Upsampling factor for the shift registration.
lowpass_fwhm_bright_field (float or None) – FWHM of the lowpass filter applied to the bright field.
bin_factors (tuple of int) – Bin factors for the bright field.
verbosity (int) – Verbosity level.
correct_order (int) – Order of the aberrations the autofocus stage corrects.
gradient_mask (tuple of bool or None) – Which of the 12 coefficients the autofocus may adjust;
Nonemeans all of them.num_iterations (int) – Number of autofocus iterations.
lr (float) – Learning rate of the autofocus optimizer.
bright_field_mask_threshold (float) – Bright-field mask threshold.
roi_center (str or tuple of int) – Center of the region of interest.
update_dataset (bool) – Whether the fit records its results on the (copied) metadata.
n_center_indices (int) – Number of center indices for the bright-field shift fit.
phase_sign ({"preserve", "positive", "negative"}) – Sign convention for the fitted phase.
sharpness_metric (str) – Autofocus objective,
"sparsity"or"tv".reg_weight (float) – L2 regularization weight toward the seed in the autofocus.
alignment_method (str) – Alignment method of the bright-field shift fit.
peak_selection ({"argmax", "guided"}) – Which cross-correlation peak is each bright-field shift. Use
"guided"on crystals: their correlation is multi-peaked, and the global maximum ("argmax") can pick a lattice copy and flip the sign of C10.init_method ({"closed_form", "zeros"}) – Seed of the bright-field-shift fit.
use_com_rotation_prior ({"auto", "off"}) – Whether an unset
meta.rotationis seeded from the diffraction centre of mass.check_defocus_sign (bool) – Whether the fit compares the corrected image at the fitted coefficients and at their negative, and keeps the more coherent one. The result then carries the decision in
diagnostics["defocus_sign_check"]. Off by default: it costs two passes over the bright-field stack and can change the fit.
- class scatterem.reconstruction.ptychography.direct.AberrationFitResult(*, provenance: ~scatterem.reconstruction._runner.Provenance, diagnostics: ~collections.abc.Mapping[str, ~typing.Any] = <factory>, aberrations: ~torch.Tensor, meta_updates: ~collections.abc.Mapping[str, ~typing.Any], rotation: float | None = None)#
Result of
AberrationFitConfig.- Parameters:
provenance (Provenance) – Where the result came from.
diagnostics (Mapping, optional) –
{"vbf_cache": ...}when the run was given one to carry through, and{"defocus_sign_check": {...}}whencheck_defocus_signwas set:c10_fitted,c10_kept,energy_fitted,energy_flippedandflipped. Empty otherwise.aberrations (torch.Tensor) – The 12 fitted aberration coefficients.
meta_updates (Mapping) – The metadata attributes the fit changed, by name, with their new values (read-only): what the older entry point wrote onto
dataset.metathrough the sharedvBF.meta. Withupdate_dataset=Truethese areaberrations,rotationanddefocus_guess(reset to 0.0: the fitted defocus is inaberrations[0]).rotation (float or None, optional) – The scan rotation (deg) the aberrations hold at: the fitted one with
fit_rotation, else the rotation the fit held. It is set also withupdate_dataset=False, which writes nometa.Nonewhen the fit did not report one.
- as_tuple() tuple[Tensor]#
Return
(aberrations,): the fitted tensor wrapped in a 1-tuple.- Returns:
The fitted coefficients, wrapped in a 1-tuple.
- Return type:
- applied_to(meta: Any) Any#
Return a new copy of
metawith this fit applied.The copy gets every entry of
meta_updatesand a newAberrationsholdingaberrations, withdefocus_guessset to 0.0: the fitted C10 is inaberrations[0]alone, also when the fit ran withupdate_dataset=False. Whenmeta_updateshas norotation(update_dataset=False, or a held rotation), the copy getsrotation, so the aberrations keep the rotation they hold at.metaitself is not modified, and the copy shares no tensor with this result.
- class scatterem.reconstruction.ptychography.direct.DirectPtychographyConfig(upsample: float | str = 'nyquist', bright_field_mask_threshold: float = 0.5, verbosity: int = 0, n_batches: int = 25, return_snr: bool = False, phase_sign: Literal['preserve', 'positive', 'negative'] = 'preserve', ssnr_method: str = 'analytical', gamma_weighting: Literal['phase', 'wiener'] = 'phase', wiener_alpha: float = 0.001, snr_blur_sigma: float = 0.0, rolloff_start: float | None = None)#
Single-side-band direct ptychography, run through
run().Fields and defaults are those of
scatterem.reconstruction.ptychography.direct.direct_ptychography(); see it for their meaning.snr_blur_sigmais the one keyword that function takes through**kwargs(used by the empirical SSNR).datais aDataset4DStemor an already-builtDatasetVirtualBrightField4DStem.reuse={"vbf": provider}supplies a vBF built at this config’sbright_field_mask_thresholdfrom the same dataset, instead of building one; it is not checked against the threshold.Memory: the run frees its virtual bright field and the bright-field Fourier stack
Gwhen it returns, so repeated runs on one dataset (a defocus sweep, say) all peak at the first run’s level.- Parameters:
bright_field_mask_threshold (float) – Bright-field mask threshold.
verbosity (int) – Verbosity level.
n_batches (int) – Number of bright-field chunks.
return_snr (bool) – Whether to compute the SSNR.
phase_sign ({"preserve", "positive", "negative"}) – Global phase-sign convention.
ssnr_method (str) –
"analytical"or"empirical".gamma_weighting ({"phase", "wiener"}) – How
Gamma(Q, K)weights each bright-field pixel.wiener_alpha (float) – Tikhonov floor for
gamma_weighting="wiener".snr_blur_sigma (float) – Blur sigma of the empirical SSNR.
rolloff_start (float or None) – When set, the phase spectrum is rolled off with a raised cosine from
rolloff_start * 2 alpha / lambdato zero at2 alpha / lambda, the transfer limit of direct ptychography, where the noise makes a bright rim in the spectrum (seerolloff_2alpha()). Typical value 0.9. The SSNR map is not changed. Default is None, no roll-off.
- class scatterem.reconstruction.ptychography.direct.DirectPtychographyResult(*, provenance: Provenance, diagnostics: Mapping[str, ~typing.Any]=<factory>, phase: Tensor, ssnr: Tensor | None, sampling: Sampling)#
Result of
DirectPtychographyConfig.- Parameters:
provenance (Provenance) – Where the result came from.
diagnostics (Mapping, optional) – Secondary outputs (read-only).
phase (torch.Tensor) – The reconstructed phase image, shape
(Ny * uy, Nx * ux)for the resolved upsampling(uy, ux), on the dataset’s device.ssnr (torch.Tensor or None) – The SSNR map of
phase(same shape), orNoneunlessreturn_snrwas set.sampling (Sampling) – The pixel size
(dy, dx)ofphaseand its units, the scan step divided by the upsample factor (fromreconstruction_sampling()). Pass it tovis.show_2d(..., sampling=)ordiagnostics.metrics.frc(..., pixel_size=).
- as_tuple() tuple[Tensor, Tensor | None]#
Return
(phase, ssnr), whatdirect_ptychographyreturns.- Returns:
The phase image and the SSNR map (or
None).- Return type:
tuple of (torch.Tensor, torch.Tensor or None)
Bright-field parallax#
Measure the translation of every BF image. |
|
Fit the aberrations and rotation to the bright field shifts. |
|
First determine the bright field shifts, then fit aberrations and rotation. |
- scatterem.reconstruction.ptychography.direct.measure_bf_parallax(image_spectra, detector_coords_px, *, shift_estimator: str = 'mean_template', binning: int = 1, peak_grid_divisor: int = 20, lowpass_sigma_px: float | None = None, start_template=None, n_refinements: int = 2, peak_tolerance: float = 0.02, remove_image_mean: bool = True, status_line: bool = False, quiet: bool = False) Tensor#
Measure the translation of every BF image.
- Parameters:
image_spectra (Tensor, numpy.ndarray or SpectrumSource) – The 2-D Fourier transforms of the N BF images (convention of the module docstring): a complex stack
(N, n0, n1), or a source that delivers them in parts (SpectrumSource,ChunkedSpectrumSource).detector_coords_px (array_like) – Real
(N, 2)detector coordinates in pixels, relative to the BF disc centre, in the order of the images. Finite, no duplicate rows.shift_estimator ({"mean_template", "neighbour_mesh"}, optional) –
"mean_template": common reference; starting reference = the mean of all (binned) spectra, which is the incoherent BF image with the best signal-to-noise ratio; thenn_refinementsrebuilds as the aligned average."neighbour_mesh": register detector neighbours (|Δq| <= 1.5 p,pthe detector pitch; bins: indices within one) onto each other and solve the least-squares fit ofs_j − s_i = d_ij. Use it when a large aberration blurs the mean. It also recovers shifts larger than half the lattice repeat on a periodic specimen, withbinning=1, provided the shift difference between detector neighbours stays below half the lattice repeat and the neighbour graph is connected.binning (int, optional) – Detector binning factor (>= 1). Bins are centred on multiples of
binning · p; a bin spectrum is the mean of its members. Each BF pixel then gets a shift by a quadratic moving least-squares fit over the bins (Gaussian weights of widthbinning · p), so every pixel gets a finite shift. 1 means no binning.peak_grid_divisor (int, optional) – The final peak grid is
1/peak_grid_divisorscan pixel. Default 20: a grid error of at most 0.025 px before the parabolic step.lowpass_sigma_px (float, optional) – Gaussian low-pass
exp(−2π² σ² |k|²)on every image;σis the real-space standard deviation of the blur in scan pixels. A Gaussian has no ringing and zero phase, so it does not move the peak.start_template (array_like, optional) – Starting reference for
"mean_template": complex(n0, n1), in the same Fourier convention as the input.n_refinements (int, optional) – Number of aligned-average rebuilds (>= 0). Default 2.
peak_tolerance (float, optional) – In
[0, 1). Peaks within this fraction of the highest peak count as equal; the one nearest to zero shift wins. This gives the true shift on a scan-periodic specimen when the shift is less than half the lattice repeat. Default 0.02.remove_image_mean (bool, optional) – Remove the mean shift over all images. Default True: the absolute offset depends on the reference and carries no information.
status_line (bool, optional) – Show one progress line on
sys.stderr. Ignored when quiet.quiet (bool, optional) – No output: no log records above DEBUG, no warnings, no progress.
- Returns:
Real
(N, 2)on the device of the image data, in scan pixels, rowifor input rowi. dtype float64 for complex128 spectra, else float32: the precision follows the data. The result is the translation that registers each image onto the reference: an image equal to the reference translated bytgives−t(plus a common offset, zero after mean removal).- Return type:
Tensor
- Raises:
ValueError – For an unknown shift estimator, an invalid option, spectra that are not a complex 3-D stack or source, bad coordinates, a count mismatch, a reference spectrum of the wrong shape or with
"neighbour_mesh", or non-finite spectrum values.
Notes
All work runs in the canonical order of the coordinates (sorted by
(q0, q1)) in blocks that depend only on the scan shape. So a permutation of the input permutes the output exactly, and the chunk size of a source never changes the result.Degenerate inputs give, without an exception:
N = 0: an empty(0, 2)tensor;N = 1:[[0, 0]](withremove_image_mean=Falseand"mean_template": the shift onto the reference); all images equal: equal shifts (zero after mean removal); a constant or zero image: shift 0 relative to the reference, or dropped neighbour pairs (an isolated node gets 0);n0 = n1 = 1: zeros; one bin: every pixel gets the bin shift; a disconnected neighbour graph: zero mean per component and a WARNING record.
- scatterem.reconstruction.ptychography.direct.fit_aberrations_and_rotation_to_bright_field_shifts(target_shifts: Tensor, k_sampling: ndarray | Tensor, wavelength: float, bright_field_mask: Tensor, include_in_fit_mask: Tensor | None = None, rotation_init: Tensor | None = None, rotation_requires_grad: bool = True, init_method: str = 'closed_form', residual_warn_rtol: float = 0.15, correct_order: int = 1, max_iter: int = 250, lr: float = 0.1, verbosity: int = 0, covariance_block_px: int | None = None) BrightFieldShiftFit#
Fit the aberrations and rotation to the bright field shifts.
- Parameters:
target_shifts (torch.Tensor) – Target bright-field shifts, shape (N, 2), one row per pixel of
bright_field_maskin row-major (torch.argwhere) order, asaberrations_to_image_shifts(...)[bright_field_mask]lays them out.k_sampling (numpy.ndarray) – Real-space sampling of the detector grid,
dataset.dr(Angstrom), shape (2,) – NOT the reciprocal detector pixel size: the shift model’s frequencies arefftfreq(shape, k_sampling).wavelength (float) – Electron wavelength, in Angstrom.
bright_field_mask (torch.Tensor) – Bright-field mask, shape (H, W).
include_in_fit_mask (torch.Tensor, optional) – Mask of bright-field shifts to include in the fit. Default is None, which includes all of them.
rotation_init (torch.Tensor, optional) – Initial rotation, in degrees. Default is None, which initializes the rotation to 0.
rotation_requires_grad (bool, optional) – Whether to optimize the rotation. If False the rotation is held at rotation_init (0 when None), and the closed-form seed is solved at that rotation. Default is True.
init_method (str, optional) – Initialization method, either “closed_form” (default: the closed-form C1, C12 and rotation estimate) or “zeros”. Either seed is then refined over the coefficients
correct_orderfrees; “zeros” additionally caps that at order 1.residual_warn_rtol (float, optional) – Relative residual limit. Above it the fit emits a UserWarning and the result’s
reliableis False. The relative residual is RMS(final_shifts - target_shifts) / RMS(target_shifts). Default is 0.15.correct_order (int, optional) – Highest aberration order refined: 0 is C1 only, 1 (default) C1 and C12a/b, 2 adds coma and three-fold astigmatism (C21, C23), 3 adds C30, C32 and C34. Higher-order terms correlate strongly with the low-order ones over the bright-field disk, so freeing them without such aberrations in the data biases C1 (about 6% on low-defocus data); conversely an order-1 fit absorbs a real spherical aberration into C1.
max_iter (int, optional) – Maximum number of LBFGS iterations. Default is 250.
lr (float, optional) – Learning rate. Default is 1e-1.
verbosity (int, optional) – Verbosity level. Default is 0.
covariance_block_px (int, optional) – If given, the result also carries
covariance_bootstrap: a block bootstrap over the bright-field pixels, with square blocks of this side in detector pixels (choose it larger than the correlation length of the shift errors). Default is None: only the formal covariance, which is not calibrated when the shift errors are correlated.
- Returns:
The fitted aberrations (Angstrom) and rotation (degrees), with the relative residual, the
reliableflag and, forinit_method="closed_form"andcorrect_order=1, the covariance of C1, C12 (and the rotation, when it is fitted). It unpacks asaberrations, rotation = fit. Checkreliablebefore a pipeline writes the values as results; the class docstring gives the fallback order. The aberrations are in the SHIFT-MODEL frame ofscatterem.utils.transfer.aberrations_to_image_shifts(the model fitted here): atrotation != 0every m-fold pair differs from the detector-frame vectormeta.aberrationsholds. Convert withscatterem.utils.transfer.shift_model_to_detector_frameat the fitted rotation before using them asmeta.aberrations;aberrations_and_rotation_from_bright_field_shifts()does.- Return type:
BrightFieldShiftFit
Notes
The refinement runs in float64 whatever the input dtype (outputs are float32), with LBFGS in coordinates scaled by each coefficient’s shift sensitivity, so it converges and its result does not depend on float32 rounding of the inputs.
- scatterem.reconstruction.ptychography.direct.aberrations_and_rotation_from_bright_field_shifts(dataset: DatasetVirtualBrightField4DStem, fit_rotation: bool = True, target_percentage_nonzero_pixels: float = 0.75, registration_upsample_factor: int = 10, lowpass_fwhm_bright_field: float | None = None, bin_factors: tuple[int, ...] = (2, 1), verbosity: int = 0, update_dataset: bool = True, n_center_indices: int = 25, use_com_rotation_prior: str = 'auto', alignment_method: str = 'reference', init_method: str = 'closed_form', peak_selection: str = 'argmax', correct_order: int = 1, covariance_block_px: int | None = None) BrightFieldShiftFit#
First determine the bright field shifts, then fit aberrations and rotation.
- Parameters:
dataset (DatasetVirtualBrightField4DStem) – Dataset4DStem or DatasetVirtualBrightField4DStem object containing the diffraction pattern.
fit_rotation (bool, optional) – Whether to fit the rotation. Default is True.
target_percentage_nonzero_pixels (float, optional) – Target percentage of nonzero pixels for the bright field. Default is 0.75.
registration_upsample_factor (int, optional) – The final cross-correlation peak grid is
1 / registration_upsample_factorscan pixel (peak_grid_divisorofmeasure_bf_parallax()). Default is 10.lowpass_fwhm_bright_field (float, optional) – FWHM of the lowpass filter for the bright field. Default is None, which applies no lowpass filter.
bin_factors (tuple of int, optional) – Bin factors for the bright field, applied in order. Default is (2, 1).
verbosity (int, optional) – Verbosity level. Default is 0.
update_dataset (bool, optional) – Whether to write the fitted aberrations (detector frame, as returned) and rotation back onto dataset.meta. Default is True. The write happens whether or not the fit is
reliable, and a vBF sharesmetawith its parent dataset. To write only a reliable fit, pass False, checkreliableand then write the values.n_center_indices (int, optional) – Number of center indices to use for the bright field shifts. Default is 25.
use_com_rotation_prior (str, optional) – When “auto” (default), computes a diffraction COM-curl rotation prior and uses it as the initial rotation when meta.rotation is unset (< 1e-6 deg). An out-of-core parent dataset is measured block by block, to the same prior as its eager twin. If no pattern has a finite COM, a warning is logged and meta.rotation is kept. Set to “off” to always use meta.rotation directly.
alignment_method (str, optional) – “reference” (default) registers every BF image onto one common reference (
shift_estimator="mean_template"ofmeasure_bf_parallax()). “pairwise” registers detector neighbours onto each other and solves for all shifts by least squares (shift_estimator="neighbour_mesh"), which is more robust when large aberration shifts blur the reference image.init_method (str, optional) – How the aberration fit is initialised, forwarded to fit_aberrations_and_rotation_to_bright_field_shifts. “closed_form” (default) seeds it with the closed-form C1, C12 and rotation estimate; “zeros” starts from zero and caps the fit at order 1. Either way the refined orders are set by
correct_order.peak_selection (str, optional) – Which cross-correlation peak is taken as each shift: “argmax” (default, the global maximum) or “guided” (for periodic specimens, whose correlation is multi-peaked). With “guided” and
alignment_method="reference"on a periodic reference image, the images (or detector bins) are registered in order of increasing detector radius; each one takes the highest peak near a smooth prediction from the ones nearer the centre (see_peak_selection). The low-pass and the bin factors apply as for “argmax”. On a non-periodic reference image “guided” is “argmax”. Withalignment_method="pairwise", “guided” takes, among the peaks within 2 % of the highest, the one nearest to zero shift. With “argmax” on a periodic specimen aUserWarningflags a likely wrong pick.correct_order (int, optional) – Highest aberration order the fit refines, forwarded to fit_aberrations_and_rotation_to_bright_field_shifts. Default is 1 (C1, C12 and rotation); a real spherical aberration is then absorbed into C1 unless 3 is requested.
covariance_block_px (int, optional) – Forwarded to fit_aberrations_and_rotation_to_bright_field_shifts: if given, the result carries a block-bootstrap covariance as well as the formal one. Default is None.
- Returns:
The aberrations (Angstrom) and rotation (degrees) of the last bin level. Every level fits the shifts MEASURED up to that level (the sum of the measured increments); the fitted shifts are not fed back into the data. The covariance fields (detector frame) are those of the last level’s fit. The aberrations are
(12,)in the DETECTOR frame ofmeta.aberrations(the frame the direct-ptychography kernels and tilt-corrected dark field read): the shift-model-frame fit converted withscatterem.utils.transfer.shift_model_to_detector_frameat the fitted rotation, the same as the fit atrotation == 0.relative_residualis the largest over the bin levels, andwell_posedis False if any level was not well posed, so a failed earlier level makes the result notreliable. It unpacks asaberrations, rotation = fit. Whenreliableis False, use the fallback order in the BrightFieldShiftFit docstring.- Return type:
BrightFieldShiftFit
- Raises:
ValueError – If the dataset is not a valid Dataset4DStem object, if
bin_factorsis empty, or if the vBF does not carry its detector sampling (a 4-entrysamplingand a 2-Dbright_field_mask).
Scan rotation and centre-of-mass calibration#
Find the rotation between scan and detector from the CoM field. |
|
Result of |
|
Record of the angle search, for |
|
Fit the drift of the diffraction-space origin across the scan. |
|
Fit a surface model |
|
Affine surface |
|
General 2-D quadratic surface, evaluated in Horner form. |
|
Tensor-product quadratic Bezier (biquadratic Bernstein) surface. |
- scatterem.data.calibration.find_scan_rotation(centroid_a0, centroid_a1, *, run_device=None, quiet: bool = False, angle_grid_deg=None, fixed_angle_deg: float | None = None, fixed_axes_exchanged: bool | None = None, resolve_180: bool = True, curve_kind: str = 'curl', scan_spacing=(1.0, 1.0), keep_search: bool = False, evaluator: str = 'by_capability') ScanRotation#
Find the rotation between scan and detector from the CoM field.
The solver evaluates the objective of
rotation_objective()over the trial angles, picks the extremum (minimum for curl, maximum for divergence) and decides the handedness: the hypothesis with the better extremum wins. On an exact tie the field stays as measured, because a reflection is a strong claim that needs evidence. On exact ties within a curve the first angle in the caller’s order wins. Then the 180° test of_rotation_sign.resolve_half_turn()decides the sign.The solver reports with
logging(INFO for the decision, WARNING for an inconclusive 180° test) and withScanReflectionWarningfor a found reflection: only the caller can fix that, by a change to the data, and a warnings filter can turn it into an error.quiet=Truereports nothing above DEBUG. The solver draws no figure.- Parameters:
centroid_a0 (Tensor or numpy.ndarray) – CoM components along axis 0 and axis 1: 2-D, real, one shape, at least
2 × 2, finite.centroid_a1 (Tensor or numpy.ndarray) – CoM components along axis 0 and axis 1: 2-D, real, one shape, at least
2 × 2, finite.run_device (str or torch.device, optional) – Device rule: an explicit device wins; else the device of the first tensor input; else the CPU.
quiet (bool, optional) – No log records above DEBUG and no warnings.
angle_grid_deg (array_like, optional) – Trial angles in degrees, 1-D, finite, any order. Default
DEFAULT_ANGLE_GRID_DEG,[-90, 90)in steps of 0.1°: one period of the objective, with a grid error of at most 0.05°.fixed_angle_deg (float, optional) – Skip the search and use this angle. The result angle is this angle wrapped into
[-180, 180). No 180° test runs, and no record is returned (searchis None). Iffixed_axes_exchangedis None, the two hypotheses are compared at this angle.fixed_axes_exchanged (bool, optional) – Fix the handedness and skip its test.
resolve_180 (bool, optional) – Run the 180° test. Default True: without it the angle is ambiguous by 180°, which inverts the sign of every phase downstream.
curve_kind ({"curl", "divergence"}, optional) – Default
"curl": its target is 0 for an ideal field, so its minimum tells how good the fit is.scan_spacing (float or (float, float), optional) – Scan step along axis 0 and axis 1. Only the ratio matters.
keep_search (bool, optional) – Also return the search record. The other outputs are bit-identical with and without it.
evaluator ({"by_capability", "tensor_ops"}, optional) – Implementation of the objective, see
rotation_objective().
- Returns:
scan_turn_degin[-180, 180): the total rotation, including a half-turn from the 180° test. The corrected field isR(scan_turn_deg) P^h f: the half-turn is applied as an exact negation.rotated_180flags the half-turn.- Return type:
- Raises:
ValueError – If the inputs are not two finite real 2-D arrays of one shape of at least
2 × 2, or an option is invalid.
- class scatterem.data.calibration.ScanRotation(scan_turn_deg: float, centroid_a0: Tensor, centroid_a1: Tensor, axes_exchanged: bool, rotated_180: bool, search: RotationSearch | None)#
Result of
find_scan_rotation().- Variables:
scan_turn_deg (float) – Total rotation applied to the (possibly swapped) field, in degrees, in the half-open interval
[-180, 180). It includes the half-turn of the 180° test.centroid_a1 (centroid_a0,) – The corrected field on the resolved device. dtype float64 if either input was float64, else float32.
axes_exchanged (bool) – True when the components were exchanged before the rotation.
rotated_180 (bool) – True when the 180° test added a half-turn. Then
scan_turn_degholds the half-turn and the corrected field is the negated field.search (RotationSearch or None) – The search record when the caller asked for it and a search ran.
- class scatterem.data.calibration.RotationSearch(curve_kind: str, angle_grid_deg: ndarray, hypothesis_curves: dict, search_angle_deg: float, scan_turn_deg: float, axes_exchanged: bool, rotated_180: bool, sign_test: str, potential_skewness: float | None, evaluator: str)#
Record of the angle search, for
scatterem.vis.rotation_figures.angle_search_figure().- Variables:
curve_kind (str) –
"curl"or"divergence".angle_grid_deg (numpy.ndarray) – float64
(A,): the trial angles as given.hypothesis_curves (dict of str to numpy.ndarray) –
"axes_kept"and/or"axes_exchanged", float64(A,). A hypothesis that was not evaluated has no key.search_angle_deg (float) – The trial angle at the extremum of the chosen hypothesis.
scan_turn_deg (float) – The returned angle, equal to
ScanRotation.scan_turn_deg.axes_exchanged (bool) – The chosen hypothesis.
rotated_180 (bool) – True when the 180° test added a half-turn.
sign_test (str) –
"kept","flipped","undecided"or"off".potential_skewness (float or None) – Skewness of the integrated potential; None when the test did not run.
evaluator (str) –
"tensor_ops"or"gpu_kernel".
- scatterem.data.calibration.fit_origin(data: tuple[Tensor, Tensor], mask: Tensor | None = None, fit_function: str = 'plane', return_fit_params: bool = False, robust: bool = False, robust_steps: int = 3, robust_thresh: float = 2, device: str | device | None = None)#
Fit the drift of the diffraction-space origin across the scan.
The two components of the measured origin are fitted independently, each with the same smooth surface model, and the residuals returned alongside.
- Parameters:
data ((Tensor, Tensor)) – Measured origin, as (x-component, y-component), each (Rx, Ry).
mask (Tensor, optional) – Boolean (Rx, Ry); scan positions where False are excluded from the fit but still get a fitted value and a residual.
fit_function (str) –
'constant'(per-component mean) or one of the keys of_ORIGIN_SURFACES.return_fit_params (bool) – Also return the coefficients and covariances of the two fits. They are
Noneforfit_function='constant', which has no fitted model.robust – Outlier rejection, forwarded to
fit_2D().robust_steps – Outlier rejection, forwarded to
fit_2D().robust_thresh – Outlier rejection, forwarded to
fit_2D().device (str, torch.device or None) – Default: the device of
data[0]if it is a tensor, else CPU.
- Returns:
Each (Rx, Ry). If
return_fit_params, a 2-tuple of that and(popt_x, popt_y, pcov_x, pcov_y).- Return type:
(qx0_fit, qy0_fit, qx0_residuals, qy0_residuals)
Notes
Clean-room implementation from a behavioural specification (see
_surfaces). The method is that of Savitzky et al. (2021) and Ophus (2019): the descan is a slow, smooth drift, so a low-order surface fitted to each component removes it and leaves the specimen signal in the residual.
- scatterem.data.calibration.fit_2D(function, data: Tensor, data_mask: Tensor | None = None, popt=None, robust: bool = False, robust_steps: int = 3, robust_thresh: float = 2, device: str | device | None = None, need_pcov: bool = True)#
Fit a surface model
function(xy, *coefficients)to a 2-D field.The field is sampled on the unit square (
_make_xy_flat()). The three models of this module are solved in closed form by linear least squares; any other callable is fitted by L-BFGS frompopt. Clean-room implementation from a behavioural specification (see the module docstring); method of Savitzky et al. (2021) and Ophus (2019).- Parameters:
function (callable) – Model whose first argument is the
(2, N)coordinates and whose other arguments are thePcoefficients.data (Tensor (H, W)) – Field to fit; it is read as float32 and fitted in float64.
data_mask (Tensor (H, W), optional) – Boolean; only points where it is True enter the fit. Default: all.
popt (sequence or Tensor, optional) – Initial coefficients,
Pof them. Default: zeros. Used only by the L-BFGS path.robust (bool) – Re-fit
robust_stepsmore times, each time removing from the mask the points whose squared residual is larger thanrobust_thresh**2times the mean squared residual over the whole field.robust_steps (int)
robust_thresh (float)
device (str, torch.device or None) – Default: the device of
dataif it is a tensor, else CPU.need_pcov (bool) –
Falseskips the parameter covariance of a linear basis and returns the NaN placeholder in its slot; everything else is unchanged. DefaultTrue.
- Returns:
popt (Tensor (P,), float64)
pcov (Tensor (P, P), float64)
fit (Tensor (H, W), float32)
mask (Tensor (H, W), bool) – The points used by the last fit.
- scatterem.data.calibration.plane(xy, mx, my, b)#
Affine surface
z = mx*x + my*y + b(gradient(mx, my), offsetb).
- scatterem.data.calibration.parabola(xy, c0, cx1, cx2, cy1, cy2, cxy)#
General 2-D quadratic surface, evaluated in Horner form.
z = c0 + cx1*x + cx2*x^2 + cy1*y + cy2*y^2 + cxy*x*y– the complete second-order polynomial in two variables, grouped asc0 + x*(cx1 + cx2*x + cxy*y) + y*(cy1 + cy2*y)so each variable is touched once.
- scatterem.data.calibration.bezier_two(xy, c00, c01, c02, c10, c11, c12, c20, c21, c22)#
Tensor-product quadratic Bezier (biquadratic Bernstein) surface.
z = sum_{i,j} c_ij * B_i(x) * B_j(y)over the degree-2 Bernstein basis of_bernstein_quadratic(), i.e. a 3x3 grid of control valuesc_ijwithiindexingxandjindexingy. Because the basis is a partition of unity the surface interpolates the corner coefficients (c00at(0,0),c22at(1,1)) and stays within the convex hull of all nine.
Scan-rotation figures#
Plot the objective curves of a scan-rotation search. |
|
Show 2-D scan maps in physical scan coordinates. |
- scatterem.vis.rotation_figures.angle_search_figure(search: RotationSearch, *, figure_inches=(5.0, 3.2)) Figure#
Plot the objective curves of a scan-rotation search.
Layout: one axes, one line per evaluated hypothesis against the trial angle (sorted by angle for drawing; the record is not changed). Colours are the first two colours of the categorical role
"labels"; line styles are solid for “as measured” and dashed for “components swapped (reflection)”, so the hypotheses stay apart without colour vision too. Each legend label ends with the extremum of its curve. A dotted dark-grey vertical line markssearch_angle_deg: that line lies in the plotted range, and its label gives the final angle when the 180° test added a half-turn. NaN and ±inf values are drawn as gaps; a constant curve is a flat line; if no value is finite, the axes say so. No case raises.- Parameters:
search (RotationSearch) – The record from
find_scan_rotation(..., keep_search=True).figure_inches ((float, float), optional) – Figure size in inches. Default
(5.0, 3.2).
- Returns:
A new open figure with one axes.
- Return type:
- Raises:
ValueError – If
searchis not aRotationSearch.
- scatterem.vis.rotation_figures.plot_scan_maps(scan_images: Sequence, *, scan_spacing, distance_unit, map_captions: Sequence[str] | None = None, panel_grid: tuple[int, int] | None = None, figure_inches: tuple[float, float] | None = None, colour_role=None, colour_map=None, limits=None, colour_key: bool = True, length_bar: bool = True) Figure#
Show 2-D scan maps in physical scan coordinates.
Geometry: each map is drawn as stored, rows (axis 0, “x”) vertical and columns (axis 1, “y”) horizontal,
origin="upper". Pixel centres sit atk · step, so the axes spann · stepalong each axis, with equal aspect in data units. Colour: by default a map with any finite value below zero takes the diverging role"signed"with limits symmetric about 0, so the neutral colour sits at zero; other maps take"intensity". NaN shows in the NaN colour of the policy. Each panel has a horizontal scale bar along axis 1, its title and (by default) a colour bar.- Parameters:
scan_images (sequence of Tensor or numpy.ndarray) – Real 2-D maps; shapes may differ. Tensors may be on any device.
scan_spacing (float or (float, float)) – Step between scan positions along axis 0 and axis 1. Required: a silent default would hide a missing calibration.
distance_unit (str or (str, str)) – Length unit per axis;
"A"prints as “Å”. Required.map_captions (sequence of str, optional) – One per map. Default
"map 0","map 1", …panel_grid ((int, int), optional) –
(rows, cols). Defaultcols = ceil(sqrt(n)),rows = ceil(n / cols). Unused panels are removed.figure_inches ((float, float), optional) – Override. Default
(3.4 · cols, 3.0 · rows)inches.colour_role (str or sequence of str, optional) – Override of the automatic colour role, one for all or one per map.
colour_map (str or Colormap, optional) – Override with an explicit map (an unscientific map warns).
limits ((float, float) or sequence of them, optional) – Override of the display limits
(vmin, vmax), one for all or one per map.colour_key (bool, optional) – Draw a colour bar per panel. Default True.
length_bar (bool, optional) – Draw a scale bar per panel. Default True.
- Returns:
A new open figure with one image panel per map.
- Return type:
- Raises:
ValueError – For an empty map list, a map that is not real 2-D, a bad step or unit, a wrong count of captions, roles or limits, or a panel grid that does not fit the maps.
Tilt-corrected dark field#
Tilt-corrected dark field, run through |
|
Result of |
|
Stack tcDF reconstructions swept over a defocus (depth) series. |
- class scatterem.reconstruction.darkfield.TiltCorrectedDarkFieldConfig(n_dark_field_segments: int = 32, verbosity: int = 0, bright_field_mask_threshold: float = 0.3, upsample: float | str = 'nyquist', return_snr: bool = False, snr_blur_sigma: float = 0.0, shift_method: str = 'drizzle', drizzle_pixfrac: float = 1.0, drizzle_kde_sigma: float = 0.0, dark_field_scaling: bool = False, dead_frame_fraction: float = 0.001, region: str = 'dark_field')#
Tilt-corrected dark field, run through
run().Fields and defaults are those of
scatterem.reconstruction.darkfield.core.tilt_corrected_dark_field()(its private_segment_geometryhook excepted); see it for their meaning.datais aDataset4DStem;reuse={"segment_geometry": g}passes the private precomputed segment geometry (built ondatawith this config’s parameters; a mismatch raisesValueError).- Parameters:
n_dark_field_segments (int) – Number of azimuthal detector segments.
verbosity (int) – Diagnostic-plot verbosity.
bright_field_mask_threshold (float) – Bright-field mask threshold.
return_snr (bool) – Whether to compute the half-split SSNR.
snr_blur_sigma (float) – Blur sigma of the SSNR curve.
shift_method ({"drizzle", "fourier"}) – How segments are shifted and accumulated.
drizzle_pixfrac (float) – Drizzle drop size.
drizzle_kde_sigma (float) – Drizzle smoothing sigma.
dark_field_scaling (bool) – Rescale segments for scattering past the detector edge.
dead_frame_fraction (float) – Minimum recorded fraction for dark_field_scaling.
region ({"dark_field", "bright_field"}) – Which detector pixels feed the segments.
- class scatterem.reconstruction.darkfield.TiltCorrectedDarkFieldResult(*, provenance: Provenance, diagnostics: Mapping[str, ~typing.Any]=<factory>, image: Tensor, ssnr: Tensor | None, sampling: Sampling)#
Result of
TiltCorrectedDarkFieldConfig.- Parameters:
provenance (Provenance) – Where the result came from.
diagnostics (Mapping, optional) – Secondary outputs (read-only; empty for this family).
image (torch.Tensor) – The tilt-corrected dark-field (or, with
region="bright_field", bright-field) image on the upsampled grid, on the dataset’s device.ssnr (torch.Tensor or None) – The half-split SSNR map (same shape), or
Noneunlessreturn_snrwas set.sampling (Sampling) – The pixel size
(dy, dx)ofimageand its units, the scan step divided by the upsample factor (fromreconstruction_sampling()). Pass it tovis.show_2d(..., sampling=)ordiagnostics.metrics.frc(..., pixel_size=).
- as_tuple() tuple[Tensor, Tensor | None]#
Return
(image, ssnr), whattilt_corrected_dark_fieldreturns.- Returns:
The image and the SSNR map (or
None).- Return type:
tuple of (torch.Tensor, torch.Tensor or None)
- scatterem.reconstruction.darkfield.tilt_corrected_dark_field_depth_section(dataset: Dataset4DStem, depth_angstroms=<built-in method tensor of type object>, bright_field_mask_threshold: float = 0.3, return_device: device | None = None, upsample: float | str = 'nyquist', n_dark_field_segments: int = 32, verbosity: int = 0, dark_field_scaling: bool = False, dead_frame_fraction: float = 0.001, region: str = 'dark_field', return_snr: bool = False, ssnr_return_device: device | None = None, _segment_geometry: _SegmentGeometry | None = None) Tensor | tuple[Tensor, Tensor | None]#
Stack tcDF reconstructions swept over a defocus (depth) series.
Runs
tilt_corrected_dark_field()once per entry ofdepth_angstroms(each added toaberrations[0]) and stacks the results as(n_depths, ny * up, nx * up), withupthe one isotropic factortilt_corrected_dark_field()uses (the larger of the two per-axis factorsupsampleresolves to).dark_field_scaling/dead_frame_fraction/regionare those oftilt_corrected_dark_field()and are shared by all depths: the segment geometry that carries them is built once. The probe has the aberrationsmeta.aberrationswith C10 lessmeta.defocus_guess, as indirect_ptychography().- Parameters:
dataset (Dataset4DStem) – The 4D-STEM dataset to reconstruct from.
depth_angstroms (torch.Tensor) – Defocus offsets, in Angstrom, added to
aberrations[0]at each step. The guessmeta.defocus_guessis subtracted once.bright_field_mask_threshold (float, optional) – Fraction of the peak mean-CBED intensity above which a detector pixel is classified as bright field.
return_device (torch.device, optional) – Device the returned stack is placed on. Defaults to CPU.
upsample (float or str, optional) – Upsampling factor applied to the reconstructed grid, or
"nyquist"to resolve it from the acquisition geometry. On an anisotropic scan,"nyquist"resolves to two factors, and the larger one applies to both axes.n_dark_field_segments (int, optional) – Number of azimuthal detector segments.
verbosity (int, optional) – Diagnostic-plot verbosity, forwarded to
tilt_corrected_dark_field().dark_field_scaling (bool, optional) – Rescale each segment image to account for scattering past the detector edge.
dead_frame_fraction (float, optional) – Minimum fraction of the incident current a scan position must record to receive dark_field_scaling correction.
region ({"dark_field", "bright_field"}, optional) – Which detector pixels feed the azimuthal segments.
return_snr (bool, optional) – Also return the per-plane half-set SSNR stack – a by-product of the two half-set images
tilt_corrected_dark_field()builds either way. With the defaultFalsethe return is the bare image stack, unchanged.ssnr_return_device (torch.device, optional) – Device the SSNR stack is placed on. Defaults to return_device, so a fusion that consumes the SSNR on the GPU can keep it resident while the image cube goes to the host.
_segment_geometry (_SegmentGeometry, optional) – Precomputed segment geometry, built on dataset with these parameters. Private. Default builds it.
- Returns:
The stacked tcDF images, shape
(n_depths, ny * up, nx * up), on return_device. Withreturn_snr=True, that stack and the per-plane half-set SSNR stack on ssnr_return_device; the SSNR slot isNoneonly whendepth_angstromsis empty (no plane to size it by).- Return type:
torch.Tensor or tuple of torch.Tensor
Fused full field#
SSNR-weighted FF-STEM fusion, run through |
|
Result of |
- class scatterem.reconstruction.fusion.ffstem.FusedFullFieldConfig(n_batches: int = 32, upsample: float | str = 'nyquist', verbosity: int = 0, bright_field_mask_threshold: float | None = None, return_snr: bool = True, snr_blur_sigma: float = 0.0, ssnr_method: str = 'analytical', ptycho_lowq_cutoff_frac: float = 0.0, tcdf_shift_method: str = 'drizzle', drizzle_pixfrac: float = 1.0, drizzle_kde_sigma: float = 0.0, n_dark_field_segments: int | None = None, dark_field_scaling: bool = False, dead_frame_fraction: float = 0.001, phase_channel: str = 'ptychography', n_bright_field_segments: int = 8, phase_sign: Literal['preserve', 'positive', 'negative'] = 'preserve')#
SSNR-weighted FF-STEM fusion, run through
run().bright_field_mask_threshold=Noneresolves todata.bright_field_mask_threshold, andn_dark_field_segments=Noneton_batcheswith a warning.Memory: the ptychography channel frees its virtual bright field and the bright-field Fourier stack
Gwhen it returns, before the tcDF channel runs. So the launch caches add noGto the peak of a repeated run on one dataset.- Parameters:
n_batches (int) – Bright-field chunks of the ptychography channel.
verbosity (int) – Verbosity level.
bright_field_mask_threshold (float or None) – Bright-field mask threshold of both channels.
return_snr (bool) – Whether the channels compute their SSNR (the fusion needs it).
snr_blur_sigma (float) – SSNR blur sigma of both channels.
ssnr_method (str) – The ptychography SSNR,
"analytical"or"empirical".ptycho_lowq_cutoff_frac (float) – Low-q band handed to the dark field.
tcdf_shift_method (str) – The tcDF shift method.
drizzle_pixfrac (float) – Drizzle drop size.
drizzle_kde_sigma (float) – Drizzle smoothing sigma.
n_dark_field_segments (int or None) – Dark-field segments.
dark_field_scaling (bool) – The tcDF dark-field scaling.
dead_frame_fraction (float) – The tcDF dead-frame fraction.
phase_channel ({"ptychography", "bright_field"}) – What supplies the low-frequency half.
n_bright_field_segments (int) – Segments of the bright-field phase channel.
phase_sign ({"preserve", "positive", "negative"}) – Global sign convention of the ptychography channel, as in
DirectPtychographyConfig. The default"preserve"keeps the sign that the solver gives."positive"is the convention of version 0.3 and of the FF-STEM paper scripts. The bright-field phase channel ignores it.
- class scatterem.reconstruction.fusion.ffstem.FusedFullFieldResult(*, provenance: Provenance, diagnostics: Mapping[str, ~typing.Any]=<factory>, fused: Tensor, phase_weighted: Tensor | None, tcdf_weighted: Tensor | None, phase_image: Tensor, ptycho: Result, tcdf: TiltCorrectedDarkFieldResult, sampling: Sampling)#
Result of
FusedFullFieldConfig.- Parameters:
provenance (Provenance) – Where the result came from; its config has the threshold and the segment count resolved.
diagnostics (Mapping, optional) –
{"vbf_cache": ...}when a vBF cache was passed in, else empty.fused (torch.Tensor) – The fused image, on the upsampled grid, on the dataset’s device.
phase_weighted (torch.Tensor or None) – The low-frequency channel after its weight (
Noneunless the fusion’s verbosity fills it, as in the function).tcdf_weighted (torch.Tensor or None) – The dark-field channel after its weight (likewise).
phase_image (torch.Tensor) – The low-frequency image that was fused: the SSB phase, or the negated, mean-subtracted tilt-corrected bright field.
ptycho (Result) – The low-frequency channel’s own result (a
DirectPtychographyResult, or aTiltCorrectedDarkFieldResultwithregion="bright_field").tcdf (TiltCorrectedDarkFieldResult) – The dark-field channel’s result.
sampling (Sampling) – The pixel size
(dy, dx)offusedand its units, the scan step divided by the upsample factor (fromreconstruction_sampling()). Pass it tovis.show_2d(..., sampling=)ordiagnostics.metrics.frc(..., pixel_size=).
Reconstruction functions#
Reconstruct a phase image with single-side-band direct ptychography. |
|
Tilt-corrected dark-field reconstruction. |
|
Fuse a ptychographic and a dark-field image by their measured SSNR. |
- scatterem.reconstruction.direct_ptychography(dataset: Dataset4DStem | DatasetVirtualBrightField4DStem, upsample: float | str = 'nyquist', bright_field_mask_threshold: float = 0.5, verbosity: int = 0, n_batches: int = 25, return_snr: bool = False, phase_sign: Literal['preserve', 'positive', 'negative'] = 'preserve', ssnr_method: str = 'analytical', gamma_weighting: Literal['phase', 'wiener'] = 'phase', wiener_alpha: float = 0.001, **kwargs) tuple[Tensor, Tensor | None]#
Reconstruct a phase image with single-side-band direct ptychography.
- Parameters:
dataset (Dataset4DStem or DatasetVirtualBrightField4DStem) – Dataset containing the diffraction pattern. The probe has the aberrations
meta.aberrationswith C10 lessmeta.defocus_guess, as in iterative ptychography and WDD.upsample (float or str, optional) – Upsampling factor for the diffraction pattern, or “nyquist” to derive it from the data. Default is “nyquist”. At 2 or more (on either axis) the image and its SSNR are 0 on the scan-lattice frequencies
Q = (m / dy, n / dx), which read each bright-field pixel’s scan DC. At 1 the one such frequency isQ = 0: with an aberration above C12 the image mean is taken out there.bright_field_mask_threshold (float, optional) – Threshold for the bright-field mask. Default is 0.5.
verbosity (int, optional) – Verbosity level. Default is 0.
n_batches (int, optional) – Number of batches for the virtual bright-field pass. Default is 25.
return_snr (bool, optional) – Whether to compute the ptychography SSNR (method selected by ssnr_method). Default is False.
phase_sign ({"preserve", "positive", "negative"}, optional) – “preserve” keeps the sign the forward model gives: positive phase for positive projected potential, fixed by the aberrations and rotation (the bright-field-shift fit resolves its (C1, rotation) <-> (-C1, rotation + 180 deg) branch with the rotation prior), so it does not depend on the image. “positive”/”negative” flip the image to positive/negative skewness; that is data dependent and can invert a correct image (e.g. low-contrast weak-phase specimens). Default is “preserve”.
ssnr_method (str, optional) – How to compute the SSNR when return_snr is True. “analytical” (default) uses the phase-contrast-transfer-function noise model (CTF-aware: ptycho SSNR -> 0 at low q, no DC/low-q transfer); “empirical” reconstructs a checkerboard BF half-split and forms the raw half-difference power ratio (data-driven, better at high dose; at an upsampling of 2 or more it is 0 on the scan-lattice frequencies, as the image is). Below
_config._MIN_HALFSPLIT_PIXELSbright-field pixels per half it warns and returns the analytical SSNR, also 0 there.gamma_weighting ({"phase", "wiener"}, optional) – How the double-overlap function
Gamma(Q, K)weights each bright-field pixel."phase"(default, and the only behaviour before this argument existed) normalisesGammato unit modulus and applies its phase alone, dividing the sum by the bright-field pixel count."wiener"keeps|Gamma|in the numerator and divides by the Q-dependentsum_K |Gamma|^2, which down-weights the upsampling replica (the aliased copies of the scan spectrum) – measured at the multiples of the scan sampling frequency1/dron a test case, 124x -> 11.8x the local background against the phase-only image of the time. Both images are now 0 on those frequencies, which read the scan DC. It runs a slower plain-torch assembly (see_gamma_weighting) and is incompatible withssnr_method="empirical". Its analytical SSNR is the phase-only one times the per-Q gain of the wiener weights, both on the bright_field_mask_threshold mask, so it describes the wiener image.wiener_alpha (float, optional) – Tikhonov floor on
sum_K |Gamma|^2, as a fraction of its maximum. Only used whengamma_weighting="wiener". Default is1e-3.**kwargs –
snr_blur_sigmais forwarded to the empirical SSNR path.
- Returns:
phase_image (torch.Tensor) – The reconstructed phase image (imaginary part).
snr_ptycho (torch.Tensor or None) – The SNR of the reconstructed phase image if return_snr is True, otherwise None.
- Raises:
ValueError – If the dataset is not a valid Dataset4DStem object, if upsample is invalid, if gamma_weighting is unknown, or if
gamma_weighting="wiener"is combined withssnr_method="empirical".
Examples
On a tiny bright-field-disk cube,
upsample=2doubles the scan grid;return_snr=Falseleaves the second returnNone;phase_sign"positive"and"negative"are exact opposites:>>> import numpy as np, torch >>> import warp >>> warp.config.log_level = warp.LOG_WARNING # module-load chatter depends on the cache >>> from scatterem.data import Aberrations >>> from scatterem.data.datasets import Dataset4DStem >>> from scatterem.reconstruction.ptychography.direct import ( ... direct_ptychography, ... ) >>> n_scan, n_det = 8, 16 >>> rng = np.random.default_rng(0) >>> ky, kx = np.meshgrid( ... np.arange(n_det) - n_det // 2, ... np.arange(n_det) - n_det // 2, ... indexing="ij", ... ) >>> disk = (np.hypot(ky, kx) <= 4).astype(np.float32) >>> ry, rx = np.meshgrid( ... np.arange(n_scan), np.arange(n_scan), indexing="ij" ... ) >>> mod = 1 + 0.15 * np.cos(2 * np.pi * ry / n_scan) * np.cos( ... 2 * np.pi * rx / n_scan ... ) >>> cube = disk[None, None] * mod[:, :, None, None].astype(np.float32) >>> cube = np.clip( ... cube + 0.01 * rng.standard_normal(cube.shape).astype(np.float32), ... 0, ... None, ... ) >>> ab = Aberrations(array=torch.zeros(12)) >>> ab.array[0] = -2.2e4 >>> ds = Dataset4DStem.from_array( ... np.ascontiguousarray(cube), ... energy=300e3, ... semiconvergence_angle=4e-3, ... scan_step=29.0, ... reciprocal_step=8.3e-3, ... transform_to_amplitudes=True, ... aberrations=ab, ... device=torch.device("cpu"), ... ) >>> phase, snr = direct_ptychography( ... ds, upsample=2, n_batches=4, return_snr=False, phase_sign="preserve" ... ) >>> tuple(phase.shape), snr is None ((16, 16), True) >>> _, snr = direct_ptychography( ... ds, upsample=2, n_batches=4, return_snr=True, phase_sign="preserve" ... ) >>> tuple(snr.shape) (16, 16) >>> pos, _ = direct_ptychography( ... ds, upsample=2, n_batches=4, phase_sign="positive" ... ) >>> neg, _ = direct_ptychography( ... ds, upsample=2, n_batches=4, phase_sign="negative" ... ) >>> bool(torch.allclose(pos, -neg)) True
- scatterem.reconstruction.tilt_corrected_dark_field(dataset: Dataset4DStem, n_dark_field_segments: int = 32, verbosity: int = 0, bright_field_mask_threshold: float = 0.3, upsample: float | str = 'nyquist', return_snr: bool = False, snr_blur_sigma: float = 0.0, shift_method: str = 'drizzle', drizzle_pixfrac: float = 1.0, drizzle_kde_sigma: float = 0.0, dark_field_scaling: bool = False, dead_frame_fraction: float = 0.001, region: str = 'dark_field', _segment_geometry: _SegmentGeometry | None = None) tuple[Tensor, Tensor | None]#
Tilt-corrected dark-field reconstruction.
The probe has the aberrations
meta.aberrationswith C10 lessmeta.defocus_guess, as indirect_ptychography().regionselects which detector pixels feed the azimuthal segments."dark_field"(default) uses everything outside the bright-field disk."bright_field"uses the disk itself, which makes this tilt-corrected BRIGHT field – the segment/shift/drizzle/half-split-SSNR machinery is not specific to the dark field. tcBF is dark where the specimen scatters, i.e. the OPPOSITE contrast sense to tcDF;fused_full_fieldflips it when it uses it as the phase channel. The bright-field disk holds far fewer pixels than the dark field, so use a smallern_dark_field_segments(empty wedges are dropped rather than allowed to poison the image with NaN).dark_field_scalingaccounts for the electrons scattered clean past the detector edge. A pixelated detector only records the dark field that lands on it, so on a thick, strongly scattering specimen the recorded dark field under-reports the scattering cross-section exactly where the specimen is thickest. Taking the incident probe current to be the largest total count recorded anywhere in the scan (a position that scatters nothing off the detector, i.e. vacuum), everything outside the bright-field disk must be dark field whether or not it was recorded, so each segment image is scaled per scan position by(max_p’ I_total(p’) - I_BF(p)) / I_DF_recorded(p) >= 1.
OFF by default: the assumption fails if the scan contains no such vacuum position, or if the detector already subtends the full scattering distribution (then the factor is ~1 and only adds noise).
dead_frame_fractionguards the factor against dropped detector frames. A scan position recording less than this fraction of the incident current measured no probe – its factor degenerates towardsincident/0and its recorded angular distribution is meaningless – so it is left uncorrected. The default only catches all-but-blank frames; raise it (e.g. 0.05) for a detector that reads its flyback row back partially, which clears the default guard while still being garbage. It must stay well below the smallest genuinerecorded/incidentin the scan (a thick specimen can legitimately lose over half its electrons past the detector edge).shift_methodselects how each azimuthal dark-field segment is sub-pixel shifted (by its parallax shift) and accumulated onto the up-sampled grid:"drizzle"(default) — area-overlap drizzle (box splat + hit-map normalization). Non-negative and ringing-free, which is the physically correct behaviour for counting data: at low dose the segment images are single electron counts and Fourier shifting turns each into a sinc with ~20% negative side-lobes.drizzle_pixfracsets the drop size (fraction of an input pixel; 1.0 fills the grid from one frame) anddrizzle_kde_sigmaoptionally Nadaraya-Watson-smooths sparse holes."fourier"— Fourier zero-pad upsample + phase-ramp shift. Marginally sharper on dense, well-sampled (high-dose) data, but rings on sparse data.
Each segment image is moved by its full parallax: the
aberrations_to_image_shiftsshift (Angstrom, from C10 and A1 only) divided by the scan step. tcBF registers at the true defocus. Dark-field tcDF focuses at about 0.8-1.1 times the true defocus, depending on how the object scatters over angle (atomic number, feature size): a dark-field segment image moves with the incident-beam angle, while the published rule (Ma et al. 2025) assumes the mean of a uniformly filled aperture, 2/3 of its radius. On a Gaussian phase object the segment images move 0.80 times the applied shift at a width of 0.25 A and 1.04-1.11 times at 0.4-1.2 A.- Parameters:
dataset (Dataset4DStem) – The 4D-STEM dataset to reconstruct from.
n_dark_field_segments (int, optional) – Number of azimuthal detector segments.
verbosity (int, optional) – Diagnostic-plot verbosity;
> 0shows the bright-field mask,> 1also plots the SSNR curves and (withdark_field_scaling) the scaling factor map.bright_field_mask_threshold (float, optional) – Fraction of the peak mean-CBED intensity above which a detector pixel is classified as bright field.
upsample (float or str, optional) – Upsampling factor applied to the reconstructed grid, or
"nyquist"to resolve it from the acquisition geometry.return_snr (bool, optional) – Also compute and return the half-split SSNR map.
snr_blur_sigma (float, optional) – Gaussian blur sigma (in radial bins) applied to the SSNR curve before it is scattered back onto the 2D grid.
shift_method ({"drizzle", "fourier"}, optional) – How each segment is sub-pixel shifted and accumulated onto the upsampled grid.
drizzle_pixfrac (float, optional) – Drizzle drop size, as a fraction of an input pixel; used only when shift_method is
"drizzle".drizzle_kde_sigma (float, optional) – Drizzle Nadaraya-Watson smoothing sigma for sparse holes; used only when shift_method is
"drizzle".dark_field_scaling (bool, optional) – Rescale each segment image to account for scattering past the detector edge.
dead_frame_fraction (float, optional) – Minimum fraction of the incident current a scan position must record to receive dark_field_scaling correction.
region ({"dark_field", "bright_field"}, optional) – Which detector pixels feed the azimuthal segments.
_segment_geometry (_SegmentGeometry, optional) – Private. Precomputed aberration-independent segment geometry, to skip rebuilding it. Default builds it.
- Returns:
The tilt-corrected (dark- or bright-field) image, and the half-split SSNR map when return_snr is True, else
None.- Return type:
tuple of (torch.Tensor, torch.Tensor or None)
Examples
The image lies on the scan grid up-sampled by
upsamplealong both scan axes, in(scan_y, scan_x)order. The second slot isNoneunlessreturn_snr=True, and then it is an SSNR map of the image’s shape:>>> import numpy as np, torch >>> import warp >>> warp.config.log_level = warp.LOG_WARNING # module-load chatter depends on the cache >>> from scatterem.data.datasets import Dataset4DStem >>> from scatterem.reconstruction.darkfield.core import ( ... tilt_corrected_dark_field, ... ) >>> ky, kx = np.mgrid[:16, :16] - 8 >>> disk = (np.hypot(ky, kx) <= 4).astype(np.float32) >>> rng = np.random.default_rng(0) >>> cube = disk + 0.05 * rng.random((6, 5, 16, 16), dtype=np.float32) >>> ds = Dataset4DStem.from_array( ... cube, ... energy=300e3, ... semiconvergence_angle=4e-3, ... scan_step=29.0, ... reciprocal_step=8.3e-3, ... device=torch.device("cpu"), ... ) >>> image, ssnr = tilt_corrected_dark_field( ... ds, n_dark_field_segments=8, upsample=2 ... ) >>> tuple(image.shape), image.dtype, ssnr is None ((12, 10), torch.float32, True) >>> image, ssnr = tilt_corrected_dark_field( ... ds, n_dark_field_segments=8, upsample=2, return_snr=True ... ) >>> ssnr.shape == image.shape True
- scatterem.reconstruction.fused_full_field(dataset: Dataset4DStem, ptycho_image: Tensor, tcdf_image: Tensor, ptycho_ssnr: Tensor, tcdf_ssnr: Tensor, verbosity=0, taper: bool = False, q_soft_start_frac: float = 0.5, q_soft_end_frac: float = 0.7, q_hard_cutoff_frac: float = 1.0, ptycho_lowq_cutoff_frac: float = 0.0) tuple[Tensor, Tensor | None, Tensor | None]#
Fuse a ptychographic and a dark-field image by their measured SSNR.
Implements the SSNR-weighted full-field fusion of the FF-STEM paper: at each spatial frequency the two channels are combined with weights
ssnr_i / (ssnr_1 + ssnr_2), so each contributes where it actually carries information. Neither channel transfers beyond the2 * alphaband limit, which is imposed explicitly.A channel that is partly non-finite – the tilt-correction can produce NaN shifts on low-convergence data – is zeroed with a warning so the fusion falls back to the surviving channel instead of returning all-NaN. If both SSNRs are about zero inside the passband the result would be silently all-zero, so that case warns and falls back to ptychography-only weights.
- Parameters:
dataset (Dataset4DStem) – Supplies the device, the real-space sampling and the
semiconvergence_angle/wavelengththat set the2 * alphaband limit.ptycho_image (Tensor) – Real-space ptychographic phase image, shape
(Ny, Nx), already on the up-sampled grid.tcdf_image (Tensor) – Tilt-corrected dark-field image, same shape as
ptycho_image.ptycho_ssnr (Tensor) – Spectral signal-to-noise ratio of
ptycho_image, on the same frequency grid.tcdf_ssnr (Tensor) – Spectral signal-to-noise ratio of
tcdf_image, same shape asptycho_ssnr.verbosity (int) – Above zero, plot the weights, the filtered channels and the fused image with matplotlib. Default 0.
taper (bool) – Apply the legacy empirical apodization of the dark-field weight. Not part of the paper’s equation; kept for reproducibility. Default False.
q_soft_start_frac (float) – Start and end of that taper, as fractions of
2 * alpha. Ignored unlesstaperis set.q_soft_end_frac (float) – Start and end of that taper, as fractions of
2 * alpha. Ignored unlesstaperis set.q_hard_cutoff_frac (float) – Hard band limit as a fraction of
2 * alpha. Both weights are zero beyond it. Default 1.0.ptycho_lowq_cutoff_frac (float) – When positive, transfer the ptychographic weight to the dark-field below
ptycho_lowq_cutoff_frac * q_nyquistwith a cosine ramp, to suppress the low-frequency cupping halo of the direct-ptychography phase.0.0disables it. Default 0.0.
- Returns:
fused (Tensor) – The fused real-space image.
ptycho_filtered (Tensor or None) – The ptychographic channel after its weight was applied.
Noneunlessverbosity > 1(the filtered channels are only materialised for the diagnostic plots).tcdf_filtered (Tensor or None) – The dark-field channel after its weight was applied.
Noneunlessverbosity > 1.
- Raises:
ValueError – If the two images, or the two SSNRs, do not have matching shapes.
Examples
Default
verbosity=0returns the fused image and twoNoneplaceholders (filtered channels are only built whenverbosity > 1). Mismatched image shapes raise:>>> import numpy as np, torch >>> import warp >>> warp.config.log_level = warp.LOG_WARNING # module-load chatter depends on the cache >>> from scatterem.data import Aberrations >>> from scatterem.data.datasets import Dataset4DStem >>> from scatterem.reconstruction.ptychography.direct import ( ... direct_ptychography, ... ) >>> from scatterem.reconstruction.darkfield.core import ( ... tilt_corrected_dark_field, ... ) >>> from scatterem.reconstruction.fusion.ffstem.core import fused_full_field >>> n_scan, n_det = 8, 16 >>> rng = np.random.default_rng(0) >>> ky, kx = np.meshgrid( ... np.arange(n_det) - n_det // 2, ... np.arange(n_det) - n_det // 2, ... indexing="ij", ... ) >>> disk = (np.hypot(ky, kx) <= 4).astype(np.float32) >>> ry, rx = np.meshgrid( ... np.arange(n_scan), np.arange(n_scan), indexing="ij" ... ) >>> mod = 1 + 0.15 * np.cos(2 * np.pi * ry / n_scan) * np.cos( ... 2 * np.pi * rx / n_scan ... ) >>> cube = disk[None, None] * mod[:, :, None, None].astype(np.float32) >>> cube = np.clip( ... cube + 0.01 * rng.standard_normal(cube.shape).astype(np.float32), ... 0, ... None, ... ) >>> ab = Aberrations(array=torch.zeros(12)) >>> ab.array[0] = -2.2e4 >>> ds = Dataset4DStem.from_array( ... np.ascontiguousarray(cube), ... energy=300e3, ... semiconvergence_angle=4e-3, ... scan_step=29.0, ... reciprocal_step=8.3e-3, ... transform_to_amplitudes=True, ... aberrations=ab, ... device=torch.device("cpu"), ... ) >>> phase, _ = direct_ptychography( ... ds, upsample=2, n_batches=4, phase_sign="preserve" ... ) >>> tcdf, _ = tilt_corrected_dark_field( ... ds, ... n_dark_field_segments=8, ... upsample=2, ... bright_field_mask_threshold=0.3, ... ) >>> fused, ptycho_f, tcdf_f = fused_full_field( ... ds, ... phase, ... tcdf, ... torch.ones_like(phase), ... torch.ones_like(tcdf), ... verbosity=0, ... ) >>> tuple(fused.shape), ptycho_f is None, tcdf_f is None ((16, 16), True, True) >>> fused_full_field( ... ds, phase, tcdf[:, :8], torch.ones_like(phase), torch.ones_like(tcdf) ... ) Traceback (most recent call last): ... ValueError: Input image shapes do not match: ptycho_image.shape=torch.Size([16, 16]), tcdf_image.shape=torch.Size([16, 8])
Second-order ptychography#
Cold-start second-order solver for a ptychography model. |
|
2D mixed-state ptychography model and second-order solve target. |
|
Per-pass constraints of the 2D model; each one is off by default. |
|
When to stop a sequence of solver passes. |
|
The |
|
The model interface of |
- scatterem.reconstruction.ptychography.iterative.second_order.solve_ptychography(module, batches, n_iter: int, optimize_probe: bool = True, optimize_positions: bool = False, position_step_px: float | None = 0.5, per_group_alpha: bool = True, solver: str = 'bh_gd', fallback: float = 0.01, max_backtracks: int = 8, probe_mode_groups: bool = False, batch_growth: bool = False, early_stop: bool = False, compile_forward: bool = False, callback: Callable[[int, BHLog], bool | None] | None = None, precond: Callable | None = None, optimize_object: bool = True, position_preconditioner: Callable | None = None, heldout: Any = None, object_prior: Any = None) BHLog#
Cold-start second-order solver for a ptychography model.
moduleis aSolveTarget: the unifiedPtychographymodule (through its registered adapter) or the 2D mixed-state modelPlanarPtychography. The rest of this text describes thePtychographymodule; the 2D model has its own batches and refuses compile_forward, heldout and object_prior.Optimizes the object (sampler parameters) and, with
optimize_probe=True, the probe parameters — each tensor its own step-size group — against the module’s own assembled training loss (data term + enabled regularizers), so it minimizes exactly what Adam training minimizes. Withoptimize_positions=Truethe per-angle position offsets (model.dr) join as their own group(s);drenters the forward unconditionally, so no extra flag is needed.free_pathis never touched. Meant to be called directly (cold start); calling it after a partial Adam fit works the same way.batchesis a DataLoader or any iterable of the model’s 6/8-tuple batches; it is materialized ONCE into a fixed full-batch list (BH needs deterministic full-data statistics — the requirement is statistical, not memory: gradients and curvature scalars accumulate per batch). The batches hold centred patterns, as forPtychography.fit; the model’sprepare_datachecks the first and resamples a padded grid. It does not stream: every batch’s patterns sit on the device for the whole solve, also when the loader streams them from host RAM or disk (pattern streaming v1), so a streamed series larger than the GPU fails here; fit it with Adam (Ptychography.fit) instead.The solvers:
"bh_gd"(default),"bh_cg": full-batch gradient descent and conjugate gradients with step sizes from the exact bilinear Hessian. Cost: 2 full passes over the data per iteration (gradient pass + one fused curvature pass viaChunkedAutogradOracle.hess_quad_matrix), roughly 2-3 Adam epochs, with no learning rates to tune."bh_cg"is for object-only refinement (withoptimize_probe=False)."bh_gd_incremental": minibatch gradient descent; every batch step solves its step sizes from the exact bilinear Hessian of that batch."secant_gd": minibatch gradient descent with per-group Newton step sizes. Each step solves a smallG x Gsystem for one step size per parameter group (object, probe or probe mode, positions), so the step lies in the span of the group gradients, after Carlsson et al., “The bilinear Hessian for large scale optimization”, arXiv:2502.03070. The curvature in that system is a secant estimate from gradient differences (plain backward passes, no double-backward), not the bilinear Hessian, and it is solved again every 8th batch step only. Each step backtracks on the batch loss; adaptive acceptance tests only every few steps after a run of clean accepts. The final state is the one of lowest full loss among the last iterate, the tail average of the iterates and the best pass (log.polyak). This isbh_gd_incrementalwithcurvature_freq=8,fd_curvature,adaptive_acceptandpolyak.
probe_mode_groups, batch_growth, early_stop, position_preconditioner, heldout and object_prior need a minibatch solver: with them,
"bh_gd"and"bh_cg"change to"bh_gd_incremental".log.solverrecords the solver that ran.compile_forward=Truecompiles the model’s tilt-agnostic physics core (the forward model’scompile_forward, auto-selecting the fused real-waves path) and prepares the fixed batch list for it: per-batch gather indices are precomputed and PADDED to a common unique-count so every same-sized batch presents identical shapes to one compiled graph. Requiressolver="secant_gd"— the exact curvature path is a double-backward, whichtorch.compile’s AOTAutograd rejects; the secant curvature uses plain gradients only.- Parameters:
module (SolveTarget or object) – The model to optimize: a
SolveTarget, or aPtychographymodule through its registered adapter. Its assembled training loss (data term + enabled regularizers) is what the solver minimizes.batches (Iterable) – A DataLoader or any iterable of the model’s batches (6/8-tuples for
Ptychography); materialized once into a fixed full-batch list.n_iter (int) – Number of solver iterations (full-data passes, see cost note above).
optimize_probe (bool, optional) – Include the probe model’s parameters as their own step-size group(s).
optimize_positions (bool, optional) – Include the per-angle position offsets (
model.dr) as their own step-size group(s), trust-bounded by position_step_px.position_step_px (float or None, optional) – Trust-region bound, in pixels, on each optimize_positions step. Default 0.5. None leaves the position steps unbounded.
per_group_alpha (bool, optional) – Solve a separate step size per parameter group rather than one shared step size.
"secant_gd"requires True.solver ({"bh_gd", "bh_cg", "bh_gd_incremental", "secant_gd"}, optional) – Solver to use, see above. The minibatch-only options change
"bh_gd"and"bh_cg"to"bh_gd_incremental".fallback (float, optional) – Step size used when the curvature-based step size is rejected.
max_backtracks (int, optional) – Maximum backtracking line-search steps per iteration.
probe_mode_groups (bool, optional) – Give each probe mode (dim 0) its own step-size group instead of sharing the dominant mode’s; selects bh_gd_incremental.
batch_growth (bool, optional) – Enable incremental-solver batch growth; selects bh_gd_incremental.
early_stop (bool, optional) – Enable incremental-solver early stopping; selects bh_gd_incremental.
compile_forward (bool, optional) – Compile the model’s tilt-agnostic physics core and pad the fixed batch list so every same-sized batch presents identical shapes to one compiled graph. Requires
solver="secant_gd".callback (callable, optional) – Called as
callback(iteration, log)after each iteration; a truthy return stops the solve after that iteration (log.early_stop,reason="callback") andlog.revertedflags an undone pass.precond (callable, optional) – Diagonal preconditioner over the solver’s parameter list (object sampler parameters, then probe parameters, then position offsets);
precond(params)returns one map per parameter,Nonefor identity. Forwarded tobh_gd_incremental(re-evaluated once per pass) or tobh_gd/bh_cg(per iteration).optimize_object (bool, optional) – Include the object (sampler parameters).
Falserefines only the probe (and positions) against a fixed, known object – e.g. one reconstructed once and reused across many probe settings. Therequires_gradflag of every tensor the solve touches is restored on exit, including when it raises.position_preconditioner (callable or None, optional) – A
direction(g, params)callable preconditioning each batch step’s direction; selects"bh_gd_incremental", requires optimize_positions and excludes precond.heldout (object, optional) – Scores the held-out positions (its dataset and held_out_indices) after every pass; selects
"bh_gd_incremental". Itshistorygets the start state (epoch=-1) and one entry per pass, and the held-out deviance becomes the solver’s selectionscore: the final state is the candidate (start state, best pass, last pass or tail average) with the lowest deviance, so the solve never returns a state worse on the holdout than its start (log.polyak["best_pass_index"] == -1when the start wins). early_stop also stops after 3 passes without a new best. The pass revert, the stall test, batch_growth and the plateau stop still judge the training loss. No batch may hold a held-out position.object_prior (object, optional) – A proximal denoiser prior on the object, configured as for an Adam fit (
cadence="prox"only; requires optimize_object); selects"bh_gd_incremental". Its step runs from the solver’s step hook everyevery_n_patternstraining patterns (orevery_n_stepsbatch steps), from passstart_epochon, on the support of the training positions. A merged batch step (batch_growth) that covers several intervals applies one step only, so after a merge the prior runs less often than everyevery_n_patterns.log.hook_stepscounts the steps per pass andobject_prior.sigmasholds thesigmaof each. A step raises the training loss. Pass heldout too: without it, the best-pass and final-state selection judge the training loss. Even with it, the pass revert, the stall test, batch_growth and the plateau stop judge the training loss, prox changes included: a pass whose loss rises by more than 0.5 % of the start loss is reverted, its prox steps too. No prior is attached by default; the module’sobject_denoiser="auto"affects Adam fits only.
- Returns:
Log of the solve (per-iteration losses, step sizes and diagnostics).
- Return type:
- Raises:
ValueError – If solver is unknown, if compile_forward is True with another solver than
"secant_gd", if"secant_gd"comes with per_group_alpha False, if batches is empty, if no trainable parameters are found, or if position_preconditioner is given without optimize_positions or together with precond, if object_prior has another cadence than"prox"or comes without optimize_object, if heldout has no held-out positions, or if a batch holds a held-out position.NotImplementedError – If heldout scores held-out pixels, or the model does not support an option (the 2D model: compile_forward, heldout, object_prior).
TypeError – If object_prior cannot act on the module’s object sampler, or module is neither a
SolveTargetnor aPtychographymodule.
- class scatterem.reconstruction.ptychography.iterative.second_order.PlanarPtychography(amplitudes: Tensor, positions: Tensor, offsets: Tensor, probe: Tensor, object_shape: tuple[int, int], norm: float, detector_mask: Tensor | None = None, constraints: PlanarConstraints | None = None)#
2D mixed-state ptychography model and second-order solve target.
- Parameters:
amplitudes (Tensor) –
(K, My, Mx)measured amplitudes (square roots of the counts), centred. They stay on their device; they are not instate_dict.positions (Tensor) –
(K, 2)integer top-left object pixels of the probe windows.offsets (Tensor) –
(K, 2)sub-pixel offsetsdrin pixels; refined withoptimize_positions.probe (Tensor) –
(M, 1, N, N)complex real-space probe modes on the model grid,N >= My.object_shape (tuple of int) –
(H, W)of the object potential; it starts at zero (vacuum).norm (float) – The measurement norm, the power the probe was normalised to.
detector_mask (Tensor or None, optional) –
(My, Mx)bool, True for a pixel in the loss. Default None (all).constraints (PlanarConstraints or None, optional) – The constraints of
apply_pass_constraints(). Default none.
- class scatterem.reconstruction.ptychography.iterative.second_order.PlanarConstraints(orthogonalize: bool = False, radial_support: tuple[float, float] | None = None, aperture_support: Tensor | None = None, absorption_width: float | None = None, absorption_margin: int = 64)#
Per-pass constraints of the 2D model; each one is off by default.
- Parameters:
orthogonalize (bool) – Orthogonalize the modes, dominant first.
radial_support (tuple of float or None) –
(radius_frac, margin)of the real-space disk.aperture_support (Tensor or None) –
(N, N)real map on the centred aperture plane of the model grid.absorption_width (float or None) – Allowed distance of
Im Vfrom its median.absorption_margin (int) – Border, in pixels, left out of that median.
- class scatterem.reconstruction.ptychography.iterative.second_order.PassStopRule(probe_tol: float | None = None, loss_tol: float = 0.002, min_iters: int = 2, patience: int = 1, purity_tol: float | None = None, needs_move: bool = False, passes_after_move: int | None = None)#
When to stop a sequence of solver passes.
The rule acts only when
probe_tolis set and the pass has a state changerel(from the second pass on). A pass “meets” the rule when all of these hold:rel < probe_tol(the state stopped changing);|dloss| < loss_tol(the loss stopped changing);the pass was not reverted;
dpurity < purity_tol, whenpurity_tolis set;the state has moved (one pass with
rel > probe_tol), whenneeds_moveis set. Before that, a seed on the plateau before the transition hasrelnear 0 while the loss still falls.
The solve stops after
patienceconsecutive passes that meet the rule, but not beforemin_iterspasses. Independently, withpasses_after_moveset, it stops after that number of accepted passes after the state moved.- Parameters:
probe_tol (float or None, optional) – Bound on the state change per pass. None disables the rule. Default None.
loss_tol (float, optional) – Bound on the relative loss change per pass. Default 2e-3.
min_iters (int, optional) – Earliest stop, in passes. Default 2.
patience (int, optional) – Consecutive passes that must meet the rule. Default 1.
purity_tol (float or None, optional) – Bound on the purity change per pass; None skips this test. Default None.
needs_move (bool, optional) – Never stop before the state has moved. Default False.
passes_after_move (int or None, optional) – Stop after this number of accepted passes after the move. Default None.
- class scatterem.reconstruction.ptychography.iterative.second_order.PassStopCallback(module: Any, rule: PassStopRule, *, apply_constraints: bool = True, return_last: bool = False)#
The
callback(k, log)of the BH driver with aPassStopRule.For each pass
k, in this order: if the pass was accepted, apply the module’s constraints (apply_constraints) and keep a copy of its state (return_last); then compute the state change of probe 0 against the previous pass (state_change(), no gauge removed) and the loss change, and ask the rule.- Parameters:
module (PlanarPtychography or object) – The module that the driver optimises: a
PlanarPtychographyor aPtychographymodule. Its constraints aremodule.apply_pass_constraints()if it has that method, else the constraint schedulemodule._apply_all_constraints(), gated on the pass index:start_epochandfreqcount passes.rule (PassStopRule) – The stop rule; it keeps its own state.
apply_constraints (bool, optional) – Apply the module’s constraints after each accepted pass. Default True.
return_last (bool, optional) – Keep the state of the last accepted pass for
restore_last(). Default False.
- Variables:
history (list of dict) – Per pass:
k,loss,rel,dloss,revertedand, withrule.purity_tolset,purity.
- class scatterem.reconstruction.ptychography.iterative.second_order.SolveTarget(*args, **kwargs)#
The model interface of
driver.solve_ptychography().A batch is whatever
solve_batches()returns; the driver only counts the batches and passes each one back tobatch_loss().- Parameters:
*args – Unused: a protocol is a type, not instantiated.
**kwargs – Unused: a protocol is a type, not instantiated.
All modes but the last times a soft real-space disk (a new tensor). |
- scatterem.reconstruction.ptychography.iterative.second_order.planar_constraints.radial_support(probe: Tensor, radius_frac: float, margin: float) Tensor#
All modes but the last times a soft real-space disk (a new tensor).
Purity |
|
Change |
- scatterem.reconstruction.ptychography.iterative.second_order.stop_rule.mode_purity(probe: Tensor, drop_last: bool = True) float#
Purity
sum(p_i^2)of the normalised mode powersp_i.- Parameters:
probe (torch.Tensor) –
(M, ...)complex modes.drop_last (bool, optional) – Leave the last mode out when
M > 1(the free mode of a mixed state). Default True.
- Returns:
The purity, in
(0, 1].- Return type:
- scatterem.reconstruction.ptychography.iterative.second_order.stop_rule.state_change(previous: Tensor, current: Tensor) float#
Change
1 - Fof the mixed state between two passes.F = Tr(rho_1 rho_2) / sqrt(Tr rho_1^2 Tr rho_2^2)withrho = sum_i |m_i><m_i|, the normalised Hilbert-Schmidt fidelity of the two mode sets.Fdoes not change with the scale, the phase of a mode or a unitary mixing of the modes. No gauge is removed: consecutive passes share a frame.1 - Fis quadratic in a small change of a mode, so it is computed in double precision.- Parameters:
previous (torch.Tensor) –
(M, ...)complex modes; each mode is flattened.current (torch.Tensor) –
(M, ...)complex modes; each mode is flattened.
- Returns:
1 - Fin[0, 1]; 0 when the two density matrices are proportional.- Return type:
The |
|
Register an adapter that turns a model into a |
- scatterem.reconstruction.ptychography.iterative.second_order.target.as_solve_target(model: Any) SolveTarget#
The
SolveTargetofmodel.- Parameters:
model (object) – A model that implements
SolveTarget, or one that a registered adapter accepts.- Returns:
modelitself, or the target the first accepting adapter returns.- Return type:
- Raises:
TypeError – If no adapter accepts
model.
- scatterem.reconstruction.ptychography.iterative.second_order.target.register_solve_target(factory: Callable[[Any], SolveTarget | None]) Callable[[Any], SolveTarget | None]#
Register an adapter that turns a model into a
SolveTarget.- Parameters:
factory (callable) –
factory(model)returns the target, or None for a model it does not handle.- Returns:
factory, so the function can be a decorator.- Return type:
callable
Second-order optimisers#
Gradient descent with the Newton step-size rule (BH-GD, paper eq. |
|
Minibatch (incremental) per-group BH-GD — LSQML-style updates. |
|
Nonlinear CG with Daniel's Hessian beta and Newton step size (BH-CG). |
|
Truncated-Newton method (BH-QN): inner linear CG solves H y = -g. |
|
Per-iteration log shared by all BH solvers. |
|
Generic bilinear-Hessian oracle via double-backward autograd. |
|
Autograd oracle over per-batch loss closures; |
|
Oracle for a sum-of-mse loss with linear per-batch forwards. |
|
Real inner product Re<x, y> summed over a parameter list. |
- scatterem.optim.second_order.bh_gd(oracle, n_iter: int, rho: Sequence[float] | None = None, fallback: float = 0.01, per_group_alpha: bool = False, max_backtracks: int = 0, callback: Callable[[int, BHLog], bool | None] | None = None, precond: Callable[[Sequence[Tensor]], Sequence[Tensor]] | None = None) BHLog#
Gradient descent with the Newton step-size rule (BH-GD, paper eq. (15)).
max_backtracksis a step-acceptance safeguard (as inbh_qn()): if the step increases the loss, halve it and retry, up tomax_backtrackstimes, reverting fully if none is accepted; 0 disables. Essential on flat-tailed objectives (e.g. cold-start amplitude-loss ptychography), where near-zero positive curvature makes the raw Newton fallback overshoot catastrophically.With backtracking on, the loss at an accepted step is already in
loss_after, so it is logged without a neworacle.loss()call; and withcallback=Nonethe next iteration’sloss_beforeis the logged loss, becausegrad()and the curvature solve do not move the parameters. This matters for an oracle without a forward cache (ChunkedAutogradOracle: one sweep perloss()).- Parameters:
oracle (object) – Full-batch oracle exposing
params,grad(),hess_op()andloss().n_iter (int) – Number of gradient-descent iterations.
rho (Sequence[float] or None, optional) – Per-parameter preconditioner scale forwarded to _rho2. Default None.
fallback (float, optional) – Step size when the Newton-rule curvature is non-positive. Default 1e-2.
per_group_alpha (bool, optional) – Solve a per-parameter-group step size instead of one scalar Newton step. Default False.
max_backtracks (int, optional) – Maximum halvings tried when a step increases the loss; 0 (the default) disables backtracking.
callback (callable, optional) – Called as
callback(k, log)after every iteration; a truthy return stops the run (log.early_stop, seeBHLog). Default None.precond (callable, optional) – Per-iteration diagonal preconditioner:
precond(params)returns one positive map per parameter; the direction becomes-precond_i * g_i(supersedesrho; the Newton rule sizes any direction).
- Returns:
Log of losses, step sizes and timing across iterations.
- Return type:
- scatterem.optim.second_order.bh_gd_incremental(closures: Sequence[Callable[[], Tensor]], params: Sequence[Tensor], n_passes: int, per_group_alpha: bool = True, fallback: float = 0.01, max_backtracks: int = 8, relax: float = 1.0, seed: int | None = None, step_clip: Sequence[float | None] | None = None, curvature_freq: int = 1, fd_curvature: bool = False, adaptive_accept: bool = False, polyak: bool = False, group_slices: list[tuple] | None = None, batch_growth: bool = False, early_stop: bool = False, callback: Callable[[int, BHLog], bool | None] | None = None, precond: Callable[[Sequence[Tensor]], Sequence[Tensor | None]] | None = None, direction: Callable[[list[Tensor], list[Tensor]], list[Tensor]] | None = None, score: Callable[[], float] | None = None, score_patience: int = 3, step_hook: Callable[[range], bool] | None = None) BHLog#
Minibatch (incremental) per-group BH-GD — LSQML-style updates.
step_clip(aligned withparams,None= unbounded) is a per-group trust radius on the inf-norm of a single batch step: the solved alpha is rescaled somax|alpha * step|never exceeds the bound. Needed for parameters the forward is PERIODIC in (scan position offsets enter as FFT phase ramps), where a wrapped-around giant step can still lower the batch loss and defeat backtracking.Iterates the per-batch loss closures; for each batch, takes a Newton-rule step (per-group G x G solve when
per_group_alpha) computed from that batch’s local gradient/curvature, so every mini-step uses the LATEST parameters. This trades the full-batch quadratic-model exactness for the update cadence that makes minibatch methods win on real ptychography (each pass =len(closures)parameter updates instead of one).Safeguards: per-batch step-acceptance backtracking on the batch loss (
max_backtrackshalvings, full revert on failure) and an optional globalrelaxfactor on the solved step sizes.seedenables per-pass batch shuffling (deterministic). With a single closure, one pass is exactly one full-batchbh_gd()iteration.Fast-path options (all default off; per-group mode only):
curvature_freq=k: re-solve the G x G step sizes every k-th step and reuse the cached alphas between (step sizes drift slowly across batches); any backtrack invalidates the cache so the next step re-solves. The clip and acceptance safeguards run on every step.fd_curvature: secant curvature (hess_quad_matrix_fd) — plain gradient sweeps instead of thecreate_graphdouble-backward; same memory as a gradient pass.adaptive_accept: after_ADAPTIVE_ACCEPT_WARMUPconsecutive tested clean accepts, test only every_ADAPTIVE_ACCEPT_STRIDE-th step; any backtrack resets to testing every step.polyak: average the iterates over the last half of the passes; on exit the parameters are set to whichever of (last iterate, average) has the lower full loss, recorded inlog.polyak.group_slices: explicit step-size groups as (param_index, mode) pairs —mode=Nonefor the whole tensor, an int for one dim-0 slice (e.g. per-probe-mode groups on a (modes,K,M,M) tensor). When given,step_clipaligns with the GROUPS, not the params.batch_growth: variance annealing — whenever a pass stalls (improves by <_STALL_FRACof the observed descent range) or is reverted, double the effective batch by merging adjacent closures (capped so a pass keeps at least_MIN_STEPS_PER_PASSsteps, i.e.n_batches // 8for large batch counts — one step per full-data sweep is wasted compute); merge factor per pass inlog.batch_merge.early_stop:n_passesbecomes a CAP. The run ends after_EARLY_STOP_PATIENCEconsecutive stalled passes — withbatch_growtheach non-terminal stall first buys a batch doubling AND resets the patience (every merge level gets a fresh chance), so the run only stops when growing stopped helping. Withearly_stoporpolyakthe best-loss pass is snapshotted and the final parameters are the best of {last iterate, tail average, best pass} (log.polyak);log.early_stoprecords where and why the run ended.
log.losses/log.wallcarry one entry per PASS (the exact full loss after the pass — costs one extra forward sweep);log.group_alphasone vector per batch step.- Parameters:
closures (Sequence[Callable[[], Tensor]]) – Per-batch loss closures; each call re-evaluates that batch’s loss at the current params.
params (Sequence[Tensor]) – Parameters to optimize in place.
n_passes (int) – Number of passes over closures (a cap when early_stop is set).
per_group_alpha (bool, optional) – Whether to solve a per-group G x G Newton step instead of one scalar step. Default is True.
fallback (float, optional) – Step size used when the curvature estimate is non-positive. Default is 1e-2.
max_backtracks (int, optional) – Maximum halvings tried when a batch step increases its loss. Default is 8.
relax (float, optional) – Global multiplier applied to every solved step size. Default is 1.0.
seed (int or None, optional) – Seed for per-pass batch-order shuffling; None disables shuffling. Default is None.
step_clip (Sequence[float or None] or None, optional) – Per-group (or per-param, without group_slices) inf-norm trust radius on a single batch step. Default is None (unbounded).
curvature_freq (int, optional) – Re-solve per-group step sizes every k-th step, reusing cached alphas between. Default is 1.
fd_curvature (bool, optional) – Use finite-difference secant curvature instead of the exact double-backward Hessian. Default is False.
adaptive_accept (bool, optional) – After a warm-up of clean accepts, test step acceptance only every _ADAPTIVE_ACCEPT_STRIDE-th step. Default is False.
polyak (bool, optional) – Average iterates over the tail of the run and keep whichever of {last iterate, average} has lower full loss. Default is False.
group_slices (list[GroupSlice] or None, optional) – Explicit step-size groups as (param_index, mode) pairs; when given, step_clip aligns with the groups, not params. Default is None.
batch_growth (bool, optional) – Double the effective batch size (merging adjacent closures) whenever a pass stalls or is reverted. Default is False.
early_stop (bool, optional) – Stop after _EARLY_STOP_PATIENCE consecutive stalled passes, turning n_passes into a cap. Default is False.
callback (callable, optional) – Called as
callback(k, log)after every pass;log.revertedsays whether passkwas undone. A truthy return stops the run after this pass, final-state selection included. Default is None.precond (callable, optional) – Diagonal preconditioner, re-evaluated once per PASS at the pass-start iterate:
precond(params)returns one positive map per parameter (None= identity); every batch direction becomes-precond_i * g_i. The per-group Newton rule sizes the preconditioned direction, so the maps need no normalization.direction (callable, optional) –
direction(g, params)replaces-g; excludes precond. Default is None.score (callable, optional) – The selection score at the current parameters, lower is better (e.g. a held-out loss), at the start and after each pass revert, before callback (pass scores in
log.scores). The best state, start included, is kept; the final state is the lowest-score candidate; early_stop also ends after score_patience passes without a new best (reason="score"). Pass revert, stall test, batch_growth and plateau stop still judge the training loss. Default None judges by the training loss.score_patience (int, optional) – See score. Default is 3.
step_hook (callable, optional) –
step_hook(span)after every batch step (after the acceptance test), with therangeof closure indices the step used. It may change the parameters in place (for example a proximal step) and returns True when it did (log.hook_steps). The next step’s acceptance test evaluates the loss at the changed parameters, so no solver state needs an update. A reverted pass restores its snapshot and so also undoes the hook’s changes in that pass. Default is None.
- Returns:
Log of losses, step sizes, timing and (when applicable) the early-stop/polyak selection across passes.
- Return type:
- scatterem.optim.second_order.bh_cg(oracle, n_iter: int, rho: Sequence[float] | None = None, fallback: float = 0.01, per_group_alpha: bool = False, callback: Callable[[int, BHLog], bool | None] | None = None, precond: Callable[[Sequence[Tensor]], Sequence[Tensor]] | None = None) BHLog#
Nonlinear CG with Daniel’s Hessian beta and Newton step size (BH-CG).
Paper eqs. (16)-(18): s_k = -rho^2 g_k + beta s_{k-1}, beta = H(rho^2 g_k, s_{k-1}) / H(s_{k-1}, s_{k-1}), evaluated at x_k. Restarts (beta = 0) on non-positive or non-finite curvature.
per_group_alpha=Truereplaces the scalar Newton step size by the per-parameter-group G x G solve (see_per_group_alphas()); the conjugacy history then tracks the actually applied stepsum_i alpha_i e_i(Daniel’s beta is invariant to its scale).Oracle capabilities (scalar step size only, except the second):
constant_hessian = True(e.g.LinearLeastSquaresOracle):H s_prevequals theH sof the previous iteration, so that product is reused, not computed again.fused_grad_loss = True: the logged loss and the next iteration’s gradient come from onegrad_and_loss()call, because both are evaluated at the same iterate. This needscallback=None(a callback may move the iterate). Bit-identical.forward_hess_quad = True: on the last iterationH sis used only through<H s, s>, sohess_quad_forward(s)gives it from forwards only and the last adjoint pass is skipped. It rounds differently fromrdot(hess_op(s), s), so the last step is close to, not equal to, the plain one.
- Parameters:
oracle (object) – Full-batch oracle exposing
params,grad(),hess_op()andloss().n_iter (int) – Number of CG iterations.
rho (Sequence[float] or None, optional) – Per-parameter preconditioner scale forwarded to _rho2. Default None.
fallback (float, optional) – Step size when the Newton-rule curvature is non-positive. Default 1e-2.
per_group_alpha (bool, optional) – Solve a per-parameter-group step size instead of one scalar Newton step. Default False.
callback (callable, optional) – Called as
callback(k, log)after every iteration; a truthy return stops the run (log.early_stop). Default None.precond (callable, optional) – Diagonal-preconditioner callable, as in
bh_gd()(flexible preconditioning: Daniel’s beta and the restarts keep the recurrence stable while the maps evolve).
- Returns:
Log of losses, step sizes, CG betas and timing across iterations.
- Return type:
- scatterem.optim.second_order.bh_qn(oracle, n_iter: int, inner_iters: int = 12, inner_tol: float = 1e-10, rho: Sequence[float] | None = None, fallback: float = 0.01, max_backtracks: int = 8, callback: Callable[[int, BHLog], bool | None] | None = None) BHLog#
Truncated-Newton method (BH-QN): inner linear CG solves H y = -g.
The inner loop is standard preconditioned CG on the (fixed) Hessian at the current iterate, truncated at the last positive-curvature iterate (Newton-CG practice). The outer step uses the Newton step-size rule. Cost: 1 grad + (inner CG iterations + 1) hess_op per outer step.
max_backtracksis a step-acceptance safeguard: if the Newton-rule step increases the loss, revert and halve alpha, up tomax_backtrackstimes; 0 disables.- Parameters:
oracle (object) – Full-batch oracle exposing
params,grad(),hess_op()andloss().n_iter (int) – Number of outer (truncated-Newton) iterations.
inner_iters (int, optional) – Maximum inner CG iterations per outer step. Default is 12.
inner_tol (float, optional) – Relative residual tolerance that stops the inner CG solve early. Default is 1e-10.
rho (Sequence[float] or None, optional) – Per-parameter preconditioner scale forwarded to _rho2 and used as the inner-CG preconditioner. Default is None.
fallback (float, optional) – Step size used when the outer Newton-rule curvature estimate is non-positive. Default is 1e-2.
max_backtracks (int, optional) – Maximum halvings tried when the outer step increases the loss; 0 disables. Default is 8.
callback (callable, optional) – Called as
callback(k, log)after every outer iteration; a truthy return stops the run (log.early_stop). Default is None.
- Returns:
Log of losses, step sizes and timing across outer iterations.
- Return type:
- class scatterem.optim.second_order.BHLog(losses: list[float] = <factory>, alphas: list[float] = <factory>, betas: list[float] = <factory>, group_alphas: list[list[float]] = <factory>, wall: list[float] = <factory>, polyak: dict | None = None, reverts: list[int] = <factory>, batch_merge: list[int] = <factory>, early_stop: dict | None = None, steps_per_pass: list[int] = <factory>, curvature_freq: int | None = None, reverted: bool = False, scores: list[float] = <factory>, hook_steps: list[int] = <factory>, solver: str = '')#
Per-iteration log shared by all BH solvers.
With
per_group_alphasolvers,alphasrecords the first group’s step size andgroup_alphasthe full per-group vector; otherwisegroup_alphasstays empty.- Parameters:
alphas (list[float]) – Step size recorded at each pass (first group’s, under
per_group_alpha).betas (list[float]) – Momentum/curvature coefficient recorded at each pass.
group_alphas (list[list[float]]) – Full per-group step-size vector at each pass, under
per_group_alphasolvers; empty otherwise.wall (list[float]) – Cumulative solver work, in seconds, at each pass (diagnostic
loss()evaluations excluded).polyak (dict, optional) – Final-state selection outcome, for incremental solvers.
batch_merge (list[int]) – Merge factor applied at each pass.
early_stop (dict, optional) – Why and where a run ended early:
reason="plateau"orreason="score"(bh_gd_incremental(early_stop=True)), orreason="callback"(any solver whose callback returned a truthy value).steps_per_pass (list[int]) – Number of steps actually run at each pass.
curvature_freq (int, optional) – Number of steps between
G x Gcurvature solves.reverted (bool) – Whether the most recent pass (or step) was reverted, i.e. its index is
reverts[-1]; set just before the callback runs, so a callback can skip constraints on a pass whose update was undone.scores (list[float]) – The selection
scoreafter each pass (bh_gd_incremental(score=...)); empty without a score.hook_steps (list[int]) – Number of
step_hookcalls per pass that returned True (bh_gd_incremental(step_hook=...)); empty without a hook. A reverted pass (reverts) undid the changes of its calls.solver (str) – The solver that ran, set by
solve_ptychography(it can switch to"bh_gd_incremental"); empty when a solver is called directly.
- class scatterem.optim.second_order.AutogradOracle(closure: Callable[[], Tensor], params: Sequence[Tensor])#
Generic bilinear-Hessian oracle via double-backward autograd.
- Parameters:
closure (callable) – Callable returning the scalar loss, built from
params. Must be re-evaluable (called fresh for every gradient / HVP).params (sequence of Tensor) – Leaf tensors the loss depends on.
requires_gradis enabled on them here.
- class scatterem.optim.second_order.ChunkedAutogradOracle(closures: Sequence[Callable[[], Tensor]], params: Sequence[Tensor])#
Autograd oracle over per-batch loss closures;
f = sum_b closure_b().loss/grad/hess_opaccumulate exactly across batches — each batch’s graph is built and freed within the loop, so peak memory is O(batch) regardless of how many batches the objective sums over (the full-batch requirement of BH is statistical, not a memory constraint).hess_quad_matrix(basis)is the fused per-group curvature pass: the G x G matrixA_ij = H(e_i, e_j)computed in ONE sweep over the batches (onecreate_graphbackward per batch, then one directional double-backward per basis direction, reduced to scalars immediately). Together with the gradient pass this puts per-group BH-GD at 2 full data passes per iteration — the structural floor, since the search direction depends on the full-batch gradient.- Parameters:
closures (sequence of callable) – Per-batch callables, each returning that batch’s scalar loss contribution, built from
params. Must be re-evaluable (called fresh for every gradient / HVP sweep).params (sequence of Tensor) – Leaf tensors the loss depends on.
requires_gradis enabled on them here.
- class scatterem.optim.second_order.LinearLeastSquaresOracle(param: Tensor, batches: Sequence[tuple])#
Oracle for a sum-of-mse loss with linear per-batch forwards.
f(x) = sum_i mse(A_i(x), b_i) / n_batcheswith LINEAR per-batch forwardsA_i(e.g. tomographic projection of a volume).batchesis a sequence of(pred_fn, data)pairs wherepred_fn()evaluates that batch’s forward at the current value ofparamand is linear in it. The gradient is one forward + one backward (adjoint) per batch, accumulated — memory stays O(batch), no cross-batch graph and no double-backward.hess_opexploits linearity: the Hessian is the constant mse-normalized2 A^T A, soH vequals the gradient evaluated atx = vwith zero data; it is computed by temporarily writingvinto the parameter (restored afterwards, also on error).With this oracle,
bh_cg()is exact-step CGLS on the normal equations — finite-step exact on the quadratic, zero hyperparameters.constant_hessian = Truetellsbh_cg()that it may reuseH sof the previous iteration asH s_prev.fused_grad_loss = Truetells it thatgrad_and_loss()returns the values ofgrad()andloss()at the same iterate.forward_hess_quad = Truetells it thathess_quad_forward()gives<H s, s>without the adjoint.- Parameters:
param (Tensor) – Leaf tensor the loss depends on.
requires_gradis enabled on it here.batches (sequence of tuple) – Sequence of
(pred_fn, data)pairs wherepred_fn()evaluates that batch’s forward, linear inparam, at its current value, anddatais the corresponding target tensor.
- scatterem.optim.second_order.rdot(xs: Sequence[Tensor], ys: Sequence[Tensor]) Tensor#
Real inner product Re<x, y> summed over a parameter list.
For real tensors this is the ordinary dot product; for complex tensors it is the real part of the complex inner product, i.e. the inner product of the underlying real space R^{2n}.
- Parameters:
xs (Sequence of Tensor) – First list of parameter tensors.
ys (Sequence of Tensor) – Second list of parameter tensors, same shapes as
xs.
- Returns:
Scalar sum of
Re<x, y>over every(x, y)pair.- Return type:
Tensor
Probe and object constraints#
Project the probe modes onto an aperture-plane support, power kept. |
|
The bounding box of the measured pixels, as a float support. |
|
A band of |
|
Place a centred recorded-detector map on a larger centred grid. |
- scatterem.reconstruction.ptychography.iterative.regularization.aperture_support.probe_aperture_support(model: Any, regul_dict: dict[str, Any], probe_index: int = 0) Tensor#
Project the probe modes onto an aperture-plane support, power kept.
The constrained modes are all modes but the last for a mixed state (
exclude_last_mode, default True; the last mode stays free to take what the model cannot describe) and the one mode of a single-mode probe. They are multiplied bysupportin the centred aperture plane and then rescaled together, by one factor, to their summed power before the projection.- Parameters:
model (Any) – Forward model exposing
probe_model.regul_dict (dict) –
support: real(H, W)map (bool or float in[0, 1]) on the centred aperture plane of the probe grid (required).exclude_last_mode(default True).preserve_power(default True).probe_index (int, optional) – Probe (tilt) to constrain. Default 0.
- Returns:
Constrained probe, same shape and dtype as the probe.
- Return type:
- Raises:
KeyError – If
supportis missing.ValueError – If the support shape is not the probe grid.
- scatterem.reconstruction.ptychography.iterative.regularization.aperture_support.measured_bbox_support(measured: Tensor, shape: tuple[int, int] | None = None) Tensor#
The bounding box of the measured pixels, as a float support.
- Parameters:
measured (torch.Tensor) – Bool
(My, Mx), True for a pixel that holds data (for example the sum of the patterns over the scan is positive), centred.shape (tuple of int or None, optional) – Probe (model) grid; the box is placed on it by
embed_centred(). None keeps the recorded grid. Default None.
- Returns:
float32 map, 1 inside the box and 0 outside.
- Return type:
- Raises:
ValueError – If no pixel is measured.
- scatterem.reconstruction.ptychography.iterative.regularization.aperture_support.ray_band_mask(shape: tuple[int, int], center: tuple[float, float], angle_deg: float, half_width: float, device: device | str | None = None) Tensor#
A band of
half_widthpixels along a ray fromcenter.With
(dy, dx)the offset of a pixel fromcenter, the ray points along(sin a, cos a)(a = angle_deg, from the +x axis towards +y). A pixel is in the band when its distance from the ray’s line is at mosthalf_widthand it is on the ray’s side of the centre.- Parameters:
center (tuple of float) – Start point
(cy, cx)in pixels (for example the intensity centroid of the mean pattern).angle_deg (float) – Ray direction in degrees.
half_width (float) – Half width of the band in pixels.
device (torch.device or str or None, optional) – Device of the result. Default None (CPU).
- Returns:
Bool
(H, W), True in the band.- Return type:
- scatterem.reconstruction.ptychography.iterative.regularization.aperture_support.embed_centred(mask: Tensor, shape: tuple[int, int]) Tensor#
Place a centred recorded-detector map on a larger centred grid.
Pixel
(My // 2, Mx // 2)ofmaskgoes to(N0 // 2, N1 // 2), as thedetector_pad_tomodel grid places the recorded block. The pixels outside the block are zero (False).- Parameters:
mask (torch.Tensor) –
(My, Mx)map, centred.
- Returns:
(N0, N1)map, dtype and device ofmask.- Return type:
- Raises:
ValueError – If the target is smaller than
mask.
|
|
Reset opaque pixels and remove 2 pi phase jumps of one object slice. |
|
5 x 5 median filter of a 2-D tensor, optionally over good pixels only. |
- scatterem.reconstruction.ptychography.iterative.regularization.absorption_bound.absorption_bound(amplitude: Tensor, phase: Tensor, regul_dict: dict[str, Any]) tuple[Tensor, Tensor]#
bound_absorption()as aregularization:object constraint.The absorption is
-log(amplitude); a zero amplitude (an opaque pixel whose transmission underflowed) givesinfand counts as bad. Each 2-D slice of a 3-D object is bounded on its own.- Parameters:
amplitude (torch.Tensor) – Transmission amplitude
exp(-Im V), shape(..., H, W).phase (torch.Tensor) – Phase
Re V, same shape.regul_dict (dict) –
width(required, for example 2.5) andmarginin pixels (default 64).
- Returns:
The new
(amplitude, phase), same shapes.- Return type:
- Raises:
KeyError – If
widthis missing.
- scatterem.reconstruction.ptychography.iterative.regularization.absorption_bound.bound_absorption(phase: Tensor, absorption: Tensor, width: float, margin: int = 64) tuple[Tensor, Tensor, int]#
Reset opaque pixels and remove 2 pi phase jumps of one object slice.
A pixel is bad when
|absorption - med| > width, withmedthe median absorption of the central region (amarginpixel border left out, clipped to leave at least 2 x 2 pixels).A bad pixel gets the 5 x 5 median (
median5()) of the phase and of the absorption over its good neighbours; the absorption is then clamped tomed +- width.Every pixel loses the multiple of 2 pi that brings its phase nearest to the 5 x 5 median phase.
- Parameters:
phase (torch.Tensor) – Real
(H, W)phaseRe Vin rad.absorption (torch.Tensor) – Real
(H, W)absorptionIm V;inffor a fully opaque pixel is allowed.width (float) – Allowed distance of the absorption from its median.
margin (int, optional) – Border, in pixels, left out of the median. Default 64.
- Returns:
The new phase, the new absorption and the number of bad pixels.
- Return type:
tuple of (torch.Tensor, torch.Tensor, int)
- scatterem.reconstruction.ptychography.iterative.regularization.absorption_bound.median5(x: Tensor, bad: Tensor | None = None) Tensor#
5 x 5 median filter of a 2-D tensor, optionally over good pixels only.
The border is padded by replication. A pixel marked in
baddoes not enter any median. Where all 25 neighbours are bad, the input value is kept. For an even number of good neighbours, the lower median is used (torch.Tensor.nanmedian()).- Parameters:
x (torch.Tensor) – Real
(H, W)tensor.bad (torch.Tensor or None, optional) – Bool
(H, W), True for a pixel to leave out. Default None.
- Returns:
The filtered
(H, W)tensor, dtype ofx.- Return type:
Orthogonalize the selected probe modes by SVD, dominant mode at index 0. |
- scatterem.reconstruction.ptychography.iterative.regularization.probe_modes.orthogonalize_probe(model: Any, regul_dict: dict[str, Any], probe_index: int = 0) Tensor#
Orthogonalize the selected probe modes by SVD, dominant mode at index 0.
The highest-intensity mode is placed at index 0 (the coherent-mode convention).
torch.linalg.eighreturns ascending eigenvalues, which alone would pin the WEAKEST mode at index 0 and make the dominant mode hop slots each call; a stable dominant-first ordering also keeps the per-element optimizer (Adam) state aligned with mode content across iterations.Generic over the K (probe-broadcast) axis: modes are orthogonalized as full
(K, M1, M2)vectors, so the returned tensor keeps the probe-parameter shape(Nmodes, K, M1, M2)for any K (the previoussqueeze(1)path only handled K == 1 and broke the write-back for PRISM probes).
Ptychography losses#
Compute the normalized amplitude RMSE between two diffraction stacks. |
|
|
|
Mean of |
- scatterem.nn.losses.normalized_amplitude_rmse_loss(pred: Tensor, target: Tensor) Tensor#
Compute the normalized amplitude RMSE between two diffraction stacks.
Both arguments are amplitudes (see the module docstring), so they are compared directly:
sqrt(mean((pred - target)**2)) / mean(target)
A 1e-12 epsilon guards the normalizer against an all-zero target. It is negligible for real amplitude data.
- Parameters:
pred (Tensor) – Predicted diffraction amplitudes. Any shape, real floating point; broadcasting is not performed, the two shapes must match.
target (Tensor) – Measured diffraction amplitudes, same shape, dtype and device as
pred.
- Returns:
Scalar (0-dim) loss on the device and dtype of the inputs. Differentiable with respect to
pred.- Return type:
Tensor
- scatterem.nn.losses.masked_normalized_amplitude_rmse_loss(pred: Tensor, target: Tensor, valid: Tensor) Tensor#
normalized_amplitude_rmse_loss()over the valid detector pixels only.sqrt(mse) / mean(target), both means over the True pixels ofvalid. An all-True mask givesnormalized_amplitude_rmse_loss(). A masked pixel has no value and no gradient. A batch with no valid pixel gives 0 with a zero gradient (sqrt'(0)is infinite, so its mse is replaced before the root).- Parameters:
pred (Tensor) – Predicted and measured amplitudes, same shape.
target (Tensor) – Predicted and measured amplitudes, same shape.
valid (Tensor) – Bool mask, broadcastable to
pred; True for a pixel in the loss.
- Returns:
Scalar loss.
- Return type:
Tensor
- scatterem.nn.losses.masked_mean(values: Tensor, valid: Tensor) Tensor#
Mean of
valuesover the True pixels ofvalid(broadcast).- Parameters:
values (Tensor) – Real values, any shape.
valid (Tensor) – Bool mask, broadcastable to
values.
- Returns:
Scalar: the sum over the valid pixels divided by their number (at least 1).
- Return type:
Tensor
Probe gauges and orbital angular momentum#
Canonical mode stack of a reconstructed probe, gauges removed. |
|
Shift all modes together so the total-intensity centroid is at the centre. |
|
Remove the linear phase ramp that ptychography cannot attribute. |
|
Transform real-space-centred modes to the centred aperture plane. |
|
Compute the OAM power spectrum of a mixed state about a sorting axis. |
|
Return the mean OAM |
|
Project a mixed state onto the OAM basis, tracing out the radius. |
|
Degree of coherence between the dominant OAM channel and a neighbour. |
- scatterem.diagnostics.metrics.remove_probe_gauges(probe: ndarray | Tensor, *, drop_last: bool = False, translation: bool = True, phase_ramp: bool = True) ndarray | Tensor#
Canonical mode stack of a reconstructed probe, gauges removed.
- Parameters:
probe (numpy.ndarray or torch.Tensor) – Complex real-space modes, shape
(M, H, W)or the solver layout(M, 1, H, W).drop_last (bool, optional) – Discard the last mode before anything else (some mixed-state solvers reserve it as a background/”junk” mode). Ignored for
M == 1. Default False.translation (bool, optional) – Apply
remove_translation_gauge(). Default True.phase_ramp (bool, optional) – Apply
remove_phase_ramp_gauge(). Default True.
- Returns:
Complex modes, shape
(M', H, W).- Return type:
- Raises:
ValueError – If
probeis neither(M, H, W)nor(M, 1, H, W).
- scatterem.diagnostics.metrics.remove_translation_gauge(fields: ndarray | Tensor) ndarray | Tensor#
Shift all modes together so the total-intensity centroid is at the centre.
The centroid of
sum_m |psi_m|^2(over all leading dims) is moved to the fftshift origin(H // 2, W // 2)by one common subpixel Fourier shift, which is cyclic and power-preserving. A common probe/object translation leaves ptychographic data invariant, so this pins that gauge; to keep the data invariant the object has to be shifted by the same amount.- Parameters:
fields (numpy.ndarray or torch.Tensor) – Complex real-space modes, shape
(..., H, W).- Returns:
Shifted modes, same shape and dtype family as
fields.- Return type:
- scatterem.diagnostics.metrics.remove_phase_ramp_gauge(fields: ndarray | Tensor) ndarray | Tensor#
Remove the linear phase ramp that ptychography cannot attribute.
P e^{2 pi i q.r}withO e^{-2 pi i q.r}gives the same data. The ramp shifts the aperture-plane intensity byq, so the centroidq(pixels, relative to(H // 2, W // 2)) ofsum_m |A_m|^2withA = fftshift(fft2(ifftshift(psi)))is measured andexp(-2 pi i (q_y (y - H//2) / H + q_x (x - W//2) / W))is applied to all modes. Real-space intensity is unchanged; a non-integerqmakes the ramp slightly non-periodic on the grid.- Parameters:
fields (numpy.ndarray or torch.Tensor) – Complex real-space modes centred on
(H // 2, W // 2), shape(..., H, W).- Returns:
De-ramped modes, same shape and array family as
fields.- Return type:
- scatterem.diagnostics.metrics.to_aperture_plane(fields: ndarray | Tensor) ndarray | Tensor#
Transform real-space-centred modes to the centred aperture plane.
Computes
fftshift(fft2(ifftshift(fields), norm="ortho"))over the last two axes, so the real-space centre(H // 2, W // 2)maps to zero frequency, zero frequency lands at(H // 2, W // 2), and the power of every mode is preserved.- Parameters:
fields (numpy.ndarray or torch.Tensor) – Complex mode stack, shape
(..., H, W), real space, centred on(H // 2, W // 2).- Returns:
Aperture-plane modes, same shape and array family as
fields; one pixel is1 / (W * dx)in reciprocal space.- Return type:
- scatterem.diagnostics.metrics.oam_spectrum(fields: ndarray | Tensor, *, center: tuple[float, float] | None = None, l_max: int | None = None, r_min: float = 0.5, r_max: float | None = None, n_r: int | None = None, n_theta: int = 256, l_sign: int = 1) tuple[ndarray | Tensor, ndarray | Tensor]#
Compute the OAM power spectrum of a mixed state about a sorting axis.
P_l = sum_m sum_r r |c_l^m(r)|^2(theris the polar area element), normalised tosum_l P_l = 1over-l_max..l_max. Bilinear ring sampling; samples outside the array count as zero.- Parameters:
fields (numpy.ndarray or torch.Tensor) – Complex mode stack, shape
(..., H, W); leading dims are modes of one state, a(H, W)array is one mode. Real input is promoted.center (tuple of float, optional) – Sorting axis
(cy, cx)in pixels. Default: the centroid of the total intensitysum_m |psi_m|^2.l_max (int, optional) – Largest
|l|reported; must be< n_theta / 2. Defaultn_theta // 2 - 1(all resolvable charges).r_min (float, optional) – Radial sampling range in pixels.
r_maxdefaults tomin(H, W) / 2 - 1.r_max (float, optional) – Radial sampling range in pixels.
r_maxdefaults tomin(H, W) / 2 - 1.n_r (int, optional) – Number of radii, uniformly spaced. Default about one per pixel.
n_theta (int, optional) – Azimuthal samples per ring. Default 256.
l_sign (int, optional) –
+1(default) reportsexp(+i l theta)as+l;-1flips the handedness.
- Returns:
ls (numpy.ndarray or torch.Tensor) – Integer charges
-l_max..l_max, shape(2 l_max + 1,).spectrum (numpy.ndarray or torch.Tensor) – Real populations, same shape, summing to 1.
- Raises:
ValueError – If
l_maxis out of range orl_signis not+-1.
- scatterem.diagnostics.metrics.mean_oam(ls: ndarray | Tensor, spectrum: ndarray | Tensor) float#
Return the mean OAM
sum_l l P_l / sum_l P_lin units of hbar.- Parameters:
ls (numpy.ndarray or torch.Tensor) – Integer charges, shape
(L,).spectrum (numpy.ndarray or torch.Tensor) – Populations, shape
(L,), e.g. fromoam_spectrum().
- Returns:
Population-weighted mean charge.
- Return type:
- scatterem.diagnostics.metrics.oam_density_matrix(fields: ndarray | Tensor, *, center: tuple[float, float] | None = None, l_max: int | None = None, r_min: float = 0.5, r_max: float | None = None, n_r: int | None = None, n_theta: int = 256, l_sign: int = 1) tuple[ndarray | Tensor, ndarray | Tensor]#
Project a mixed state onto the OAM basis, tracing out the radius.
rho[a, b] = sum_m sum_r r c_a^m(r) conj(c_b^m(r))restricted to-l_max..l_maxand normalised toTr rho = 1. It is Hermitian and positive semi-definite; its diagonal equalsoam_spectrum()with the same arguments. Off-diagonalrho[a, a+1]is the coherence between adjacent OAM channels: zero for an incoherent mixture of OAM eigenstates.- Parameters:
fields (numpy.ndarray or torch.Tensor) – Complex mode stack, shape
(..., H, W); seeoam_spectrum().center (tuple of float, optional) – Sorting axis
(cy, cx)in pixels; default the intensity centroid.l_max (int, optional) – Largest
|l|kept; defaultn_theta // 2 - 1.r_min (float, optional) – Radial sampling range in pixels;
r_maxdefaultmin(H, W)/2 - 1.r_max (float, optional) – Radial sampling range in pixels;
r_maxdefaultmin(H, W)/2 - 1.n_r (int, optional) – Number of radii; default about one per pixel.
n_theta (int, optional) – Azimuthal samples per ring. Default 256.
l_sign (int, optional) – Handedness of the reported charge,
+1(default) or-1.
- Returns:
ls (numpy.ndarray or torch.Tensor) – Integer charges, shape
(L,)withL = 2 l_max + 1.rho (numpy.ndarray or torch.Tensor) – Complex density matrix, shape
(L, L), rows/columns ordered asls.
- Raises:
ValueError – If
l_maxis out of range orl_signis not+-1.
- scatterem.diagnostics.metrics.adjacent_coherence(rho: ndarray | Tensor) tuple[float, int, int]#
Degree of coherence between the dominant OAM channel and a neighbour.
g = |rho[i0, j]| / sqrt(rho[i0, i0] rho[j, j])wherei0is the most populated channel andjthe more populated ofi0 - 1andi0 + 1.g = 0for an incoherent OAM mixture,g = 1for a coherent superposition with a common radial profile.- Parameters:
rho (numpy.ndarray or torch.Tensor) – OAM density matrix, shape
(L, L), e.g. fromoam_density_matrix().- Returns:
g (float) – Degree of coherence in
[0, 1].i0 (int) – Row index of the dominant channel.
j (int) – Row index of the neighbour used.
- Raises:
ValueError – If
rhohas fewer than two channels.
Named datasets#
Amorphous carbon, 300 kV (paper Figure 2). |
|
Co3O4, 200 kV (paper Figure 2). |
|
Au nanoparticle, 200 kV, low dose (paper Figure 4). |
|
Gd2O3 nanoparticles, 60 kV (paper Figure 1). |
- class scatterem.data.public.You2026Carbon(root: str | Path, download: bool = False, device: str | device = 'cpu', calibrate: bool = True, **dataset_kwargs: Any)#
Amorphous carbon, 300 kV (paper Figure 2).
- Parameters:
root (str or pathlib.Path) – Directory holding (or to receive) the raw files.
download (bool, optional) – Fetch any missing/corrupt file (Hugging Face mirror first, then Zenodo; md5-checked), by default False.
device (str or torch.device, optional) – Torch device for the data array, by default
"cpu".calibrate (bool, optional) – Run reciprocal-space calibration from the bright-field disk after construction, by default True.
**dataset_kwargs – Forwarded to
Dataset4DStem.__init__(e.g.normalize,clip_neg_values,transform_to_amplitudes).
- class scatterem.data.public.You2026Co3O4(root: str | Path, download: bool = False, device: str | device = 'cpu', calibrate: bool = True, **dataset_kwargs: Any)#
Co3O4, 200 kV (paper Figure 2).
- Parameters:
root (str or pathlib.Path) – Directory holding (or to receive) the raw files.
download (bool, optional) – Fetch any missing/corrupt file (Hugging Face mirror first, then Zenodo; md5-checked), by default False.
device (str or torch.device, optional) – Torch device for the data array, by default
"cpu".calibrate (bool, optional) – Run reciprocal-space calibration from the bright-field disk after construction, by default True.
**dataset_kwargs – Forwarded to
Dataset4DStem.__init__(e.g.normalize,clip_neg_values,transform_to_amplitudes).
- class scatterem.data.public.You2026AuLowDose(*args, repair_bad_pixels=None, scan_edge_crop=None, **kwargs)#
Au nanoparticle, 200 kV, low dose (paper Figure 4).
Three files: the Dectris master plus its two external data blocks. The 180 deg rotation is this acquisition’s known scan/detector offset.
- Parameters:
*args – Forwarded to
PublicDataset4DStem.__init__(root,download,device,calibrate, …).repair_bad_pixels (bool, optional) – Replace the known-bad 2x2 detector patch with the nanmean of its surrounding ring, by default True.
scan_edge_crop (int, optional) – Number of scan rows/columns to drop from each edge, by default 128.
**kwargs – Forwarded to
PublicDataset4DStem.__init__.
- class scatterem.data.public.You2026Gd2O3(root: str | Path, download: bool = False, device: str | device = 'cpu', calibrate: bool = True, **dataset_kwargs: Any)#
Gd2O3 nanoparticles, 60 kV (paper Figure 1).
(512, 512, 112, 112)uint16, ~6.5 GB. The 84 deg scan rotation is load-bearing: the bright-field-shift parallax auto-fit is unreliable on this low-dose data, and without the correct rotation the aberration autofocus absorbs the error into a spurious ~85 A astigmatism.- Parameters:
root (str or pathlib.Path) – Directory holding (or to receive) the raw files.
download (bool, optional) – Fetch any missing/corrupt file (Hugging Face mirror first, then Zenodo; md5-checked), by default False.
device (str or torch.device, optional) – Torch device for the data array, by default
"cpu".calibrate (bool, optional) – Run reciprocal-space calibration from the bright-field disk after construction, by default True.
**dataset_kwargs – Forwarded to
Dataset4DStem.__init__(e.g.normalize,clip_neg_values,transform_to_amplitudes).
Metadata#
Metadata class containing physical parameters and scan geometry for 4D-STEM. |
- class scatterem.data.acquisition.AcquisitionMetadata(energy: float, semiconvergence_angle: float, sampling: NDArray | tuple | list | float | int, shape: NDArray | None = None, units: list[str] | tuple | list | None = None, rotation: float | None = 0, defocus_guess: float | None = 0, aberrations: Aberrations | None = None, slice_thickness: float | None = 0, sample_thickness_guess: float | None = 0, vacuum_probe: Tensor | None = None, scan_affine: Tensor | NDArray | list[float] | None = None, *, geometry: Geometry | None = None, parent_scan: Any = None, detector_warp: Any = None, detector_warp_centre: Any = None)#
Metadata class containing physical parameters and scan geometry for 4D-STEM.
The one acquisition-metadata class: the beam, the per-axis sampling, units and shape of the 4D-STEM array, and the lens state.
- Parameters:
energy (float) – Electron beam energy in electron volts.
semiconvergence_angle (float) – Beam convergence semi-angle in radians.
sampling (array-like or float or int) – Per-axis sampling (real- and/or reciprocal-space) of the 4D-STEM array.
shape (numpy.ndarray) – Shape of the 4D-STEM array.
units (list of str, optional) – Per-axis units for
sampling. Default is inferred from sampling’s dimensionality.rotation (float, optional) – Sample rotation angle in degrees. Default is 0.
defocus_guess (float, optional) – Initial guess of the defocus in Angstroms. Default is 0.
aberrations (Aberrations, optional) – Lens aberration coefficients. Default is all zeros.
slice_thickness (float, optional) – Multislice slice thickness in Angstroms. Default is 0.
sample_thickness_guess (float, optional) – Initial guess of sample thickness in Angstroms. Default is 0.
vacuum_probe (Tensor, optional) – Complex vacuum probe wavefunction. Default is None.
scan_affine (Tensor, optional) – Affine correction applied to the scan grid. Default is None.
geometry (Geometry, optional) – Keyword only. Scan/projection pose of this acquisition. Default is None, which the ptychography models read as zero rotation and translation (see
with_geometry).parent_scan (sequence of int, optional) – Keyword only.
(y0, x0, NY, NX): this scan is the window of a parent raster ofNY x NXpositions (same step and rotation) that starts at rowy0and columnx0. The ptychography models then place each position where the parent raster puts it, and size the object field of view for the whole parent raster, so tilts with different windows share one frame. Default is None: the scan is its own raster, centred in the field of view.detector_warp (array_like, optional) – Keyword only. The detector warp: the
(2, 2)elliptical k-metricW(a pixel at offsetpfrom the disk centre recordsk = W (p dk)) or a(T, 2)polynomial table. Seescatterem.data.detector_warp. Default is None (no warp).detector_warp_centre ((float, float), optional) – Keyword only. The disk centre
(y, x)in pixels of the stored detector, the pivot of the warp. Detector crops, bins and pads move it (data.datasets._meta). Default is None:(H // 2, W // 2).
Aberration coefficients and scan metadata#
Lens aberration coefficients with named access and convention helpers. |
|
Beam and beamlet metadata for a (partitioned) PRISM S-matrix. |
- class scatterem.data.Aberrations(array: Tensor | None = None, **named: float)#
Lens aberration coefficients with named access and convention helpers.
- Parameters:
array (Tensor, optional) – 12-element 1-D tensor (or anything
torch.as_tensor()accepts) in Cartesian layout. Defaults to a fresh zero vector.**named (float) – Coefficients to set by name after construction, e.g.
Aberrations(C10=-150.0, C30=1.2e7)orAberrations(defocus=150.0).
Examples
>>> from scatterem.data.aberrations import Aberrations >>> ab = Aberrations(defocus=150.0, C30=1e7) >>> ab["C10"], ab.defocus (tensor(-150.), tensor(150.)) >>> ab.to_polar()["C30"] 10000000.0
- class scatterem.data.SMeta(all_beams: NDArray | Tensor, parent_beams: NDArray | Tensor, numerical_aperture_radius_pixels: int, dx: NDArray[float32], M: tuple[int, int], device: device)#
Beam and beamlet metadata for a (partitioned) PRISM S-matrix.
Precomputes the Fourier grid, per-beam coordinates/frequencies and (optionally) the natural-neighbor beamlet weights that
PrismScanOpuses to build and project the S-matrix.- Parameters:
all_beams (numpy.typing.NDArray or torch.Tensor) – Boolean
(MY, MX)mask of every beam inside the aperture.parent_beams (numpy.typing.NDArray or torch.Tensor) – Boolean
(MY, MX)mask of the parent-beam subset (all_beamsfor pure PRISM).numerical_aperture_radius_pixels (int) – Aperture radius, in pixels, on the
(MY, MX)grid.dx (numpy.typing.NDArray) – Real-space pixel size per axis.
device (torch.device) – Device to build the tensors on.
Aberrations and the probe#
Labels of the 12 slots of a lens vector, in order: the Krivanek names |
|
|
|
Labels of the magnitude-angle form: first the seven magnitudes |
|
Make a lens vector from labelled values. |
|
Make labelled values from a lens vector. |
|
Evaluate the lens wavefront |
|
Evaluate the slope |
|
Convert a lens vector to the magnitude-angle form. |
|
Convert the magnitude-angle form back to a lens vector. |
|
Convert a string or number to a floating-point number, if possible. |
|
Return a disc with a logistic rim on a grid in DFT order. |
|
Return a ring with logistic rims on a grid in DFT order. |
|
Return the disc of a convergent beam on a frequency grid. |
- scatterem.physics.optics.LENS_LAYOUT: tuple[str, ...] = ('C10', 'C12a', 'C12b', 'C21a', 'C21b', 'C23a', 'C23b', 'C30', 'C32a', 'C32b', 'C34a', 'C34b')#
Labels of the 12 slots of a lens vector, in order: the Krivanek names
"C10","C12a","C12b", …,"C34b"(Krivanek et al. 1999). The order is by ordern, then multiplicitym, then theapart (factorcos(m phi)) before thebpart (factorsin(m phi)).
- scatterem.physics.optics.LENS_TERMS: tuple[tuple[int, int, str], ...] = ((1, 0, 'c'), (1, 2, 'c'), (1, 2, 's'), (2, 1, 'c'), (2, 1, 's'), (2, 3, 'c'), (2, 3, 's'), (3, 0, 'c'), (3, 2, 'c'), (3, 2, 's'), (3, 4, 'c'), (3, 4, 's'))#
(order n, multiplicity m, part)of each slot. Partcmultipliescos(m phi), partsmultipliessin(m phi).
- scatterem.physics.optics.AMPLITUDE_LAYOUT: tuple[str, ...] = ('C10', 'C12', 'C21', 'C23', 'C30', 'C32', 'C34', 'phi12', 'phi21', 'phi23', 'phi32', 'phi34')#
Labels of the magnitude-angle form: first the seven magnitudes
"C10","C12","C21","C23","C30","C32","C34", then the five angles"phi12","phi21","phi23","phi32","phi34". Each part is in the order ofLENS_TERMS. A slot withm = 0holds its signed value. Form > 0the"C<n><m>"slot holds the magnitudeM[Angstrom] and the"phi<n><m>"slot holds the anglealpha[rad].
- scatterem.physics.optics.pack_lens(values: Mapping[str, float], *, layout: Sequence[str] = ('C10', 'C12a', 'C12b', 'C21a', 'C21b', 'C23a', 'C23b', 'C30', 'C32a', 'C32b', 'C34a', 'C34b'), dtype: dtype = torch.float64, device: device | str | None = None) Tensor#
Make a lens vector from labelled values.
- Parameters:
values (Mapping[str, float]) – Map from slot label to value. Lengths are in [Angstrom], angles of
AMPLITUDE_LAYOUTare in [rad]. A missing label gives 0 in its slot (also 0 rad for a missing angle).layout (tuple of str, optional) –
LENS_LAYOUT(default) orAMPLITUDE_LAYOUT.dtype (torch.dtype, optional) – Real dtype of the result. The default float64 keeps all digits of coefficients that span many decades.
device (torch.device or str, optional) – Device of the result.
Nonemeans CPU.
- Returns:
Shape
(12,), in the order oflayout.- Return type:
- Raises:
TypeError – If
valuesis not a mapping, a value is not real, ordtypeis not float32 or float64.ValueError – If a label is not in
layout, a value is not finite, orlayoutis unknown.
- scatterem.physics.optics.unpack_lens(vector: Tensor | Sequence[float], *, layout: Sequence[str] = ('C10', 'C12a', 'C12b', 'C21a', 'C21b', 'C23a', 'C23b', 'C30', 'C32a', 'C32b', 'C34a', 'C34b')) dict[str, float]#
Make labelled values from a lens vector.
This is a host-side helper. It copies a CUDA tensor to the host.
- Parameters:
vector (torch.Tensor or sequence of float) – Shape
(12,), in the order oflayout.layout (tuple of str, optional) –
LENS_LAYOUT(default) orAMPLITUDE_LAYOUT.
- Returns:
All 12 labels with their values.
- Return type:
dict of str to float
- Raises:
ValueError – If the shape is not
(12,)orlayoutis unknown.
- scatterem.physics.optics.lens_wavefront(lens: Tensor | Sequence[float], fy: Tensor, fx: Tensor, *, lambda_a: float) Tensor#
Evaluate the lens wavefront
W[rad] on frequency coordinates.Batch rule (outer product): the result has the shape
(*B, *G), withBthe batch shape oflensandGthe broadcast shape offyandfx. Lensbgives the wavefront at[b]. The function never pairs lens dimensions with grid dimensions.- Parameters:
lens (torch.Tensor or sequence of float) – Lens vector
(12,)or batch(*B, 12)[Angstrom], in the order ofLENS_LAYOUT. A tensor must be on the device offy. The function casts it to the result dtype and keeps its autograd graph. A sequence is copied to the device offy; this copy can make the host wait.fy (torch.Tensor) – Frequency coordinates
k_yandk_x[1/Angstrom], float32 or float64, on one device, broadcastable to the grid shapeG.fx (torch.Tensor) – Frequency coordinates
k_yandk_x[1/Angstrom], float32 or float64, on one device, broadcastable to the grid shapeG.lambda_a (float) – Wavelength [Angstrom], a finite host scalar larger than zero.
- Returns:
Wavefront [rad], shape
(*B, *G), dtype promoted fromfyandfx. With a lens tensor on CUDA, the call does not synchronise the host.- Return type:
- Raises:
TypeError – If
fyorfxis not a real float tensor,lensis not a floating tensor orlambda_ais not a host real scalar.ValueError – If the devices differ, the grids do not broadcast, the last dimension of
lensis not 12 orlambda_ais not finite and positive.
- scatterem.physics.optics.lens_wavefront_slope(lens: Tensor | Sequence[float], fy: Tensor, fx: Tensor, *, lambda_a: float) Tensor#
Evaluate the slope
(dW/dk_y, dW/dk_x)[rad Angstrom] of the wavefront.The function uses the exact derivatives of the basis polynomials. The inputs, the batch rule, the dtype rule and the device rule are those of
lens_wavefront(). The autograd graph allows a second backward pass.slope / (2 pi)is the beam shift(y, x)[Angstrom].- Parameters:
lens (torch.Tensor or sequence of float) – Lens vector
(12,)or batch(*B, 12)[Angstrom].fy (torch.Tensor) – Frequency coordinates
k_yandk_x[1/Angstrom].fx (torch.Tensor) – Frequency coordinates
k_yandk_x[1/Angstrom].lambda_a (float) – Wavelength [Angstrom], finite and larger than zero.
- Returns:
Shape
(*B, *G, 2)[rad Angstrom].[..., 0]isdW/dk_yand[..., 1]isdW/dk_x.- Return type:
- Raises:
TypeError – As
lens_wavefront().ValueError – As
lens_wavefront().
- scatterem.physics.optics.lens_to_amplitude(lens: Tensor | Sequence[float]) Tensor#
Convert a lens vector to the magnitude-angle form.
For a term with
m > 0,(A, B)becomesM = hypot(A, B)[Angstrom] andalpha[rad] withA = M cos(m alpha)andB = M sin(m alpha). The angle is in[0, 2 pi / m).M = 0givesalpha = 0; there the derivative by the coefficients is not defined. A slot withm = 0keeps its signed value. The order of the result isAMPLITUDE_LAYOUT.- Parameters:
lens (torch.Tensor or sequence of float) – Shape
(..., 12)in the order ofLENS_LAYOUT[Angstrom]. A sequence becomes a float64 CPU tensor.- Returns:
Same shape, dtype and device as
lens.- Return type:
- Raises:
TypeError – If
lensis a tensor without a floating dtype.ValueError – If the last dimension is not 12.
- scatterem.physics.optics.lens_from_amplitude(amp: Tensor | Sequence[float]) Tensor#
Convert the magnitude-angle form back to a lens vector.
A = M cos(m alpha)andB = M sin(m alpha). Any realMandalphaare accepted.- Parameters:
amp (torch.Tensor or sequence of float) – Shape
(..., 12)in the order ofAMPLITUDE_LAYOUT. Magnitudes are in [Angstrom], angles in [rad].- Returns:
Lens vector in the order of
LENS_LAYOUT[Angstrom], same shape, dtype and device.- Return type:
- Raises:
TypeError – If
ampis a tensor without a floating dtype.ValueError – If the last dimension is not 12.
- scatterem.physics.optics.RIM_WIDTH_PX = 2.0#
Convert a string or number to a floating-point number, if possible.
- scatterem.physics.optics.smooth_disc(shape: Sequence[int], radius_px: float, *, rim_px: float = 2.0, px_ratio: float | None = None, dtype: dtype | None = None, device: device | str | None = None) Tensor#
Return a disc with a logistic rim on a grid in DFT order.
The value at distance
dis1 / (1 + exp(4 (d - R) / w)), withd = sqrt(i_y^2 + (s i_x)^2)and(i_y, i_x)the signed DFT indices.- Parameters:
shape (sequence of int) – Grid shape
(Ny, Nx).radius_px (float) – Radius
R[axis-0 pixel], finite and zero or larger.rim_px (float, optional) – Rim width
w[axis-0 pixel], finite and larger than zero. DefaultRIM_WIDTH_PX.px_ratio (float, optional) – Ratio
sof the axis-1 pixel width to the axis-0 pixel width [1], finite and larger than zero.Nonemeans square pixels (s = 1).dtype (torch.dtype, optional) – Real dtype.
Nonemeanstorch.get_default_dtype().device (torch.device or str, optional) – Device.
Nonemeanstorch.get_default_device().
- Returns:
Shape
(Ny, Nx), values in[0, 1], no autograd graph.- Return type:
- Raises:
TypeError – If an input has a bad type.
ValueError – If an input has a bad value.
- scatterem.physics.optics.smooth_annulus(shape: Sequence[int], inner_px: float, outer_px: float, *, rim_px: float = 2.0, px_ratio: float | None = None, dtype: dtype | None = None, device: device | str | None = None) Tensor#
Return a ring with logistic rims on a grid in DFT order.
The ring is
f(d; q) * (1 - f(d; p)), withfthe disc profile ofsmooth_disc(),pthe inner andqthe outer radius.- Parameters:
shape (sequence of int) – Grid shape
(Ny, Nx).inner_px (float) – Radii
p <= q[axis-0 pixel], finite and zero or larger.outer_px (float) – Radii
p <= q[axis-0 pixel], finite and zero or larger.rim_px (float, optional) – Rim width
wof both rims [axis-0 pixel]. DefaultRIM_WIDTH_PX.px_ratio (float, optional) – Pixel width ratio
s[1].Nonemeans square pixels.dtype (torch.dtype, optional) – Real dtype.
Nonemeanstorch.get_default_dtype().device (torch.device or str, optional) – Device.
Nonemeanstorch.get_default_device().
- Returns:
Shape
(Ny, Nx), values in[0, 1], no autograd graph.- Return type:
- Raises:
TypeError – If an input has a bad type.
ValueError – If an input has a bad value or
inner_px > outer_px.
- scatterem.physics.optics.illumination_disc(shape: Sequence[int], step_inv_a: Sequence[float], opening_rad: float, *, lambda_a: float, dtype: dtype | None = None, device: device | str | None = None) Tensor#
Return the disc of a convergent beam on a frequency grid.
The disc has the radius
R = a / (lambda g_y)[axis-0 pixel], the pixel width ratios = g_x / g_yand the rim widthRIM_WIDTH_PX. Thus its rim is at the angleain every direction.- Parameters:
shape (sequence of int) – Grid shape
(Ny, Nx).step_inv_a (sequence of float) – Frequency steps
(g_y, g_x)[1/Angstrom], finite and positive.opening_rad (float) – Semi-angle
aof the condenser opening [rad], zero or larger.lambda_a (float) – Wavelength [Angstrom], finite and larger than zero.
dtype (torch.dtype, optional) – Real dtype.
Nonemeanstorch.get_default_dtype().device (torch.device or str, optional) – Device.
Nonemeanstorch.get_default_device().
- Returns:
Shape
(Ny, Nx), values in[0, 1], no autograd graph.- Return type:
- Raises:
TypeError – If an input has a bad type.
ValueError – If an input has a bad value.
Calibration helpers#
Measure the radius and the centre of the bright-field disk. |
|
Radius and centre of the bright-field disk. |
|
Built-in immutable sequence. |
- scatterem.data.pupil_gauge.measure_pupil(pupil_frame: Any, estimator: str = 'integral', *, radius_cap: float = 0.45, contrast_floor: float = 1.5, edge_reach: float | None = None, arc_floor: float | None = None) PupilEstimate#
Measure the radius and the centre of the bright-field disk.
The disk is the image of the probe-forming aperture (the pupil). Its radius is the radius of the circle on which the intensity is
(I_in + I_out) / 2. One detector pixel then corresponds toalpha / (lambda * radius)[1/length], for the aperture semi-anglealpha[rad] and the wavelengthlambda[length].A 3 x 3 median filter and the intermeans threshold give a coarse disk. Pixels that differ from their local median by more than the contrast are replaced by that median, which removes bright defective pixels. The levels
I_inandI_outcome from the regions inside and outside the edge band. All steps are equivariant under an added constant and a positive factor, so the result does not change with them. The function uses no random numbers.- Parameters:
pupil_frame (numpy.ndarray or torch.Tensor) – One 2-D pattern
(Ny, Nx)of intensities, integer or real, for example the mean over all probe positions. A tensor can be on any device and can have autograd enabled; it is only read.estimator ({"integral", "rayfit"}, optional) –
"integral"(default) is for complete disks."rayfit"also measures a disk with a missing sector or with a part outside the detector. Each estimator raises an error if it cannot give a result; it never gives the result of the other estimator.radius_cap (float, optional) – The largest plausible radius, relative to the shorter detector side, in
(0, 1]. Default 0.45: it accepts all complete disks that keep a margin to the border and refuses a disk that fills nearly the whole detector. Use a value up to 1 for a pattern cut down to the disk.contrast_floor (float, optional) – The smallest ratio
I_in / I_outthat counts as a disk, at least 1. Default 1.5. IfI_out <= 0the ratio counts as infinite.edge_reach (float, optional) – The half-width of the band around the edge [pixel] that the estimators integrate over. The band uses
min(edge_reach, 0.6 R). Default (None): 2 for"integral", 10 for"rayfit". A wide band reads a disk with a sloped top too small: on the Gd2O3 mean pattern a 10-pixel band gives a radius 4 % small, a 2-pixel band 0.5 %."rayfit"needs the wide band on a disk with a large missing sector: with 2 pixels it reads a disk with a 90-degree notch 11 % small. Increase it for soft edges: 10 covers edges up to a tanh width of 4 pixels.arc_floor (float, optional) – Only for
"rayfit": the smallest fraction of the full circle, in(0, 1], that the accepted edge points must cover. Default (None) 0.4.
- Returns:
(rim_radius, rim_center): the radius [pixel] as a float, and the centre(y, x)[pixel] as a new NumPy float64 array of shape(2,).- Return type:
- Raises:
TypeError – If
pupil_frameis complex, bool or not an array, or a setting has a wrong type.ValueError – If
pupil_frameis not 2-D or is empty, a setting is out of range, or the pattern has no clear disk (no contrast, no compact disk, a radius aboveradius_cap, a level ratio belowcontrast_floor, an incomplete disk for"integral", or an edge coverage belowarc_floorfor"rayfit").
- class scatterem.data.pupil_gauge.PupilEstimate(rim_radius: float, rim_center: np.ndarray)#
Radius and centre of the bright-field disk.
- Parameters:
rim_radius (float) – The radius of the half-level circle [pixel].
rim_center (numpy.ndarray) – Shape
(2,), float64, the centre(y, x)[pixel].
- scatterem.data.pupil_gauge.ESTIMATORS = ('integral', 'rayfit')#
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
Physics#
Return the relativistic de Broglie wavelength of an electron. |
|
Return the Lorentz factor |
|
Return the mass |
|
Return the interaction parameter |
|
Return |
|
Planck constant |
|
Elementary charge |
|
Speed of light in vacuum |
|
Avogadro constant |
|
Boltzmann constant |
|
Electron rest mass |
|
Atomic mass constant |
|
Fine-structure constant |
|
Magnetic constant |
|
Classical electron radius |
|
Reduced Planck constant |
|
Electron rest energy |
|
Coupling |
- scatterem.physics.constants.debroglie_at(kinetic_ev: float) float#
Return the relativistic de Broglie wavelength of an electron.
lambda = h c / sqrt(E_J (E_J + 2 m0 c^2))(Kirkland 2020, ch. 2).- Parameters:
kinetic_ev (float) – Kinetic energy
E[eV], larger than zero.- Returns:
Wavelength
lambda[Angstrom].- Return type:
- Raises:
TypeError – If
kinetic_evis not a real number.ValueError – If
kinetic_evis zero, negative, NaN or infinite.
Notes
An electron that a potential difference of
Uvolts accelerates hasE = UeV. Thus the caller can give the high tension of the microscope in volts. The function accepts a Python or numpy real scalar and a 0-d tensor. For a 0-d tensor it calls.item(), which waits for the device if the tensor is on a GPU.
- scatterem.physics.constants.gamma_at(kinetic_ev: float) float#
Return the Lorentz factor
gamma = 1 + E_J / (m0 c^2)[1].The function accepts
E = 0and then returns 1.0, because an electron at rest has a defined Lorentz factor.- Parameters:
kinetic_ev (float) – Kinetic energy
E[eV], zero or larger.- Returns:
Lorentz factor
gamma[1].- Return type:
- Raises:
TypeError – If
kinetic_evis not a real number.ValueError – If
kinetic_evis negative, NaN or infinite.
Notes
An electron that a potential difference of
Uvolts accelerates hasE = UeV. Thus the caller can give the high tension of the microscope in volts. The function accepts a Python or numpy real scalar and a 0-d tensor. For a 0-d tensor it calls.item(), which waits for the device if the tensor is on a GPU.
- scatterem.physics.constants.moving_mass_at(kinetic_ev: float) float#
Return the mass
m = gamma m0[kg] of a moving electron.The function accepts
E = 0and then returnsm0.- Parameters:
kinetic_ev (float) – Kinetic energy
E[eV], zero or larger.- Returns:
Mass
m[kg].- Return type:
- Raises:
TypeError – If
kinetic_evis not a real number.ValueError – If
kinetic_evis negative, NaN or infinite.
Notes
An electron that a potential difference of
Uvolts accelerates hasE = UeV. Thus the caller can give the high tension of the microscope in volts. The function accepts a Python or numpy real scalar and a 0-d tensor. For a 0-d tensor it calls.item(), which waits for the device if the tensor is on a GPU.
- scatterem.physics.constants.phase_per_potential_at(kinetic_ev: float) float#
Return the interaction parameter
sigma = 2 pi m e lambda / h^2.A projected potential
v[Volt Angstrom] gives the transmitted electron the extra phasesigma v[rad] (Kirkland 2020, ch. 5).- Parameters:
kinetic_ev (float) – Kinetic energy
E[eV], larger than zero.- Returns:
Interaction parameter
sigma[rad / (Volt Angstrom)].- Return type:
- Raises:
TypeError – If
kinetic_evis not a real number.ValueError – If
kinetic_evis zero, negative, NaN or infinite.
Notes
An electron that a potential difference of
Uvolts accelerates hasE = UeV. Thus the caller can give the high tension of the microscope in volts. The function accepts a Python or numpy real scalar and a 0-d tensor. For a 0-d tensor it calls.item(), which waits for the device if the tensor is on a GPU.
- scatterem.physics.constants.bend_per_tesla_at(kinetic_ev: float) float#
Return
e / p[1 / (Tesla Angstrom)] of an electron.p c = sqrt(E_J^2 + 2 E_J m0 c^2)is the relativistic momentum. The valuee / p = 1 / (B r)is the curvature1 / rof the path per Tesla of transverse magnetic field.- Parameters:
kinetic_ev (float) – Kinetic energy
E[eV], larger than zero.- Returns:
e / p[1 / (Tesla Angstrom)].- Return type:
- Raises:
TypeError – If
kinetic_evis not a real number.ValueError – If
kinetic_evis zero, negative, NaN or infinite.
Notes
An electron that a potential difference of
Uvolts accelerates hasE = UeV. Thus the caller can give the high tension of the microscope in volts. The function accepts a Python or numpy real scalar and a 0-d tensor. For a 0-d tensor it calls.item(), which waits for the device if the tensor is on a GPU.
- scatterem.physics.constants.EXACT_PLANCK = 6.62607015e-34#
Planck constant
h[J s]. Exact in the SI.
- scatterem.physics.constants.EXACT_E_CHARGE = 1.602176634e-19#
Elementary charge
e[C]. Exact in the SI.
- scatterem.physics.constants.EXACT_LIGHT_SPEED = 299792458.0#
Speed of light in vacuum
c[m/s]. Exact in the SI.
- scatterem.physics.constants.EXACT_AVOGADRO = 6.02214076e+23#
Avogadro constant
N_A[1/mol]. Exact in the SI.
- scatterem.physics.constants.EXACT_BOLTZMANN = 1.380649e-23#
Boltzmann constant
k_B[J/K]. Exact in the SI.
- scatterem.physics.constants.CODATA18_ELECTRON_MASS = 9.1093837015e-31#
Electron rest mass
m0[kg]. CODATA 2018, u_r = 3.0e-10.
- scatterem.physics.constants.CODATA18_DALTON = 1.6605390666e-27#
Atomic mass constant
m_u[kg]. CODATA 2018, u_r = 3.0e-10.
- scatterem.physics.constants.CODATA18_FINE_STRUCTURE = 0.0072973525693#
Fine-structure constant
alpha[1]. CODATA 2018, u_r = 1.5e-10.
- scatterem.physics.constants.CODATA18_VACUUM_MU = 1.25663706212e-06#
Magnetic constant
mu_0[N/A^2]. CODATA 2018, u_r = 1.5e-10.
- scatterem.physics.constants.CODATA18_ELECTRON_RADIUS = 2.8179403262e-15#
Classical electron radius
r_e[m]. CODATA 2018, u_r = 4.5e-10.
- scatterem.physics.constants.DERIVED_PLANCK_BAR = 1.0545718176461565e-34#
Reduced Planck constant
hbar = h / (2 pi)[J s]. Exact in principle.
- scatterem.physics.constants.DERIVED_ELECTRON_REST_EV = 510998.9499961642#
Electron rest energy
m0 c^2 / e[eV]. u_r = 3.0e-10 (fromm0).
- scatterem.physics.constants.DERIVED_AB_COUPLING = 1.519267447878626e-05#
Coupling
e / hbar[rad / (Tesla Angstrom^2)]. Exact in principle.The Aharonov-Bohm phase of a path is
-DERIVED_AB_COUPLINGtimes the line integral of the vector potential [Tesla Angstrom]. The factor1e-20converts 1/m^2 to 1/Angstrom^2.
Structures#
One atomic structure in a rectangular, axis-aligned box (immutable). |
|
Build an |
|
Return True if any site fraction is below |
|
Convert a string or number to a floating-point number, if possible. |
|
Site fractions at or above |
|
int([x]) -> integer int(x, base=10) -> integer |
- class scatterem.physics.atom_set.AtomSet(box_spec, fractional, element_z, *, site_fraction=None, msd=None, adp=None, remark: str = '', charge=None, tilt_sine: float = 0.005)#
One atomic structure in a rectangular, axis-aligned box (immutable).
- Parameters:
box_spec (array_like) – Any real dtype, Å. Either (3,) side lengths of a rectangular box, or (3, 3) lattice vectors as rows (any orientation, any handedness, orthogonal or oblique). Rows are reduced to a rectangular box with
scatterem.physics._orthobox.plan_orthobox(); the beam (axis 2) is then alongrow0 x row1, and every periodic image carries the data of its source atom.fractional (array_like) – (N, 3), any real dtype. Fractional coordinates of box_spec. N may be 0. For a (3,) box they are kept as given (no wrap: a finite specimen may have atoms outside [0, 1)). For (3, 3) rows the result is in [0, 1).
element_z (array_like) – (N,), integers or integer-valued floats, 1 to 118. Atomic number Z.
site_fraction (None, float or array_like, optional) – (N,) or scalar, in [0, 1]. Site occupancy. None means full occupancy. Values in (1, 1 + FULL_OCCUPANCY_TOLERANCE] are file rounding and become 1.
msd (None, float or array_like, optional) – (N,) or scalar, Ų, >= 0. Isotropic mean-square displacement <u²> along one direction. None gives
scatterem.crystal.phase.DEFAULT_U2. Never derived from adp.adp (None or array_like, optional) – (N, 3, 3), Ų. Symmetric anisotropic U tensors, Cartesian in the frame of box_spec (the box for (3,), the rows for (3, 3)). For (3, 3) rows they become
Q U Q^TwithQthe frame of the reduction (its small strain is neglected; Grosse-Kunstleve and Adams 2002).remark (str, optional) – Free text.
charge (None or array_like, optional) – (N,), integers or integer-valued floats. Net charge (oxidation state) of each atom, positive for a cation. None (default) means no charges are known. The potential builders ignore it unless a caller asks for ion potentials.
tilt_sine (float, optional) – Largest sine of the tilt of a new box edge from its lattice vector in the reduction of (3, 3) rows, in (0, 0.1]. Always validated.
- Raises:
ValueError – For a bad argument. The message starts with the argument name.
- with_fractional(fractional) AtomSet#
Return a new structure with new positions and all other data shared.
- Parameters:
fractional (array_like) – (N, 3), any real dtype, the same N. Fractional coordinates of this box. One float64 copy is made; no wrap, no reduction.
- Returns:
Shares sides, Z, site fractions, msd, adp, charge and remark with this structure. This structure does not change.
- Return type:
- with_rotation(*, axis_vec, turn_radians, fixed_point=None, as_crystal: bool = False, padding: float = 0.0, tilt_sine: float = 0.005) AtomSet#
Return the structure after a rigid rotation.
A point at Cartesian
r(box frame, Å) moves tofixed_point + R @ (r - fixed_point), withRthe active, right-handed turn ofscatterem.rotation.axis_angle.to_matrix(). Z, site fractions, <u²>, charges and the atom order are kept; tensors becomeR U R^T. This structure does not change. All parameters are keyword-only, so an axis and an angle cannot be swapped by mistake.- Parameters:
axis_vec (array_like) – (3,), any real dtype, any non-zero length, box frame. Turn axis.
turn_radians (float) – Turn angle, radians.
fixed_point (array_like, optional) – (3,), Å, box frame. The point that does not move. Default: the mean Cartesian position of the atom rows (each row counts once); for N = 0 the box centre
sides / 2. Reason: the mean position belongs to the material, not to the box, so the default does not change when a caller adds or removes vacuum, and a specimen that is not centred in its box turns about its own middle. For the finite specimen the result does not depend on this point, because the new box is fitted around the turned content (a different point gives only a common shift, which the fit removes). For a periodic crystal it sets the origin of the turned lattice.as_crystal (bool, optional) – False (default): finite specimen. True: periodic crystal. The default never fails; a periodic result exists only for special rotations, so the caller must ask for it.
padding (float, optional) – Å, >= 0, only for
as_crystal=False. Default 0: the new box always holds the turned input box, so vacuum in the input stays.tilt_sine (float, optional) – Only for
as_crystal=True: largest sine of the tilt of a box edge from its lattice vector, in (0, 0.1].
- Returns:
The turned structure, a new object.
- Return type:
Notes
Finite specimen: the input box turns about its centre into a tilted block. Its extent along box axis
iis the turned centre plus or minussum_j |R_ij| sides_j / 2. The new box is the smallest box with faces normal to the box axes that holds this extent and every turned atom with padding added on each side. So each atom keeps a gap of at least padding to every face. The result is not periodic: give enough padding for a calculation with periodic boundaries.Periodic crystal: the result is periodic, and is the same crystal in the new frame, when each box axis is parallel (within tilt_sine) to a lattice vector of the turned crystal with indices of at most
MAX_AXIS_INDEX(24). Examples: any multiple of a quarter turn about a box axis; a turn that brings a low-index zone axis onto a box axis. Each box edge is the shortest such vector. For any other rotation it raisesValueError; useas_crystal=Falsethen.
- replicated(replicas) AtomSet#
Return the n0 x n1 x n2 periodic supercell.
- Parameters:
replicas (sequence of int) – Three integers >= 1, the copies along box axes 0, 1 and 2 (Python or NumPy integers; bool and float are refused).
- Returns:
New sides
sides * replicas. Rows are atom-major: allM = n0 * n1 * n2copies of atomjcome first as one block, then those of atomj + 1. Inside a block the copy index isi0 + n0 * (i1 + n1 * i2)(i0runs fastest). So rowj * M + i0 + n0 * (i1 + n1 * i2)is atomjmoved by(i0, i1, i2)box lengths, and its source isrow // M. Positions are(f + i) / replicas. A value that rounds to exactly 1.0 from an input below 1 becomes the float just below 1, so input in [0, 1) gives output in [0, 1). Replicas (1, 1, 1) give a structure that shares the arrays. This structure does not change.- Return type:
- scatterem.physics.atom_set.read_atom_set(source_file, *, file_style: str | None = None, displacement_kind: str | None = None, position_kind: str | None = None, tilt_sine: float = 0.005) AtomSet#
Build an
AtomSetfrom one structure file on disk.- Parameters:
source_file (str or os.PathLike) – The file. A missing file raises
FileNotFoundError.file_style (str, optional) –
"kirkland","poscar","mustem","cif"or"extxyz". None selects by the lower-case extension:.xyzkirkland,.p1poscar,.xtlmustem,.cifcif,.extxyzextxyz.displacement_kind (str, optional) – Quantity of the thermal numbers in the file:
"mean_square"(<u²>, Ų),"rms_length"(Å, squared on reading) or"b_factor"(Debye-Waller B, Ų, divided by 8 pi²; Willis and Pryor 1975, Trueblood et al. 1996). None: the quantity the format specification defines (kirkland"rms_length", mustem"mean_square", poscar"mean_square"), so a file that follows its specification reads correctly without the option. CIF values are already <u²> and are used as they are; extxyz has no thermal column. The value is validated for every file_style. If the file gives no number for an atom, that atom keepsDEFAULT_U2with no conversion.position_kind (str, optional) –
"relative"(fractional) or"absolute"(Cartesian Å): overrides the coordinate type of the format, for kirkland (default absolute) and mustem (default relative) only. Other readers refuse a value other than None: POSCAR states the type in the file, CIF and extxyz have one type.tilt_sine (float, optional) – Largest tilt sine of the reduction of (3, 3) lattice rows.
- Returns:
The remark is the comment or title line (kirkland, poscar, mustem) or the file name (cif, extxyz).
- Return type:
- Raises:
ValueError – For a bad option or a line that the file_style cannot parse (the message names the file and the 1-based line number).
- scatterem.physics.atom_set.has_partial_occupancy(site_fraction) bool#
Return True if any site fraction is below
1 - FULL_OCCUPANCY_TOLERANCE.- Parameters:
site_fraction (array_like) – Any shape, any real dtype. Callers must not pass NaN.
- Returns:
False for empty input. A value exactly at
1 - toleranceis full.- Return type:
- scatterem.physics.atom_set.DEFAULT_TILT_SINE = 0.005#
Convert a string or number to a floating-point number, if possible.
- scatterem.physics.atom_set.FULL_OCCUPANCY_TOLERANCE = 0.0001#
Site fractions at or above
1 - FULL_OCCUPANCY_TOLERANCEcount as full. Reason: the supported formats write occupancies with four decimals or more (CIF practice0.3333; muSTEM and Kirkland files1.0000). A full site written with four decimals is off by at most 5e-5 when rounded and 1e-4 when truncated (0.9999). A real vacancy fraction below 1e-4 changes the scattered intensity by less than 1e-4, which no multislice comparison resolves. This is the only copy of the value.
- scatterem.physics.atom_set.MAX_SUPERCELL_FACTOR = 10000#
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Slicing along the beam#
Slicing of the cell along the beam, with exact fractional edges. |
|
Return the distinct atomic numbers of an atom set in ascending order. |
|
Return the snap margin |
|
Lower bound of the snap margin in units of the machine epsilon of the coordinate dtype. |
- class scatterem.physics.beam_partition.BeamPartition(edges: tuple[Fraction, ...])#
Slicing of the cell along the beam, with exact fractional edges.
- Parameters:
edges (sequence of numbers.Real) –
S + 1strictly increasing edges in[0, 1][fractional]. Each value is converted exactly withFraction; a float converts exactly. Python and numpy reals andFractionare accepted.- Raises:
TypeError – If an edge is not a real number (also
bool,str, complex).ValueError – If there are fewer than 2 edges, an edge is not finite, the edges are not strictly increasing,
e_0 < 0ore_S > 1.
Notes
Slice
kis[e_k, e_{k+1}). Exact edges give the rule “slicekis[k/n, (k+1)/n)” one exact meaning, and the slicing does not depend on the box depth. A slice of zero thickness is refused: it has no propagation length and holds no atom under the half-open rule. The object is hashable; partitions with equal edges are equal.- classmethod uniform(count) BeamPartition#
Return the slicing of
countequal slices of the cell.- Parameters:
count (int) – Number of slices, at least 1. Python or numpy integer, not bool.
- Returns:
Edges
Fraction(k, count)fork = 0 .. count.- Return type:
- Raises:
TypeError – If
countis not an integer.ValueError – If
count < 1.
- classmethod from_thicknesses(thicknesses, depth) BeamPartition#
Return the slicing with given slice lengths along the beam.
- Parameters:
- Returns:
Edges are the exact partial sums of
Fraction(t_k)divided byFraction(depth), starting at 0. A last edge withinEDGE_SNAP_ULPS * 2**-53of 1 becomes exactly 1, because a sum of float lengths carries rounding.- Return type:
- Raises:
TypeError – If a value is not a real number.
ValueError – If a value is not finite or not > 0, or if the edges leave
[0, 1].
- edge_values(dtype=torch.float64, device=None) Tensor#
Return the edges rounded once to
dtype.- Parameters:
dtype (torch.dtype, optional) – Real floating dtype. Default float64.
device (torch.device or str, optional) – Device. Default the CPU.
- Returns:
Shape
(S + 1,)[fractional]. The float64 values are the correctly rounded edges; other dtypes round these once more.- Return type:
- subrange(first: int, stop: int) BeamPartition#
Return the partition of slices
first .. stop - 1.- Parameters:
- Returns:
Edges
e_first .. e_stop.- Return type:
- Raises:
ValueError – If the range is empty or outside
0 .. S.
- bin_index(beam_fraction, *, edge_snap: bool = True, margin_dtype=None)#
Return the slice of each atom in the periodic cell.
Rules, in this order:
Reduce into
[0, 1):r = z - floor(z); a roundedr == 1becomes 0 (the cell is periodic along the beam).Interval test on the float64 edges
f_k = float(e_k): slicekwithf_k <= r < f_{k+1}. A coordinate equal to an edge goes to the slice after the edge (the upstream end is closed). This also holds whenf_kis belowe_k, so the computed layerk / nis in slicekofuniform(n).With
edge_snap, a coordinate withe_{k+1} - mu <= rfor an inner edge (k + 1 < S) goes to slicek + 1, withmu = edge_snap_margin(dtype)of the input dtype. The last edge never moves.A reduced coordinate below
e_0or at/aftere_S(only for a partition that does not cover the cell) gives-1.
- Parameters:
beam_fraction (numpy.ndarray or torch.Tensor) – Fractional beam coordinates, any shape, real.
edge_snap (bool, optional) – Snap atomic layers that lie less than
mubefore an inner edge into the slice after it. Default True: a layer that a file or a computation puts a little before its edge is then in the slice of exact arithmetic.margin_dtype (torch.dtype, optional) – The dtype of the coordinate source that sets the snap margin, when the values come converted (for example float32 data in a float64 tensor). Default: the dtype of
beam_fraction.
- Returns:
The int64 slice indices of the input shape: numpy for numpy input, a tensor on the input device for tensor input. No autograd.
- Return type:
- bin_index_clamped(beam_fraction, *, edge_snap: bool = True, margin_dtype=None)#
Return the slice of each source term, without periodic reduction.
A coordinate with
z < e_0gives slice 0; a coordinate withz >= e_Sgives sliceS - 1. Other coordinates follow the interval test and the edge snap ofbin_index().- Parameters:
beam_fraction (numpy.ndarray or torch.Tensor) – Fractional beam coordinates, any shape, real.
edge_snap (bool, optional) – As in
bin_index(). Default True.margin_dtype (torch.dtype, optional) – As in
bin_index().
- Returns:
The int64 slice indices in
0 .. S - 1, as inbin_index().- Return type:
- scatterem.physics.beam_partition.species_order(atom_set) tuple[int, ...]#
Return the distinct atomic numbers of an atom set in ascending order.
- scatterem.physics.beam_partition.edge_snap_margin(dtype: dtype = torch.float64) float#
Return the snap margin
mufor coordinates of one dtype.- Parameters:
dtype (torch.dtype, optional) – Real floating dtype of the coordinate source. Default float64.
- Returns:
max(EDGE_SNAP_RELATIVE, EDGE_SNAP_ULPS * torch.finfo(dtype).eps)[dimensionless]:1e-9for float64 and6.10e-5for float32. For cells deeper than about 100 Angstrom, use float64 coordinates: the float32 margin is6.1e-5 * depth.- Return type:
- Raises:
TypeError – If
dtypeis not a real floating torch dtype.
- scatterem.physics.beam_partition.EDGE_SNAP_ULPS = 512#
Lower bound of the snap margin in units of the machine epsilon of the coordinate dtype. Reason: a computed float32 coordinate such as
float32(0.7)is 1.2e-8 below the edge 7/10, more thanEDGE_SNAP_RELATIVE. 512epscovers the fewepsof such an error with a factor of more than 10. It sets the float32 margin and the end tolerance ofBeamPartition.from_thicknesses().
Projected potentials#
Return the projected potential of each slice of a periodic field of view. |
|
Check the shared inputs of a potential build. |
|
Validated values of a potential request. |
|
Return the device of a build. |
- scatterem.physics.potential_stack.potential_stack(partition: BeamPartition, atom_set: AtomSet, points, *, replicas=None, beam_spread: str = 'binned', edge_snap: bool = True, ignore_site_fraction: bool = False, atom_scale=None, scale_squared: bool = False, form_spectra=None, overrides: RowReplacements | None = None, jitter: ThermalJitter | None = None, rolloff: float | None = 0.3333333333333333, dtype=None, device=None) Tensor#
Return the projected potential of each slice of a periodic field of view.
Physics: on the field of view of
(c_y, c_x)cell copies, areaA = L_y L_x, the Fourier coefficient of slicesis:V_s(q) = (1 / A) sum_{(j, c)} p_{j,c,s} a_j F_{Z_j}(q) exp(-2 pi i q . r_{j,c})
with
r_{j,c}the position of atomjin copyc(after the thermal offset),pits share in the slice (beam_spread),a_j = o_j w_j(o_jthe site fraction when site fractions are in use, else 1;w_jthe coefficientc_jorc_j**2, else 1) andF_Zthe form spectrum [Volt Angstrom^3]. A caller spectrum enters through its even part(F(q) + F(-q)) / 2.Meaning of a pixel: the output at grid point
nis the band-limited point value of the series over the FFT-order frequenciesJ:v_s[n] = Re sum_{q in J} T(q) V_s(q) exp(2 pi i q . r_n) = Re(ifft2(Ny Nx T V_s))[n]
with the rolloff
T(1 without a rolloff). The mean of slicesisV_s(0).Method: each atom copy goes on two interlaced grids (points
n handn h + h/2) with the cubic B-spline; the mean of the phase-corrected rfft2 spectra divided bysinc^4gives the layout spectrum (Hockney and Eastwood 1988). Positions stay exact (float64). Relative L2 error inside the alias-free ellipse: about 1e-4 for one atom on a 0.1 Angstrom grid. One slice is in work at a time.- Parameters:
partition (BeamPartition) – The slicing along the beam.
atom_set (AtomSet) – The structure.
points (tuple of int) – Grid point counts
(Ny, Nx)on the field of view.replicas (tuple of int, optional) – Copy counts
(c_y, c_x). Default None: one copy per axis.beam_spread (str, optional) –
"binned"(default),"tent"or"smeared"; seeaxial_shares().edge_snap (bool, optional) – Edge snap of atomic layers (default True); see
bin_index().ignore_site_fraction (bool, optional) – If False (default), the build uses site fractions when the set has a partial site. In use, every site fraction enters as given, also
0.99995. If True, every prefactor has the site factor 1.atom_scale (array_like or torch.Tensor, optional) – Real, finite coefficient
c_jper atom(N,).scale_squared (bool, optional) – Use
c_j**2(default False).form_spectra (array_like or torch.Tensor, optional) – Real, finite
(E, Ny, Nx)in FFT order [Volt Angstrom^3], rows inspecies_order(). Defaultpotential_spectra(Z <= 103). With autograd through it, the graph keepsS Ehalf-layout grids. Build it for this field of view (samepointsandreplicas); only the shape is checked.overrides (RowReplacements, optional) – Per-site replacement tensors.
jitter (ThermalJitter, optional) – Thermal draws. Default None: static potential.
rolloff (float or None, optional) – Rolloff depth (see
potential_rolloff.rolloff_mask()). DefaultDEFAULT_ROLLOFF; None for no rolloff.dtype (torch.dtype, optional) – The float32 or float64 dtype; complex64/complex128 give their real partner. Default the torch default dtype.
device (torch.device or str, optional) – Default: the device of the tensor inputs, else the CPU.
- Returns:
Real
(S, Ny, Nx)[Volt Angstrom]. Zeros for an empty set.- Return type:
- Raises:
TypeError – For an input of a wrong type.
ValueError – For a bad value, or a combination without a correct gradient: a beam coordinate with grad and
"binned"; anmsdwith grad,"binned"and draws along the beam;"smeared"with draws along the beam; a group with<u^2> = 0where a derivative is needed; a site fraction replacement withignore_site_fraction=True, or with grad and no partial value.
- scatterem.physics.potential_stack.check_stack_request(points, atom_set, *, replicas=None, atom_scale=None, scale_squared: bool = False, dtype=None) StackRequest#
Check the shared inputs of a potential build.
- Parameters:
points (tuple of int) – Grid point counts
(Ny, Nx), each at least 1.atom_set (AtomSet) – The structure.
replicas (tuple of int, optional) – Copy counts
(c_y, c_x)of the cell, each at least 1. Default None: one copy per axis,(1, 1).atom_scale (array_like or torch.Tensor, optional) – Per-atom real, finite coefficients
(N,).scale_squared (bool, optional) – Use
c_j**2instead ofc_j.dtype (torch.dtype, optional) – One of float32, float64, complex64 or complex128. Default the torch default dtype. A complex dtype selects its real partner.
- Returns:
(replicas, lengths, points, real_dtype)with Python ints and floats;lengths[Angstrom].- Return type:
- Raises:
TypeError – For a value of a wrong type (also
boolas an integer, a complex or non-numericatom_scale, a baddtype).ValueError – For a wrong pair length, a count below 1, or an
atom_scalewith a wrong shape or a value that is not finite.
- class scatterem.physics.potential_stack.StackRequest(replicas: tuple[int, int], lengths: tuple[float, float], points: tuple[int, int], real_dtype: torch.dtype)#
Validated values of a potential request.
- scatterem.physics.potential_stack.resolve_stack_device(device, *tensors) device#
Return the device of a build.
Rules:
A given
devicewins. Tensor inputs move to it.Else the device of the tensor inputs (form spectra, coefficients, replacement tensors). Inputs on more than one device raise.
Else the CPU. The rule never selects a GPU by itself.
- Parameters:
device (torch.device or str or None) – Requested device.
*tensors (object) – Inputs; only
torch.Tensorobjects count.
- Returns:
The device of the build.
- Return type:
- Raises:
ValueError – If
deviceis None and the tensors are on more than one device.
Per-row replacements#
Tensors that replace per-atom data of an |
- class scatterem.physics.row_replacements.RowReplacements(beam_fraction: Tensor | None = None, plane_fraction: Tensor | None = None, msd: Tensor | None = None, site_fraction: Tensor | None = None)#
Tensors that replace per-atom data of an
AtomSetin a build.Each field is optional. A given field has one entry per atom row and replaces that data of the
AtomSet. Each tensor may require grad; the build keeps its graph.- Parameters:
beam_fraction (torch.Tensor, optional) –
(N,)fractional beam coordinates [dimensionless].plane_fraction (torch.Tensor, optional) –
(N, 2)fractional coordinates alongyandx.msd (torch.Tensor, optional) –
(N,)mean-square displacement<u^2>[Angstrom^2], >= 0.site_fraction (torch.Tensor, optional) –
(N,)site fractions in[0, 1 + FULL_OCCUPANCY_TOLERANCE]. Values above 1 are used as given (a clip has no derivative). A build withignore_site_fraction=Truerefuses this field, because it would ignore the values without notice.
- Raises:
TypeError – If a field is not a tensor, or has an integer, bool or complex dtype.
ValueError – If a shape is wrong, the fields disagree on
N, a value is not finite, or anmsdor site fraction is out of range.
Notes
The discrete decisions of a build (slice of an atom, groups of rows at one site, whether site fractions are in use) use the replacement values as an
AtomSetwith these values would. The object stores the tensors as given, without a copy.
Thermal displacements#
Request for one frozen-phonon configuration of a build. |
|
Return the thermal offsets of one build, per cell copy [Angstrom]. |
|
Return group labels of rows that describe one site. |
|
Largest distance [Angstrom] between rows that describe one site. |
- class scatterem.physics.thermal_jitter.ThermalJitter(draw_seed: int | None = None, transverse_only: bool = True)#
Request for one frozen-phonon configuration of a build.
- Parameters:
draw_seed (int, optional) – Integer in
0 .. 2**63 - 1that fixes the draws. It seeds a localtorch.Generatoron the build device; the global generators do not change. Withoutdraw_seed, the object takes a fresh 63-bit value fromsecrets.randbits(), stores it and logs it at INFO, so a run can be repeated afterwards. Every build with one object uses itsdraw_seed.transverse_only (bool, optional) – If True (default), the atoms move only along
yandx. If False, they also move along the beam.
- Raises:
TypeError – If
draw_seedis not an integer ortransverse_onlyis not a bool.ValueError – If
draw_seedis outside0 .. 2**63 - 1.
Notes
Stream order (float64 standard normal values on the build device): block 1 has the shape
(c_y, c_x, G, 2)(copyi_yslowest, theni_x, then the row group, then the axis(y, x)). Withtransverse_only=False, block 2(c_y, c_x, G)follows. So block 1 is the same with and without block 2. CPU and CUDA generators give different streams.
- scatterem.physics.thermal_jitter.jitter_offsets(atom_set: AtomSet, replicas, jitter: ThermalJitter, *, overrides: RowReplacements | None = None, device=None) Tensor#
Return the thermal offsets of one build, per cell copy [Angstrom].
Each row group (see
colocated_rows()) of each cell copy moves bysqrt(u_g) * xialongyandx, and withjitter.transverse_only=Falsebysqrt(u_g) * zetaalong the beam.u_gis the arithmetic mean of the<u^2>of the rows of the group (replacement values when given): it is symmetric in the rows and smooth, so the pathwise derivativexi / (2 G_g sqrt(u_g))reaches each of theG_grows. The valuesxiandzetaare the stream ofThermalJitter, the same thatpotential_stack()uses.- Parameters:
atom_set (AtomSet) – The structure.
jitter (ThermalJitter) – Draw seed and beam-direction switch.
overrides (RowReplacements, optional) – Replacement values; the groups use the replaced coordinates.
device (torch.device or str, optional) – Device. Default: the device of the replacement tensors, else the CPU.
- Returns:
The float64 offsets
(c_y, c_x, N, 3)[Angstrom]; axis 2 is 0 withtransverse_only. Copy(i_y, i_x)is the cell moved by(i_y sides[0], i_x sides[1]). The fractional beam offset isoffset[..., 2] / sides[2]. The result carries the graph ofoverrides.msd.- Return type:
- Raises:
ValueError – If
overrides.msdrequires grad and a group hasu_g = 0: the offset there is 0, but its derivative does not exist.
- scatterem.physics.thermal_jitter.colocated_rows(source, sides=None, *, tolerance=0.01)#
Return group labels of rows that describe one site.
Two rows are in one group if a chain of rows links them, with each step at a minimum-image Chebyshev distance
max_i |sides_i (d_i - round(d_i))|of at mosttolerance(dthe difference of fractional coordinates, all three box axes). The cell is periodic, so rows at0.0and0.99999can be one site. The chain rule makes the result independent of the row order.- Parameters:
source (AtomSet or array_like or torch.Tensor) – An
AtomSet(thensidesis None), or(N, 3)fractional coordinates together withsides.sides (array_like, optional) –
(3,)box side lengths [Angstrom] for an array source.tolerance (float, optional) – Largest step [Angstrom], finite, > 0 and below half of the smallest side. Default
COLOCATION_TOLERANCE(0.01 Angstrom).
- Returns:
The int64 labels
(N,)in0 .. G - 1. Labels follow the first row of each group in row order, so row 0 has label 0.- Return type:
- Raises:
ValueError – For a bad shape, a value that is not finite or a bad tolerance.
Notes
Rows go into periodic cube bins of side at least
tolerance; each row looks at the 27 neighbour bins, and a label propagation finds the connected components. Time and memory are O(N) for the bounded number of rows per bin of a real structure.
- scatterem.physics.thermal_jitter.COLOCATION_TOLERANCE = 0.01#
Largest distance [Angstrom] between rows that describe one site. Reason: rows of a mixed site are copies of one written position; four decimals in a 100 Angstrom cell give at most 0.005 Angstrom. The shortest real distance between atoms (H-H, 0.74 Angstrom) is 74 times larger.
Potential rolloff#
Return the rolloff |
|
Return a valid rolloff setting. |
|
Default rolloff depth |
- scatterem.physics.potential_rolloff.rolloff_mask(points, rolloff, *, half_layout: bool = False, device=None, dtype=None) Tensor#
Return the rolloff
Ton the DFT grid, in FFT order.With the normalised radius
r = sqrt((q_y / qN_y)**2 + (q_x / qN_x)**2),qN_i = N_i / (2 L_i), and the depthw:T = 1 for r <= 1 - w T = sin(pi/2 * (1 - r) / w)**2 for 1 - w < r < 1 T = 0 for r >= 1
This is
ellipse_mask(points, 1.0, fade_depth=w).T(0) = 1,Tdoes not increase along any ray from 0, andT = 0at and beyond the Nyquist frequency.- Parameters:
rolloff (float or None) – Depth
win(0, 1), orNonefor ones.half_layout (bool, optional) – If True, return the
rfft2layout(Ny, Nx // 2 + 1).device (torch.device or str, optional) – Device. Default the CPU.
dtype (torch.dtype, optional) – Real dtype. Default the torch default dtype.
- Returns:
Real rolloff,
(Ny, Nx)or(Ny, Nx // 2 + 1).- Return type:
- scatterem.physics.potential_rolloff.check_rolloff(rolloff_depth) float | None#
Return a valid rolloff setting.
- Parameters:
rolloff_depth (float or None) –
None(no rolloff) or the depthw[normalised radius] in(0, 1).- Returns:
Noneorfloat(rolloff_depth).- Return type:
float or None
- Raises:
TypeError – If
rolloff_depthis abool, astror not a real number.ValueError – If
rolloff_depthis not finite or not in(0, 1).
- scatterem.physics.potential_rolloff.DEFAULT_ROLLOFF = 0.3333333333333333#
Default rolloff depth
w. Reason: withw = 1/3the rolloff is 1 forr <= 2/3, so it does not change any frequency of the alias-free band that multislice keeps. It removes the ringing of the truncated series near the atom cores, the Nyquist frequencies and the band corners where the residual alias error is largest.
Spectrum reuse#
Open a scope in which potential builds reuse their layout spectra. |
|
Store and counters of one reuse scope. |
- scatterem.physics.spectrum_sweep.spectrum_sweep(max_entries: int = 4)#
Open a scope in which potential builds reuse their layout spectra.
Inside the scope, a build keeps the layout spectra
D_{s,e}(deposit and smoothing removal, with the prefactors inside, before the form spectra and the rolloff). A later build with the same key uses them again. The key holds content digests of the atom data, the coefficients and the replacement tensors (read at each build, so an in-place change of a caller array gives a new key), and every other input that changesD. The form spectra are not in the key: they act afresh in each build, so their gradients stay correct.Only builds without thermal draws and without any input that requires grad (other than the form spectra) take part; others count as
bypassed. Results inside the scope equal results outside it bit for bit, because both use the same functions.- Parameters:
max_entries (int, optional) – Positive number of stored entries (default 4); the least recently used entry goes first. One entry holds
S E Ny (Nx // 2 + 1)complex values.- Yields:
SweepLedger – The counters of this scope.
Notes
Scopes nest. The inner scope starts empty and does not see the outer store. When a scope ends, also through an exception, the store is emptied and the outer scope is active again. The scope is local to a thread and to an asyncio task (
contextvars). Outside all scopes, no build keeps anything.
- class scatterem.physics.spectrum_sweep.SweepLedger(max_entries: int)#
Store and counters of one reuse scope.
- Parameters:
max_entries (int) – Largest number of stored entries. The least recently used entry goes first.
- Variables:
hits (int) – Builds that used stored layout spectra.
misses (int) – Builds that computed and stored layout spectra.
bypassed (int) – Builds that could not use the scope (thermal draws, or an input other than the form spectra that requires grad).
entries (int) – Stored entries. 0 after the scope ends.
nbytes (int) – Bytes of the stored tensors.
Potential routes#
Settings of the real-space route (immutable, hashable). |
|
Resolve the route choice of a simulator. |
|
Resolve the potential rolloff for a route. |
|
Return a route name after a check. |
|
Return a positive, finite threshold as a Python float. |
|
Route spellings: the Fourier-space route and the real-space route. |
|
Projected potential at the truncation radius [Volt Angstrom]. |
- class scatterem.physics.route_settings.SpatialRouteSettings(axial_mode: str = 'projected', volume_cutoff: float | None = None, projected_cutoff: float = 0.0005)#
Settings of the real-space route (immutable, hashable).
- Parameters:
axial_mode (str, optional) –
"projected"(default): each atom is integrated through all depth and put wholly into the slice that holds it; this matches the default"binned"spread of the Fourier route and is cheaper."sectioned": the integral of the 3-D potential over each slice that the atom reaches.volume_cutoff (float or None, optional) – 3-D potential at the truncation radius [Volt],
"sectioned"only.None(default) means the route’s own value.projected_cutoff (float, optional) – Projected potential at the truncation radius [Volt Angstrom]. Default
DEFAULT_PROJECTED_CUTOFF.
- Raises:
TypeError – For a non-str mode or a non-real threshold.
ValueError – For an unknown mode, a threshold that is not finite or
<= 0, or avolume_cutoffwith"projected".
- scatterem.physics.route_settings.choose_route(*, multi_device, preference='either') str#
Resolve the route choice of a simulator.
- Parameters:
multi_device (bool) – True if the run is distributed over several devices.
preference (str, optional) –
"either"(default) or a name ofROUTE_NAMES.
- Returns:
For
"either":"spatial"whenmulti_device, else"spectral". A route name gives itself.- Return type:
- Raises:
TypeError – If
multi_deviceis not a bool orpreferencenot a str.ValueError – For an unknown
preference.
- scatterem.physics.route_settings.route_rolloff(*, route, preference: float | str | None = 'either') float | None#
Resolve the potential rolloff for a route.
- Parameters:
route (str) – A name of
ROUTE_NAMES.preference (str or float or None, optional) –
"either"(default),None(no rolloff) or a rolloff depth.
- Returns:
"spectral":DEFAULT_ROLLOFFfor"either",NoneforNone,check_rolloff(w)for a number."spatial":Nonefor"either"andNone.- Return type:
float or None
- Raises:
ValueError – For a rolloff depth with the
"spatial"route (low-pass filter the transmission function instead), or a string other than"either".
- scatterem.physics.route_settings.check_route(value) str#
Return a route name after a check.
- Parameters:
value (str) – One of
ROUTE_NAMES.- Returns:
The checked route name.
- Return type:
- Raises:
TypeError – If
valueis not astr.ValueError – If
valueis another string (also"either").
- scatterem.physics.route_settings.check_cutoff(cutoff_level, *, field_label: str) float#
Return a positive, finite threshold as a Python float.
- Parameters:
- Returns:
The checked threshold.
- Return type:
- Raises:
TypeError – For
bool,str, complex or any non-real value.ValueError – For a value that is not finite or
<= 0.
- scatterem.physics.route_settings.ROUTE_NAMES = ('spectral', 'spatial')#
Route spellings: the Fourier-space route and the real-space route.
- scatterem.physics.route_settings.DEFAULT_PROJECTED_CUTOFF = 0.0005#
Projected potential at the truncation radius [Volt Angstrom]. Reason, measured on 2026-11-08 against a cut at 1e-6 V Angstrom (3 x 3 cells, 0.05 Angstrom pixels, one slice per cell): at 300 kV (
sigma = 6.526e-4rad/(V Angstrom)) the largest phase error per 10 nm of specimen is 3.9e-5 rad on the Si, Au, Cu and MoS2 test CIFs (MoS2 the largest), half the 7.8e-5 rad of a cut at 1e-3. The radius is then 3.2 (H), 3.8 (C), 4.9 (Si), 5.2 (Cu) and 4.9 (Au) Angstrom, about 6 % more than at 1e-3; the build time of these cells grew by 5 to 25 %.
Transmission functions#
Return the thin-slice transmission function of each slice. |
|
Return the phase shift |
- scatterem.physics.thin_slice.thin_slice_transmission(beam_ev, projected: Tensor, *, attenuation=None, bandlimit=None) Tensor#
Return the thin-slice transmission function of each slice.
t = exp(i sigma V) * exp(-sigma V')withsigma = phase_per_potential_at(E). The code evaluatestorch.polar(amp, phi)withphi = sigma Vandamp = 1(no absorption) oramp = exp(-sigma V'). So|t| = 1to rounding without absorption.- Parameters:
beam_ev (float) – Kinetic energy [eV], finite and > 0.
projected (torch.Tensor) – Real float32 or float64 projected potential
V(..., Ny, Nx)[Volt Angstrom], at least 2-D, no empty dimension. Leading dimensions are slices or batches.attenuation (torch.Tensor or float, optional) – Projected absorptive potential
V'[Volt Angstrom] (Hall and Hirsch 1965). It is given in the unit ofV, because it comes from the same projected build with absorptive form spectra; so no slice length enters. Real; it broadcasts to the shape ofVwithout enlarging it, and moves to the device and dtype ofVwith its graph.bandlimit (float or tuple of float, optional) – If given, the result is
lowpass_ellipse(t, bandlimit): a fraction of the Nyquist frequency, one value or(rho_y, rho_x). There is no default fraction; the alias-free limit is 2/3 (seeellipse_mask()). Without it, no FFT runs.
- Returns:
The transmission, complex64 for float32 input and complex128 for float64 input, with the shape and device of
V. The inputs do not change; the gradient reachesVandV'.- Return type:
- Raises:
TypeError – For a non-tensor or non-real
V, a complexV'or a bad energy type.ValueError – For fewer than 2 dimensions, an empty dimension, a
V'that would enlarge the shape, or a bad energy value.
- scatterem.physics.thin_slice.phase_from_projection(beam_ev, projected: Tensor) Tensor#
Return the phase shift
phi = sigma(E) V[rad].- Parameters:
beam_ev (float) – Kinetic energy
E[eV], finite and > 0.projected (torch.Tensor) – Projected potential
V[Volt Angstrom], float32 or float64, any shape.
- Returns:
New tensor with the shape, dtype, device and autograd graph of
projected.sigmaisphase_per_potential_at()[rad / (Volt Angstrom)].- Return type:
- Raises:
TypeError – For a non-tensor or another dtype, or a non-real
beam_ev.ValueError – For an energy that is not finite or
<= 0.
Scattering amplitudes#
Return the electron scattering amplitude |
|
Return |
|
Return |
|
Return the Fourier transforms of atomic potentials on a 2-D grid. |
|
Return the product of the Lorentz factor and the wavelength. |
|
Return the atomic number as |
|
|
- scatterem.physics.atom_amplitudes.born_amplitude(frequency: Tensor, atomic_number: int) Tensor#
Return the electron scattering amplitude
f_e(g)of a neutral atom.The formula is eq. 13 of Lobato and Van Dyck (2014):
f_e(g) = sum_i a_i (2 + b_i g^2) / (1 + b_i g^2)^2
The code evaluates it in float64 and rounds the result once to the input dtype. The error is at most about 1e-13 of
f_e(0)before that rounding, also for rows with strong cancellation (Z = 2, 6). Autograd givesd f_e / d gthrough the same float64 graph.- Parameters:
frequency (torch.Tensor) – Spatial frequency
g[1/Angstrom], real floating tensor of any shape.f_eis even ing, so a negative value givesf_e(|g|).atomic_number (int) – Atomic number
Zin1..103.
- Returns:
f_e[Angstrom], with the shape, dtype and device offrequency.- Return type:
- Raises:
TypeError – If
frequencyis not a real floating tensor.ValueError – If the atomic number is not valid.
- scatterem.physics.atom_amplitudes.born_amplitude_array(frequency, atomic_number: int) ndarray#
Return
f_e(g)[Angstrom] as a numpy float64 array.The formula and the evaluation are those of
born_amplitude().- Parameters:
frequency (array_like) – Spatial frequency
g[1/Angstrom].atomic_number (int) – Atomic number
Zin1..103.
- Returns:
f_e[Angstrom], float64, shapenp.shape(frequency).- Return type:
- Raises:
ValueError – If the atomic number is not valid.
- scatterem.physics.atom_amplitudes.born_amplitudes(frequency, atomic_numbers: Sequence[int])#
Return
f_e(g)[Angstrom] for a list of atomic numbers.- Parameters:
frequency (torch.Tensor or array_like) – Spatial frequency
g[1/Angstrom]. A tensor selects the torch form (born_amplitude()); other input selects the numpy form (born_amplitude_array()).atomic_numbers (sequence of int) –
Satomic numbers, each in1..103.
- Returns:
(S, *shape). Slicekis equal bit for bit to the one-element form for thek-th number.- Return type:
- Raises:
ValueError – If the list is empty or holds a number that is not valid.
- scatterem.physics.atom_amplitudes.potential_spectra(grid: PeriodicGrid, atomic_numbers: Sequence[int]) ndarray#
Return the Fourier transforms of atomic potentials on a 2-D grid.
For each atom, the value at frequency
gisV(g) = POTENTIAL_PER_AMPLITUDE * f_e(|g|)[Volt Angstrom^3] (Lobato and Van Dyck 2014, eq. 2), with|g|^2 = k_y^2 + k_x^2fromdft_sample_frequencies(). On a 2-D grid this is the 3-D transform atk_z = 0, which equals the 2-D transform of the projected potential (projection-slice theorem). It is the continuous transform, not a DFT of samples: to get the projected potential [Volt Angstrom] on a cell of areaA[Angstrom^2], divide byAand apply the inverse FFT (torch.fft.ifft2includes the factor1 / (Ny Nx), so multiply its result byNy Nx).- Parameters:
grid (PeriodicGrid) – A 2-D grid
(y, x).atomic_numbers (sequence of int) –
Satomic numbers, each in1..103.
- Returns:
Float64 array
(S, Ny, Nx)in FFT order [Volt Angstrom^3]. The code computes in float64. numpy has no device, so the caller moves the result once withtorch.from_numpy(out).to(device, dtype).- Return type:
- Raises:
ValueError – If the grid is not 2-D, the list is empty or a number is not valid.
- scatterem.physics.atom_amplitudes.gamma_wavelength(kinetic_ev: float) float#
Return the product of the Lorentz factor and the wavelength.
The phase of a slice is
sigma * vwith the projected potentialv[Volt Angstrom]. Whenvcomes fromf_e[Angstrom] throughPOTENTIAL_PER_AMPLITUDE, the product of the two factors is:sigma * h^2 / (2 pi m0 e) = (2 pi gamma m0 e lambda / h^2) * (h^2 / (2 pi m0 e)) = gamma lambda
So
gamma lambdatimes a sum off_eterms, divided by the cell area, is the phase [rad].- Parameters:
kinetic_ev (float) – Kinetic energy [eV]. Must be positive.
- Returns:
gamma * lambda[Angstrom].- Return type:
- Raises:
ValueError – If
kinetic_evis not positive.
- scatterem.physics.atom_amplitudes.validated_atomic_number(atomic_number) int#
Return the atomic number as
intafter a check against Table 1.- Parameters:
atomic_number (int) – Atomic number
Z. Python and numpy integers are accepted.- Returns:
Z, in1..103.- Return type:
- Raises:
ValueError – If
Zis not an integer (boolandfloatare rejected), or if it is outside1..103. The message names the number and the range.
- scatterem.physics.atom_amplitudes.POTENTIAL_PER_AMPLITUDE = 47.877647305682395#
h^2 / (2 pi m0 e)[Volt Angstrom^2]: the Fourier transform of the atomic potential [Volt Angstrom^3] is this factor timesf_e[Angstrom] (Lobato and Van Dyck 2014, eq. 2). Rest massm0; about 47.8776.
Sampling grids and pass bands#
A periodic sampling grid: point counts and periods per axis. |
|
Return the spatial frequencies that the DFT samples on a grid. |
|
Isotropic pass band in physical frequency on a 2-D grid. |
|
Return the band-limited real-space field |
|
Return a low-pass mask that keeps the frequencies inside an ellipse. |
|
Return a complex real-space field band-limited by the ellipse mask. |
|
Counters of the mask store. |
|
Return the counters of the mask store. |
|
Remove all stored masks and set the counters to zero. |
- class scatterem.physics.periodic_sampling.PeriodicGrid(points: tuple[int, ...], lengths: tuple[float, ...])#
A periodic sampling grid: point counts and periods per axis.
- Parameters:
- Raises:
ValueError – If the tuples differ in length, are empty, if a count is not an integer of at least 1, or if a period is not finite and positive.
Notes
The grid stores the period, not the pixel size. One IEEE division of the exact integer
jbyLthen gives the correctly roundedj / L. The object is hashable.- classmethod from_pixel_sizes(points, pixel_sizes) PeriodicGrid#
Make a grid from point counts and pixel sizes.
- Parameters:
- Returns:
The grid with
L_i = N_i * d_i, rounded once. The storedL_iis the reference for all frequencies.- Return type:
- scatterem.physics.periodic_sampling.dft_sample_frequencies(grid: PeriodicGrid) tuple[ndarray, ...]#
Return the spatial frequencies that the DFT samples on a grid.
On an axis with
Npoints and periodL[Angstrom], the DFT samples the spectrum atj / Lfor the FFT-order integersj:0, 1, ..., (N - 1) // 2and then-(N // 2), ..., -1(Press et al. 2007, sec. 12.1).- Parameters:
grid (PeriodicGrid) – The grid.
- Returns:
One float64 array per axis [1/Angstrom]. The array of axis
ihas lengthN_ion axisiand length 1 on all other axes, so the arrays broadcast to the full grid.np.broadcast_arraysgives full views without a copy. Each value is one IEEE division of an exact integer and is correctly rounded. The arrays are new on each call.- Return type:
- class scatterem.physics.periodic_sampling.CircularPassBand(band_grid: PeriodicGrid, cut_fraction: float, rim_samples: float = 2.0)#
Isotropic pass band in physical frequency on a 2-D grid.
The cut radius is
k_c = cut_fraction * min(N_y / (2 L_y), N_x / (2 L_x))[1/Angstrom]. The rim width isw = rim_samples * max(1 / L_y, 1 / L_x)[1/Angstrom], and the flat radius isk_f = k_c - w. With|k|^2 = (j_y / L_y)**2 + (j_x / L_x)**2(float64), the mask is 1 for|k| <= k_f, 0 for|k| >= k_candsin(pi/2 * (k_c - |k|) / w)**2on the rim. The rim is the Hann taper (Harris 1978). In exact arithmetic rim values are strictly between 0 and 1. A rim point within rounding ofk_fork_ccan round to 1 or 0.- Parameters:
band_grid (PeriodicGrid) – A 2-D grid
(y, x). Pixel sizes can differ.cut_fraction (float) –
k_cas a fraction of the lower Nyquist frequency [dimensionless], in (0, 1]. The argument is required. A value of at most 1 keeps the circle inside the Nyquist rectangle. A value of at most 2/3 makes a product of two band-limited fields alias-free on both axes (seeellipse_mask()).rim_samples (float, optional) – Rim width in frequency steps of the coarser axis [dimensionless], greater than 0. The default 2 is the smallest width that puts at least one sample strictly on the rim on each axis. A wider rim gives less ringing and a smaller flat band.
- Raises:
ValueError – If the grid is not 2-D, if a parameter is out of range, or if
k_f < 0.
Notes
Keep one object for one multislice run. The transmission step and the propagation step then use identical pass bands. The object has no mutable state, and equal inputs give equal masks.
- mask(*, device: device | str | None = None, dtype: dtype | None = None) Tensor#
Return the pass-band mask.
- Parameters:
device (torch.device or str, optional) – Device. Default: the CPU.
dtype (torch.dtype, optional) – Real floating dtype. Default: the torch default dtype.
- Returns:
Real mask
(Ny, Nx)in FFT order, values in [0, 1]. The caller owns the tensor. A float32 mask is the float64 mask rounded once.- Return type:
- min_crop_shape() tuple[int, int]#
Return the smallest lossless centred crop box
(M_y, M_x).The centred crop of
Mpoints keepsjfrom-(M // 2)toM - 1 - M // 2. Padding back returns every kept value to its own frequency. WithJ_ithe largest|j_i|where the float64 mask is not zero, the smallest box isM_i = 2 J_i + 1, never aboveN_i. A mask of lower precision has no more non-zero points, so the box is valid for every dtype.
- scatterem.physics.periodic_sampling.apply_pass_band(field: Tensor, mask: Tensor) Tensor#
Return the band-limited real-space field
ifft2(fft2(field) * mask).- Parameters:
field (torch.Tensor) – Complex field
(..., Ny, Nx)in real space.mask (torch.Tensor) – Real mask
(Ny, Nx)in FFT order, for example fromCircularPassBand.mask(). The function moves it to the device and real dtype offield.
- Returns:
New field with the shape and dtype of
field. Neither input changes; the autograd graph offieldstays intact. Acomplex32field is computed incomplex64and cast back, so the FFT sum cannot overflow.- Return type:
- Raises:
TypeError – If
fieldis not complex.ValueError – If the mask shape does not match the last two axes of
field.OverflowError – If a
complex32result has a part above the float16 range.
- scatterem.physics.periodic_sampling.ellipse_mask(shape: tuple[int, int], nyquist_fraction: float | tuple[float, float], *, half_last_axis: bool, fade_depth: float = 0.0, device: device | str | None = None, dtype: dtype | None = None) Tensor#
Return a low-pass mask that keeps the frequencies inside an ellipse.
The ellipse is centred on zero frequency, with its axes on the grid axes. Its semi-axis on axis
iisrho_itimes the Nyquist frequency. In index units it isR_i = rho_i N_i / 2. For the FFT integers(j_y, j_x)the code computes, in float64:num = (j_y R_x)**2 + (j_x R_y)**2, den = (R_y R_x)**2
The normalised radius is
r = sqrt(num / den). A point is inside ifnum < den. A point withnum >= den(r >= 1, alsorexactly 1) gets the value 0. ForR_iinteger or half-integer below about2**20this test is exact.Alias-free size: let two fields have spectra in the open ellipse
E. Their product has its spectrum inE + E = 2E. The DFT wraps frequencyjontoj + (m_y N_y, m_x N_x)with integerm. A wrapped copy reachesEonly if the shift lies in2E - E = 3E. The shortest shifts are along one axis, with normalised lengthN_i / R_i. So no copy reachesEifN_i / R_i >= 3on both axes, that isrho_i <= 2/3. Boundary points are removed, so equality is safe. This is the 2/3 rule of Kirkland (2010, sec. 6.8).Smooth edge: with depth
t = 1 - randw = fade_depth > 0, the value is 0 fornum >= den, 1 fort >= w, andsin(pi/2 * t / w)**2between. This is the Hann taper (Harris 1978). It is monotone int, has a continuous slope at both ends and stays inside the cut, so the alias-free result stays true.- Parameters:
shape (tuple of int) – Full grid shape
(Ny, Nx), also for the half layout.nyquist_fraction (float or tuple of float) –
rho[dimensionless], one value for both axes or(rho_y, rho_x), each in (0, 1]. The argument is required. The value 2/3 is the largest alias-free value; its float64 value is a little below 2/3.half_last_axis (bool) – Required. If True, return the
torch.fft.rfft2layout(Ny, Nx // 2 + 1); columnnholdsj_x = n. If False, return the full layout(Ny, Nx).fade_depth (float, optional) – Depth
wof the smooth edge [normalised radius], in [0, 1). The default 0 gives the hard edge: it keeps the full alias-free band and filtering twice equals filtering once.device (torch.device or str, optional) – Device of the result. Default: the CPU.
dtype (torch.dtype, optional) – Real floating dtype of the result. Default: the torch default dtype.
- Returns:
Real mask
(Ny, Nx)in FFT order, values in [0, 1]. The caller owns the tensor and can change it.- Return type:
- Raises:
ValueError – If
shape,nyquist_fractionorfade_depthis out of range.TypeError – If
dtypeis not a real floating dtype.
Notes
The code builds the mask once in float64 on the CPU and keeps the result of each dtype and device in a bounded LRU store (32 masks, 256 MiB). A repeat request returns a clone of the stored mask. A float32 mask is the float64 mask rounded once, so the two agree to 0.5 float32 ulp at every point. The brief allows differences for points within float32 rounding of the cut or of the inner end of the edge; this design has none. CPU and CUDA masks are equal bit for bit.
- scatterem.physics.periodic_sampling.lowpass_ellipse(field: Tensor, nyquist_fraction: float | tuple[float, float], *, fade_depth: float = 0.0) Tensor#
Return a complex real-space field band-limited by the ellipse mask.
The function computes
ifft2(fft2(field) * mask)with the mask ofellipse_mask()for the shape, real dtype and device offield. The arguments and their reasons are those ofellipse_mask().- Parameters:
field (torch.Tensor) – Complex field
(..., Ny, Nx)in real space. The mask broadcasts over the leading axes.nyquist_fraction (float or tuple of float) – Semi-axes as fractions of the Nyquist frequency [dimensionless]. Required; 2/3 is the largest alias-free value.
fade_depth (float, optional) – Depth of the smooth edge [normalised radius]; 0 is the hard edge.
- Returns:
New complex field with the shape and dtype of
field. The input does not change, and the autograd graph stays intact.- Return type:
- Raises:
TypeError – If
fieldis not complex.
- class scatterem.physics.periodic_sampling.MaskCacheStats(hits: int, misses: int, entries: int, nbytes: int)#
Counters of the mask store.
- scatterem.physics.periodic_sampling.mask_cache_stats() MaskCacheStats#
Return the counters of the mask store.
- Returns:
hits,misses(number of builds),entriesandnbytes[bytes].- Return type:
STEM-EELS and PRISM driver#
Core-loss EELS and elastic CBED of a periodic cell with PRISM kernels. |
|
The output of one |
- class scatterem.simulation.eels.PrismEelsSimulator(structure: AtomSet, *, eV: float, semiconvergence_angle: float, pixels: Sequence[int], scan: Sequence[int], num_slices: int = 1, defocus: float = 0.0, interpolation_factor: int = 1, num_frozen_phonons: int = 1, displacements: bool = False, seed: int | None = None, device: str | device | None = None, dtype: dtype = torch.complex64)#
Core-loss EELS and elastic CBED of a periodic cell with PRISM kernels.
The grid is the whole cell:
pixelssamplesstructure.sides[:2]. The scan is a regular raster ofscanpositions over the cell, half a step from its edges. An ionized site contributes with the weight that its atom has in the elastic potential: itssite_fractionwhen the structure has a partial occupancy, else 1. A site with fraction 0 does not ionize.- Parameters:
structure (AtomSet) – Rectangular box and atoms (fractional
(y, x, depth)andZ).eV (float) – Probe energy [eV].
semiconvergence_angle (float) – Probe-forming aperture semi-angle [mrad].
pixels (sequence of int) – Real-space grid
(Ny, Nx)across the cell.scan (sequence of int) – Number of scan positions
(Sy, Sx).num_slices (int, optional) – Number of equal slices of the cell along the beam. Default 1.
defocus (float, optional) – Probe defocus [Angstrom]; the aperture carries
exp(-i pi lambda defocus |q|^2). Default 0.interpolation_factor (int, optional) – PRISM interpolation factor
f(Ophus 2017) of every output. Default 1 keeps every aperture beam.num_frozen_phonons (int, optional) – Number of specimen configurations averaged. Default 1.
displacements (bool, optional) – Draw thermal displacements for each configuration. Default False. In each EELS configuration the ionized atoms move with their atoms in the elastic potential (one draw for both).
seed (int or None, optional) – Draw seed of configuration 0; configuration
cusesThermalJitter(draw_seed=seed + c). Default None: each configuration takes a fresh seed, whichThermalJitterlogs at INFO.device (str or torch.device or None, optional) – Device of every tensor.
None(default): the CPU, the device of the NumPyAtomSet(simulator convention). Pass"cuda"for the GPU.dtype (torch.dtype, optional) –
torch.complex64(default) ortorch.complex128for the EELS kernels. The elastic CBED runs in the precision ofPrismScanOp.
- Variables:
sampling (wavelength, gridsize,) – Electron wavelength [Angstrom]; cell size
sides[:2]and pixel sizegridsize / pixels[Angstrom].slice_distance (slice_thickness,) –
sides[2] / num_slices, and the propagation distance the EELS kernels take:slice_thickness, but0.0for one slice.device (torch.device) – The resolved device. Every other argument is stored under its name.
- Raises:
ValueError – If
dtypeis not complex64 or complex128, or a count is below 1.
- probe_q() Tensor#
Probe-forming aperture on the full grid, as the EELS kernels take it.
- Returns:
pixels-shaped complex aperture with defocus, corner origin, scaled so that the real-space probeifft2(probe_q)carries unit total intensity.- Return type:
- scan_pixels() Tensor#
Scan positions in grid pixels.
- Returns:
(Sy * Sx, 2)float64(y, x)positions, row-major over the raster.- Return type:
- transmissions(config: int = 0) Tensor#
Real-space transmission functions of one specimen configuration.
- Parameters:
config (int, optional) – Frozen-phonon configuration index; it offsets
seed. Default 0.- Returns:
(num_slices, Ny, Nx)transmissions of dtypedtype.- Return type:
- sites(Z: int) ndarray#
Equilibrium fractional positions of the atoms of one element.
The EELS outputs do more than this: they move the sites with the thermal draw of each configuration and weight each site by its occupancy (see the class notes).
- Parameters:
Z (int) – Atomic number.
- Returns:
(n, 3)fractional(y, x, depth)positions.- Return type:
- Raises:
ValueError – If the structure has no atom of element
Z.
- transition_potentials(edge: Sequence[int], epsilon: float, **transitions: Any) TransitionPotentials#
Transition potentials of one subshell at one continuum energy.
- Parameters:
- Returns:
The stack on this grid, in
dtype.- Return type:
- eels_map(edge: Sequence[int], *, detector_mrad: float, epsilon: float = 1.0, transitions: dict | None = None, **options: Any) PrismResult#
Core-loss elemental map behind an EELS collection aperture.
- Parameters:
edge (sequence of int) –
(Z, n, l)of the ionized subshell. Every atom of elementZionizes.detector_mrad (float) – EELS collection semi-angle [mrad].
epsilon (float, optional) – Energy of the ejected electron above the threshold [eV]. Default 1.
transitions (dict or None, optional) – Keyword arguments for
subshell_transitions. Default None.**options (Any) – Passed to
prism_eels_image:partition,partition_s2(BiP-PRISM),inelastic_crop,prism_mask,mag_preserve,focal_backprop,contract,scan_chunk,reconstruction_workspace.
- Returns:
output="map",dataof shapescan.- Return type:
- qeels(edge: Sequence[int], *, detector_mrad: float, epsilon: float = 1.0, axis: int | Literal['both'] = 'both', transitions: dict | None = None, **options: Any) PrismResult#
Momentum-resolved core-loss output (qEELS; PACBED by scan average).
- Parameters:
edge (sequence of int) –
(Z, n, l)of the ionized subshell.detector_mrad (float) – EELS collection semi-angle [mrad].
epsilon (float, optional) – Energy of the ejected electron above the threshold [eV]. Default 1.
axis ({0, 1, "both"}, optional) –
qeels_axisofprism_eels_image:"both"(default) keeps each detector beam, 0 or 1 projects onto one momentum axis.transitions (dict or None, optional) – Keyword arguments for
subshell_transitions. Default None.**options (Any) – Passed to
prism_eels_image(seeeels_map()).
- Returns:
output="qeels",dataof shapescan + (n_q,)and the matchingq_pixels. Summingdataover its last axis gives the map ofeels_map()with the same settings.- Return type:
- eels_cube(edge: Sequence[int], *, epsilon: float = 1.0, transitions: dict | None = None, **options: Any) PrismResult#
Energy-filtered 4D-STEM cube from the dual scattering matrix.
- Parameters:
edge (sequence of int) –
(Z, n, l)of the ionized subshell.epsilon (float, optional) – Energy of the ejected electron above the threshold [eV]. Default 1.
transitions (dict or None, optional) – Keyword arguments for
subshell_transitions. Default None.**options (Any) – Passed to
prism_transition_potential(partition,scan_chunk).
- Returns:
output="cube",dataof shapescan + pixels.- Return type:
- elastic_cbed(*, n_radial: int | None = None, n_angular: int = 6, focal_backprop: float | str = 'centroid') PrismResult#
Elastic 4D-STEM (CBED at each scan position) with
PrismScanOp.The probe uses the aperture of
probe_q()on the PRISM windowpixels // interpolation_factorand carries unit total intensity.- Parameters:
n_radial (int or None, optional) – None (default) is PRISM on every aperture beam of the f-lattice. An integer selects partitioned PRISM with parent beams on this many rings (
build_prism_smeta).n_angular (int, optional) – Parent beams on the first ring of a partitioned beam set. Default 6.
focal_backprop (float or str, optional) – Reference plane of the partitioned interpolation, passed to
PrismScanOp. Default"centroid". Ignored withoutn_radial.
- Returns:
output="cbed",dataof shapescan + window.- Return type:
- class scatterem.simulation.eels.PrismResult(data: Tensor, output: Literal['map', 'qeels', 'cube', 'cbed'], energy: float, detector_sampling: tuple[float, float], edge: tuple[int, int, int] | None = None, epsilon: float | None = None, energy_losses: ndarray | None = None, q_pixels: Tensor | None = None)#
The output of one
PrismEelsSimulatorcall.- Parameters:
data (torch.Tensor) –
Real, non-negative intensities, averaged over the frozen-phonon configurations. The shape depends on
output:"map":scan;"qeels":scan + (n_q,), one bin per entry ofq_pixels;"cube":scan + pixels, corner-origin diffraction patterns;"cbed":scan + window, corner-origin diffraction patterns on the PRISM windowpixels // interpolation_factor.
output ({"map", "qeels", "cube", "cbed"}) – What
dataholds.energy (float) – Probe energy [eV].
detector_sampling (tuple of float) – Reciprocal pixel
(dky, dkx)of the diffraction axes ofdata[1/Angstrom]. For"qeels"it convertsq_pixelsto 1/Angstrom.edge (tuple of int or None, optional) –
(Z, n, l)of the ionized subshell; None for"cbed".epsilon (float or None, optional) – Energy of the ejected electron above the threshold [eV]; None for
"cbed".energy_losses (numpy.ndarray or None, optional) – Energy loss of each summed transition [eV]; None for
"cbed".q_pixels (torch.Tensor or None, optional) – For
"qeels": the detector coordinates thatprism_eels_imagereturns with the patterns, in grid pixels.(n_q, 2)in(qy, qx)order forqeels_axis="both",(n_q,)for a one-axis projection. None for the other outputs.
Transition potentials#
All channels of one ionised subshell at one continuum energy. |
|
Real-space transition potentials |
|
One ionisation channel: bound orbital |
|
Real-space transition potentials of a set of channels on one grid. |
|
Radial one-electron state |
|
Bound radial state |
|
Continuum radial state |
|
Tell if |
|
Return the EELS on-disk cache directory and create it if it is missing. |
|
|
- scatterem.simulation.eels.subshell_transitions(Z: int, n: int, l: int, epsilon: float, lprimes: Sequence[int] | None = None, order: int = 1, wavefunctions: str = 'auto', xc: str = 'PBE', potential_scale: float = 1.0) list[Transition]#
All channels of one ionised subshell at one continuum energy.
- Parameters:
Z (int) – Element and the ionized bound orbital (e.g. Fe
Ledge: Z=26, n=2, l=1).n (int) – Element and the ionized bound orbital (e.g. Fe
Ledge: Z=26, n=2, l=1).l (int) – Element and the ionized bound orbital (e.g. Fe
Ledge: Z=26, n=2, l=1).epsilon (float) – Energy of the ejected electron above the ionization threshold [eV]. Selecting different
epsilonselects different points along the energy-loss edge.lprimes (list of int, optional) – Continuum angular momenta to include. Default: every
l' >= 0with|l - l'| <= order.order (int) – Maximum change in angular momentum
|l - l'|retained whenlprimesis not given explicitly. The leading small-K term of a channel has the multipole order|l - l'|, soorder = 1keeps the dipole channels and thel' = lchannel.wavefunctions (str) –
"auto"(default: GPAW if importable, else hydrogenic with aHydrogenicFallbackWarning),"gpaw"or"hydrogenic"."auto"resolves once per call, so the fallback warns once.xc (str) – Exchange-correlation functional for the GPAW wavefunctions.
potential_scale (float) – Multiplier on the atomic potential of the GPAW continuum states.
- Returns:
One entry per
(l', ml, mlprime)combination, ordered byl', thenml, thenmlprime.- Return type:
list of Transition
- scatterem.simulation.eels.build_transition_potentials(transitions: Sequence[Transition], Z: int, gpts: Sequence[int], sampling: Sequence[float], eV: float, bandlimit: float | None = 0.6666666666666666, device=None, dtype: dtype = torch.complex64, method: str = 'auto') TransitionPotentials#
Real-space transition potentials
H_n0on a periodic grid.fft2(array) = H~(2 pi f) / (dy dx)inside the band limit, withH~ = sigma(E0) sqrt(2 k_0/k_n) 4 pi (E_h a_0) epsilon_eV(K) / |K|^2(see the module docstring for the frame, phase, spin factor and units). The origin is the corner pixel. The forward models usepsi_n = H_n0 psi_0.- Parameters:
transitions (list of Transition) – Channels from
subshell_transitions().Z (int) – Atomic number of the ionized element.
gpts (int) – Shape
(2,). Grid size(Ny, Nx).sampling (float) – Shape
(2,). Real-space pixel size(dy, dx)[Å].eV (float) – Probe energy [eV].
bandlimit (float or None) – Radius of the hard elliptical band limit in reciprocal space, as a fraction of the Nyquist frequency of each axis. Default 2/3. None applies no band limit.
device (torch.device, optional) – Device of the returned
array. Default None: the CPU.dtype (torch.dtype) – Complex dtype of the returned
array.method (str) – One of
"auto","gpu"or"cpu". Backend for the partial- wave / radial-overlap / form-factor build."auto"(default) runs the vectorised path ondevice, or withdevice=Noneon CUDA when available, else on the CPU;"gpu"forces CUDA;"cpu"numpy.
- Returns:
Real-space transition potentials on the requested grid, in eV^(-1/2).
- Return type:
- class scatterem.simulation.eels.Transition(bound: AtomicRadialWavefunction, excited: AtomicRadialWavefunction, ml: int, mlprime: int)#
One ionisation channel: bound orbital
(l, ml)to continuum(l', ml').- Parameters:
bound (AtomicRadialWavefunction) – Bound-state radial wavefunction.
excited (AtomicRadialWavefunction) – Continuum-state radial wavefunction.
ml (int) – Magnetic quantum number of the bound orbital.
mlprime (int) – Magnetic quantum number of the continuum orbital.
- class scatterem.simulation.eels.TransitionPotentials(array: Tensor, Z: int, energy: float, sampling: tuple, energy_losses: ndarray = <factory>)#
Real-space transition potentials of a set of channels on one grid.
- Parameters:
array (Tensor) – Complex tensor
(n_transitions, Ny, Nx)of real-space transition potentials \(H_{n0}(\mathbf r_\perp)\).Z (int) – Atomic number of the ionized element (used to locate sites).
energy (float) – Probe energy [eV].
sampling (tuple[float, float]) – Real-space pixel size
(dy, dx)[Å].energy_losses (ndarray) – Per-transition energy loss [eV].
- class scatterem.simulation.eels.AtomicRadialWavefunction(n: int | None, l: int, energy: float, r: ndarray, u: ndarray)#
Radial one-electron state
u(r) = r R(r)on a grid in Bohr.- Parameters:
n (int | None) – Principal and orbital angular-momentum quantum numbers.
nisNonefor continuum states.l (int | None) – Principal and orbital angular-momentum quantum numbers.
nisNonefor continuum states.energy (float) – Orbital energy in eV. Negative for bound states, positive (energy above the ionization threshold) for continuum states.
r (ndarray) – Radial grid in Bohr, strictly ascending.
u (ndarray) –
u(r) = r * R(r)sampled onr.
- scatterem.simulation.eels.bound_wavefunction(Z: int, n: int, l: int, xc: str = 'PBE', wavefunctions: str = 'auto', use_cache: bool = True) AtomicRadialWavefunction#
Bound radial state
(n, l)of elementZ, cached on disk.- Parameters:
Z (int) – Atomic number of the element.
n (int) – Principal quantum number.
l (int) – Orbital angular-momentum quantum number.
xc (str, optional) – Exchange-correlation functional passed to the GPAW wavefunctions.
wavefunctions (str, optional) –
"auto"(the default: GPAW if importable, otherwise hydrogenic with aHydrogenicFallbackWarning),"gpaw"or"hydrogenic".use_cache (bool, optional) – Whether to read/write the on-disk cache in
cache_dir().
- Returns:
The bound-state radial wavefunction
u(r) = r * R_nl(r).- Return type:
- scatterem.simulation.eels.continuum_wavefunction(Z: int, lprime: int, epsilon: float, xc: str = 'PBE', wavefunctions: str = 'auto', use_cache: bool = True, potential_scale: float = 1.0) AtomicRadialWavefunction#
Continuum radial state
l'atepsiloneV above threshold, cached.- Parameters:
Z (int) – Atomic number of the element.
lprime (int) – Orbital angular-momentum quantum number of the continuum state.
epsilon (float) – Energy above the ionization threshold, in eV. Must be > 0.
xc (str, optional) – Exchange-correlation functional passed to the GPAW wavefunctions.
wavefunctions (str, optional) –
"auto"(the default: GPAW if importable, otherwise hydrogenic with aHydrogenicFallbackWarning),"gpaw"or"hydrogenic".use_cache (bool, optional) – Whether to read/write the on-disk cache in
cache_dir().potential_scale (float, optional) – Multiplier on the atomic potential of the GPAW continuum equation;
1.0leaves it unchanged. It is ignored by the analytichydrogenicwavefunctions, whose free-particle continuum has no atomic potential.
- Returns:
The continuum radial wavefunction
u_lprime(r), normalised per Rydberg (Manson 1972).- Return type:
- Raises:
ValueError – If
epsilon <= 0.
- scatterem.simulation.eels.gpaw_available() bool#
Tell if
gpawcan be imported, without importing it.- Returns:
Trueifgpawis importable,Falseotherwise.- Return type:
- scatterem.simulation.eels.cache_dir() str#
Return the EELS on-disk cache directory and create it if it is missing.
SCATTEREM_EELS_CACHEoverrides the location. Otherwise the directory is$XDG_CACHE_HOME/scatterem/eels, or~/.cache/scatterem/eelswhenXDG_CACHE_HOMEis not set. The environment is read at call time.- Returns:
Path to the (created if missing) cache directory.
- Return type:
- class scatterem.simulation.eels.HydrogenicFallbackWarning#
wavefunctions="auto"fell back to the analytic hydrogenic family.GPAW is not importable, so the bound and continuum states are the analytic approximations. Cross-sections and EELS images then differ from the GPAW results and are not quantitative.
EELS algorithms#
Energy-filtered diffraction patterns for a batch of probe positions. |
|
Dual-scattering-matrix PRISM STEM-EELS (Brown & Ophus). |
|
Hybrid PRISM/multislice STEM-EELS (single scattering matrix). |
|
Double-channeling PRISM STEM-EELS image |
|
Plane-wave scattering matrix \(\mathcal S\) advanced by multislice. |
|
Partitioned-PRISM scattering matrix (Pelz 2021) for STEM-EELS. |
|
S2: columns are detector-output beams back-propagated to the current slice. |
- scatterem.simulation.eels.multislice_transition_potential(probes: Tensor, transmissions: Tensor, transition_potentials: TransitionPotentials, sites: ndarray, *, wavelength: float, gridsize: Sequence[float], slice_distance: float, site_threshold: float = 0.0, batch_size: int | None = None, return_real_space: bool = False) Tensor#
Energy-filtered diffraction patterns for a batch of probe positions.
- Parameters:
probes (Tensor) – Complex real-space probes
(P, Ny, Nx)already placed at their scan positions.transmissions (Tensor) – Complex real-space transmission functions
(NZ, Ny, Nx)– one per depth slice.transition_potentials (TransitionPotentials) – Real-space transition potentials for the chosen edge.
sites (ndarray) – Fractional coordinates
(Nsite, 3)(y, x, z)in[0, 1)of the ionizable atoms (elementtransition_potentials.Z) within the field of view.wavelength (float) – Probe wavelength [Å].
gridsize (float) – Shape
(2,). Field-of-view size(Ly, Lx)[Å].slice_distance (float) – Inter-slice propagation distance Δz [Å].
site_threshold (float) – Skip a site when, for every probe of the batch and every transition, the probe intensity that the site sees (the
|H|^2-weighted mean of|psi|^2) is below this value. The unit is the intensity of a unit-amplitude plane wave. The module docstring gives the derivation and the error bound. The default 0 skips nothing.batch_size (int, optional) – Probe-position batch size (memory control). Defaults to all probes.
return_real_space (bool) – If True, return the accumulated real-space exit intensity instead of the diffraction-space intensity.
- Returns:
Real, non-negative intensity
(P, Ny, Nx)– the inelastically scattered diffraction pattern (corner origin) summed over all transitions and sites, per incident electron and per eV of energy loss:|fft2|^2 / (Ny Nx), or|psi|^2withreturn_real_space.- Return type:
Tensor
- scatterem.simulation.eels.prism_transition_potential(probe_q: Tensor, transmissions: Tensor, transition_potentials: TransitionPotentials, sites: ndarray, scan_pixels: Tensor, *, wavelength: float, gridsize: Sequence[float], slice_distance: float, return_real_space: bool = False, interpolation_factor=1, partition=None, scan_chunk: int | None = None) Tensor#
Dual-scattering-matrix PRISM STEM-EELS (Brown & Ophus).
Implements the two-scattering-matrix algorithm of Brown, Ciston & Ophus, Phys. Rev. Research 1, 033186 (2019), Eq. (11):
S_{n,iz} = S2 . F . H_{n0} . F^{-1} . S1,
where \(\mathcal S_1\) propagates the probe-forming plane waves from the entrance surface to the ionization slice
izand \(\mathcal S_2\) propagates the inelastically-scattered wave fromizto the exit surface.The key to the full PRISM benefit (vs.
prism_transition_potential_hybrid()) is the order of operations. Because every operator after \(\mathcal S_1\) is linear, the exit wave for scan positionpis:psi_exit(p) = S2[ H_n0 . (sum_b coeff_p[b] S1_col[b]) ] = sum_b coeff_p[b] * S2[ H_n0 . S1_col[b] ],
so the transition is applied to the
Nbeamscolumns of \(\mathcal S_1\) and those columns are propagated to the exit (the action of \(\mathcal S_2\)), then the scan positions are synthesised by the same linear combination used to form the probe. The expensive exit-surface multislice therefore runsNbeamstimes per (site, transition) – independent of the number of scan positionsP– instead ofPtimes. ForP >> Nbeams(a dense scan through a small aperture, the PRISM regime) this is the source of the near-linear scaling.With the exact per-pixel scattering matrix (
partition=None) the result is identical (to float rounding) toprism_transition_potential_hybrid(); this routine just reorders the work. Energy-filtered 4D output is preserved –S2is applied as on-the-fly multislice of the column basis (the full exit diffraction pattern is kept, so no detector reduction is made). Detector-integrating the returned cube over an EELS aperture reproduces the Brown & OphusI(x, y)image.Shrinking the column count (two compatible levers).
interpolation_factor = fsubsamples the aperture beams toNbeams / f**2columns – exact within the PRISM aliasing window – shrinking the exact columns of both legs (S1 build and exit) byf**2.partition(e.g.{"n_radial": 4}) builds S1 onBp << Nbeamsparent beams (Pelz/Ophus partitioned PRISM), then reconstructs the exact aperture columns from the parents at the ionization plane and runs the same dual-S exit. This cheapens the S1 build + memory (Bpparent propagations) and is approximate (natural-neighbor reconstruction error – accurate in-focus / thin / small-aperture, degrading with thickness/aperture); the exit leg still propagates the reconstructedNbeams / f**2columns, so the dual-SP-independence is preserved. Note partitioning does not reduce the (usually dominant) exit leg – only the S1 build;interpolation_factoris the lever for the exit. The two compose (partitionpartitions the already-subsampled aperture). Unlike partitioning S2, this is correct: the reconstruction resolves the position-dependent NNW basis beforeH_{n0}is applied (seePartitionedScatteringMatrix.reconstruct_columns).
- Parameters:
probe_q – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.transmissions – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.transition_potentials – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.sites – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.scan_pixels – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.wavelength – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.gridsize – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.slice_distance – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.return_real_space – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.interpolation_factor – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.partition – As in
prism_transition_potential_hybrid().partitionandinterpolation_factormay be combined.scan_chunk (int, optional) – Number of scan positions synthesised per batch (caps the
(scan_chunk, Ny, Nx)temporary in the linear-combination step).None(the default) sizes the batch by a byte budget instead of a row count – see_SCAN_CHUNK_BUDGET_B. An explicit value is honoured exactly.
- Returns:
Intensity
(P, Ny, Nx)summed over transitions and sites, per incident electron and per eV of energy loss:|fft2|^2 / (Ny Nx), or|psi|^2withreturn_real_space.- Return type:
Tensor
- scatterem.simulation.eels.prism_transition_potential_hybrid(probe_q: Tensor, transmissions: Tensor, transition_potentials: TransitionPotentials, sites: ndarray, scan_pixels: Tensor, *, wavelength: float, gridsize: Sequence[float], slice_distance: float, return_real_space: bool = False, interpolation_factor=1, partition=None) Tensor#
Hybrid PRISM/multislice STEM-EELS (single scattering matrix).
This is the original implementation: the first scattering matrix \(\mathcal S_1\) (reused across scan positions) forms the probe at the ionization plane, but the inelastically-scattered wave is then propagated to the exit by ordinary multislice per scan position – so the exit-leg cost still scales with the number of probe positions.
prism_transition_potential()is the proper dual-scattering-matrix algorithm (Brown & Ophus) and is the preferred entry point; this function is kept for the partitioned-PRISM path and as the equivalence oracle. The two return bit-for-bit-equivalent results (up to float rounding).- Parameters:
probe_q (Tensor) – Probe-forming aperture in reciprocal space
(Ny, Nx)(complex).transmissions (Tensor) – Real-space transmission functions
(NZ, Ny, Nx).transition_potentials (TransitionPotentials) – Transition potentials for the edge.
sites (ndarray) – Fractional
(Nsite, 3)(y, x, z)coordinates of ionizable atoms.scan_pixels (Tensor) – Scan positions
(P, 2)in pixels.wavelength – As in
multislice_transition_potential().gridsize – As in
multislice_transition_potential().slice_distance – As in
multislice_transition_potential().return_real_space (bool, optional) – If
True, return the real-space exit-wave intensity instead of the diffraction-space intensity.interpolation_factor (int or (int, int)) – PRISM interpolation factor
f(or(fy, fx)); seeScatteringMatrix.1(default) is exact;f > 1subsamples the beams to speed up the scattering matrix byf**2and is accurate while the probe fits in the1/fwindow.partition (dict or None) – If given (e.g.
{"n_radial": 4}), use aPartitionedScatteringMatrix(partitioned PRISM, Pelz 2021) instead;interpolation_factoris then ignored.None(default) uses the exact per-pixel scattering matrix.
- Returns:
Intensity
(P, Ny, Nx)summed over transitions and sites, per incident electron and per eV of energy loss:|fft2|^2 / (Ny Nx), or|psi|^2withreturn_real_space.- Return type:
Tensor
- scatterem.simulation.eels.prism_eels_image(probe_q: Tensor, transmissions: Tensor, transition_potentials: TransitionPotentials, sites: ndarray, scan_pixels: Tensor, *, wavelength: float, gridsize: Sequence[float], slice_distance: float, detector_mrad: float, interpolation_factor=1, inelastic_crop: int | None = None, prism_mask: bool = True, scan_shape: Sequence[int] | None = None, partition: dict | None = None, partition_s2: dict | None = None, qeels_axis: int | Literal['both'] | None = None, contract: Literal['auto', 'columns', 'probe'] = 'auto', mag_preserve: bool = True, focal_backprop: float | str | None = None, scan_chunk: int | None = 8192, reconstruction_workspace: int | None = None) Tensor | tuple[Tensor, Tensor]#
Double-channeling PRISM STEM-EELS image
I(x, y).- Parameters:
probe_q (Tensor (Ny, Nx)) – Probe-forming aperture in reciprocal space (complex).
transmissions (Tensor (NZ, Ny, Nx)) – Elastic transmission functions (
|T| = 1; no absorption).transition_potentials (TransitionPotentials) – Transition potentials (
.array(n_trans, Ny, Nx), centred at origin).sites (ndarray (Nsite, 3)) – Fractional
(y, x, z)of the ionized atoms.scan_pixels (Tensor (P, 2)) – Scan positions in pixels.
wavelength – As elsewhere.
gridsize – As elsewhere.
slice_distance – As elsewhere.
detector_mrad (float) – EELS detector collection semi-angle [mrad]; output beams within it.
interpolation_factor (int or (int, int)) – PRISM interpolation factor for
S1(and the scan crop region).inelastic_crop (int, optional) – Crop the transition-potential / scattering-matrix window to
(Ny, Nx) // inelastic_croparound each atom (the localized transition).Noneuses the full grid (exact; equals the detector-integrated 4D dual-S).prism_mask (bool) – Restrict each atom’s contribution to scan positions within the PRISM
1/fcrop region around it (matches the interpolation-factor periodicity).scan_shape ((int, int), optional) – If given, the flat
(P,)image is reshaped toscan_shape.partition (dict, optional) – If given (e.g.
{"n_radial": 4}), buildS1onBpparent beams (PartitionedScatteringMatrix) and reconstruct the exact aperture columns on each atom’s crop window via natural-neighbor interpolation. This cheapens theS1build/advance + memory (Bpparents) at the cost of the NNW reconstruction error. A"focal_backprop"key overrides thefocal_backpropargument forS1.Noneuses the exact per-pixelS1. When one slice’s windows cover the grid, both partitioned legs reuse one full-grid reconstruction per slice, within the additional workspace thatreconstruction_workspacesets; sparse windows and focal referencing stay windowed.partition_s2 (dict, optional) – Same idea for
S2(the detector matrix): build the transpose multislice onBpparent detector beams and NNW-reconstruct the detector columns on the crop window, shrinking the residentS2fromndettoBpcolumns at a second NNW error."dechirp"(default True) removes and restores the scalar vacuum beam phase around the interpolation (seeDetectorExitSMatrix);"focal_backprop"turns on the Fresnel referencing ofS2(off unless given here).Nonekeeps the full per-beamS2.qeels_axis ({0, 1, "both"}, optional) – Momentum-resolved (qEELS) output.
None(default) returns the scalar elemental map.0or1resolves that detector-momentum axis and projects the perpendicular one away: each beam’s|amp_d|^2is binned by its signed frequency alongqeels_axisrather than summed over alld."both"keeps every detector beam in its own bin (no projection). Summing the spectrum over its momentum axis returns the map to float64 round-off – the same additions, grouped differently, so the agreement is ~1 ULP (measured 2e-16 relative) rather than bitwise. Works withpartition/partition_s2(the binning is post-|amp|^2); for a faithful resolved axis useinterpolation_factor == 1along it.contract ({"auto", "columns", "probe"}, default "auto") – How the per-atom contraction is associated (same result to rounding, different cost).
"columns"forms the scan-independent(n_det, B)couplingS2c (H S1c)once per atom and applies the scan coefficients last; it is best whenPis very large or the crop window is the full grid."probe"synthesises the probe on the crop window first (probe = c S1c) and contracts it against the detector columns; it avoids theO(n_det B |window|)intermediate and is faster for small crop windows and modestP."auto"picks the cheaper order per atom from the shapes (see_contract_orders).mag_preserve (bool, default True) – Magnitude-preserving NNW reconstruction of the partitioned
S1andS2columns: keep the complex sum’s phase but restore the interpolated magnitude. This counters the phase-decoherence amplitude loss of the plain complex average and converges to the exact result at full parents.Falseis the plain complex average. Ignored withoutpartition/partition_s2.focal_backprop (float, "centroid" or None, optional) – Fresnel referencing of the partitioned
S1parents: interpolate them at a plane back along the traversed depth, then propagate the reconstructed window forward again."centroid"takes half the traversed depth and a number takes that fraction, rounded to whole slices.None(default) or0disables it.S2uses referencing only whenpartition_s2names it.scan_chunk (int or None, default 8192) – Most scan positions one atom contracts at once. It bounds the scan-dependent intermediate memory, so the scan can be sampled arbitrarily finely. The result does not depend on the value (to rounding);
Noneprocesses all positions of an atom in one block.reconstruction_workspace (int or None, default None) – Additional device memory (bytes) that the partitioned legs may use to reuse one full-grid NNW reconstruction per slice.
Noneuses the default of 2 GiB.0turns the reuse off: every atom reconstructs its own crop window, which is the behaviour of the BiP-PRISM paper and of v0.3, with the smallest peak memory. The result does not depend on the value (to rounding). Ignored withoutpartition/partition_s2.
- Returns:
With
qeels_axis=None: the STEM-EELS image,(P,)orscan_shape, per incident electron and per eV (independent of the grid and of f). Otherwise(spectrum, q_pixels), wherespectrumcarries a trailing momentum axis ((P, n_q)orscan_shape + (n_q,)) andq_pixelsis each bin’s sorted signed pixel frequency (physicalq = q_pixels / gridsize[qeels_axis]). For"both",q_pixelsis(n_q, 2)in(qy, qx)order, one signed pair per detector beam; divide each column by its grid size to get inverse Angstrom.- Return type:
Tensor or (Tensor, Tensor)
- Raises:
ValueError – If
contractorqeels_axisis not one of the listed values, or ifreconstruction_workspaceis negative.
- class scatterem.simulation.eels.ScatteringMatrix(probe_q: Tensor, transmissions: Tensor, kernel: Tensor, interpolation_factor: Sequence[int] = (1, 1))#
Plane-wave scattering matrix \(\mathcal S\) advanced by multislice.
Each row is the multislice-propagated plane wave for one beam in the probe-forming aperture. Advancing the matrix to a given depth and forming a probe by linear combination reproduces the elastic wave at that depth for any scan position.
- Parameters:
probe_q (Tensor) – Probe-forming aperture in reciprocal space
(Ny, Nx)(complex; corner origin). Non-zero pixels define the beams.transmissions (Tensor) – Real-space transmission functions
(NZ, Ny, Nx).kernel (Tensor) – Fresnel propagator
(Ny, Nx)for one inter-slice distance.interpolation_factor ((int, int), optional) – PRISM interpolation factors
(fy, fx)(Ophus 2017);(1, 1)keeps every beam and is exact. See__init__()for the full anti-aliasing discussion.
- class scatterem.simulation.eels.PartitionedScatteringMatrix(probe_q: Tensor, transmissions: Tensor, kernel: Tensor, n_radial: int = 4, n_angular: int = 6, interpolation_factor: Sequence[int] = (1, 1), focal_backprop: float | str | None = None, mag_preserve: bool = True, wavelength: float | None = None, slice_distance: float | None = None, gridsize: Sequence[float] | None = None)#
Partitioned-PRISM scattering matrix (Pelz 2021) for STEM-EELS.
Instead of one multislice-propagated plane wave per aperture pixel, the matrix is built on a small set of
Bpparent beams (a hex-ring subsample of the aperture). The probe at a scan position is synthesised by natural- neighbor interpolation of the de-tilted parent columns:psi(r, R) = sum_p S_dt[p](r) * basis_p(r - R), S_dt[p](r) = S[p](r) * exp(-2 pi i g_p . r / N), (de-tilted column) basis_p(rho) = sum_b coeffs[b] w[b,p] exp(2 pi i g_b . rho / N),
where
w[b,p]are the natural-neighbor weights expressing aperture beambin terms of the parents. In the full-parent limit (every beam its own parent,wthe identity) this is algebraically the exact per-pixel probe, soScatteringMatrixis theBp -> Blimit and serves as the oracle. Presents theadvance_to/probe_at_current_planeinterface ofScatteringMatrixpluscoeffs_at()/reconstruct_columns(), so it can drive either the hybrid path or the dual-scattering-matrix exit (the reconstructed columns are scalar-combinable). Acceptsinterpolation_factorso PRISM beam subsampling composes with partitioning. Accuracy is regime-dependent (the natural-neighbor reconstruction error).- Parameters:
probe_q (Tensor) – Probe-forming aperture in reciprocal space
(Ny, Nx)(complex; corner origin). Non-zero pixels define the beams.transmissions (Tensor) – Real-space transmission functions
(NZ, Ny, Nx).kernel (Tensor) – Fresnel propagator
(Ny, Nx)for one inter-slice distance.n_radial (int, optional) – Number of concentric hex rings of parent beams sampled from the aperture (must be >= 2).
n_angular (int, optional) – Number of angular samples on the first hex ring (subsequent rings scale with ring index).
interpolation_factor ((int, int), optional) – PRISM interpolation factors
(fy, fx)(Ophus 2017), applied to the aperture before partitioning;(1, 1)keeps every beam.focal_backprop (float, str or None, optional) – Fresnel referencing of the parent columns before natural-neighbor fusion (Pelz 2021). A float back-propagates by that fraction of the traversed depth, rounded to whole slices;
"centroid"selects half the traversed depth. The fused columns are then propagated forward to the current plane again.None(default) or0disables the referencing. It is skipped in the full-parent limit, where the columns are exact.mag_preserve (bool, optional) – Restore each reconstructed column’s magnitude from the same NNW interpolation of
|S|, keeping the complex sum’s phase. Applies toreconstruct_columns_window().wavelength (float, optional) – Electron wavelength in Angstrom. With
slice_distanceandgridsizeit sets the windowed Fresnel step thatreconstruct_columns_window()needs whenfocal_backpropis on.slice_distance (float, optional) – Slice distance in Angstrom (see
wavelength).gridsize ((float, float), optional) – Real-space grid extent
(Ly, Lx)in Angstrom (seewavelength).
- class scatterem.simulation.eels.DetectorExitSMatrix(det_idx: Tensor, transmissions: Tensor, kernel: Tensor, partition: dict | None = None, mag_preserve: bool = True, focal_backprop: float | str | None = None, wavelength: float | None = None, slice_distance: float | None = None, gridsize: Sequence[float] | None = None)#
S2: columns are detector-output beams back-propagated to the current slice.
S2_d(r)is the adjoint (transpose) multislice of the conjugate detector plane wavee_d*from the exit surface back to the current slice, so that for any wavewat that slicesum_r S2_d(r) w(r) == fft(forward_exit(w))[d]– the amplitude reaching detector beamd. Built once covering all slices (slice 0 -> exit) andpeel_to()advances the start slice forward (removing front slices) so it is reused across every atom.With
partitionthe transpose multislice is built on onlyBpparent detector beams (a hex-ring subsample); the full detector columns are NNW-reconstructed on a crop window viacolumns_window(). By reciprocity the de-tilted back-propagated columns are locally similar, so the same partitioned-PRISM interpolation applies – shrinking the resident S2 fromndettoBpcolumns.- Parameters:
det_idx (Tensor) – Corner-origin pixel indices of the accepted detector beams, shape
(ndet, 2), integer dtype.transmissions (Tensor) – Per-slice transmission functions, shape
(nz, ny, nx), complex dtype; determines the grid shape and the build device/dtype.kernel (Tensor) – Fresnel propagator kernel for one slice step, shape
(ny, nx), complex dtype.partition (dict or None) – When given, enables partitioned (parent-beam) construction; recognized keys are
"n_radial"and"n_angular", the hex-ring subsample resolution passed to the NNW weighting, and"dechirp"(default True), which removes each column’s accumulated vacuum propagator phase before the NNW combination and restores it per output beam afterwards."dechirp": Falseis the ablation without it.Nonebuilds the fullndetcolumns directly.mag_preserve (bool, default True) – Restore the magnitude of the partitioned reconstruction from the same NNW interpolation, keeping the complex sum’s phase. Ignored when
partitionis None (the columns are then exact).focal_backprop (float, str or None, optional) – Fresnel referencing of the partitioned parents before interpolation: the parents are propagated toward the exit by that fraction of the remaining path
nz - start("centroid"is half of it, rounded to whole slices), combined on a padded window, and propagated back.None(default) or0disables it. It is skipped in the full-parent limit, where the columns are exact.wavelength (float, optional) – Electron wavelength in Angstrom. With
slice_distanceandgridsizeit sets the windowed Fresnel step thatfocal_backpropneeds.slice_distance (float, optional) – Slice distance in Angstrom (see
wavelength).gridsize ((float, float), optional) – Real-space grid extent
(Ly, Lx)in Angstrom (seewavelength).
Elastic PRISM#
Map a transmission function, probe and scan positions to exit waves. |
|
Scan-time exit-wave operator that projects a partitioned S-matrix. |
|
Standard per-position multislice. |
|
Synthesize a pure- or partitioned-PRISM, f-lattice |
|
Power-based f-lattice-shell PRISM |
- class scatterem.nn.scan_exit_wave.ScanExitWaveOperator(*args, **kwargs)#
Map a transmission function, probe and scan positions to exit waves.
Two flavours of
Tinput, decided bywants_full_fov:wants_full_fov = False–Tis per-position patches of shape(NZ_bin, K, M1, M2); the operator runs an inner multislice-style loop over scan positions. This is the default multislice path.wants_full_fov = True–Tis the full-FOV transmission stack of shape(NZ_bin, NY, NX); the operator builds an S-matrix from it (via plane-wave multislice) and projects to scan positions cheaply. This is the PRISM / partitioned-PRISM path.
The probe is always given in real space
(Nmodes, K, M1, M2); operators that need the Fourier-aperture form FFT internally.exit_antialias_aperture(defaultNone, andNoneon every reconstruction path) is the wave-side half of a band-limited forward that the Fresnel propagator cannot carry: the aperture applied once more after the last transmission, which the propagator only does BETWEEN slices. Each operator applies it through_bandlimit_exit()at its own exit point – the multislice loop on the exit wave, the PRISM family on the finished S-matrix columns – on the grid it hands the field back on.- Parameters:
*args (Any) – Forwarded to
torch.nn.Module.__init__.**kwargs (Any) – Forwarded to
torch.nn.Module.__init__.
- Variables:
exit_antialias_aperture (torch.Tensor or None) – Real
(Ny, Nx)antialiasing aperture in FFT layout on the operator’s output grid, orNone. A plain attribute, not a registered buffer, so it stays out ofstate_dict()and checkpoints written before it existed still load; being a plain attribute it is also NOT moved by.to(device)–_bandlimit_exit()moves it per call instead.
- class scatterem.nn.scan_exit_wave.PrismScanOp(s_meta: SMeta, f: int | tuple = 1, freeze_s_matrix: bool = False, scan_chunk: int | None = None, periodic: bool = True, precision_config: dict | str | None = None, focal_backprop: float | str = 'centroid', use_warp: bool | None = None, build_cols: int | None = None)#
Scan-time exit-wave operator that projects a partitioned S-matrix.
Constructs an S-matrix on a set of parent beams (a subset of the aperture beams) and projects to each scan position via beamlet-weighted natural-neighbor sums.
- Parameters:
s_meta (SMeta) – Beam/beamlet metadata (parent beams, weights, simulation grid).
f (int or tuple, optional) – Anisotropic interpolation factor
(f_y, f_x); a scalar broadcasts to both axes.freeze_s_matrix (bool, optional) – If True, detach the transmission before building the S-matrix.
scan_chunk (int or None, optional) – Chunk size for
prism_projectover scan positions.periodic (bool, optional) – Whether
prism_projecttreats the S-matrix as periodic.precision_config (dict or str or None, optional) – Precision preset resolved by
resolve_precision().focal_backprop (float or str, optional) – Fraction of the thickness (0 = exit, 1 = entrance) to back-propagate parent columns to before NNW fusion, or
"centroid"to auto-select the scattering centroid.use_warp (bool or None, optional) – Whether to use the Warp kernel for scan synthesis; None follows the
SCATTEREM_USE_WARPenvironment variable.build_cols (int or None, optional) – Parent beams propagated at once in the S-matrix build (>= 1), capping its
(cols, MY, MX)transients; None is one pass when the stack fits ~6e8 complex elements.SCATTEREM_PRISM_BUILD_COLSoverrides.
- class scatterem.nn.scan_exit_wave.MultisliceScanOp#
Standard per-position multislice.
Two transmission input flavours, selected by
inverse_index:inverse_index is None–Tis already-gathered per-position patches of shape(NZ_bin, K, M1, M2); each slice is broadcast- multiplied into the waves.inverse_indexgiven –Tis the ungathered per-unique-pixel (exponentiated) potential stack of shape(NZ_bin, U); the gather + complex multiply is fused per slice via the Warpfused_transmitkernel.
In both cases inter-slice Fresnel propagation is applied after every slice except the last (matching the model).
exit_antialias_aperture(inherited; defaultNone, andNoneon every reconstruction path) optionally applies an antialiasing aperture once to the exit wave; seeforward().checkpoint_every(default 0, off) checkpoints the slice loop in segments of that many slices when a gradient is recorded (checkpointed_slice_loopin_slice_checkpoint):O(N_sl / s + s)activation memory for one extra forward, with the same output and gradients.
- scatterem.nn.scan_exit_wave.build_prism_smeta(*, pixels: tuple[int, int], f: int | tuple[int, int], dx, wavelength: float, semiconvergence_angle: float, fov_shape: tuple[int, int] | None, device, n_radial: int | None = None, n_angular: int = 6, margin: float | None = None) SMeta#
Synthesize a pure- or partitioned-PRISM, f-lattice
SMeta(Ophus 2017).Instance-free so the reconstruction path can reuse it for f>1 later (spec forward-compat): everything is taken from the explicit arguments, not from a simulator instance.
- Parameters:
pixels ((int, int)) – Detector window
(P_y, P_x). The simulation grid isN = f * pixelsper axis; the detector isN / f = pixels(dk = f·Δq).f (int) – PRISM interpolation factor (
>= 1).dx (array-like (2,)) – Real-space pitch
Δp = unitcell / pixelsper axis (Å). UNCHANGED byf– the N grid is the larger probe window at the same pitch.wavelength (float) – Electron wavelength (Å).
semiconvergence_angle (float) – Probe semiconvergence angle (rad).
fov_shape ((int, int) or None) – Extent
(NY_fov, NX_fov)of an object that has to FIT inside the simulation grid: a finite specimen, a reconstructed volume, or anything scanned with a non-periodic crop. Raises iff * pixels < FOV.Nonefor a PERIODIC specimen under a periodic crop: theNgrid is then the crystal itself and a window leaving it wraps onto the next cell, so there is nothing to fit – which is what lets PRISM atf = 1scan at all.device (torch.device or str) – Device the SMeta tensors are built on.
n_radial (int or None) – Partitioned-PRISM knob.
None(the default) -> pure PRISM: every f-lattice beam is its own parent (the behavior below). When set, after the pure full-aperture SMeta is built it is replaced bySMeta.make_beamlet_meta(n_radial, n_angular), which selectsBp << Bparent beams onn_radial(+ DC) hex rings and builds the Voronoi natural-neighbor weights(B, Bp)+ beamlet basis(Bp, MY, MX).n_angular (int) – Beamlet hex-ring angular sample count passed through to
SMeta.make_beamlet_meta()(default 6). Ignored whenn_radial is None.margin (float or None) –
None(the default): the beams are the support of the probe-forming aperture (_geometry.aperture_support), i.e. every Fourier coefficient the probe has. A number selects the legacy disk|k| <= margin * alpha / lambdainstead, which truncates the aperture’s soft edge when the aperture is small in pixels (it was hard-coded at 1.05); kept for the reconstruction model’sprism_spec["aperture"] = "kmax_margin".
- Returns:
When
n_radial is None: a pure-PRISM SMeta on theNgrid with an f-lattice BF-disk aperture, identity natural-neighbor weights and one-hot beamlets. Whenn_radialis set: the partitioned SMeta (parent-beam subsetBp << B, Voronoi NNW(B, Bp), beamlets(Bp, MY, MX)).- Return type:
- Raises:
ValueError – If
f * pixels < FOV(object does not fit) – the message tells the caller to increasepixelssof * pixels >= scan_extent + detector.
- scatterem.nn.scan_exit_wave.build_prism_smeta_for_probe(*, probe: Tensor, pixels: tuple[int, int], f: int, dx, wavelength: float, semiconvergence_angle: float, fov_shape: tuple[int, int], device, power_fraction: float = 0.9999, n_radial: int | None = None, n_angular: int = 6) SMeta#
Power-based f-lattice-shell PRISM
SMetafrom the probe (faithful PRISM).Sizes the BF-disk aperture from the incoherent multi-mode probe power spectrum instead of the fixed
kmax*1.05margin ofbuild_prism_smeta(). The f-lattice only has beams at everyf-th N-grid frequency pixel, so the candidate aperture radii are the f-lattice shells{0, f*dk, 2f*dk, ...}(dk = 1/(N*dx)). The chosen radius is the SMALLEST shell whose cumulative power reachespower_fractionof the total, floored at ``kmax*1.2`` so the aperture is never tighter than 1.2x the convergence angle. This captures the soft (tanh) probe-edge tail the fixed margin truncates – the too-tight-aperture footgun for f-lattice PRISM (Ophus 2017).Self-contained and reusable by both the reconstruction and simulation paths (everything is taken from the explicit arguments, like
build_prism_smeta()).- Parameters:
probe (Tensor) – Complex real-space probe of shape
(Nmodes, MY, MX)on theN = f*pixelsgrid. The incoherent power spectrumP(k) = sum_m |FFT(probe[m])|^2(sum over the mode axis) drives the aperture sizing. A single-mode(1, MY, MX)probe is fine.pixels ((int, int)) – Detector window
(P_y, P_x); the sim grid isN = f*pixels.f (int) – PRISM interpolation factor (
>= 1).dx (array-like (2,)) – Real-space pitch
Delta pper axis (Aa), UNCHANGED byf.wavelength (float) – Electron wavelength (Aa).
semiconvergence_angle (float) – Probe semiconvergence angle (rad).
kmax = semiconvergence_angle / wavelengthsets thekmax*1.2floor.fov_shape ((int, int)) – Object FOV
(NY_fov, NX_fov). Raises iff*pixels < FOV.device (torch.device or str) – Device the SMeta tensors are built on.
power_fraction (float) – Target cumulative incoherent-power fraction the aperture must enclose (default
0.9999– 99.99%).n_radial (int or None) – Partitioned-PRISM knob, forwarded to
SMeta.make_beamlet_meta(None-> pure PRISM).n_angular (int) – Beamlet hex-ring angular sample count (default 6). Ignored when
n_radial is None.
- Returns:
The f-lattice BF-disk SMeta at the power-chosen radius (pure, or partitioned when
n_radialis set), enclosing>= power_fractionof the incoherent probe power and never tighter thankmax*1.2.- Return type:
- Raises:
ValueError – If
f*pixels < FOV(object does not fit), or the probe grid does not matchN = f*pixels.
Propagation#
Fresnel/angular-spectrum single-slice propagator for multislice simulation. |
|
Fourier-domain sub-pixel shift of a batch of probe wave fields. |
- class scatterem.nn.modules.Propagator(slice_thickness: float, wavelength: float, dx: float | Sequence[float] | ndarray, shape: tuple | Size | ndarray, device: str | device | None = 'cpu', method: str = 'angular_spectrum', tilt: Sequence[float] | None = None)#
Fresnel/angular-spectrum single-slice propagator for multislice simulation.
Precomputes a
(MY, MX)transfer-function phase ramp for propagating a wave field byslice_thicknessand applies it inforward()via an FFT round-trip. The ramp is built bypropagator_kernel()(paraxial) orangular_spectrum_kernel()(exact).- Parameters:
slice_thickness (float) – Propagation distance per slice, in the same length units as
dx.wavelength (float) – Electron wavelength, in the same length units as
dx.dx (float or Sequence of float or numpy.ndarray) – Real-space pixel size, scalar or per-axis.
shape (tuple or torch.Size or numpy.ndarray) – Simulation grid shape
(MY, MX).device (str or torch.device or None, optional) – Device to build the phase ramp on.
method (str, optional) –
"angular_spectrum"/"asm"(exact, default) or"fresnel"/"paraxial"(paraxial approximation).tilt (Sequence of float or None, optional) – Global crystal tilt
(theta_y, theta_x)in RADIANS (adaptive propagator ptychography, Sha et al. 2022). Multipliespropbyexp(+2*pi*i * dz * (qy*tan(theta_y) + qx*tan(theta_x))): the wave is translated by-dz*tan(theta)per slice, i.e. the object’s columns advance by+dz*tan(theta)per slice relative to the beam. Only the physical kernelpropcarries it; the reference-planefresnel_kernel()/fresnel_phase()stay untilted.Noneor all-zero leavespropbit-identical.
- class scatterem.nn.modules.SubpixShift(probe_shape: tuple | Size, device: str | device | None, subpix_shift: bool, rdtype: dtype = torch.float32)#
Fourier-domain sub-pixel shift of a batch of probe wave fields.
Shifts each wave by a per-position fractional offset
drvia a linear phase ramp applied in the Fourier domain, so probe positions need not land on integer detector pixels.- Parameters:
probe_shape (tuple or torch.Size) – Probe tensor shape
(a, b, MY, MX); only the detector-plane dimensions(MY, MX)are used to build the frequency ramps.device (str or torch.device or None) – Device to build the frequency-ramp buffers on.
subpix_shift (bool) – Whether
forwardapplies the sub-pixel shift; if False,forwardonly broadcastswavesto the batch of positions.rdtype (torch.dtype, optional) – Real dtype of the stored frequency ramps. Default is
torch.float32.
Slice transmission in ptychography#
One multislice transmission + (optional) propagation step. |
- scatterem.nn.ptychography.multislice_transmit_slice(sample_patches: Tensor, waves: Tensor, propagator: Propagator | None, inverse_index: Tensor | None = None, gather_index: Tensor | None = None) Tensor#
One multislice transmission + (optional) propagation step.
Module-level so every
MultisliceScanOproute shares the EXACT same per-slice routine.- Parameters:
sample_patches (Tensor) – Per-slice transmission. When inverse_index is given this is the ungathered per-unique-pixel (exponentiated) potential
[U]and the gather + complex multiply is fused in one Warp kernel; otherwise it is already gathered[K, ph, pw]and a plain broadcast multiply is used.waves (Tensor) – Complex exit waves, shape
Nmodes x K x M1 x M2.propagator (Propagator or None) – Fresnel propagator, or
Noneto skip inter-slice propagation (last slice in a stack / single-slice degenerate case).inverse_index (Tensor, optional) – Per-pixel -> unique-pixel map, shape
[K, ph, pw], for the fused Warp transmit path.gather_index (Tensor, optional) – The same map for the torch route:
sample_patchesis then the ungathered[U]slice and is expanded HERE, one slice at a time, so no(NZ, K, ph, pw)copy of the transmission stack ever exists.
- Returns:
Complex exit waves, shape
Nmodes x K x M1 x M2.- Return type:
Tensor
Beamlet sampling#
Select PRISM beam coordinates closest to a polar sampling pattern. |
|
Interpolation weights of |
|
Build the +-1 checkerboard that is an fftshift in the conjugate domain. |
- scatterem.utils.stem.beamlet_samples(beam_mask: ArrayLike, radius: float, n_angular_samples: int = 6, n_radial_samples: int = 3) ndarray#
Select PRISM beam coordinates closest to a polar sampling pattern.
Builds a set of target points on concentric rings (plus the origin) and, for each target, picks the nearest actual beam coordinate present in beam_mask.
- Parameters:
beam_mask (array_like) – Boolean (or 0/1) FFT-shifted mask of shape
(M, M)selecting which Fourier-space beams are available.radius (float) – Outer radius, in pixel units, of the polar sampling pattern.
n_angular_samples (int, optional) – Number of angular samples on the innermost ring; later rings use a proportionally larger count. Default is 6.
n_radial_samples (int, optional) – Number of radial rings (including the origin). Default is 3.
- Returns:
Integer
(y, x)beam coordinates closest to each polar sample point, with shape(n_samples, 2).- Return type:
- scatterem.utils.stem.natural_neighbor_weights(known_points, interp_points, minimum_weight_cutoff=0.01, method='linear', device=None)#
Interpolation weights of
interp_pointson the sitesknown_points.Every row is a partition of unity over the sites, exact at a site, and a point outside the sites’ convex hull takes weight 1 on its nearest site.
- Parameters:
known_points ((B_S, 2) ndarray) – X, y-coordinates of observations.
interp_points ((B, 2) ndarray) – Coordinates of the grid points at which to calculate the interpolation.
minimum_weight_cutoff (float, optional) – Delete weights smaller than this cutoff. Default is 1e-2. Not applied by
"sibson", which keeps every weight: dropping the small ones perturbs every other weight in the row and buys nothing.method ({"linear", "sibson"}, optional) –
"linear"(default) is the vectorised Delaunay-barycentric interpolation (_linear_barycentric_weights()): orders of magnitude faster than the Sibson loop, with the same partition-of-unity / exact-at-parents / nearest-fallback contract (piecewise-linear C0 rather than Sibson’s C1)."sibson"is natural-neighbour (area-stealing) interpolation,scatterem.utils.stem._sibson– smooth (C1), exact at the parents, and the scheme partitioned PRISM is named after.device (str or torch.device, optional) – Only used by
method="sibson": a CUDA device runs its Warp kernel there (2.5-4x faster, same weights to ~4e-15);None(default) or a CPU device runs NumPy. Pass it when the caller is already on the GPU.
- Returns:
Weights for interpolating the grid locations from the B_S sampled points.
- Return type:
(B, B_S) ndarray
- scatterem.utils.stem.fftshift_checkerboard(ny: int, nx: int) ndarray#
Build the +-1 checkerboard that is an fftshift in the conjugate domain.
Multiplying a field by
-(-1) ** (i + j)shifts its transform by half the grid along both axes. That is a +-1 pattern only for EVEN sizes (an odd axis would need the complex rampexp(-2 pi i k (n // 2) / n)), so odd sizes are refused here rather than answered with the wrong pattern.- Parameters:
- Returns:
(ny, nx)array of alternating-1/+1values,-1at[0, 0].- Return type:
- Raises:
ValueError – If either size is odd.
Notes
Shapes are
(ny, nx)here as everywhere else. Until 2026-09-18 the signature was(w, h)returning(h, w)while every caller passed(ny, nx), so a non-square probe grid raised a broadcast error.
Free-space propagation and probe shifts#
|
|
One Fresnel propagation step (FFT · kernel · IFFT). |
|
Fresnel free-space propagator |
|
Unwrapped free-space phase |
|
Exact angular-spectrum free-space propagator |
|
Free-space phase |
|
Per-slice phase |
- scatterem.physics.propagation.fourier_shift_stack(waves: Tensor, shifts: Tensor, phase_bytes: int = 134217728) Tensor#
physics.fourier.fourier_shiftfor many shifts ->(P, *waves.shape).Bitwise-identical to
torch.stack([fourier_shift(waves, s) for s in shifts])and much cheaper, for two reasons that have nothing to do with vectorised arithmetic:fourier_shiftreads each entry of a host shift withfloat(), so a loop over a scan on the GPU pays two device syncs per position – 2P pipeline stalls before any physics happens. Here the shifts stay on the device and there are none.the loop recomputes
fft2(waves)once per position; it is the same tensor every time, so it is hoisted.
Bitwise equality is why this is safe to drop in: the ramp is the same float64 elementwise arithmetic (a broadcast multiply against
(P,1,1)shifts gives the same products as a scalar multiply per position), and cuFFT’s batched 2-D transform is bitwise independent per batch element – both verified over the scan geometries this path uses, not assumed.The ramp is complex128 at
(chunk, ny, nx), so it is chunked tophase_bytesrather than built for all P at once; the output is preallocated instead oftorch.stack-ing a list, which halves the peak the loop form needed. The transform then writes into that preallocation viaout=: assigning its result without[a:b] = ifft2(...)allocates the whole chunk a second time and copies it, which is 6.9 % of this call at the shapes a scan uses.fftfreqcomes from_fftfreq_f64’s memo because it is a constant of the shape and this function is called once per scan batch (32 times per image on the benchmark), another 1.9 %.wq = fft2(waves)is constant per probe across those same calls, but hoisting it needs a cache keyed on tensor identity and lifetime, and it is measured at only 1.2 % – left alone deliberately.It is written as
polar(1, u)rather thanexp(-2j*pi*t)because the two are the same bits and the second is strictly more work: the exponent’s real part is-0.0for every element, so a complexexpspends one of its three float64 transcendentals computingexp(-0.0) == 1.0and then multiplying by it, and the-2j*pi*toperand has to be materialised as a complex128 plane (32 B/element) to say so.polartakes the float64 angle directly and calls onlycos/sin– which is whatexpreduces to here – so the identity is exact, not approximate: verifiedtorch.equalover the real scan, integer +-300 px, random fractional, zero and 1e-9 shifts, into complex64 and complex128 (0 differing float32 words of 4.2 M each). Do NOT go further and factor the ramp asexp(-2j*pi*ky*sy) * exp(-2j*pi*kx*sx): separability is nearly exact and moves 1.3e5 float32 words on this scan, which breaks the sha256 contracts ther7_eelstarget is gated on.On CUDA at complex64 the whole ramp is one Warp kernel instead (
_ramp_fused.ramp_phase_fused), which is bit-exact and 1.47x on a probe-build benchmark. The four eager passes above write 72 bytes per element to produce 8, but that traffic is NOT what the kernel is buying:polaris bound by double-precisionsin/cos, not by memory (measured,cos(u)alone 0.1556 ms +sin(u)alone 0.1546 ==polar’s 0.300), and a fused kernel that merely deletes the other three passes is worth only 1.029x. What pays is thatsincos()performs ONE Payne-Hanek argument reduction for the pair where two separate calls perform two – and at the angles a scan uses (|u|up to 804, the shifts being hundreds of pixels) that reduction is the expensive half. See_ramp_fused.py, whose docstring names the three spellings that keep it bit-exact and the reason the launch needs an explicitstream=. The kernel that runs is the certified float-float one in_ramp_df.py, with the same bits. On the single-chunk power-of-two route with 2-Dwaves, that kernel also applieswq *before its store, again with the same bits.ifft2’s own1/Nnormalisation is torch’s, not cuFFT’s – the C2C plan is unnormalised, sonorm="backward"(the default) is paid as a separate full-size pass over the(chunk, ny, nx)output. On this row that pass is 1.63 ms = 11.8 % of the whole device time and it exists only to multiply by a constant. Whenny*nxis an exact power of two,1/Nis an exponent decrement, so it commutes bit-for-bit with every multiply and add in the transform and can ride onwq– ONE small(ny, nx)plane per call – leaving the inverse unnormalised. Two things are load-bearing and neither works alone (both measured; 0.995x and 1.001x respectively):the fold needs the
out=to go, because torch fuses the normalisation into the out-variant’s copy, sonorm="forward"on its own merely turns a fused scalar-multiply into a plaincopy_of the same 2 x 16 MiB;dropping
out=needs the fold, because without it the normalisation pass is still there, just writing into a fresh allocation instead of a slice.
Together they are 1.124x on this row (and drop its peak 561 -> 545 MiB, the preallocation no longer existing), re-measured over six alternating separately-launched arms; the
smallandfinerows are a sub-bar 1.7 % and 3.8 %, same sign, and carry no claim. Only the single-chunk case takes it – which is every caller in this package at every registered size,chunkbeing 128 against a scan batch of 32 – because a multi-chunk call still needs the preallocation and the fold buys nothing there. The power-of-two test is an exactness condition, not a tuned one: at a non-power-of-twoNthe pre-scaling rounds where the post-scaling did not, which would move the sha256 contractsr7_eelsis gated on. Verified as bytes over the real scan: 0 of 134 217 728 int32 words differ. (The one regime it would not be exact in is|fft2(waves)| < 2^-126 * N~ 8e-34, where the scaled plane goes subnormal; a normalised wave function is 24 orders of magnitude clear of that –min|wq|is 6.3e-10 on this row – and testing for it would cost a device sync per call, i.e. more than the pass being removed.)- Parameters:
waves (Tensor) – Complex real-space waves
(..., ny, nx).shifts (Tensor) –
(P, 2)shifts(sy, sx)in pixels, on any device.phase_bytes (int, optional) – Byte budget of one complex128 ramp chunk (default
1 << 27).
- Returns:
(P, *waves.shape):wavesshifted by each row ofshifts.- Return type:
Tensor
- scatterem.physics.propagation.propagate(waves: Tensor, kernel: Tensor) Tensor#
One Fresnel propagation step (FFT · kernel · IFFT).
For a large beam stack (the un-tiled 20 nm S-walk: (Bp, MY, MX) ~27 GB) the naive round-trip holds
waves+ the FFT result + the IFFT result (~3x27 GB) -> OOM on 80 GB. Beam-chunk the round-trip IN PLACE so only one chunk’s FFT transient is live. The 2-D FFT is independent per beam (fft2(waves)[b] == fft2(waves[b])), so the chunked in-place result is byte-identical to the single call. In-place is gated to the no-grad (forward-sim) path; recon keeps the out-of-place round-trip.The inverse transform runs UNNORMALISED (
norm="forward") with the1/(MY*MX)folded into the propagator instead: torch applies the defaultnorm="backward"as a separate full-tensor rescale of the (B, MY, MX) result, whereas riding on the kernel costs one pass over a single (MY, MX) plane – and, via_scaled_propagator()’s memo, only on the first call for a given propagator rather than on every slice. This step is memory-bandwidth-bound (the broadcast multiply alone runs at 87.6 % of this card’s peak), so that removed pass is ~16 % of it. Deliberately NOT folded intopropagator_kernel: that is public API, and_detector_exit._conj_propagatenormalises its own inverse transform with the same kernel.Do NOT try to fold this round trip onto
waveswithout=. Bothtorch.fft.fft2(w, out=w)andout=into a distinct buffer are bit-exact, but torch’s CUDA out-variant transforms into a fresh allocation and copies intoout, so each one costs a full extra read+write of the stack: at ther7_eels/wide/conventionalshape (2048 x 192 x 192 complex128, 1152 MiB) the round trip goes 37.5 -> 41.3 ms for oneout=and 44.9 for two, and the row goes 710.6 -> 914.5 ms.- Parameters:
waves (Tensor) – Complex real-space waves
(..., MY, MX). A 3-D stack outside autograd is transformed IN PLACE and returned; otherwise a new tensor is.kernel (Tensor) – Fresnel propagator
(MY, MX)for one step (seepropagator_kernel()), corner origin.
- Returns:
The propagated waves, same shape and dtype as
waves.- Return type:
Tensor
- scatterem.physics.propagation.propagator_kernel(gpts: Sequence[int], gridsize: Sequence[float], wavelength: float, dz: float, device=None, dtype: dtype = torch.complex64) Tensor#
Fresnel free-space propagator
exp(-i π λ Δz |q|²)(corner origin).- Parameters:
gpts (sequence of int) – Grid size (Ny, Nx).
gridsize (sequence of float) – Real-space grid extent (Ly, Lx), in Angstrom.
wavelength (float) – Electron wavelength, in Angstrom.
dz (float) – Propagation distance, in Angstrom.
device (torch.device, optional) – Device of the returned tensor. Default is None (current device).
dtype (torch.dtype, optional) – Output complex dtype. Default is torch.complex64.
- Returns:
Fresnel propagator, shape (Ny, Nx), corner-origin reciprocal grid.
- Return type:
Tensor
- scatterem.physics.propagation.propagator_phase(gpts: Sequence[int], gridsize: Sequence[float], wavelength: float, dz: float, method: str = 'fresnel', device=None) Tensor#
Unwrapped free-space phase
phiwithkernel = exp(1j * phi).- Parameters:
gpts (sequence of int) – Grid size (Ny, Nx).
gridsize (sequence of float) – Real-space extent (Ly, Lx), in Angstrom.
wavelength (float) – Electron wavelength, in Angstrom.
dz (float) – Propagation distance, in Angstrom (may be fractional or negative).
method (str, optional) –
"fresnel"/"paraxial"or"angular_spectrum"/"asm".device (torch.device, optional) – Device of the returned tensor.
- Returns:
Real float64 phase in radians, shape (Ny, Nx), corner origin.
- Return type:
Tensor
- scatterem.physics.propagation.angular_spectrum_kernel(gpts: Sequence[int], gridsize: Sequence[float], wavelength: float, dz: float, device=None, dtype: dtype = torch.complex64) Tensor#
Exact angular-spectrum free-space propagator
exp(i dz (kz - k)).- Parameters:
gpts (sequence of int) – Grid size (Ny, Nx).
gridsize (sequence of float) – Real-space extent (Ly, Lx), in Angstrom.
wavelength (float) – Electron wavelength, in Angstrom.
dz (float) – Propagation distance, in Angstrom.
device (torch.device, optional) – Device of the returned tensor.
dtype (torch.dtype, optional) – Output complex dtype. Default is torch.complex64.
- Returns:
Transfer function, shape (Ny, Nx), corner-origin reciprocal grid. In the evanescent band (
|q| > 1/lambda)kzis clamped to zero, so the kernel there isexp(-i k dz): a constant phase with no decay.- Return type:
Tensor
- scatterem.physics.propagation.transfer_phase(q2: Tensor, wavelength: float, dz: float, method: str = 'fresnel') Tensor#
Free-space phase
phi(|q|^2)of a propagation bydz.- Parameters:
- Returns:
Phase in radians, shape, dtype and device of
q2; the transfer function isexp(1j * phi).- Return type:
Tensor
- Raises:
ValueError – If
methodis unknown.
- scatterem.physics.propagation.tilt_phase(q: Tensor, slice_thickness: float | Tensor, tilt: Sequence[float] | Tensor) Tensor#
Per-slice phase
2*pi*dz*(qy*tan(theta_y) + qx*tan(theta_x))[rad].- Parameters:
q (torch.Tensor) –
(2, Ny, Nx)spatial frequencies(qy, qx)in 1/length, as returned byscatterem.physics._frequency_grid.fft_frequency_grid().slice_thickness (float or torch.Tensor) – Propagation distance per slice, in the length units of
1/q.tilt (Sequence of float or torch.Tensor) –
(theta_y, theta_x)in radians; a tensor keeps the autograd graph.
- Returns:
Real
(Ny, Nx)phase, corner origin.- Return type:
Grids#
Return the DFT sample frequencies of a 2-D grid, both components. |
|
Return the mean of a spectrum over shells of constant |
|
Shell frequencies and shell means of a spectrum. |
- scatterem.utils.spectral_mesh.dual_mesh(n_yx: Any, pitch: Any, *, staggered: bool, dtype: dtype | None = None, device: device | str | None = None) Tensor#
Return the DFT sample frequencies of a 2-D grid, both components.
The frequencies of a sampled field form the dual (reciprocal) lattice of its sampling lattice. Each value is computed in exact rational arithmetic and then rounded once to the output dtype.
- Parameters:
n_yx (sequence of int) – The number of grid points
(Ny, Nx). Each count is a positive integer.pitch (float or sequence of float) – The real-space pitch
(d_y, d_x)[length]. One number applies to both axes. There is no default: give 1.0 for frequencies in cycles per sample.staggered (bool) – If True, add half of the frequency step to each axis:
1 / (2 Ny d_y)and1 / (2 Nx d_x). Use it for samples that sit midway between the grid points. Give False for the standard DFT grid. There is no default.dtype (torch.dtype, optional) –
torch.float32ortorch.float64. The default istorch.get_default_dtype().device (torch.device or str, optional) – The device of the result. The default is the CPU.
- Returns:
Shape
(2, Ny, Nx)[1/length], in FFT order. Entry[0, i, j]is theyfrequency of rowiand entry[1, i, j]is thexfrequency of columnj. Entry 0 holds the y frequencies and entry 1 the x frequencies. Usetorch.fft.fftshift(out, dim=(-2, -1))to centre it.- Return type:
- Raises:
TypeError – If a count is not an integer, a pitch is not a real number, or the dtype is not float32 or float64.
ValueError – If a count is smaller than 1, the number of pitches is not 2, or a pitch is not finite and positive.
- scatterem.utils.spectral_mesh.shell_means(spectrum_samples: Any, pitch: Any) ShellMeans#
Return the mean of a spectrum over shells of constant
|q|.Each sample has the frequency
|q| = sqrt(q_0^2 + q_1^2 + ...)from the DFT frequencies of its axes (seedual_mesh). The shells are equally spaced in|q|with the spacingD = max_a 1 / (N_a d_a), the coarsest frequency step. Shellkis atq_k = k D.A sample at
|q| = x Dwithk0 = floor(x)andt = x - k0gives the weight(1 - t) Jto shellk0andt Jto shellk0 + 1(linear interpolation). The factorJ = (D / |q|)^(n - 1)fornaxes cancels the growth of the number of samples with|q|, so the effective weight in|q|is a symmetric tent aboutq_k. The bias for a smoothf(|q|)is then aboutf''(q_k) D^2 / 12. The sample at|q| = 0gives the weight 1 to shell 0. The shell mean issum w v / sum w, so it is linear in the values and a constant array gives that constant.Outer limit:
q_limis the smallest of the largest positive axis frequencies,min_a floor((N_a - 1) / 2) / (N_a d_a). The output holds the shellskwith(k + 1) D <= q_lim: every shell in the output has all of its support inside the grid. The largest shell frequency is thus in[q_lim - 2 D, q_lim - D].- Parameters:
spectrum_samples (numpy.ndarray or torch.Tensor) – Real or integer array with two or more axes, in FFT order on every axis (zero frequency at the first element), for example
abs(torch.fft.fftn(x)) ** 2. A tensor can be on any device.pitch (float or sequence of float) – The real-space pitch of each axis [length], or one value for all axes. There is no default: give 1.0 for frequencies in cycles per sample.
- Returns:
(shell_wavenumber, shell_average): two new NumPy float64 arrays of equal length.shell_wavenumberis in [1/length].- Return type:
- Raises:
TypeError – If
spectrum_samplesis complex, bool or not an array, or a pitch is not a real number.ValueError – If
spectrum_sampleshas fewer than two axes, an axis has fewer than 3 points,spectrum_samplesholds NaN or infinite values, the number of pitches is wrong, or a pitch is not finite and positive.
- class scatterem.utils.spectral_mesh.ShellMeans(shell_wavenumber: np.ndarray, shell_average: np.ndarray)#
Shell frequencies and shell means of a spectrum.
- Parameters:
shell_wavenumber (numpy.ndarray) – Shape
(K,), float64. The frequency of each shell [1/length], equally spaced and increasing, starting at 0.shell_average (numpy.ndarray) – Shape
(K,), float64. The weighted mean of the samples of each shell, in the unit of the input values.
Visualisation#
Show 2D data as one panel or as a grid of panels. |
|
Draw panels into a grid of axes and return the figure and the axes. |
- scatterem.vis.visualization.show_2d(array, *, sampling=None, scalebar='auto', figax=None, axsize=(4, 4), tight_layout=True, combine_images=False, clip_percentile: tuple[float, float] | None = None, max_display_pixels: int | None = None, style: str | None = None, **kwargs)#
Show 2D data as one panel or as a grid of panels.
The input can be a numpy array, a torch tensor, or a list (or a list of lists) of them. A tensor goes to the CPU and becomes a numpy array. A 3D array is a stack: each slice gets a panel. The scale bar uses
sampling; without it, the.sampling_metaof the input if it has one; else the bar reads1 a.u..- Parameters:
array (numpy.ndarray or torch.Tensor or sequence) – The data. A list gives one row of panels; a list of lists gives rows.
sampling (Sampling or dict, optional) – Pixel size and units (a
Samplingor a dict of its fields). Default is None: usearray.sampling_metaif it exists.scalebar ("auto", bool, dict, or ScalebarConfig, optional) –
"auto"draws a calibrated bar when the sampling allows it. False or None still draw a bar, the “1 a.u.” bar. Default is “auto”.figax (tuple, optional) –
(fig, axes)to draw into;axesmust match the panel grid. Default is None, which makes a new figure.axsize (tuple of int, optional) – Width and height in inches of one panel of a new figure. Default is (4, 4).
tight_layout (bool, optional) – Call
fig.tight_layout()at the end. Default is True.combine_images (bool, optional) – Blend one row of arrays into a single image, one hue per array. Default is False.
clip_percentile (tuple of float, optional) –
(low, high)percentiles (0-100) used to set each array’s display vmin/vmax. A centred role keeps limits symmetric about its centre. A cyclic role ignores it and warns. Default is None.max_display_pixels (int or None, optional) – The most pixels shown along either image axis. Larger images are block-averaged by one integer factor (no aliasing); every scale-bar sampling follows, and ticks and overlays use display pixels.
None(the default) shows every pixel.style ({"screen", "paper"}, optional) – Draw with the text and line sizes of
show(style=...)(figure_params()). The axes offigaxget the tick, axis-label and spine sizes too. Save the figure insideuse_style(style=...): the dpi, the PDF font type and the font are read when the figure is saved or drawn.**kwargs – Forwarded to
show_2d_array(). Common keys:role(kind of data, e.g. “intensity” (default), “signed”, “angle”; sets colour map and limits),background(“light” or “dark”),cmap(overrides the role’s map) andcbar(colour bar; default True).
- Returns:
fig (matplotlib.figure.Figure) – The figure that holds the panels.
axs (matplotlib.axes.Axes or numpy.ndarray of matplotlib.axes.Axes) – One Axes for one panel. A 1D array for a single row or column of panels, and a 2D array for a grid.
- scatterem.vis.visualization.show_2d_array(arrays: NDArray | Sequence[NDArray] | Sequence[Sequence[NDArray]], *, figax: tuple[Any, Any] | None = None, axsize: tuple[int, int] = (4, 4), tight_layout: bool = True, combine_images: bool = False, scalebar: Any = 'auto', sampling: Sampling | None = None, scalebar_panel: Any = 'first', clip_percentile: tuple[float, float] | None = None, **kwargs: Any) tuple[Any, Any]#
Draw panels into a grid of axes and return the figure and the axes.
show_2d()converts and bounds its input, then calls this function. Each panel is drawn by_show_2d. Withcombine_images, the one row of panels is blended into one image by_show_2d_combinedinstead.- Parameters:
arrays (ndarray or sequence of ndarray or sequence of sequences of ndarray) – One 2D array, a 3D stack (one panel per slice), a list (one row), or a list of lists (one row per inner list; rows can be short).
figax (tuple, optional) –
(fig, axes)to draw into.axesis one Axes or a numpy array of them, with the shape of the panel grid (a 1D array counts as one row). Default is None, which makes a new figure.axsize (tuple, default=(4, 4)) – Width and height in inches of one panel of a new figure.
tight_layout (bool, default=True) – Call
fig.tight_layout()after drawing.combine_images (bool, default=False) – Blend a single row of arrays into one image, one hue per array. Only
norm,cmap,chroma_boost,cbarandfigsizeare accepted inkwargsthen.scalebar ("auto", bool, dict, or ScalebarConfig, default="auto") – The scale bar of the panels that
scalebar_panelselects.sampling (Sampling, optional) – Pixel size and units for the scale bar and the colour-bar unit.
scalebar_panel ("first", "all", or int, default="first") – Panels with a bar: the first, all, or the one at this flat index (row by row).
clip_percentile (tuple of (float, float), optional) –
(low, high)percentiles (0-100). Each panel then gets the limits of these percentiles of its own finite values (the modulus, for complex data), as a manual interval. It replacesnorm.**kwargs (dict) – Passed to every panel, for example
norm,cmap,roleorcbar.titleis special: one string for all panels, a flat list (row by row), or a list of lists.
- Returns:
fig (Figure) – The figure that holds the panels.
axs (Axes or ndarray of Axes) – One Axes for a 1 x 1 grid, a 1D array for one row or one column, and a 2D array otherwise.
- Raises:
ValueError – If the axes of
figaxdo not have the grid shape, or ifcombine_imagesgets several rows or a per-panel keyword.NotImplementedError – If
combine_imagesis used withcbar=True.
EELS radial states#
Resolve a |
|
Normalised hydrogenic bound state on a uniform grid. |
|
Free continuum state, normalised per Rydberg. |
- scatterem.simulation.eels.physics.radial.resolve_wavefunctions(wavefunctions: str) str#
Resolve a
wavefunctionschoice to"gpaw"or"hydrogenic".- Parameters:
wavefunctions (str) –
"auto","gpaw"or"hydrogenic"."auto"resolves to"gpaw"when GPAW is importable, else to"hydrogenic"with aHydrogenicFallbackWarning.- Returns:
"gpaw"or"hydrogenic".- Return type:
- Raises:
ValueError – If
wavefunctionsis not one of the three choices.
- scatterem.simulation.eels.physics.radial.hydrogenic_bound_wavefunction(Z: int, n: int, l: int, n_points: int | None = None, rmax: float = 40.0) AtomicRadialWavefunction#
Normalised hydrogenic bound state on a uniform grid.
With
rho = 2 Z r / n,R_nl = N rho^l exp(-rho/2) L^(2l+1)_(n-l-1)(rho)andN = sqrt((2Z/n)^3 (n-l-1)! / (2n (n+l)!)), whereLis the generalised Laguerre polynomial withL^(a)_k(0) = binom(k+a, k). The energy is-Z^2/(2 n^2)Hartree.The default grid has at least 4000 points and at least 10 points per orbital length
n / ZBohr, so a heavy K shell is sampled as finely as a light one.- Parameters:
Z (int) – Effective nuclear charge.
n (int) – Principal quantum number.
l (int) – Orbital angular-momentum quantum number, must satisfy
0 <= l < n.n_points (int, optional) – Number of samples on the radial grid
linspace(0, rmax, n_points).None(default) chooses it fromZ / nas described above.rmax (float, optional) – Outer edge of the radial grid, in Bohr.
- Returns:
The normalised hydrogenic bound state
u(r) = r * R_nl(r).- Return type:
- Raises:
ValueError – If
lis not in0 <= l < n.
- scatterem.simulation.eels.physics.radial.free_continuum_wavefunction(l: int, epsilon: float, n_points: int = 8000, rmax: float = 60.0) AtomicRadialWavefunction#
Free continuum state, normalised per Rydberg.
u(r) = (pi k)^(-1/2) k r j_l(k r), withk = sqrt(epsilon / Ry)in 1/Bohr. Far outu -> (pi k)^(-1/2) sin(k r - l pi/2), soint u_E u_E' dr = delta(E - E')withEin Ry (Manson 1972).- Parameters:
l (int) – Orbital angular-momentum quantum number of the continuum state.
epsilon (float) – Energy above the ionization threshold, in eV. Must be > 0.
n_points (int, optional) – Number of samples on the radial grid
linspace(0, rmax, n_points).rmax (float, optional) – Outer edge of the radial grid, in Bohr.
- Returns:
The free spherical-Bessel continuum state
u_l(r), units Bohr^(-1/2) Ry^(-1/2).- Return type:
- Raises:
ValueError – If
epsilon <= 0.
Crystal phases#
One crystalline phase: a general cell and its P1 sites (immutable). |
- class scatterem.crystal.phase.Phase(cell, fractional, element_z, *, site_fraction=None, msd=None, adp=None, name: str = '', point_group: str | None = None)#
One crystalline phase: a general cell and its P1 sites (immutable).
- Parameters:
cell (array_like) – Shape
(3, 3), any real dtype, Angstrom. The cell edge vectors as rows; any orientation, orthogonal or oblique, right- or left-handed.fractional (array_like) – Shape
(N, 3), any real dtype. Site positions as fractions of the cell edges (componentialong rowiof cell).Nmay be 0. Kept as given (no wrap).element_z (array_like) – Shape
(N,), integers 1 to 118. Atomic number of each site row.site_fraction (None, float or array_like, optional) –
(N,)or scalar, in [0, 1]. Occupancy of each row; None means full. A mixed site has one row per species, all at the same position. Checked as inAtomSet.msd (None, float or array_like, optional) –
(N,)or scalar, Angstrom^2, >= 0. Isotropic mean-square displacement <u^2> along one direction. None givesDEFAULT_U2.adp (None or array_like, optional) – Shape
(N, 3, 3), Angstrom^2. Symmetric anisotropic displacement tensorsU, Cartesian in the frame of the cell rows. None (default) means isotropic sites (msd only). A structure factor uses a tensor asexp(-2 pi^2 g^T U g).name (str, optional) – Free-form label.
point_group (str or None, optional) – Hermann-Mauguin point-group symbol, if known. No code reads it yet.
- Raises:
ValueError – For a bad argument. The message starts with the argument name.
Notes
The arrays are read-only and every property returns the stored array.
Elements#
Return the atomic number of an element symbol. |
|
Return the abridged standard atomic weight of an element. |
|
Return the chemical symbol of an atomic number. |
- scatterem.crystal.elements.atomic_number(symbol: str) int#
Return the atomic number of an element symbol.
- Parameters:
symbol (str) – Element symbol such as
"Si". Case is normalised ("SI"and"si"are accepted); a numeric string is read as the atomic number.- Returns:
The atomic number.
- Return type:
- Raises:
ValueError – If symbol is not an element symbol.
- scatterem.crystal.elements.atomic_weight(element: str | int) float#
Return the abridged standard atomic weight of an element.
- Parameters:
element (str or int) – Element symbol (any case, as
atomic_number()reads it) or atomic number.- Returns:
The CIAAW 2024 abridged standard atomic weight. Numerically it is the mean atomic mass in u (Da), for example 12.011 for carbon.
- Return type:
- Raises:
ValueError – If element is not an element, or if the element has no standard atomic weight (no stable isotope, for example Tc or Pm).
Fourier helpers#
Build the Fourier phase ramp that shifts a grid of |
|
Shift |
|
Resample |
|
Return the index of the zero frequency in a spectrum of real-space |
|
Return |
|
Apply |
|
Undo |
|
Return the shape of |
- scatterem.physics.fourier.phase_ramp(shape: Sequence[int], shift: Sequence[float] | Tensor, *, rfft: bool = False, dtype: dtype = torch.complex64, ramp_dtype: dtype = torch.float64, device: str | device | None = None) Tensor#
Build the Fourier phase ramp that shifts a grid of
shapebyshift.The ramp is
exp(-2j * pi * (k_0 * s_0 + k_1 * s_1 + ...)), summed in axis order, withk_ithefftfreq(cycles per pixel) of axisi. Multiplying a spectrum by it and transforming back moves the content by+shiftpixels.For real
x,irfftn(rfftn(x) * phase_ramp(x.shape, s, rfft=True), x.shape)equalsfourier_shift(x, s)(up to rounding) only when no axis but the last carries Nyquist content: exactly so on odd grids, on grids even only in the last axis, and for data with nothing in the Nyquist planes of the other axes. On white noise with an even non-last axis the two differ, becausefourier_shift()keeps the real part of a full-spectrum shift there.- Parameters:
shape (sequence of int) – Real-space grid shape
(n_0, ..., n_{D-1}).shift (sequence of float or Tensor) – Shift in pixels: a host sequence of length
D(each entry a float or a 0-d tensor, read withfloat()), or a tensor(..., D)whose leading axes become leading axes of the ramp. A sequence with an entry that requires grad is stacked and takes the tensor path, so gradients flow.rfft (bool, optional) – Build the half spectrum of
torch.fft.rfftn: the last axis hasn_{D-1} // 2 + 1non-negative frequencies. Default False.dtype (torch.dtype, optional) – Complex dtype of the returned ramp. Default
torch.complex64.ramp_dtype (torch.dtype, optional) – Real dtype the phase is computed in before the cast. Default
torch.float64.device (str or torch.device, optional) – Device of the ramp. Default: the shift’s device for a tensor shift (or a stacked sequence), otherwise the CPU.
- Returns:
(..., *shape)ramp (last axisn_{D-1} // 2 + 1whenrfft).- Return type:
Tensor
- Raises:
ValueError – If
shiftdoes not address exactlylen(shape)axes.
- scatterem.physics.fourier.fourier_shift(x: Tensor, shift: Sequence[float] | Tensor, *, ndim: int | None = None, ramp_dtype: dtype = torch.float64) Tensor#
Shift
xbyshiftpixels along its last axes (Fourier shift theorem).Periodic; equals
torch.rollfor whole-pixel shifts up to FFT rounding. For real input, a fractional shift on an even grid loses part of the Nyquist frequency component (the ramp is not Hermitian there, and the real part is returned), so it is not exactly power preserving. A host shift is read withfloat()(a device sync for 0-d CUDA tensors), unless an entry requires grad: then the entries are stacked and take the tensor path. A tensor shift stays on the device and carries gradients. With a batched tensor shift, CPU results equal a per-slice loop only up to floating-point rounding. The rfft routeirfftn(rfftn(x) * phase_ramp(..., rfft=True))agrees with this function for realxonly under the Nyquist conditionphase_ramp()states.- Parameters:
x (Tensor) – Real or complex
(..., n_0, ..., n_{D-1}); the lastDaxes move.shift (sequence of float or Tensor) – Shift in pixels, array order: a host sequence of length
D, or a tensor(..., D)whose leading axes broadcast against the leading axes ofx.ndim (int, optional) – Number of shifted axes
D. Default: inferred fromshift; when given it must agree with it.ramp_dtype (torch.dtype, optional) – Real dtype of the phase ramp before it is cast to the spectrum’s complex dtype. Default
torch.float64.
- Returns:
The shifted array. Complex input keeps its dtype; real floating input returns the real part in its dtype; integer input returns the real part in torch’s default floating dtype.
- Return type:
Tensor
- Raises:
ValueError – If
shiftandndimdisagree,Dexceedsx.ndim, or the leading shapes of a tensor shift andxdo not broadcast.
- scatterem.physics.fourier.fourier_rescale(x: Tensor, sampling_in: Sequence[float], sampling_out: Sequence[float], *, ndim: int | None = None, taper: float | None = None) tuple[Tensor, tuple[float, ...]]#
Resample
xto a new pixel size by cropping or zero-padding its spectrum.This is the anti-aliased down-sampling: every frequency above the new Nyquist frequency is removed, not folded back. A box average (
F.interpolate(mode="area")) folds a crystal lattice above the new Nyquist frequency onto the coarse grid.taperadds a raised-cosine roll-off below the band edge, which removes the ringing of a hard cut.Axis
igetsround(n_i * sampling_in[i] / sampling_out[i])samples (half rounds up). The band-limited interpolant is preserved: up-sampling by an integer factor reproduces the input at the original sample positions, and the mean value is unchanged. Sample 0 stays at the origin (corner convention).- Parameters:
x (Tensor) – Real or complex
(..., n_0, ..., n_{D-1}); the lastDaxes are resampled.sampling_in (sequence of float) – Pixel size of
xper resampled axis.sampling_out (sequence of float) – Requested pixel size per resampled axis.
ndim (int, optional) – Number of resampled axes
D. Defaultlen(sampling_in).taper (float or None, optional) – Width of a raised-cosine roll-off, as a fraction of the band edge (the lower of the two Nyquist frequencies, per axis, on an elliptical radius). The weight is 1 below
1 - taperand 0 at the edge; the DC weight is 1, so the mean stays.None(the default) is a hard cut. The roll-off also applies when no axis changes size.
- Returns:
rescaled (Tensor) – The resampled array; real input gives real output in its dtype, and integer input a floating array (never truncated back to integers). When no axis changes size,
xitself is returned, not a copy.sampling (tuple of float) – The pixel size actually achieved,
n_i * sampling_in[i] / n_out_i; exactlysampling_in[i]on an axis whose size did not change.
- Raises:
ValueError – If the sampling lengths disagree with
ndim,ndimexceedsx.ndim, a sampling is not finite and positive, an axis would get fewer than one sample, ortaperis not in(0, 1].
- scatterem.physics.fourier.dft_center(shape: Sequence[int], *, rfft: bool, fftshifted: bool) tuple[int, ...]#
Return the index of the zero frequency in a spectrum of real-space
shape.- Parameters:
- Returns:
Index of the zero frequency, one entry per axis.
- Return type:
- scatterem.physics.fourier.fftshift_last2(x: Tensor) Tensor#
Return
torch.fft.fftshift(x, dim=(-2, -1)), bit-identical, ONE buffer.Four quadrant copies instead of two rolls: half the memory.
- Parameters:
x (Tensor) – Tensor
(..., ny, nx), e.g. a 4D-STEM cube.- Returns:
New tensor; element
iof the last two dims is at(i + n//2) % n.- Return type:
Tensor
- scatterem.physics.fourier.fftshift_rfft(x: Tensor, ndim: int) Tensor#
Apply
fftshiftto every spatial axis of an rfft spectrum but the last.- Parameters:
x (Tensor) – Half spectrum
(..., n_0, ..., n_{D-1} // 2 + 1).ndim (int) – Number of spatial axes
D.
- Returns:
xwith its zero frequency moved ton_i // 2on axes0 .. D-2.- Return type:
Tensor
- scatterem.physics.fourier.ifftshift_rfft(x: Tensor, ndim: int) Tensor#
Undo
fftshift_rfft().- Parameters:
x (Tensor) – Centred half spectrum
(..., n_0, ..., n_{D-1} // 2 + 1).ndim (int) – Number of spatial axes
D.
- Returns:
xwith its zero frequency back at index 0 on axes0 .. D-2.- Return type:
Tensor
Axis-angle rotations#
Return the matrices of right-handed turns by angle about axis. |
- scatterem.rotation.axis_angle.to_matrix(axis: Tensor, angle: Tensor) Tensor#
Return the matrices of right-handed turns by angle about axis.
- Parameters:
axis (Tensor) – Rotation axes with shape
(..., 3). They need not be unit vectors, but must not be zero.angle (Tensor) – Rotation angles in radians with shape
(...), broadcastable with the batch shape of axis.
- Returns:
Rotation matrices with shape
(..., 3, 3).R @ vturns a column vectorvcounter-clockwise about axis when seen from its tip.- Return type:
Tensor
Notes
Three dtype rules apply, as in
scatterem.rotation.quaternion.from_axis_angle():The output dtype is the type promotion of axis and angle.
sinandcosof the half angle run in the dtype of angle (the default float dtype for an integer angle). A float32 angle with a float64 axis gives a float64 matrix with float32 accuracy.An integer axis is refused:
torch.linalg.vector_normraisesRuntimeError.
The quaternion route agrees with Rodrigues’ formula
cos(angle) I + sin(angle) K + (1 - cos(angle)) u u^Tto a few ulp, but not bit for bit.Examples
>>> import math, torch >>> from scatterem.rotation.axis_angle import to_matrix >>> R = to_matrix(torch.tensor([0.0, 0.0, 1.0]), torch.tensor(math.pi / 2)) >>> torch.allclose(R @ torch.tensor([1.0, 0.0, 0.0]), ... torch.tensor([0.0, 1.0, 0.0]), atol=1e-6) True
Quaternions#
Build the quaternions of right-handed turns about axes. |
|
Convert rotation matrices to quaternions. |
|
Build the unit quaternions of rotation vectors. |
|
Compute the Hamilton product |
|
Convert quaternions to rotation matrices. |
- scatterem.rotation.quaternion.from_axis_angle(axis: Tensor, angle: Tensor) Tensor#
Build the quaternions of right-handed turns about axes.
The quaternion is
(cos(angle / 2), sin(angle / 2) * axis / |axis|). The function multiplies by the sine first and divides by the axis norm after, so a single turn about a coordinate axis has exact bits.- Parameters:
axis (torch.Tensor) – Rotation axes with shape
(..., 3). They need not be unit vectors, but must not be zero.angle (torch.Tensor) – Rotation angles in radians with shape
(...), broadcastable with the batch shape of axis.
- Returns:
Unit quaternions
(w, x, y, z)with shape(..., 4).wis negative for|angle| > pi; the function does not fold the sign.- Return type:
Notes
Three dtype rules apply:
The output dtype is the type promotion of axis and angle.
sinandcosof the half angle run in the dtype of angle (the default float dtype for an integer angle). A float32 angle with a float64 axis gives a float64 result with float32 accuracy.An integer axis is refused:
torch.linalg.vector_normraisesRuntimeError.
- scatterem.rotation.quaternion.from_matrix(m: Tensor) Tensor#
Convert rotation matrices to quaternions.
- Parameters:
m (torch.Tensor) – Rotation matrices with shape
(..., 3, 3).- Returns:
Unit quaternions
(w, x, y, z)with shape(..., 4), withw >= 0.- Return type:
- scatterem.rotation.quaternion.from_rotation_vector(w: Tensor) Tensor#
Build the unit quaternions of rotation vectors.
The rotation is
exp([w]_x): the angle is|w|in radians and the axis isw. The quaternion is(cos(|w| / 2), sin(|w| / 2) w / |w|). The function writessin(|w| / 2) / |w|assinc(|w| / 2 pi) / 2, so it is smooth atw = 0and has a finite gradient there. That is where every gradient refinement of an orientation starts. Unlikefrom_axis_angle(), it accepts the zero vector, which gives the identity(1, 0, 0, 0).- Parameters:
w (torch.Tensor) – Rotation vectors with shape
(..., 3), in radians.- Returns:
Unit quaternions
(w, x, y, z)with shape(..., 4), in the dtype of w.to_matrixof the result is the rotation matrixexp([w]_x).- Return type:
- scatterem.rotation.quaternion.multiply(q1: Tensor, q2: Tensor) Tensor#
Compute the Hamilton product
q1 ⊗ q2.The result applies rotation
q2followed byq1, matching the compositionR1 @ R2of the corresponding rotation matrices.- Parameters:
q1 (torch.Tensor) – Quaternions
(w, x, y, z)with shape(..., 4).q2 (torch.Tensor) – Quaternions
(w, x, y, z)with shape(..., 4), broadcastable with q1.
- Returns:
Hamilton product quaternions with shape
(..., 4).- Return type:
- scatterem.rotation.quaternion.to_matrix(q: Tensor) Tensor#
Convert quaternions to rotation matrices.
- Parameters:
q (torch.Tensor) – Quaternions
(w, x, y, z)with shape(..., 4). Not required to be unit norm; normalized internally.- Returns:
Rotation matrices with shape
(..., 3, 3).- Return type:
Display and animation#
Show |
|
Show |
|
Write |
- scatterem.vis.show(obj: Any, *, panels=None, save=None, style: str = 'screen', width: str | None = None, background: str = 'light', env: str | None = None, block: bool = True, **opts: Any) ShownFigure#
Show
objas a good default figure.- Parameters:
obj (Any) – An array, a dataset, or a scatterem result.
panels (sequence of str, optional) – Panel names to draw, in order. None draws the default figure.
save (str or pathlib.Path, optional) – Also write the figure here (.png, .pdf or .svg).
style ({"screen", "paper"}, default="screen") – Paper is Nature style (89 or 183 mm, 5-7 pt, panel letters).
width ({None, "single", "double"}, optional) – Paper width.
background ({"light", "dark"}, default="light") – Figure background for the colour policy.
env (str, optional) – “marimo”, “jupyter”, “gui”, “headless” or “none”; default: detected.
block (bool, default=True) – Passed to
plt.showin a GUI.**opts – View-specific options, for example
point_group="m-3m".
- Returns:
The figure.
saved_pathis set when a file was written.- Return type:
- scatterem.vis.show_animated(obj: Any, *, axis: str | None = None, fps: float = 10, max_frames: int = 300, env: str | None = None, style: str = 'screen', background: str = 'light', **opts: Any) Animated#
Show
objas an animation (inline in notebooks, a file when headless).- Parameters:
obj (Any) – An object whose view has frames (multislice, volume, tilt series, …).
axis (str, optional) – Which axis to step through; the view’s default when None. Volumes take “z”, “y” or “x”; a view raises
ValueErrorfor a value it does not support.fps (float, default=10) – Frames per second.
max_frames (int, default=300) – Longer sequences are subsampled evenly, with a warning.
env (str, optional) – “marimo”, “jupyter”, “gui”, “headless” or “none”; default: detected.
**opts – View-specific options.
- Returns:
MP4 (or GIF without the
animextra) with an inline HTML form.- Return type:
- scatterem.vis.save_animated(obj: Any, path, *, axis: str | None = None, fps: float = 10, max_frames: int = 300, style: str = 'screen', background: str = 'light', **opts: Any) Path#
Write
obj’s animation topath(.mp4 or .gif).- Parameters:
obj (Any) – An object whose view has frames.
path (str or pathlib.Path) – Destination; .mp4 needs the
animextra, else a .gif is written instead.axis – As for
show_animated().fps – As for
show_animated().max_frames – As for
show_animated().style – As for
show_animated().background – As for
show_animated().**opts – As for
show_animated().
- Returns:
The written file (the .gif when MP4 was not possible).
- Return type:
- Raises:
ValueError – If the suffix is not .mp4 or .gif.
Colour maps and normalisation#
Choose a colour map by Fig. |
|
Choose the colour map for one of the named |
|
Register every Crameri map with matplotlib under its bare name. |
|
A colour map chosen by |
|
The answers to the questions of Fig. |
|
Settings for |
|
Map data into |
- scatterem.vis.choose_colormap(traits: DataTraits, *, data: ArrayLike | None = None, background: str = 'light') ColourChoice#
Choose a colour map by Fig. 6 of Crameri, Shephard & Heron (2020).
- Parameters:
traits (DataTraits) – The answers to the Fig. 6 questions.
data (array_like, optional) – The values to show. Used only to detect NaN.
background ({"light", "dark"}, default="light") – The figure background.
- Returns:
The map, its class and type, and the trail of answers.
- Return type:
- Raises:
ValueError – If
backgroundis not “light” or “dark”.
- scatterem.vis.colormap_for_role(role: str, *, data: ArrayLike | None = None, background: str = 'light') ColourChoice#
Choose the colour map for one of the named
ROLES.- Parameters:
role (str) – A key of
ROLES, for example"intensity"or"signed".data (array_like, optional) – The values to show. Used only to detect NaN.
background ({"light", "dark"}, default="light") – The figure background.
- Returns:
- Return type:
- Raises:
KeyError – If
roleis unknown. The message lists the roles.
- scatterem.vis.register_colormaps() None#
Register every Crameri map with matplotlib under its bare name.
cmcrameri registers
"cmc.batlow". This adds"batlow"and"batlow_r"too. Names matplotlib already has (berlin, managua, vanimo: the same tables) are left alone. Nothing else in matplotlib changes. The function runs once per process.
- class scatterem.vis.ColourChoice(cmap: Colormap, cls: str, kind: str, trail: tuple[tuple[str, object], ...], centre: float | None = None, period: float | None = None)#
A colour map chosen by
choose_colormap(), with its reasons.- Parameters:
cmap (matplotlib.colors.Colormap) – The map, with its NaN (“bad”) colour set.
cls (str) – Fig. 6 class: sequential, diverging, multi-sequential or cyclic.
kind (str) – Fig. 6 type: continuous, discrete or categorical.
trail (tuple of (str, object)) – Each Fig. 6 question and its answer, in order.
centre (float, optional) – Central value of diverging and multi-sequential data.
period (float, optional) – Period of cyclic data.
- class scatterem.vis.DataTraits(ordered: bool = True, centre: float | None = None, ordered_about_centre: bool = True, period: float | None = None, small_variations: bool = True, levels: int | None = None, intuitive: str | None = None)#
The answers to the questions of Fig. 6 of Crameri et al. (2020).
- Parameters:
ordered (bool, default=True) – Has the data an order? False gives a categorical map.
centre (float, optional) – The central value of the data, if it has one (for example 0).
ordered_about_centre (bool, default=True) – With a centre: True gives a diverging map, False a multi-sequential one.
period (float, optional) – The period of periodic data (for example
2 * pi); gives a cyclic map.show_2dwraps the values into[-period/2, period/2), so data on any interval of one period shows correctly.small_variations (bool, default=True) – Must small variations show? True gives a continuous map, False discrete.
levels (int, optional) – Number of colours of a discrete map. Default 10.
intuitive (str, optional) – A map with colours that suit the parameter, if there is one. A map outside the scientific allow-list warns.
- class scatterem.vis.NormalizationConfig(interval_type: str = 'quantile', stretch_type: str = 'linear', lower_quantile: float = 0.02, upper_quantile: float = 0.98, vmin: float | None = None, vmax: float | None = None, vcenter: float = 0.0, half_range: float | None = None, power: float = 1.0, logarithmic_index: float = 1000.0, asinh_linear_range: float = 0.1)#
Settings for
CustomNormalization.- Parameters:
interval_type ({"quantile", "manual", "centered"}) – How
(vmin, vmax)are chosen."quantile"uses thelower_quantile/upper_quantileof the finite data,"manual"usesvmin/vmax(falling back to the finite data range for either one left as None),"centered"usesvcenter +/- half_range(half_rangedefaults to the largest finite deviation fromvcenter).stretch_type ({"linear", "power", "logarithmic", "asinh"}) – Which stretch to apply; see
_stretch_pair()for the formulas.lower_quantile (float) – Quantiles in
[0, 1]withlower < upper, used by"quantile".upper_quantile (float) – Quantiles in
[0, 1]withlower < upper, used by"quantile".vmin (float, optional) – Explicit limits, used by
"manual".vmax (float, optional) – Explicit limits, used by
"manual".vcenter (float, optional) – Center and half-width, used by
"centered".half_range (float, optional) – Center and half-width, used by
"centered".power (float) – Exponent
p > 0of the"power"stretch.logarithmic_index (float) – Curvature
a > 0of the"logarithmic"stretch.asinh_linear_range (float) – Linear-range parameter
a > 0of the"asinh"stretch.
- class scatterem.vis.CustomNormalization(config: NormalizationConfig | None = None, *, data: Any = None, clip: bool = False, **overrides: Any)#
Map data into
[0, 1]for display: interval selection, then a stretch.- Parameters:
config (NormalizationConfig, optional) – Settings; defaults to
NormalizationConfig().data (array-like, optional) – Data used to resolve the limits immediately, so that
vmin/vmaxare populated before the first call (a colorbar needs them). Otherwise the limits are resolved on the first call, from the array passed there.clip (bool) – Accepted for
matplotlib.colors.Normalizecompatibility. The result is confined to[0, 1]in any case, because the normalized value is clipped before the stretch is applied.**overrides – Any
NormalizationConfigfield, passed directly instead of config.
Notes
The limits are resolved once and then frozen, whether by
data=here or by the first call. One instance therefore describes one interval, which is what makes it safe to share across several images: they are all mapped through the same limits, and a colorbar drawn from those limits describes all of them. Pass a fresh instance per image to normalize each by its own limits.
Figure style and scale bars#
Use the scatterem style inside a |
|
Return the rcParams of a figure style, as |
|
Draw a scale bar on |
|
Where and how the plot functions draw a scale bar. |
|
An image has no physical calibration, so its scale bar reads "1 a.u.". |
- scatterem.vis.use_style(background: str = 'light', style: str | None = None) Iterator[None]#
Use the scatterem style inside a
withblock.- Parameters:
background ({"light", "dark"}, default="light") – The figure background.
style ({"screen", "paper"}, optional) – Also use the text and line sizes of this figure style (
figure_params()), for example for a script’s own panels next toshow_2d(..., style="paper"). Save the figure inside the block:savefig.dpiand the PDF font type are read at save time.
- Yields:
None – The previous rcParams come back when the block ends.
- scatterem.vis.figure_params(style: str = 'paper', background: str = 'light') dict[Any, Any]#
Return the rcParams of a figure style, as
show(style=...)uses them.- Parameters:
style ({"screen", "paper"}, default="paper") – The figure style: text and line sizes for a screen or for print (Nature: 5-7 pt sans-serif, thin lines, PDF text that stays text).
background ({"light", "dark"}, default="light") – The figure background; it sets the line colours.
- Returns:
The text and line sizes of the style and
axes.prop_cyclefromline_colours(). A new dict on each call; a list value is a tuple, so an edit of the dict cannot change the style.- Return type:
- Raises:
ValueError – If
styleis not"screen"or"paper".
- scatterem.vis.draw_scale_bar(ax: Axes, n_pixels: float, pixel_size: float | None = None, unit: str | None = None, length: float | None = None, location: str | int = 'lower right', color: str = 'white', thickness: float = 0.014, margin: float = 0.035, label: bool = True, fontsize: float | None = None, outline: bool = True) float#
Draw a scale bar on
axand return the length it represents.- Parameters:
ax (matplotlib.axes.Axes) – Axes holding the image. Its data limits are not read (the bar sits in axes fractions), but
n_pixelsmust describe the displayed array.n_pixels (float) – Width of the displayed array, in pixels.
pixel_size (float, optional) – Physical size of one pixel. None marks the image as uncalibrated: the bar is still drawn, one fifth of the field wide, labelled “1 a.u.”.
unit (str, optional) – Unit of
pixel_size, for example"nm". None is uncalibrated, as forpixel_size.length (float, optional) – Bar length in physical units. None picks one with
nice_bar_length(). Ignored for uncalibrated data.location (str or int, default="lower right") – Which corner:
"lower right"and the like, a compass name, or a matplotlib legend corner code.color (str, default="white") – Bar and label colour.
thickness (float, default=0.014) – Bar height, as a fraction of the axes height.
margin (float, default=0.035) – Gap between the bar and the axes edges, as a fraction of the axes (
0.035is 3.5 % in from the corner).label (bool, default=True) – Write the length next to the bar.
fontsize (float, optional) – Label size in points. None scales it to the bar thickness.
outline (bool, default=True) – Stroke the bar and label in black, so a white bar stays legible over a light region of the image.
- Returns:
The length drawn, in physical units;
0.0if the geometry was degenerate and nothing was drawn.- Return type:
- class scatterem.vis.ScalebarConfig(sampling: float | None = None, units: str | None = None, length: float | None = None, width_px: float = 1, pad_px: float = 0.5, color: str = 'white', loc: str | int = 'lower right', fontsize: float | None = None)#
Where and how the plot functions draw a scale bar.
- Parameters:
sampling (float, optional) – Size of one pixel in
units. None draws the uncalibrated “1 a.u.” bar.units (str, optional) – Unit text of the bar label. None (with no sampling) shows
a.u..length (float, optional) – Bar length in
units. None picks the longest 1-2-5 length that fits in a third of the image width.width_px (float, default=1) – Thickness of the scale bar, in data pixels.
pad_px (float, default=0.5) – Padding between the bar and the axes corner, in multiples of the label font size (not pixels, despite the name – this is the
AnchoredSizeBarconvention). Values above a few push the bar out of the corner and into the image.color (str, default="white") – Matplotlib colour of the bar and of its label.
loc (str or int, default="lower right") – Corner that holds the bar, as a matplotlib legend location: a name such as
"upper left"or its integer code.fontsize (float, optional) – Label font size in points.
Nonescales it with the bar thickness.
- class scatterem.vis.UncalibratedDataWarning#
An image has no physical calibration, so its scale bar reads “1 a.u.”.
Colour#
Colour an image, using |
|
|
|
Composite a grid of same-shaped images into one RGBA mosaic. |
- scatterem.vis.complex_color.complex_to_rgba(amplitude: NDArray, phase: NDArray | None = None, *, cmap: str | Colormap = 'gray', chroma: float = 0.13) NDArray#
Colour an image, using
phaseas hue when it is given.- Parameters:
amplitude – values in
[0, 1](normalise before calling).phase – angles in radians. When None,
cmapis applied and the result is an ordinary colormapped image.cmap – matplotlib colormap name, used only when
phaseis None.chroma – Oklab chroma for the phase wheel. The default is a compromise – high enough for hue to read, low enough to stay in gamut across most of the lightness range.
- Returns:
(..., 4)RGBA in[0, 1], alpha fully opaque.
- scatterem.vis.complex_color.phase_wheel(n: int = 256, *, lightness: float = 0.72, chroma: float = 0.13)#
(colors, angles)for a phase colorbar: one full turn of hue.lightnessis fixed so the bar reads as hue alone. The default sits near the middle of the range where the sRGB gamut is widest, so the wheel keeps its chroma all the way round instead of desaturating at some hues.
- scatterem.vis.complex_color.tile_to_rgba(rows, *, norm=None, cmap: str = 'gray', chroma: float = 0.13) NDArray#
Composite a grid of same-shaped images into one RGBA mosaic.
Replaces
list_of_arrays_to_rgba. Each entry is coloured independently and the results are tiled, so a bright panel cannot darken its neighbours – the alternative, one normalisation across the whole grid, makes every panel but the brightest unreadable.- Parameters:
rows – sequence of rows, each a sequence of same-shaped 2D arrays.
norm –
callable mapping amplitude to
[0, 1], applied to each panel. If omitted, each panel is scaled by its own finite min and max.This argument is not optional in spirit:
complex_to_rgba()requires[0, 1]and clips, so handing it raw data silently renders a 0..1000 image as 99.9% pure white. An earlier version of this function did exactly that.cmap – colormap for real-valued panels.
chroma – Oklab chroma for the phase hue of complex panels.
Scale bars#
Per-axis image calibration. |
|
The real-space pixel of an image reconstructed from a scanned dataset. |
- class scatterem.data.sampling.Sampling(pixel_size: tuple[float, ...] | None = None, units: tuple[str, ...] | None = None, value_unit: str | None = None)#
Per-axis image calibration.
Replaces the removed
UnitTensor: numeric data stays a plain tensor/ndarray; this sidecar is threaded explicitly so units cannot vanish through tensor ops.- Parameters:
pixel_size (float or tuple of float, optional) – Physical size of one pixel along each axis, in axis order
(dy, dx)for a 2D image.Nonemeans uncalibrated.units (str or tuple of str, optional) – Unit string per axis, e.g.
("Å", "Å")(real space) or("1/Å", "1/Å")(reciprocal space).value_unit (str, optional) – Unit of the stored values, used for the colorbar label.
Examples
The scale bar reads the last axis; mismatched axis counts raise:
>>> from scatterem.data import Sampling >>> s = Sampling(pixel_size=(0.1, 0.2), units=("A", "A"), value_unit="e") >>> s.is_calibrated, s.scalebar_sampling() (True, (0.2, 'A')) >>> Sampling(pixel_size=(1.0,), units=("A", "A")) Traceback (most recent call last): ... ValueError: pixel_size has 1 axes but units has 2
- scatterem.data.sampling.reconstruction_sampling(dataset: Any, image: Any = None, *, shape: Sequence[int] | None = None) Sampling#
The real-space pixel of an image reconstructed from a scanned dataset.
A reconstruction is up-sampled relative to the scan, so its pixel is smaller than the scan step. It covers the same field of view as the scan, so:
pixel_size = scan_step * scan_px / image_px
per axis. The formula reads the upsample factor off the output shape, so the caller need not know which factor
upsample="nyquist"picked.- Parameters:
dataset (object) – The dataset the reconstruction came from. Its
shape[:2]is the scan shape and itssampling[:2]the scan step. Itsunits[:2]label the axes when present, else("Å", "Å").image (array-like, optional) – The reconstruction. Its last two dimensions give the output shape.
shape (sequence of int, optional) – The output shape
(H, W), in place ofimage.
- Returns:
The pixel size
(dy, dx)and the units of the two real-space axes.- Return type:
- Raises:
ValueError – If neither
imagenorshapeis given, or the shape is not 2-D.
Saving and loading#
Give a declared-schema class |
|
Read a file written by |
|
The class, version and field list of a file, without constructing anything. |
|
A file cannot be written, or cannot be loaded faithfully. |
|
Bumped when the on-disk layout changes in a way older readers cannot handle. |
- class scatterem.utils.store.Serializable#
Give a declared-schema class
save()andload.Subclasses set
SERIAL_FIELDSto the attribute names to persist, and must be constructible from those names as keyword arguments – or override_from_fields()if construction needs more than that. A field holding anotherSerializable(or a list of them) names the class it holds inSERIAL_NESTED; a tuple there allows any one of several classes.A subclass that declares neither
SERIAL_FIELDSnor_from_fieldsitself adds behaviour but not state, and a file it wrote loads as its nearest ancestor that does – a download wrapper whose constructor fetches data cannot be rebuilt from fields. A subclass that shares its ancestor’s schema and is built the same way says so with a class keyword,class Sub(Base, load_as_self=True), and then loads as itself.
- scatterem.utils.store.load_serializable(path: str | Path, candidates: Sequence[type], *, device: str | device = 'cpu')#
Read a file written by
Serializable.save(), as one ofcandidates.- Parameters:
path (str or pathlib.Path) – The HDF5 file.
candidates (sequence of type) – The classes the caller allows, each a
Serializablesubclass. Their subclasses are allowed too; nothing else is.device (str or torch.device, optional) – Device every tensor field is placed on. Default
"cpu".
- Returns:
The loaded object.
- Return type:
- Raises:
SerializationError – If the file is missing, has another schema version, holds no allowed class, or its field list disagrees with the class’s.
- scatterem.utils.store.read_schema(path: str | Path) dict[str, Any]#
The class, version and field list of a file, without constructing anything.
Useful for telling why a load was refused.
- Parameters:
path (str or pathlib.Path) – A file written by
Serializable.save().- Returns:
schema_version(int,-1if absent),class(the stored class name),module(its module,Nonefor files that predate it) andfields(the recorded field list).- Return type:
- class scatterem.utils.store.SerializationError#
A file cannot be written, or cannot be loaded faithfully.
- scatterem.utils.store.SCHEMA_VERSION = 1#
Bumped when the on-disk layout changes in a way older readers cannot handle. Additions an older reader simply ignores (the
moduleand__pytypeattributes, numbered subgroups for a list of objects) do not bump it.
Supporting modules#
scatterem.data.detector_warp#
Validate a detector warp: None, a |
|
The wave vector |
|
The area-preserving stretch |
|
|
|
The |
- scatterem.data.detector_warp.as_detector_warp(value: Any) Tensor | None#
Validate a detector warp: None, a
(2, 2)Wor a(T, 2)table.- Parameters:
value (array_like or None) – The warp
W, the polynomial table (see the module docstring), or None for no warp.- Returns:
A float64 tensor on the CPU, or None.
- Return type:
torch.Tensor or None
- Raises:
ValueError – If the shape is neither
(2, 2)nor(T, 2)with a triangularT >= 3, an entry is not finite, ordet Wis not positive (a fold or a mirror is not a warp: a transposed detector is a separate setting).
- scatterem.data.detector_warp.bright_field_k(centered: Tensor, sampling: Tensor, meta: Any) Tensor#
The wave vector
(ky, kx)each bright-field pixel records, float32.- Parameters:
centered (torch.Tensor) –
(n, 2)pixel offsets from the bright-field centroid,(row, col).sampling (torch.Tensor) –
(1, 2)reciprocal samplingdkper detector axis, 1/A per pixel, on the device ofcentered.meta (object) – The acquisition metadata. Its
detector_warp(absent or None: no warp) is applied ask = W (p dk), or as the polynomial.
- Returns:
(n, 2)float32. With no warp it is(centered * sampling)cast to float32, bit for bit as before the warp existed.- Return type:
- scatterem.data.detector_warp.detector_warp_matrix(ellipticity: float, tilt_deg: float) ndarray#
The area-preserving stretch
Wof an elliptical bright-field disk.- Parameters:
- Returns:
(2, 2)float64,(row, col)order. Symmetric,det W = 1. It maps a pixel offset on the major axis tosqrt(1 - e)times that offset, and one on the minor axis to1 / sqrt(1 - e)times it, so the elliptical disk maps to a round one.- Return type:
- Raises:
ValueError – If
ellipticityis not in[0, 1)or a value is not finite.
- scatterem.data.detector_warp.polynomial_warp(k: Tensor, table: Tensor) Tensor#
k + sum_ab c_ab (k_y / k_ref)^a (k_x / k_ref)^bfor a(T, 2)table.- Parameters:
k (torch.Tensor) –
(..., 2)nominal(k_y, k_x), 1/A.table (torch.Tensor) –
(T, 2)coefficients (module docstring), on the device ofk.
- Returns:
(..., 2)truek, dtype ofk.- Return type:
- scatterem.data.detector_warp.warp_table(warp: Any, reference: float = 1.0) Tensor#
The
(T, 2)polynomial table of a warp;Wbecomes degree 1.- Parameters:
warp (array_like) – A
(2, 2)Wor a(T, 2)table (as_detector_warp()).reference (float, optional) –
k_refof the returned table, 1/A (defaultWARP_REFERENCE). The same field: a degree-drow scales by(reference / WARP_REFERENCE)^d. Ak_refnear the detector’s reach keeps a Newton inverse well scaled.
- Returns:
(T, 2)float64 on the CPU.- Return type:
- Raises:
ValueError – If
warpis None or not a valid warp.
scatterem.data.geometry#
Rigid-body scan/projection geometry (translation and rotation). |
- class scatterem.data.geometry.Geometry(translation: Tensor, rotation: Tensor)#
Rigid-body scan/projection geometry (translation and rotation).
- Parameters:
translation (Tensor) – Real-space translation, shape
(2,).rotation (Tensor) – Euler angles
(phi, theta, psi)in radians, shape(3,), in the conventionR = Rx(psi) @ Ry(theta) @ Rz(phi).Rmaps lab -> volume.
scatterem.nn.regularizers.tv#
Exact (sub)gradient of the mean anisotropic TV loss. |
|
Exact gradient of the mean isotropic TV loss of |
|
Mean absolute forward difference of vol along dim. |
|
Mean anisotropic total variation over the last two axes of an image. |
|
Mean 3D total variation of a dense |
- scatterem.nn.regularizers.tv.anisotropic_tv_subgradient(volume: Tensor) Tensor#
Exact (sub)gradient of the mean anisotropic TV loss.
The loss is
sum_axes mean_n |v[n+1] - v[n]|over the forward differences of each axis:total_variation_3d()withisotropic=Falseon a[D, H, W]volume. Its derivative is the discrete divergence ofsign(grad v)scaled by1 / numel(diff)of that axis:signof each forward difference is subtracted at the left voxel and added at the right voxel. Away from ties this equals autograd of the loss; at a kink (a zero difference) the subgradient 0 is chosen, as autograd’sabsdoes. Pure tensor math (no autograd graph, no backward), so it can be injected straight intoobject.grad– cheaper than building a TV loss term and backpropagating it.- Parameters:
volume (Tensor) – Real floating dense volume, any number of dimensions. An axis with fewer than two voxels has no differences and contributes nothing (where the mean loss would be NaN).
- Returns:
Subgradient of the mean anisotropic TV, same shape, dtype and device as volume.
- Return type:
Tensor
- scatterem.nn.regularizers.tv.isotropic_tv_subgradient(volume: Tensor, eps: float = 1e-08) Tensor#
Exact gradient of the mean isotropic TV loss of
total_variation_3d().The loss is
mean_i sqrt(dz^2 + dy^2 + dx^2 + eps)over the common interiori in [0, D-1) x [0, H-1) x [0, W-1), with forward differencesd.[i] = v[i + e.] - v[i]. It couples the three axes through the per-voxel gradient norm, so it smooths more uniformly than the axis-separable anisotropic version. Witheps > 0the loss is smooth, so this is its gradient everywhere, computed analytically without autograd.- Parameters:
volume (Tensor) – Real floating dense
[D, H, W]volume. When an axis has fewer than two voxels the interior is empty and the result is all zeros (where the mean loss would be NaN).eps (float, optional) – Smoothing term inside the gradient-norm square root, by default 1.0e-8, the default of
total_variation_3d().
- Returns:
Gradient of the mean isotropic TV, shape
[D, H, W], on the dtype and device of volume.- Return type:
Tensor
- scatterem.nn.regularizers.tv.mean_abs_forward_diff(vol: Tensor, dim: int) Tensor#
Mean absolute forward difference of vol along dim.
Shared anisotropic-TV building block:
mean(|vol[n+1] - vol[n]|)on axis dim. Used bytotal_variation_3d()(anisotropic).- Parameters:
vol (Tensor) – Real floating tensor of any shape.
dim (int) – Axis along which to take the forward difference. The axis length must be at least 2 or the mean is NaN.
- Returns:
Scalar mean absolute difference on the dtype and device of vol.
- Return type:
Tensor
- scatterem.nn.regularizers.tv.total_variation_2d(image: Tensor, *, per_item: bool = False) Tensor#
Mean anisotropic total variation over the last two axes of an image.
Forward differences:
mean(|dH|) + mean(|dW|). When per_item is False the means cover the whole tensor; when True they reduce only the last two axes, returning one value per leading index. Matches the"tv"branch of the direct-ptychography image-sharpness metric.- Parameters:
image (Tensor) – Real floating image
[..., H, W].per_item (bool, optional) – Reduce only over
HandWwhen True. Default False.
- Returns:
Scalar mean TV, or a tensor of shape
image.shape[:-2]when per_item is True.- Return type:
Tensor
- scatterem.nn.regularizers.tv.total_variation_3d(vol: Tensor, isotropic: bool = True, eps: float = 1e-08) Tensor#
Mean 3D total variation of a dense
[D, H, W]volume (differentiable).Isotropic: mean of
sqrt(dz^2 + dy^2 + dx^2 + eps)over the common interior (edge-preserving, rotation-invariant). Anisotropic: sum of the mean absolute forward differences along each axis (cheaper, axis-aligned). Scale on this data: a converged 170^3 volume has TV ~1.6e-2 vs inner MSE ~2e-3, sotv_weightin 0.01-0.1 spans a gentle-to-strong prior.- Parameters:
vol (Tensor) – Real floating volume of shape
(D, H, W). Differences are per voxel, without physical voxel-spacing normalization. Each axis must contain at least two voxels for a finite mean; an empty difference yields NaN.isotropic (bool, optional) – Couple the three differences on the common interior when True; otherwise sum their separate mean absolute values. Default True.
eps (float, optional) – Squared-difference smoothing term for isotropic TV, default 1.0e-8. Ignored for anisotropic TV. Inputs and eps are not validated.
- Returns:
Differentiable scalar mean TV on the input dtype and device.
- Return type:
Tensor
scatterem.physics.kernels.lens_wavefront_wp#
Return a lens vector as a 1-D float32 Warp array in the same order. |
|
Return the lens wavefront |
|
Return |
- scatterem.physics.kernels.lens_wavefront_wp.lens_to_warp(lens: Tensor | Sequence[float], *, device: str | device | None = None) array#
Return a lens vector as a 1-D float32 Warp array in the same order.
A float32 contiguous tensor on the target device is shared without a copy. Other inputs are cast to float32 and copied first.
- Parameters:
lens (torch.Tensor or sequence of float) – Lens vector of shape
(12,)[Angstrom].device (str or torch.device, optional) – Target device.
Nonemeans the device of the tensor, or CPU for a sequence.
- Returns:
Shape
(12,), dtypewp.float32.- Return type:
wp.array
- Raises:
ValueError – If the shape is not
(12,).
- scatterem.physics.kernels.lens_wavefront_wp.lens_wavefront_f32(lens: array(ndim=1, dtype=float32), fy: float32, fx: float32, lambda_a: float32) float32#
Return the lens wavefront
W[rad] at one frequency point, in float32.Accuracy. For inputs that are exact in float32, the result
W32and the float64 valueW64of the same inputs satisfy:|W32 - W64| <= 32 eps (2 pi / lambda) sum_j |c_j P_j| / (n_j + 1) + 4 eps |W64|, eps = 2^-23,
with
P_jthe basis polynomial of slotj. Each term takes at most about 10 roundings, the sum of 12 terms adds 11 and the scaling adds 2.- Parameters:
lens (wp.array of wp.float32) – The 12 coefficients [Angstrom] in the order of
LENS_LAYOUT.fy (wp.float32) – Frequency coordinates
k_yandk_x[1/Angstrom].fx (wp.float32) – Frequency coordinates
k_yandk_x[1/Angstrom].lambda_a (wp.float32) – Wavelength [Angstrom], larger than zero.
- Returns:
Wavefront [rad].
- Return type:
wp.float32
- scatterem.physics.kernels.lens_wavefront_wp.lens_wavefront_focus_f32(lens: array(ndim=1, dtype=float32), fy: float32, fx: float32, lambda_a: float32) float32#
Return
W[rad] for a lens vector whose sole non-zero slot is 0.The function reads only
lens[0](the defocus slotC10). If the other 11 slots are+0.0or-0.0and all inputs are finite, it returns the same float32 bits aslens_wavefront_f32(). This needs the default Warp setting without fast-math; fast-math would void it.Rule: the host picks
lens_wavefront_focus_f32orlens_wavefront_f32before the launch (for example as a kernel template argument or by building one of two kernels). Do not choose between them inside a kernel with a run-time condition.- Parameters:
lens (wp.array of wp.float32) – The 12 coefficients [Angstrom] in the order of
LENS_LAYOUT.fy (wp.float32) – Frequency coordinates
k_yandk_x[1/Angstrom].fx (wp.float32) – Frequency coordinates
k_yandk_x[1/Angstrom].lambda_a (wp.float32) – Wavelength [Angstrom], larger than zero.
- Returns:
Wavefront [rad].
- Return type:
wp.float32
scatterem.reconstruction.darkfield.core#
Estimate the radial spectral SNR from two independent half-set images. |
|
Apply 1D Gaussian blur to a 1D torch tensor. |
- scatterem.reconstruction.darkfield.core.compute_ssnr_from_halfset_images(tcDF1, tcDF2, sampling, gaussian_sigma=0.0, verbosity=0)#
Estimate the radial spectral SNR from two independent half-set images.
Treats
tcDF1/tcDF2as two independent noise realizations of the same signal (N = (FA - FB) / 2estimates the noise spectrum,S = (FA + FB) / 2the signal-plus-noise spectrum), radially bins their power in Fourier space, and formsSSNR(q) = (S_power - N_power) / N_power.- Parameters:
tcDF1 (torch.Tensor) – First half-set real-space image, shape
(H, W).tcDF2 (torch.Tensor) – Second half-set real-space image, same shape as tcDF1.
sampling (tuple of float) – Real-space pixel sampling
(dy, dx), used to build the Fourier frequency grid.gaussian_sigma (float, optional) – If greater than 0, 1D-Gaussian-smooth the radial SSNR curve with this sigma, in radial bins.
verbosity (int, optional) – If greater than 1, plot the radial noise power, signal power and SSNR curves.
- Returns:
The radial SSNR curve, the per-bin mean spatial frequency
|q|, and the flattened per-pixel radial bin index (for scattering the radial curve back onto the 2D grid).- Return type:
- scatterem.reconstruction.darkfield.core.gaussian_blur1d(x, sigma)#
Apply 1D Gaussian blur to a 1D torch tensor.
- Parameters:
x (torch.Tensor) – 1D tensor to blur.
sigma (float) – Gaussian standard deviation, in samples. Values
<= 0return x unchanged.
- Returns:
The blurred 1D tensor, reflect-padded at the edges.
- Return type:
scatterem.reconstruction.darkfield.drizzle#
Drizzle a stack of shifted frames onto a common up-sampled grid. |
- scatterem.reconstruction.darkfield.drizzle.drizzle_resample(images: Tensor, shifts: Tensor, upsample: int, *, pixfrac: float = 1.0, kde_sigma: float = 0.0, eps: float = 1e-12, return_parts: bool = False)#
Drizzle a stack of shifted frames onto a common up-sampled grid.
Runs under
torch.no_grad: this is a resampling step, not part of an autograd path. Accumulation is forced to at least float32 – manyindex_add_into a half-precision grid loses precision – and the normalized result is cast back to the input dtype.- Parameters:
images (Tensor) – Shape
(N, H, W), real. TheNdithered frames of the same scene, e.g. dark-field azimuthal-segment images. Non-negative input gives non-negative output.shifts (Tensor) – Shape
(N, 2), the per-frame(dy, dx)shift in output (HR) pixels. Framen’s input pixel(i, j)is deposited at HR position(i * U + dy_n, j * U + dx_n): input pixelimaps to HR pixeli * U, matching Fourier zero-pad upsampling, plus the sub-pixel shift. Moved to the device and accumulation dtype ofimages.upsample (int) – Integer output magnification
U; the output isH * UbyW * U.pixfrac (float) – Drizzle drop size as a fraction of one input pixel, in
(0, 1]. The deposited footprint is a box of sidepixfrac * UHR pixels. A smaller value is sharper but needs denser coverage to avoid holes. Default 1.0.kde_sigma (float) – When positive, Nadaraya-Watson smoothing: a Gaussian of this standard deviation in HR pixels is applied to numerator and denominator before dividing. Fills small holes and denoises, at the cost of resolution. Default 0.0.
eps (float) – Denominator floor, so uncovered output pixels read 0 rather than NaN. Default 1e-12.
return_parts (bool) – Also return the raw accumulation grids. Default False.
- Returns:
The hit-normalised
(H * U, W * U)image, in the dtype and on the device ofimages. Withreturn_parts=True, the triple(image, accum, hits):accumis the flux grid, which conservesimages.sum()for in-frame content, andhitsis the summed coverage weight.- Return type:
Tensor or tuple of Tensor
- Raises:
ValueError – If
imagesis not 3-dimensional, ifshiftsis not(N, 2)matching it, ifupsampleis below 1, or ifpixfracis outside(0, 1].
scatterem.vis.colors#
A plot was asked to use a colour map outside the scientific allow-list. |
|
The colour choice and normalisation for one displayed image. |
|
Simulate how a person with a full dichromacy sees sRGB colours. |
|
CIELAB coordinates of sRGB colours. |
|
Warn when |
- class scatterem.vis.colors.UnscientificColormapWarning#
A plot was asked to use a colour map outside the scientific allow-list.
- scatterem.vis.colors.resolve_display(cmap: str | Colormap | None, role: str, norm: Any, *, data: ArrayLike | None = None, background: str = 'light') tuple[ColourChoice, Any]#
The colour choice and normalisation for one displayed image.
- Parameters:
cmap (str or Colormap or None) – An explicit map. It wins over
role, with a warning if unscientific.role (str) – A key of
ROLES. It sets the class and the limits.norm (Any) – The caller’s normalisation. None takes the role’s limits.
data (array_like, optional) – The values to show. Used to detect NaN and, for a centred class, to set the half-range of the limits.
background ({"light", "dark"}, default="light") – The figure background.
- Returns:
(ColourChoice, norm), wherenormis the caller’s or the role’s.- Return type:
- scatterem.vis.colors.simulate_cvd(colours: ArrayLike, kind: str) NDArray#
Simulate how a person with a full dichromacy sees sRGB colours.
- Parameters:
colours (array_like) –
(N, 3)or(N, 4)sRGB values in[0, 1].kind ({"protanopia", "deuteranopia", "tritanopia"}) – Which cone type is missing (Machado et al. 2009, severity 1.0).
- Returns:
(N, 3)simulated sRGB values in[0, 1].- Return type:
- Raises:
ValueError – If
kindis not one of the three dichromacies.
- scatterem.vis.colors.srgb_to_lab(colours: ArrayLike) NDArray#
CIELAB coordinates of sRGB colours.
- Parameters:
colours (array_like) –
(N, 3)or(N, 4)sRGB values in[0, 1]. An alpha column is ignored.- Returns:
(N, 3)array ofL*,a*,b*.- Return type:
- scatterem.vis.colors.warn_if_unscientific(cmap: str | Colormap, stacklevel: int = 3) None#
Warn when
cmapis not on the scientific allow-list.The
warningsfilters decide how often the warning shows, sosimplefilter("error")catches every call.show_2dwarns once per call, not once per panel. For one warning per process, usewarnings.filterwarnings("once", category=UnscientificColormapWarning).- Parameters:
cmap (str or matplotlib.colors.Colormap) – The map a caller asked for. An object is judged by its
name.stacklevel (int, default=3) – Passed to
warnings.warn(), so the warning points at the caller.
scatterem.vis.normalization#
Preset name -> a callable that returns a new |
|
Built-in immutable sequence. |
|
Built-in immutable sequence. |
- scatterem.vis.normalization.NORMALIZATION_PRESETS: dict[str, Callable[[], NormalizationConfig]]#
Preset name -> a callable that returns a new
NormalizationConfig.Any
norm=argument of the plot functions accepts these names.
- scatterem.vis.normalization.INTERVAL_TYPES = ('quantile', 'manual', 'centered')#
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
- scatterem.vis.normalization.STRETCH_TYPES = ('linear', 'power', 'logarithmic', 'asinh')#
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
scatterem.vis.scale_bar#
Longest 1-2-5 length that fits comfortably across |
- scatterem.vis.scale_bar.nice_bar_length(span: float) float#
Longest 1-2-5 length that fits comfortably across
span.- Parameters:
span – extent of the field of view, in physical units.
- Returns:
The chosen length in the same units, or
0.0ifspanis not a usable positive number – a degenerate axis should produce no bar rather than a NaN one.
scatterem.vis.show#
An encoded animation that notebooks show inline (once in Jupyter). |
|
Options that every view and panel sees. |
|
The frames of an animated view. |
|
One panel of a figure: a name, a drawing function and a screen title. |
|
The figure |
|
Register the panel function decorated by this as the view for |
- class scatterem.vis.show.Animated(data: bytes, mime: str, path: Path | None = None, shown: bool = False)#
An encoded animation that notebooks show inline (once in Jupyter).
- Parameters:
data (bytes) – The encoded file.
mime (str) – “video/mp4” or “image/gif”.
path (pathlib.Path, optional) – Where the file was written, if it was.
shown (bool, default=False) – True once Jupyter has displayed it, so it appears only once.
- class scatterem.vis.show.FigureContext(style: str = 'screen', width: str | None = None, background: str = 'light', panels: tuple[str, ...] | None=None, opts: Mapping[str, ~typing.Any]=<factory>)#
Options that every view and panel sees.
- Parameters:
style ({"screen", "paper"}) – Screen keeps titles and larger text; paper is Nature style.
width ({None, "single", "double"}) – Paper width: 89 mm (single, the default) or 183 mm (double).
background ({"light", "dark"}) – Figure background, used by the colour policy.
panels (tuple of str, optional) – Panel names to draw, in this order. None draws the default set.
opts (mapping) – View-specific options (for example
point_group).
- class scatterem.vis.show.FrameSource(frames: Sequence[Any], axis: str, role: str | None = 'intensity', sampling: Any = None, labels: Sequence[str] | None = None, norm: dict[str, Any] | None = None)#
The frames of an animated view.
- Parameters:
frames (sequence) – 2D arrays (values), or (H, W, 3) RGB arrays in [0, 1] when
roleis None.axis (str) – What the frames step through (“slice”, “tilt”, “energy”, …).
role (str or None) – Colour role for value frames; None for RGB frames.
sampling (Sampling, optional) – Calibration for the scale bar.
labels (sequence of str, optional) – One label per frame, shown as the title.
norm (dict, optional) – Shared NormalizationConfig; default: 2-98 % over all frames.
- class scatterem.vis.show.Panel(name: str, draw: Callable[[Axes, FigureContext], None], title: str = '')#
One panel of a figure: a name, a drawing function and a screen title.
- class scatterem.vis.show.ShownFigure(*args: Any, **kwargs: Any)#
The figure
showreturns.In Jupyter,
showdisplays it at once and_ipython_display_then does nothing, so it appears exactly once. In marimo it renders through_display_when it is a cell’s last expression (marimo’s convention).- Parameters:
*args – Passed to
matplotlib.figure.Figure.**kwargs – Passed to
matplotlib.figure.Figure.
- scatterem.vis.show.register(target: type | str, *, name: str, frames: Callable | None = None) Callable#
Register the panel function decorated by this as the view for
target.- Parameters:
target (type or str) – The type to show, or its qualified name (“package.module.Class”) so the registering module need not import a heavy type. Subclasses use the view.
name (str) – Short name used for file names (
"dataset4dstem").frames (callable, optional) –
frames(obj, axis, ctx) -> FrameSourceforshow_animated.
- Returns:
The decorator.
- Return type:
callable
scatterem.vis.style#
Categorical line colours from batlowS that stand out on |
|
Return the rcParams of the scatterem style. |
- scatterem.vis.style.line_colours(background: str = 'light', n: int = 8) list[str]#
Categorical line colours from batlowS that stand out on
background.- Parameters:
background ({"light", "dark"}, default="light") – The figure background.
n (int, default=8) – Number of colours.
- Returns:
Hex colours. Each one differs from the background by at least
LINE_MIN_DLin L*. Each next colour is the one farthest (in CIELAB) from those already picked.- Return type:
- scatterem.vis.style.style_params(background: str = 'light') dict[RcKeyType, Any]#
Return the rcParams of the scatterem style.
- Parameters:
background ({"light", "dark"}, default="light") – The figure background.
- Returns:
image.cmap(batlow),image.interpolation(none) and anaxes.prop_cyclefromline_colours().- Return type:
scatterem.vis.visualization_utils#
Draw a colorbar for |
|
Add the value colour bar to |
|
Colour-bar ticks for data that round ticks describe badly. |
|
Positional adapter for |
|
A round bar length for an image |
- scatterem.vis.visualization_utils.add_cbar_to_ax(fig: Figure, cax: Axes, norm: Normalize, cmap: Colormap, eps: float = 1e-08, label: str | None = None, ticks: Any = None) Colorbar#
Draw a colorbar for
norm/cmapinto an existing axes.- Parameters:
fig (matplotlib.figure.Figure) – The figure that gets the bar.
cax (matplotlib.axes.Axes) – The empty axes that the bar fills, for example from
make_axes_locatable(ax).append_axes.norm (matplotlib.colors.Normalize) – Value mapping of the image. Its
vminandvmaxmust be set; they bound the ticks.cmap (matplotlib.colors.Colormap) – The colour map of the image.
eps (float, optional) – Tolerance when discarding ticks that fall outside the limits, so a tick sitting exactly on a limit is not lost to rounding. Default is 1e-8.
label (str or None, optional) – Axis label; omitted when None. Default is None.
ticks (sequence of float or None, optional) – Explicit ticks, written without offset or exponent. Default is None, which picks round ticks.
- Returns:
The new bar, for more styling by the caller.
- Return type:
- scatterem.vis.visualization_utils.add_colorbars(fig: Figure, ax: Axes, norm: Normalize, cmap: Colormap, *, value_unit: str | None, is_complex: bool, ticks: Any = None) None#
Add the value colour bar to
ax, plus a phase bar for complex data.The phase bar sits far enough to the right for the tick labels of the value bar. The value bar says “abs” in a title above it, away from its ticks.
- Parameters:
fig (matplotlib.figure.Figure) – Figure the colour bars belong to.
ax (matplotlib.axes.Axes) – Image axes; the bars are appended to its right.
norm (matplotlib.colors.Normalize) – Normalization of the shown values. Equal limits (constant data) give one solid colour.
cmap (matplotlib.colors.Colormap) – Colour map of the value bar.
value_unit (str or None) – Unit of the values: the label of the value bar, or part of its “abs” title for complex data. None shows no unit.
is_complex (bool) – Whether the image shows complex data, which adds the phase bar.
ticks (sequence of float or None, optional) – Explicit ticks of the value bar, as in
add_cbar_to_ax. Default is None, which picks round ticks.
- scatterem.vis.visualization_utils.special_ticks(data: Any, role: str) ndarray | None#
Colour-bar ticks for data that round ticks describe badly.
Constant data gets one tick at its value. Data with the role
labelsand at most 20 distinct integer values gets one tick per value.- Parameters:
data (array_like) – The displayed values (the amplitude, for complex data).
role (str) – Colour role of the data.
- Returns:
The ticks, or None when round ticks are fine.
- Return type:
numpy.ndarray or None
- scatterem.vis.visualization_utils.add_scalebar_to_ax(ax: Axes, array_size: float, sampling: float | None, length_units: float | None, units: str | None, width_px: float, pad_px: float, color: str, loc: str | int) None#
Positional adapter for
scatterem.vis.scale_bar.draw_scale_bar().The drawing lives in
scatterem.vis.scale_bar; this signature exists because the figure scripts andScalebarConfigalready speak it.Two arguments are reinterpreted on the way through, because their names describe the old
AnchoredSizeBarimplementation rather than the geometry:width_pxBar thickness. Was a count of data pixels; now converted to the fraction of the axes height it corresponds to, so it means the same thing on screen for a square image.
pad_pxCorner inset. Was in multiples of the label font size despite the name. Now read as a fraction of the axes –
0.5was the old default and landed a little inside the corner, so values in that range map to a comparable inset, while a caller who passes a pixel count no longer pushes the bar into the middle of the image.
Prefer
draw_scale_barin new code: it names its arguments after what they do and returns the length it drew.- Parameters:
ax (matplotlib.axes.Axes) – Axes to draw the scale bar into.
array_size (float) – Width of the displayed array, in pixels.
sampling (float or None) – Physical units per pixel; None leaves the bar uncalibrated.
length_units (float or None) – Bar length in
units; None picks a round length.units (str or None) – Unit label shown next to the bar.
width_px (float) – Bar thickness, in data pixels.
pad_px (float) – Corner inset, in multiples of the label font size (legacy
AnchoredSizeBarconvention).color (str) – Matplotlib colour of the bar and of its label.
loc (str or int) – Corner that holds the bar, as a matplotlib legend location.
- scatterem.vis.visualization_utils.estimate_scalebar_length(n_pixels: float, sampling: float) tuple[float, float]#
A round bar length for an image
n_pixelswide atsamplingper pixel.Thin adapter over
scatterem.vis.scale_bar.nice_bar_length(), kept because callers want the length in pixels as well.- Parameters:
- Returns:
(length_in_units, length_in_pixels), or(0.0, 0.0)when the geometry is degenerate – a zero or negative sampling produces no bar rather than a divide-by-zero and a NaN one.- Return type: