API reference

Contents

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#

configure

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. None leaves the setting untouched.

Returns:

The value every setting had before this call, keyed by parameter name, so configure(**previous) restores them. A value is None when 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_precision is 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 flag torch.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 makes torch.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#

Dataset

An array plus the calibration needed to interpret its axes.

Dataset4DStem

A 4D STEM dataset with metadata for electron diffraction patterns.

DatasetVirtualBrightField4DStem

A virtual bright field 4D STEM dataset with metadata for electron diffraction patterns.

with_meta

A cheap view of dataset that reads meta instead of its own.

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.

  • units (list of str, or tuple) – One unit string per axis.

  • 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) – None keeps 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.

  • units (list of str) – One unit string per axis.

  • 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 fftshift on 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) – None keeps 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: pass normalize=False (and clip_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 on normalize.

  • 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. FusedFullFieldConfig reads 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:

PupilEstimate

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 dk from the bright field.

Sets dk = alpha / rBF / wavelength and self.sampling = (dr, dr, dk, dk) in place (the setter updates self.meta.sampling). rBF comes from the mean pattern of the whole detector (bright_field_radius_and_center()). A scratch crop (as crop_brightfield_, same edge_reach, no normalisation, so the array does not change) recentres the detector entries of self.origin, sets self._radius_bright_field and refuses a disk near the detector edge.

Parameters:
Returns:

The calibrated reciprocal-space sampling dk.

Return type:

float

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 meta describes (meta.sampling), else 1.0 per 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 None and energy is 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 fftshift in 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: pass normalize=False (and clip_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 on normalize.

  • 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) – None keeps 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 meta is None and energy is given, an AcquisitionMetadata is built internally (shape derived from array, sampling = (dr, dr, dk, dk) with dr from scan_step and dk from reciprocal_step – both scalar or a length-2 pair, dk defaulting to a (1.0, 1.0) placeholder to be calibrated later, e.g. via calibrate_reciprocal_from_bright_field). origin defaults 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:

Dataset4DStem

classmethod load(path: str | Path, *, device: str | device = 'cpu')#

Read an instance of cls (or of a subclass) from path.

Parameters:
Returns:

The object. When the file holds a subclass of cls that declares its own schema, an instance of that subclass.

Return type:

Serializable

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:

pathlib.Path

Raises:

SerializationError – If the file exists and overwrite is 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.

  • units (list of str or tuple or list) – Units of each 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_inds centered on their mean.

  • bright_field_inds_radial_order (torch.Tensor, optional) – Permutation sorting bright_field_inds by radius.

  • bright_field_inds_ordered_by_radius (torch.Tensor, optional) – bright_field_inds sorted by radius.

  • bright_field_inds_centered_ordered_by_radius (torch.Tensor, optional) – bright_field_inds_centered sorted 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 from from_4dstem_dataset()).

  • probe_index (int, optional) – Probe index for multi-probe datasets.

  • device (torch.device or str or None, optional) – None keeps 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 dataset that reads meta instead 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. Only meta differs, and the view starts with an empty virtual-bright- field cache, so a get_vbf on it builds a provider under meta. dataset itself 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() takes meta= and does this for you.

Parameters:
  • dataset (object) – A dataset with a settable meta (a Dataset4DStem, …).

  • meta (object) – The metadata the view reads. It is bound by reference, not copied, as an assignment dataset.meta = meta would bind it.

Returns:

The view, of the same type as dataset.

Return type:

object

Raises:

TypeError – If dataset has no meta attribute or it cannot be set.

Running a reconstruction#

run

Run the reconstruction config selects on data.

Result

Base of every reconstruction result.

ReconstructionConfig

Base of every reconstruction config.

Provenance

Where a Result came from.

register_runner

Register the function run() calls for config_type.

scatterem.reconstruction.run(data: Any, config: ReconstructionConfig[R], *, reuse: Mapping[str, Any] | None = None, meta: Any = None) → R#

Run the reconstruction config selects on data.

The family is chosen by type(config) (the nearest registered class in its MRO). data and data.meta are never written to; outputs are placed on data.device or, for a runner that departs from that rule (see the module docstring), where provenance.device says.

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 G stack 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 a with_meta() view of data: it shares the array, starts with an empty vBF cache and leaves data unchanged. The result’s provenance.meta_override is True. A reused vBF ("vbf" / "vbf_cache") must have been built under this meta, for example with_meta(data, meta).get_vbf(t).

Returns:

The family’s result type, as config’s type parameter declares.

Return type:

Result

Raises:
  • TypeError – If config is not a ReconstructionConfig, if no runner is registered for its type, or if the runner does not return a Result.

  • ValueError – If reuse holds a key the family does not accept, or, with meta, a vBF provider built under other metadata.

Warns:

UserWarning – If data is 4D-STEM data whose reciprocal sampling dk is still the (1.0, 1.0) placeholder of Dataset4DStem.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]) so run() is typed per family, and sets the class attribute method.

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 Result came 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) – True when the run read metadata other than the dataset’s own (run(..., meta=...) or a with_meta() view); meta is then that metadata. Default False.

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 for config_type.

Used as a decorator in the module that implements the family. The runner is called as runner(data, config, reuse), with reuse a read-only mapping holding only keys from reuse_keys.

Parameters:
  • config_type (type) – A ReconstructionConfig subclass that sets method.

  • 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:

Direct ptychography and the aberration fit#

AberrationFitConfig

The aberration fit on a 4D-STEM dataset, run through run().

AberrationFitResult

Result of AberrationFitConfig.

DirectPtychographyConfig

Single-side-band direct ptychography, run through run().

DirectPtychographyResult

Result of DirectPtychographyConfig.

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_dataset keeps its old effect on the fit itself (whether it records the rotation, the defocus guess and the coefficients on the metadata, here reported in AberrationFitResult.meta_updates); run() writes nothing.

data is a Dataset4DStem or a DatasetVirtualBrightField4DStem.

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; None means 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_shape (tuple of int) – Shape of the region of interest.

  • roi_center (str or tuple of int) – Center of the region of interest.

  • upsample (int or str) – Upsampling factor, or "nyquist".

  • 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.rotation is 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": {...}} when check_defocus_sign was set: c10_fitted, c10_kept, energy_fitted, energy_flipped and flipped. 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.meta through the shared vBF.meta. With update_dataset=True these are aberrations, rotation and defocus_guess (reset to 0.0: the fitted defocus is in aberrations[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 with update_dataset=False, which writes no meta. None when 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:

tuple of torch.Tensor

applied_to(meta: Any) → Any#

Return a new copy of meta with this fit applied.

The copy gets every entry of meta_updates and a new Aberrations holding aberrations, with defocus_guess set to 0.0: the fitted C10 is in aberrations[0] alone, also when the fit ran with update_dataset=False. When meta_updates has no rotation (update_dataset=False, or a held rotation), the copy gets rotation, so the aberrations keep the rotation they hold at. meta itself is not modified, and the copy shares no tensor with this result.

Parameters:

meta (object) – The metadata to start from, typically the fitted data’s own.

Returns:

The updated copy.

Return type:

object

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_sigma is the one keyword that function takes through **kwargs (used by the empirical SSNR).

data is a Dataset4DStem or an already-built DatasetVirtualBrightField4DStem. reuse={"vbf": provider} supplies a vBF built at this config’s bright_field_mask_threshold from 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 G when it returns, so repeated runs on one dataset (a defocus sweep, say) all peak at the first run’s level.

Parameters:
  • upsample (float or str) – Upsampling factor, or "nyquist".

  • 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 / lambda to zero at 2 alpha / lambda, the transfer limit of direct ptychography, where the noise makes a bright rim in the spectrum (see rolloff_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), or None unless return_snr was set.

  • sampling (Sampling) – The pixel size (dy, dx) of phase and its units, the scan step divided by the upsample factor (from reconstruction_sampling()). Pass it to vis.show_2d(..., sampling=) or diagnostics.metrics.frc(..., pixel_size=).

as_tuple() → tuple[Tensor, Tensor | None]#

Return (phase, ssnr), what direct_ptychography returns.

Returns:

The phase image and the SSNR map (or None).

Return type:

tuple of (torch.Tensor, torch.Tensor or None)

Bright-field parallax#

measure_bf_parallax

Measure the translation of every BF image.

fit_aberrations_and_rotation_to_bright_field_shifts

Fit the aberrations and rotation to the bright field shifts.

aberrations_and_rotation_from_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; then n_refinements rebuilds as the aligned average. "neighbour_mesh": register detector neighbours (|Δq| <= 1.5 p, p the detector pitch; bins: indices within one) onto each other and solve the least-squares fit of s_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, with binning=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 width binning · 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_divisor scan 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, row i for input row i. 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 by t gives −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]] (with remove_image_mean=False and "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_mask in row-major (torch.argwhere) order, as aberrations_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 are fftfreq(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_order frees; “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 reliable is 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 reliable flag and, for init_method="closed_form" and correct_order=1, the covariance of C1, C12 (and the rotation, when it is fitted). It unpacks as aberrations, rotation = fit. Check reliable before a pipeline writes the values as results; the class docstring gives the fallback order. The aberrations are in the SHIFT-MODEL frame of scatterem.utils.transfer.aberrations_to_image_shifts (the model fitted here): at rotation != 0 every m-fold pair differs from the detector-frame vector meta.aberrations holds. Convert with scatterem.utils.transfer.shift_model_to_detector_frame at the fitted rotation before using them as meta.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_factor scan pixel (peak_grid_divisor of measure_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 shares meta with its parent dataset. To write only a reliable fit, pass False, check reliable and 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" of measure_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”. With alignment_method="pairwise", “guided” takes, among the peaks within 2 % of the highest, the one nearest to zero shift. With “argmax” on a periodic specimen a UserWarning flags 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 of meta.aberrations (the frame the direct-ptychography kernels and tilt-corrected dark field read): the shift-model-frame fit converted with scatterem.utils.transfer.shift_model_to_detector_frame at the fitted rotation, the same as the fit at rotation == 0. relative_residual is the largest over the bin levels, and well_posed is False if any level was not well posed, so a failed earlier level makes the result not reliable. It unpacks as aberrations, rotation = fit. When reliable is 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_factors is empty, or if the vBF does not carry its detector sampling (a 4-entry sampling and a 2-D bright_field_mask).

Scan rotation and centre-of-mass calibration#

find_scan_rotation

Find the rotation between scan and detector from the CoM field.

ScanRotation

Result of find_scan_rotation().

RotationSearch

Record of the angle search, for scatterem.vis.rotation_figures.angle_search_figure().

fit_origin

Fit the drift of the diffraction-space origin across the scan.

fit_2D

Fit a surface model function(xy, *coefficients) to a 2-D field.

plane

Affine surface z = mx*x + my*y + b (gradient (mx, my), offset b).

parabola

General 2-D quadratic surface, evaluated in Horner form.

bezier_two

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 with ScanReflectionWarning for 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=True reports 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 (search is None). If fixed_axes_exchanged is 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_deg in [-180, 180): the total rotation, including a half-turn from the 180° test. The corrected field is R(scan_turn_deg) P^h f: the half-turn is applied as an exact negation. rotated_180 flags the half-turn.

Return type:

ScanRotation

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_deg holds 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 None for fit_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 from popt. 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 the P coefficients.

  • 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, P of them. Default: zeros. Used only by the L-BFGS path.

  • robust (bool) – Re-fit robust_steps more times, each time removing from the mask the points whose squared residual is larger than robust_thresh**2 times the mean squared residual over the whole field.

  • robust_steps (int)

  • robust_thresh (float)

  • device (str, torch.device or None) – Default: the device of data if it is a tensor, else CPU.

  • need_pcov (bool) – False skips the parameter covariance of a linear basis and returns the NaN placeholder in its slot; everything else is unchanged. Default True.

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), offset b).

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 as c0 + 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 values c_ij with i indexing x and j indexing y. Because the basis is a partition of unity the surface interpolates the corner coefficients (c00 at (0,0), c22 at (1,1)) and stays within the convex hull of all nine.

Scan-rotation figures#

angle_search_figure

Plot the objective curves of a scan-rotation search.

plot_scan_maps

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 marks search_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:

matplotlib.figure.Figure

Raises:

ValueError – If search is not a RotationSearch.

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 at k · step, so the axes span n · step along 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). Default cols = 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:

matplotlib.figure.Figure

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#

TiltCorrectedDarkFieldConfig

Tilt-corrected dark field, run through run().

TiltCorrectedDarkFieldResult

Result of TiltCorrectedDarkFieldConfig.

tilt_corrected_dark_field_depth_section

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_geometry hook excepted); see it for their meaning. data is a Dataset4DStem; reuse={"segment_geometry": g} passes the private precomputed segment geometry (built on data with this config’s parameters; a mismatch raises ValueError).

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.

  • upsample (float or str) – Upsampling factor, or "nyquist".

  • 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 None unless return_snr was set.

  • sampling (Sampling) – The pixel size (dy, dx) of image and its units, the scan step divided by the upsample factor (from reconstruction_sampling()). Pass it to vis.show_2d(..., sampling=) or diagnostics.metrics.frc(..., pixel_size=).

as_tuple() → tuple[Tensor, Tensor | None]#

Return (image, ssnr), what tilt_corrected_dark_field returns.

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 of depth_angstroms (each added to aberrations[0]) and stacks the results as (n_depths, ny * up, nx * up), with up the one isotropic factor tilt_corrected_dark_field() uses (the larger of the two per-axis factors upsample resolves to). dark_field_scaling / dead_frame_fraction / region are those of tilt_corrected_dark_field() and are shared by all depths: the segment geometry that carries them is built once. The probe has the aberrations meta.aberrations with C10 less meta.defocus_guess, as in direct_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 guess meta.defocus_guess is 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 default False the 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. With return_snr=True, that stack and the per-plane half-set SSNR stack on ssnr_return_device; the SSNR slot is None only when depth_angstroms is empty (no plane to size it by).

Return type:

torch.Tensor or tuple of torch.Tensor

Fused full field#

FusedFullFieldConfig

SSNR-weighted FF-STEM fusion, run through run().

FusedFullFieldResult

Result of FusedFullFieldConfig.

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=None resolves to data.bright_field_mask_threshold, and n_dark_field_segments=None to n_batches with a warning.

Memory: the ptychography channel frees its virtual bright field and the bright-field Fourier stack G when it returns, before the tcDF channel runs. So the launch caches add no G to the peak of a repeated run on one dataset.

Parameters:
  • n_batches (int) – Bright-field chunks of the ptychography channel.

  • upsample (float or str) – Upsampling factor, or "nyquist".

  • 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 (None unless 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 a TiltCorrectedDarkFieldResult with region="bright_field").

  • tcdf (TiltCorrectedDarkFieldResult) – The dark-field channel’s result.

  • sampling (Sampling) – The pixel size (dy, dx) of fused and its units, the scan step divided by the upsample factor (from reconstruction_sampling()). Pass it to vis.show_2d(..., sampling=) or diagnostics.metrics.frc(..., pixel_size=).

as_tuple() → tuple[Tensor, Tensor | None, Tensor | None]#

Return (fused, phase_weighted, tcdf_weighted).

Returns:

The three images of the result, in this order.

Return type:

tuple

Reconstruction functions#

direct_ptychography

Reconstruct a phase image with single-side-band direct ptychography.

tilt_corrected_dark_field

Tilt-corrected dark-field reconstruction.

fused_full_field

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.aberrations with C10 less meta.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 is Q = 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_PIXELS bright-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) normalises Gamma to 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-dependent sum_K |Gamma|^2, which down-weights the upsampling replica (the aliased copies of the scan spectrum) – measured at the multiples of the scan sampling frequency 1/dr on 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 with ssnr_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 when gamma_weighting="wiener". Default is 1e-3.

  • **kwargs – snr_blur_sigma is 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 with ssnr_method="empirical".

Examples

On a tiny bright-field-disk cube, upsample=2 doubles the scan grid; return_snr=False leaves the second return None; 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.aberrations with C10 less meta.defocus_guess, as in direct_ptychography().

region selects 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_field flips it when it uses it as the phase channel. The bright-field disk holds far fewer pixels than the dark field, so use a smaller n_dark_field_segments (empty wedges are dropped rather than allowed to poison the image with NaN).

dark_field_scaling accounts 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_fraction guards the factor against dropped detector frames. A scan position recording less than this fraction of the incident current measured no probe – its factor degenerates towards incident/0 and 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 genuine recorded/incident in the scan (a thick specimen can legitimately lose over half its electrons past the detector edge).

shift_method selects 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_pixfrac sets the drop size (fraction of an input pixel; 1.0 fills the grid from one frame) and drizzle_kde_sigma optionally 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_shifts shift (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; > 0 shows the bright-field mask, > 1 also plots the SSNR curves and (with dark_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 upsample along both scan axes, in (scan_y, scan_x) order. The second slot is None unless return_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 the 2 * alpha band 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 / wavelength that set the 2 * alpha band 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 as ptycho_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 unless taper is set.

  • q_soft_end_frac (float) – Start and end of that taper, as fractions of 2 * alpha. Ignored unless taper is 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_nyquist with a cosine ramp, to suppress the low-frequency cupping halo of the direct-ptychography phase. 0.0 disables 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. None unless verbosity > 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. None unless verbosity > 1.

Raises:

ValueError – If the two images, or the two SSNRs, do not have matching shapes.

Examples

Default verbosity=0 returns the fused image and two None placeholders (filtered channels are only built when verbosity > 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#

solve_ptychography

Cold-start second-order solver for a ptychography model.

PlanarPtychography

2D mixed-state ptychography model and second-order solve target.

PlanarConstraints

Per-pass constraints of the 2D model; each one is off by default.

PassStopRule

When to stop a sequence of solver passes.

PassStopCallback

The callback(k, log) of the BH driver with a PassStopRule.

SolveTarget

The model interface of driver.solve_ptychography().

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.

module is a SolveTarget: the unified Ptychography module (through its registered adapter) or the 2D mixed-state model PlanarPtychography. The rest of this text describes the Ptychography module; 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. With optimize_positions=True the per-angle position offsets (model.dr) join as their own group(s); dr enters the forward unconditionally, so no extra flag is needed. free_path is never touched. Meant to be called directly (cold start); calling it after a partial Adam fit works the same way.

batches is 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 for Ptychography.fit; the model’s prepare_data checks 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 via ChunkedAutogradOracle.hess_quad_matrix), roughly 2-3 Adam epochs, with no learning rates to tune. "bh_cg" is for object-only refinement (with optimize_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 small G x G system 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 is bh_gd_incremental with curvature_freq=8, fd_curvature, adaptive_accept and polyak.

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.solver records the solver that ran.

compile_forward=True compiles the model’s tilt-agnostic physics core (the forward model’s compile_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. Requires solver="secant_gd" — the exact curvature path is a double-backward, which torch.compile’s AOTAutograd rejects; the secant curvature uses plain gradients only.

Parameters:
  • module (SolveTarget or object) – The model to optimize: a SolveTarget, or a Ptychography module 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") and log.reverted flags 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, None for identity. Forwarded to bh_gd_incremental (re-evaluated once per pass) or to bh_gd/bh_cg (per iteration).

  • optimize_object (bool, optional) – Include the object (sampler parameters). False refines only the probe (and positions) against a fixed, known object – e.g. one reconstructed once and reused across many probe settings. The requires_grad flag 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". Its history gets the start state (epoch=-1) and one entry per pass, and the held-out deviance becomes the solver’s selection score: 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"] == -1 when 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 every every_n_patterns training patterns (or every_n_steps batch steps), from pass start_epoch on, 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 every every_n_patterns. log.hook_steps counts the steps per pass and object_prior.sigmas holds the sigma of 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’s object_denoiser="auto" affects Adam fits only.

Returns:

Log of the solve (per-iteration losses, step sizes and diagnostics).

Return type:

BHLog

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 SolveTarget nor a Ptychography module.

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 in state_dict.

  • positions (Tensor) – (K, 2) integer top-left object pixels of the probe windows.

  • offsets (Tensor) – (K, 2) sub-pixel offsets dr in pixels; refined with optimize_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 V from 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_tol is set and the pass has a state change rel (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, when purity_tol is set;

  • the state has moved (one pass with rel > probe_tol), when needs_move is set. Before that, a seed on the plateau before the transition has rel near 0 while the loss still falls.

The solve stops after patience consecutive passes that meet the rule, but not before min_iters passes. Independently, with passes_after_move set, 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 a PassStopRule.

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 PlanarPtychography or a Ptychography module. Its constraints are module.apply_pass_constraints() if it has that method, else the constraint schedule module._apply_all_constraints(), gated on the pass index: start_epoch and freq count 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, reverted and, with rule.purity_tol set, 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 to batch_loss().

Parameters:
  • *args – Unused: a protocol is a type, not instantiated.

  • **kwargs – Unused: a protocol is a type, not instantiated.

radial_support

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).

Parameters:
  • probe (Tensor) – (M, 1, N, N) complex modes.

  • radius_frac (float) – Radius of the flat part as a fraction of N / 2.

  • margin (float) – Width of the cosine edge in pixels.

Returns:

The constrained modes; a one-mode probe comes back unchanged.

Return type:

Tensor

mode_purity

Purity sum(p_i^2) of the normalised mode powers p_i.

state_change

Change 1 - F of the mixed state between two passes.

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 powers p_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:

float

scatterem.reconstruction.ptychography.iterative.second_order.stop_rule.state_change(previous: Tensor, current: Tensor) → float#

Change 1 - F of the mixed state between two passes.

F = Tr(rho_1 rho_2) / sqrt(Tr rho_1^2 Tr rho_2^2) with rho = sum_i |m_i><m_i|, the normalised Hilbert-Schmidt fidelity of the two mode sets. F does 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 - F is 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 - F in [0, 1]; 0 when the two density matrices are proportional.

Return type:

float

as_solve_target

The SolveTarget of model.

register_solve_target

Register an adapter that turns a model into a SolveTarget.

scatterem.reconstruction.ptychography.iterative.second_order.target.as_solve_target(model: Any) → SolveTarget#

The SolveTarget of model.

Parameters:

model (object) – A model that implements SolveTarget, or one that a registered adapter accepts.

Returns:

model itself, or the target the first accepting adapter returns.

Return type:

SolveTarget

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#

bh_gd

Gradient descent with the Newton step-size rule (BH-GD, paper eq.

bh_gd_incremental

Minibatch (incremental) per-group BH-GD — LSQML-style updates.

bh_cg

Nonlinear CG with Daniel's Hessian beta and Newton step size (BH-CG).

bh_qn

Truncated-Newton method (BH-QN): inner linear CG solves H y = -g.

BHLog

Per-iteration log shared by all BH solvers.

AutogradOracle

Generic bilinear-Hessian oracle via double-backward autograd.

ChunkedAutogradOracle

Autograd oracle over per-batch loss closures; f = sum_b closure_b().

LinearLeastSquaresOracle

Oracle for a sum-of-mse loss with linear per-batch forwards.

rdot

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_backtracks is a step-acceptance safeguard (as in bh_qn()): if the step increases the loss, halve it and retry, up to max_backtracks times, 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 new oracle.loss() call; and with callback=None the next iteration’s loss_before is the logged loss, because grad() and the curvature solve do not move the parameters. This matters for an oracle without a forward cache (ChunkedAutogradOracle: one sweep per loss()).

Parameters:
  • oracle (object) – Full-batch oracle exposing params, grad(), hess_op() and loss().

  • 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, see BHLog). Default None.

  • precond (callable, optional) – Per-iteration diagonal preconditioner: precond(params) returns one positive map per parameter; the direction becomes -precond_i * g_i (supersedes rho; the Newton rule sizes any direction).

Returns:

Log of losses, step sizes and timing across iterations.

Return type:

BHLog

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 with params, None = unbounded) is a per-group trust radius on the inf-norm of a single batch step: the solved alpha is rescaled so max|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_backtracks halvings, full revert on failure) and an optional global relax factor on the solved step sizes. seed enables per-pass batch shuffling (deterministic). With a single closure, one pass is exactly one full-batch bh_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 the create_graph double-backward; same memory as a gradient pass.

  • adaptive_accept: after _ADAPTIVE_ACCEPT_WARMUP consecutive 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 in log.polyak.

  • group_slices: explicit step-size groups as (param_index, mode) pairs — mode=None for 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_clip aligns with the GROUPS, not the params.

  • batch_growth: variance annealing — whenever a pass stalls (improves by < _STALL_FRAC of 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_PASS steps, i.e. n_batches // 8 for large batch counts — one step per full-data sweep is wasted compute); merge factor per pass in log.batch_merge.

  • early_stop: n_passes becomes a CAP. The run ends after _EARLY_STOP_PATIENCE consecutive stalled passes — with batch_growth each 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. With early_stop or polyak the best-loss pass is snapshotted and the final parameters are the best of {last iterate, tail average, best pass} (log.polyak); log.early_stop records where and why the run ended.

log.losses/log.wall carry one entry per PASS (the exact full loss after the pass — costs one extra forward sweep); log.group_alphas one 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.reverted says whether pass k was 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 the range of 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:

BHLog

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=True replaces 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 step sum_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_prev equals the H s of 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 one grad_and_loss() call, because both are evaluated at the same iterate. This needs callback=None (a callback may move the iterate). Bit-identical.

  • forward_hess_quad = True: on the last iteration H s is used only through <H s, s>, so hess_quad_forward(s) gives it from forwards only and the last adjoint pass is skipped. It rounds differently from rdot(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() and loss().

  • 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:

BHLog

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_backtracks is a step-acceptance safeguard: if the Newton-rule step increases the loss, revert and halve alpha, up to max_backtracks times; 0 disables.

Parameters:
  • oracle (object) – Full-batch oracle exposing params, grad(), hess_op() and loss().

  • 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:

BHLog

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_alpha solvers, alphas records the first group’s step size and group_alphas the full per-group vector; otherwise group_alphas stays empty.

Parameters:
  • losses (list[float]) – Loss value recorded at each pass.

  • 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_alpha solvers; 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.

  • reverts (list[int]) – Pass indices that were reverted.

  • batch_merge (list[int]) – Merge factor applied at each pass.

  • early_stop (dict, optional) – Why and where a run ended early: reason="plateau" or reason="score" (bh_gd_incremental(early_stop=True)), or reason="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 G curvature 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 score after each pass (bh_gd_incremental(score=...)); empty without a score.

  • hook_steps (list[int]) – Number of step_hook calls 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_grad is 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_op accumulate 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 matrix A_ij = H(e_i, e_j) computed in ONE sweep over the batches (one create_graph backward 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_grad is 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_batches with LINEAR per-batch forwards A_i (e.g. tomographic projection of a volume).

batches is a sequence of (pred_fn, data) pairs where pred_fn() evaluates that batch’s forward at the current value of param and 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_op exploits linearity: the Hessian is the constant mse-normalized 2 A^T A, so H v equals the gradient evaluated at x = v with zero data; it is computed by temporarily writing v into 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 = True tells bh_cg() that it may reuse H s of the previous iteration as H s_prev. fused_grad_loss = True tells it that grad_and_loss() returns the values of grad() and loss() at the same iterate. forward_hess_quad = True tells it that hess_quad_forward() gives <H s, s> without the adjoint.

Parameters:
  • param (Tensor) – Leaf tensor the loss depends on. requires_grad is enabled on it here.

  • batches (sequence of tuple) – Sequence of (pred_fn, data) pairs where pred_fn() evaluates that batch’s forward, linear in param, at its current value, and data is 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#

probe_aperture_support

Project the probe modes onto an aperture-plane support, power kept.

measured_bbox_support

The bounding box of the measured pixels, as a float support.

ray_band_mask

A band of half_width pixels along a ray from center.

embed_centred

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 by support in 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:

torch.Tensor

Raises:
  • KeyError – If support is 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:

torch.Tensor

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_width pixels along a ray from center.

With (dy, dx) the offset of a pixel from center, 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 most half_width and it is on the ray’s side of the centre.

Parameters:
  • shape (tuple of int) – Grid (H, W).

  • 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:

torch.Tensor

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) of mask goes to (N0 // 2, N1 // 2), as the detector_pad_to model grid places the recorded block. The pixels outside the block are zero (False).

Parameters:
  • mask (torch.Tensor) – (My, Mx) map, centred.

  • shape (tuple of int) – Target (N0, N1), at least (My, Mx).

Returns:

(N0, N1) map, dtype and device of mask.

Return type:

torch.Tensor

Raises:

ValueError – If the target is smaller than mask.

absorption_bound

bound_absorption() as a regularization: object constraint.

bound_absorption

Reset opaque pixels and remove 2 pi phase jumps of one object slice.

median5

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 a regularization: object constraint.

The absorption is -log(amplitude); a zero amplitude (an opaque pixel whose transmission underflowed) gives inf and 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) and margin in pixels (default 64).

Returns:

The new (amplitude, phase), same shapes.

Return type:

tuple of torch.Tensor

Raises:

KeyError – If width is 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.

  1. A pixel is bad when |absorption - med| > width, with med the median absorption of the central region (a margin pixel border left out, clipped to leave at least 2 x 2 pixels).

  2. 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 to med +- width.

  3. 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) phase Re V in rad.

  • absorption (torch.Tensor) – Real (H, W) absorption Im V; inf for 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 bad does 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 of x.

Return type:

torch.Tensor

orthogonalize_probe

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.eigh returns 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 previous squeeze(1) path only handled K == 1 and broke the write-back for PRISM probes).

Ptychography losses#

normalized_amplitude_rmse_loss

Compute the normalized amplitude RMSE between two diffraction stacks.

masked_normalized_amplitude_rmse_loss

normalized_amplitude_rmse_loss() over the valid detector pixels only.

masked_mean

Mean of values over the True pixels of valid (broadcast).

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 of valid. An all-True mask gives normalized_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 values over the True pixels of valid (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#

remove_probe_gauges

Canonical mode stack of a reconstructed probe, gauges removed.

remove_translation_gauge

Shift all modes together so the total-intensity centroid is at the centre.

remove_phase_ramp_gauge

Remove the linear phase ramp that ptychography cannot attribute.

to_aperture_plane

Transform real-space-centred modes to the centred aperture plane.

oam_spectrum

Compute the OAM power spectrum of a mixed state about a sorting axis.

mean_oam

Return the mean OAM sum_l l P_l / sum_l P_l in units of hbar.

oam_density_matrix

Project a mixed state onto the OAM basis, tracing out the radius.

adjacent_coherence

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:

numpy.ndarray or torch.Tensor

Raises:

ValueError – If probe is 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:

numpy.ndarray or torch.Tensor

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} with O e^{-2 pi i q.r} gives the same data. The ramp shifts the aperture-plane intensity by q, so the centroid q (pixels, relative to (H // 2, W // 2)) of sum_m |A_m|^2 with A = fftshift(fft2(ifftshift(psi))) is measured and exp(-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-integer q makes 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:

numpy.ndarray or torch.Tensor

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 is 1 / (W * dx) in reciprocal space.

Return type:

numpy.ndarray or torch.Tensor

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 (the r is the polar area element), normalised to sum_l P_l = 1 over -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 intensity sum_m |psi_m|^2.

  • l_max (int, optional) – Largest |l| reported; must be < n_theta / 2. Default n_theta // 2 - 1 (all resolvable charges).

  • r_min (float, optional) – Radial sampling range in pixels. r_max defaults to min(H, W) / 2 - 1.

  • r_max (float, optional) – Radial sampling range in pixels. r_max defaults to min(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) reports exp(+i l theta) as +l; -1 flips 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_max is out of range or l_sign is 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_l in units of hbar.

Parameters:
Returns:

Population-weighted mean charge.

Return type:

float

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_max and normalised to Tr rho = 1. It is Hermitian and positive semi-definite; its diagonal equals oam_spectrum() with the same arguments. Off-diagonal rho[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); see oam_spectrum().

  • center (tuple of float, optional) – Sorting axis (cy, cx) in pixels; default the intensity centroid.

  • l_max (int, optional) – Largest |l| kept; default n_theta // 2 - 1.

  • r_min (float, optional) – Radial sampling range in pixels; r_max default min(H, W)/2 - 1.

  • r_max (float, optional) – Radial sampling range in pixels; r_max default min(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,) with L = 2 l_max + 1.

  • rho (numpy.ndarray or torch.Tensor) – Complex density matrix, shape (L, L), rows/columns ordered as ls.

Raises:

ValueError – If l_max is out of range or l_sign is 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]) where i0 is the most populated channel and j the more populated of i0 - 1 and i0 + 1. g = 0 for an incoherent OAM mixture, g = 1 for a coherent superposition with a common radial profile.

Parameters:

rho (numpy.ndarray or torch.Tensor) – OAM density matrix, shape (L, L), e.g. from oam_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 rho has fewer than two channels.

Named datasets#

You2026Carbon

Amorphous carbon, 300 kV (paper Figure 2).

You2026Co3O4

Co3O4, 200 kV (paper Figure 2).

You2026AuLowDose

Au nanoparticle, 200 kV, low dose (paper Figure 4).

You2026Gd2O3

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#

AcquisitionMetadata

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 of NY x NX positions (same step and rotation) that starts at row y0 and column x0. 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-metric W (a pixel at offset p from the disk centre records k = W (p dk)) or a (T, 2) polynomial table. See scatterem.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#

Aberrations

Lens aberration coefficients with named access and convention helpers.

SMeta

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) or Aberrations(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 PrismScanOp uses 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_beams for 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.

  • M (tuple of int) – Simulation grid shape (MY, MX).

  • device (torch.device) – Device to build the tensors on.

Aberrations and the probe#

LENS_LAYOUT

Labels of the 12 slots of a lens vector, in order: the Krivanek names "C10", "C12a", "C12b", ..., "C34b" (Krivanek et al. 1999).

LENS_TERMS

(order n, multiplicity m, part) of each slot.

AMPLITUDE_LAYOUT

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".

pack_lens

Make a lens vector from labelled values.

unpack_lens

Make labelled values from a lens vector.

lens_wavefront

Evaluate the lens wavefront W [rad] on frequency coordinates.

lens_wavefront_slope

Evaluate the slope (dW/dk_y, dW/dk_x) [rad Angstrom] of the wavefront.

lens_to_amplitude

Convert a lens vector to the magnitude-angle form.

lens_from_amplitude

Convert the magnitude-angle form back to a lens vector.

RIM_WIDTH_PX

Convert a string or number to a floating-point number, if possible.

smooth_disc

Return a disc with a logistic rim on a grid in DFT order.

smooth_annulus

Return a ring with logistic rims on a grid in DFT order.

illumination_disc

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 order n, then multiplicity m, then the a part (factor cos(m phi)) before the b part (factor sin(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. Part c multiplies cos(m phi), part s multiplies sin(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 of LENS_TERMS. A slot with m = 0 holds its signed value. For m > 0 the "C<n><m>" slot holds the magnitude M [Angstrom] and the "phi<n><m>" slot holds the angle alpha [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_LAYOUT are 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) or AMPLITUDE_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. None means CPU.

Returns:

Shape (12,), in the order of layout.

Return type:

torch.Tensor

Raises:
  • TypeError – If values is not a mapping, a value is not real, or dtype is not float32 or float64.

  • ValueError – If a label is not in layout, a value is not finite, or layout is 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 of layout.

  • layout (tuple of str, optional) – LENS_LAYOUT (default) or AMPLITUDE_LAYOUT.

Returns:

All 12 labels with their values.

Return type:

dict of str to float

Raises:

ValueError – If the shape is not (12,) or layout is 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), with B the batch shape of lens and G the broadcast shape of fy and fx. Lens b gives 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 of LENS_LAYOUT. A tensor must be on the device of fy. The function casts it to the result dtype and keeps its autograd graph. A sequence is copied to the device of fy; this copy can make the host wait.

  • fy (torch.Tensor) – Frequency coordinates k_y and k_x [1/Angstrom], float32 or float64, on one device, broadcastable to the grid shape G.

  • fx (torch.Tensor) – Frequency coordinates k_y and k_x [1/Angstrom], float32 or float64, on one device, broadcastable to the grid shape G.

  • lambda_a (float) – Wavelength [Angstrom], a finite host scalar larger than zero.

Returns:

Wavefront [rad], shape (*B, *G), dtype promoted from fy and fx. With a lens tensor on CUDA, the call does not synchronise the host.

Return type:

torch.Tensor

Raises:
  • TypeError – If fy or fx is not a real float tensor, lens is not a floating tensor or lambda_a is not a host real scalar.

  • ValueError – If the devices differ, the grids do not broadcast, the last dimension of lens is not 12 or lambda_a is 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_y and k_x [1/Angstrom].

  • fx (torch.Tensor) – Frequency coordinates k_y and k_x [1/Angstrom].

  • lambda_a (float) – Wavelength [Angstrom], finite and larger than zero.

Returns:

Shape (*B, *G, 2) [rad Angstrom]. [..., 0] is dW/dk_y and [..., 1] is dW/dk_x.

Return type:

torch.Tensor

Raises:
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) becomes M = hypot(A, B) [Angstrom] and alpha [rad] with A = M cos(m alpha) and B = M sin(m alpha). The angle is in [0, 2 pi / m). M = 0 gives alpha = 0; there the derivative by the coefficients is not defined. A slot with m = 0 keeps its signed value. The order of the result is AMPLITUDE_LAYOUT.

Parameters:

lens (torch.Tensor or sequence of float) – Shape (..., 12) in the order of LENS_LAYOUT [Angstrom]. A sequence becomes a float64 CPU tensor.

Returns:

Same shape, dtype and device as lens.

Return type:

torch.Tensor

Raises:
  • TypeError – If lens is 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) and B = M sin(m alpha). Any real M and alpha are accepted.

Parameters:

amp (torch.Tensor or sequence of float) – Shape (..., 12) in the order of AMPLITUDE_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:

torch.Tensor

Raises:
  • TypeError – If amp is 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 d is 1 / (1 + exp(4 (d - R) / w)), with d = 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. Default RIM_WIDTH_PX.

  • px_ratio (float, optional) – Ratio s of the axis-1 pixel width to the axis-0 pixel width [1], finite and larger than zero. None means square pixels (s = 1).

  • dtype (torch.dtype, optional) – Real dtype. None means torch.get_default_dtype().

  • device (torch.device or str, optional) – Device. None means torch.get_default_device().

Returns:

Shape (Ny, Nx), values in [0, 1], no autograd graph.

Return type:

torch.Tensor

Raises:
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)), with f the disc profile of smooth_disc(), p the inner and q the 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 w of both rims [axis-0 pixel]. Default RIM_WIDTH_PX.

  • px_ratio (float, optional) – Pixel width ratio s [1]. None means square pixels.

  • dtype (torch.dtype, optional) – Real dtype. None means torch.get_default_dtype().

  • device (torch.device or str, optional) – Device. None means torch.get_default_device().

Returns:

Shape (Ny, Nx), values in [0, 1], no autograd graph.

Return type:

torch.Tensor

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 ratio s = g_x / g_y and the rim width RIM_WIDTH_PX. Thus its rim is at the angle a in 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 a of the condenser opening [rad], zero or larger.

  • lambda_a (float) – Wavelength [Angstrom], finite and larger than zero.

  • dtype (torch.dtype, optional) – Real dtype. None means torch.get_default_dtype().

  • device (torch.device or str, optional) – Device. None means torch.get_default_device().

Returns:

Shape (Ny, Nx), values in [0, 1], no autograd graph.

Return type:

torch.Tensor

Raises:

Calibration helpers#

measure_pupil

Measure the radius and the centre of the bright-field disk.

PupilEstimate

Radius and centre of the bright-field disk.

ESTIMATORS

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 to alpha / (lambda * radius) [1/length], for the aperture semi-angle alpha [rad] and the wavelength lambda [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_in and I_out come 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_out that counts as a disk, at least 1. Default 1.5. If I_out <= 0 the 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:

PupilEstimate

Raises:
  • TypeError – If pupil_frame is complex, bool or not an array, or a setting has a wrong type.

  • ValueError – If pupil_frame is 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 above radius_cap, a level ratio below contrast_floor, an incomplete disk for "integral", or an edge coverage below arc_floor for "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#

debroglie_at

Return the relativistic de Broglie wavelength of an electron.

gamma_at

Return the Lorentz factor gamma = 1 + E_J / (m0 c^2) [1].

moving_mass_at

Return the mass m = gamma m0 [kg] of a moving electron.

phase_per_potential_at

Return the interaction parameter sigma = 2 pi m e lambda / h^2.

bend_per_tesla_at

Return e / p [1 / (Tesla Angstrom)] of an electron.

EXACT_PLANCK

Planck constant h [J s].

EXACT_E_CHARGE

Elementary charge e [C].

EXACT_LIGHT_SPEED

Speed of light in vacuum c [m/s].

EXACT_AVOGADRO

Avogadro constant N_A [1/mol].

EXACT_BOLTZMANN

Boltzmann constant k_B [J/K].

CODATA18_ELECTRON_MASS

Electron rest mass m0 [kg].

CODATA18_DALTON

Atomic mass constant m_u [kg].

CODATA18_FINE_STRUCTURE

Fine-structure constant alpha [1].

CODATA18_VACUUM_MU

Magnetic constant mu_0 [N/A^2].

CODATA18_ELECTRON_RADIUS

Classical electron radius r_e [m].

DERIVED_PLANCK_BAR

Reduced Planck constant hbar = h / (2 pi) [J s].

DERIVED_ELECTRON_REST_EV

Electron rest energy m0 c^2 / e [eV].

DERIVED_AB_COUPLING

Coupling e / hbar [rad / (Tesla Angstrom^2)].

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:

float

Raises:
  • TypeError – If kinetic_ev is not a real number.

  • ValueError – If kinetic_ev is zero, negative, NaN or infinite.

Notes

An electron that a potential difference of U volts accelerates has E = U eV. 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 = 0 and 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:

float

Raises:
  • TypeError – If kinetic_ev is not a real number.

  • ValueError – If kinetic_ev is negative, NaN or infinite.

Notes

An electron that a potential difference of U volts accelerates has E = U eV. 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 = 0 and then returns m0.

Parameters:

kinetic_ev (float) – Kinetic energy E [eV], zero or larger.

Returns:

Mass m [kg].

Return type:

float

Raises:
  • TypeError – If kinetic_ev is not a real number.

  • ValueError – If kinetic_ev is negative, NaN or infinite.

Notes

An electron that a potential difference of U volts accelerates has E = U eV. 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 phase sigma 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:

float

Raises:
  • TypeError – If kinetic_ev is not a real number.

  • ValueError – If kinetic_ev is zero, negative, NaN or infinite.

Notes

An electron that a potential difference of U volts accelerates has E = U eV. 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 value e / p = 1 / (B r) is the curvature 1 / r of 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:

float

Raises:
  • TypeError – If kinetic_ev is not a real number.

  • ValueError – If kinetic_ev is zero, negative, NaN or infinite.

Notes

An electron that a potential difference of U volts accelerates has E = U eV. 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 (from m0).

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_COUPLING times the line integral of the vector potential [Tesla Angstrom]. The factor 1e-20 converts 1/m^2 to 1/Angstrom^2.

Structures#

AtomSet

One atomic structure in a rectangular, axis-aligned box (immutable).

read_atom_set

Build an AtomSet from one structure file on disk.

has_partial_occupancy

Return True if any site fraction is below 1 - FULL_OCCUPANCY_TOLERANCE.

DEFAULT_TILT_SINE

Convert a string or number to a floating-point number, if possible.

FULL_OCCUPANCY_TOLERANCE

Site fractions at or above 1 - FULL_OCCUPANCY_TOLERANCE count as full.

MAX_SUPERCELL_FACTOR

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 along row0 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^T with Q the 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:

AtomSet

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 to fixed_point + R @ (r - fixed_point), with R the active, right-handed turn of scatterem.rotation.axis_angle.to_matrix(). Z, site fractions, <u²>, charges and the atom order are kept; tensors become R 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:

AtomSet

Notes

Finite specimen: the input box turns about its centre into a tilted block. Its extent along box axis i is the turned centre plus or minus sum_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 raises ValueError; use as_crystal=False then.

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: all M = n0 * n1 * n2 copies of atom j come first as one block, then those of atom j + 1. Inside a block the copy index is i0 + n0 * (i1 + n1 * i2) (i0 runs fastest). So row j * M + i0 + n0 * (i1 + n1 * i2) is atom j moved by (i0, i1, i2) box lengths, and its source is row // 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:

AtomSet

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 AtomSet from 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: .xyz kirkland, .p1 poscar, .xtl mustem, .cif cif, .extxyz extxyz.

  • 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 keeps DEFAULT_U2 with 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:

AtomSet

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 - tolerance is full.

Return type:

bool

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_TOLERANCE count as full. Reason: the supported formats write occupancies with four decimals or more (CIF practice 0.3333; muSTEM and Kirkland files 1.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#

BeamPartition

Slicing of the cell along the beam, with exact fractional edges.

species_order

Return the distinct atomic numbers of an atom set in ascending order.

edge_snap_margin

Return the snap margin mu for coordinates of one dtype.

EDGE_SNAP_ULPS

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 + 1 strictly increasing edges in [0, 1] [fractional]. Each value is converted exactly with Fraction; a float converts exactly. Python and numpy reals and Fraction are 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 < 0 or e_S > 1.

Notes

Slice k is [e_k, e_{k+1}). Exact edges give the rule “slice k is [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 count equal slices of the cell.

Parameters:

count (int) – Number of slices, at least 1. Python or numpy integer, not bool.

Returns:

Edges Fraction(k, count) for k = 0 .. count.

Return type:

BeamPartition

Raises:
classmethod from_thicknesses(thicknesses, depth) → BeamPartition#

Return the slicing with given slice lengths along the beam.

Parameters:
  • thicknesses (sequence of float) – Slice lengths [Angstrom], each finite and > 0.

  • depth (float) – Box length along the beam sides[2] [Angstrom], finite, > 0.

Returns:

Edges are the exact partial sums of Fraction(t_k) divided by Fraction(depth), starting at 0. A last edge within EDGE_SNAP_ULPS * 2**-53 of 1 becomes exactly 1, because a sum of float lengths carries rounding.

Return type:

BeamPartition

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:

torch.Tensor

thicknesses(depth) → tuple[float, ...]#

Return the slice lengths for a box of length depth.

Parameters:

depth (float) – Box length along the beam [Angstrom], finite and > 0.

Returns:

float((e_{k+1} - e_k) * Fraction(depth)) [Angstrom], each rounded once.

Return type:

tuple of float

subrange(first: int, stop: int) → BeamPartition#

Return the partition of slices first .. stop - 1.

Parameters:
  • first (int) – Slice range, 0 <= first < stop <= S.

  • stop (int) – Slice range, 0 <= first < stop <= S.

Returns:

Edges e_first .. e_stop.

Return type:

BeamPartition

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:

  1. Reduce into [0, 1): r = z - floor(z); a rounded r == 1 becomes 0 (the cell is periodic along the beam).

  2. Interval test on the float64 edges f_k = float(e_k): slice k with f_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 when f_k is below e_k, so the computed layer k / n is in slice k of uniform(n).

  3. With edge_snap, a coordinate with e_{k+1} - mu <= r for an inner edge (k + 1 < S) goes to slice k + 1, with mu = edge_snap_margin(dtype) of the input dtype. The last edge never moves.

  4. A reduced coordinate below e_0 or at/after e_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 mu before 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:

numpy.ndarray or torch.Tensor

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_0 gives slice 0; a coordinate with z >= e_S gives slice S - 1. Other coordinates follow the interval test and the edge snap of bin_index().

Parameters:
Returns:

The int64 slice indices in 0 .. S - 1, as in bin_index().

Return type:

numpy.ndarray or torch.Tensor

scatterem.physics.beam_partition.species_order(atom_set) → tuple[int, ...]#

Return the distinct atomic numbers of an atom set in ascending order.

Parameters:

atom_set (AtomSet) – The structure.

Returns:

Ascending distinct Z; () for an empty set. The order depends only on the content, so a permuted atom set gives the same sequence. The rows of per-element form spectra follow this sequence.

Return type:

tuple of int

scatterem.physics.beam_partition.edge_snap_margin(dtype: dtype = torch.float64) → float#

Return the snap margin mu for 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-9 for float64 and 6.10e-5 for float32. For cells deeper than about 100 Angstrom, use float64 coordinates: the float32 margin is 6.1e-5 * depth.

Return type:

float

Raises:

TypeError – If dtype is 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 than EDGE_SNAP_RELATIVE. 512 eps covers the few eps of such an error with a factor of more than 10. It sets the float32 margin and the end tolerance of BeamPartition.from_thicknesses().

Projected potentials#

potential_stack

Return the projected potential of each slice of a periodic field of view.

check_stack_request

Check the shared inputs of a potential build.

StackRequest

Validated values of a potential request.

resolve_stack_device

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, area A = L_y L_x, the Fourier coefficient of slice s is:

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 atom j in copy c (after the thermal offset), p its share in the slice (beam_spread), a_j = o_j w_j (o_j the site fraction when site fractions are in use, else 1; w_j the coefficient c_j or c_j**2, else 1) and F_Z the 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 n is the band-limited point value of the series over the FFT-order frequencies J:

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 slice s is V_s(0).

Method: each atom copy goes on two interlaced grids (points n h and n h + h/2) with the cubic B-spline; the mean of the phase-corrected rfft2 spectra divided by sinc^4 gives 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"; see axial_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_j per 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 in species_order(). Default potential_spectra (Z <= 103). With autograd through it, the graph keeps S E half-layout grids. Build it for this field of view (same points and replicas); 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()). Default DEFAULT_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:

torch.Tensor

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"; an msd with grad, "binned" and draws along the beam; "smeared" with draws along the beam; a group with <u^2> = 0 where a derivative is needed; a site fraction replacement with ignore_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**2 instead of c_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:

StackRequest

Raises:
  • TypeError – For a value of a wrong type (also bool as an integer, a complex or non-numeric atom_scale, a bad dtype).

  • ValueError – For a wrong pair length, a count below 1, or an atom_scale with 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.

Parameters:
  • replicas (tuple of int) – Copy counts (c_y, c_x).

  • lengths (tuple of float) – Field-of-view lengths (c_y sides[0], c_x sides[1]) [Angstrom].

  • points (tuple of int) – Grid point counts (Ny, Nx).

  • real_dtype (torch.dtype) – The real dtype, float32 or float64.

scatterem.physics.potential_stack.resolve_stack_device(device, *tensors) → device#

Return the device of a build.

Rules:

  1. A given device wins. Tensor inputs move to it.

  2. Else the device of the tensor inputs (form spectra, coefficients, replacement tensors). Inputs on more than one device raise.

  3. 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.Tensor objects count.

Returns:

The device of the build.

Return type:

torch.device

Raises:

ValueError – If device is None and the tensors are on more than one device.

Per-row replacements#

RowReplacements

Tensors that replace per-atom data of an AtomSet in a build.

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 AtomSet in 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 along y and x.

  • 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 with ignore_site_fraction=True refuses 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 an msd or 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 AtomSet with these values would. The object stores the tensors as given, without a copy.

Thermal displacements#

ThermalJitter

Request for one frozen-phonon configuration of a build.

jitter_offsets

Return the thermal offsets of one build, per cell copy [Angstrom].

colocated_rows

Return group labels of rows that describe one site.

COLOCATION_TOLERANCE

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 - 1 that fixes the draws. It seeds a local torch.Generator on the build device; the global generators do not change. Without draw_seed, the object takes a fresh 63-bit value from secrets.randbits(), stores it and logs it at INFO, so a run can be repeated afterwards. Every build with one object uses its draw_seed.

  • transverse_only (bool, optional) – If True (default), the atoms move only along y and x. If False, they also move along the beam.

Raises:
  • TypeError – If draw_seed is not an integer or transverse_only is not a bool.

  • ValueError – If draw_seed is outside 0 .. 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) (copy i_y slowest, then i_x, then the row group, then the axis (y, x)). With transverse_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 by sqrt(u_g) * xi along y and x, and with jitter.transverse_only=False by sqrt(u_g) * zeta along the beam. u_g is 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 derivative xi / (2 G_g sqrt(u_g)) reaches each of the G_g rows. The values xi and zeta are the stream of ThermalJitter, the same that potential_stack() uses.

Parameters:
  • atom_set (AtomSet) – The structure.

  • replicas (tuple of int) – Copy counts (c_y, c_x).

  • 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 with transverse_only. Copy (i_y, i_x) is the cell moved by (i_y sides[0], i_x sides[1]). The fractional beam offset is offset[..., 2] / sides[2]. The result carries the graph of overrides.msd.

Return type:

torch.Tensor

Raises:

ValueError – If overrides.msd requires grad and a group has u_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 most tolerance (d the difference of fractional coordinates, all three box axes). The cell is periodic, so rows at 0.0 and 0.99999 can 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 (then sides is None), or (N, 3) fractional coordinates together with sides.

  • 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,) in 0 .. G - 1. Labels follow the first row of each group in row order, so row 0 has label 0.

Return type:

numpy.ndarray

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.

Depth shares#

axial_shares

Return the share of each item in each slice.

AxialShares

Sparse shares of items in slices.

BEAM_SPREADS

Spellings of the models of the distribution along the beam.

GAUSS_IMAGE_REACH

Periodic images of the normal profile reach this many standard deviations.

scatterem.physics.axial_shares.axial_shares(partition: BeamPartition, beam_fraction: Tensor, msd: Tensor, depth: float, *, beam_spread: str = 'binned', edge_snap: bool = True, snap_dtype: dtype | None = None) → AxialShares#

Return the share of each item in each slice.

Rules:

  • "binned": share 1 in partition.bin_index(r, edge_snap=...). Items in no slice get no entry.

  • "tent": with the midpoints m_k = (e_k + e_{k+1}) / 2 and m_k <= r < m_{k+1}, slice k gets (m_{k+1} - r) / (m_{k+1} - m_k) and slice k + 1 gets (r - m_k) / (m_{k+1} - m_k). Below m_0 the pair is (S - 1, 0) with midpoints m_{S-1} - 1 and m_0; at or after m_{S-1} it is (S - 1, 0) with m_{S-1} and m_0 + 1. On a midpoint the slice gets 1. At a midpoint, autograd gives the slope of the segment that starts there (the right-hand derivative).

  • "smeared": with s = sqrt(<u^2>) / depth, slice k gets sum_{m=-M..M} [Phi((e_{k+1} - r - m) / s) - Phi((e_k - r - m) / s)] with M = ceil(GAUSS_IMAGE_REACH * max s). Each difference is taken on the tail side. An item with <u^2> = 0 gets the binned share, exactly.

Parameters:
  • partition (BeamPartition) – The slicing. "tent" and "smeared" need a partition that covers the cell.

  • beam_fraction (torch.Tensor) – (K,) real beam coordinates [fractional], after any draw along the beam, not reduced.

  • msd (torch.Tensor) – (K,) <u^2> of the row group of each item [Angstrom^2].

  • depth (float) – Box length along the beam sides[2] [Angstrom].

  • beam_spread (str, optional) – One of BEAM_SPREADS. Default "binned".

  • edge_snap (bool, optional) – Edge snap of the binned share (see bin_index()).

  • snap_dtype (torch.dtype, optional) – The dtype of the coordinate source, which sets the snap margin. Default the dtype of beam_fraction.

Returns:

Sparse (item, slab, share). Memory is O(K) for "binned" and "tent" and O(K S) for "smeared".

Return type:

AxialShares

Raises:

ValueError – For an unknown model, or "tent"/"smeared" with a partition that does not cover the cell.

class scatterem.physics.axial_shares.AxialShares(item: torch.Tensor, slab: torch.Tensor, share: torch.Tensor)#

Sparse shares of items in slices.

Entries are sorted by slab, then by item.

Parameters:
  • item (torch.Tensor) – The int64 (P,) index into the inputs.

  • slab (torch.Tensor) – The int64 (P,) slice index.

  • share (torch.Tensor) – The float64 (P,) share [dimensionless], with the autograd graph of the beam coordinates and <u^2>.

scatterem.physics.axial_shares.BEAM_SPREADS = ('binned', 'tent', 'smeared')#

Spellings of the models of the distribution along the beam.

scatterem.physics.axial_shares.GAUSS_IMAGE_REACH = 8#

Periodic images of the normal profile reach this many standard deviations. Reason: the sum over all slices and images telescopes to Phi((1 - r + M) / s) - Phi((-r - M) / s) with both arguments at least 8 in magnitude, and Phi(-8) = 6.2e-16; so the shares add up to 1 within 1.3e-15 plus rounding, 100 times below the bound 1e-12.

Potential rolloff#

rolloff_mask

Return the rolloff T on the DFT grid, in FFT order.

check_rolloff

Return a valid rolloff setting.

DEFAULT_ROLLOFF

Default rolloff depth w.

scatterem.physics.potential_rolloff.rolloff_mask(points, rolloff, *, half_layout: bool = False, device=None, dtype=None) → Tensor#

Return the rolloff T on 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 depth w:

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, T does not increase along any ray from 0, and T = 0 at and beyond the Nyquist frequency.

Parameters:
  • points (tuple of int) – Grid point counts (Ny, Nx).

  • rolloff (float or None) – Depth w in (0, 1), or None for ones.

  • half_layout (bool, optional) – If True, return the rfft2 layout (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:

torch.Tensor

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 depth w [normalised radius] in (0, 1).

Returns:

None or float(rolloff_depth).

Return type:

float or None

Raises:
  • TypeError – If rolloff_depth is a bool, a str or not a real number.

  • ValueError – If rolloff_depth is not finite or not in (0, 1).

scatterem.physics.potential_rolloff.DEFAULT_ROLLOFF = 0.3333333333333333#

Default rolloff depth w. Reason: with w = 1/3 the rolloff is 1 for r <= 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#

spectrum_sweep

Open a scope in which potential builds reuse their layout spectra.

SweepLedger

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 changes D. 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#

SpatialRouteSettings

Settings of the real-space route (immutable, hashable).

choose_route

Resolve the route choice of a simulator.

route_rolloff

Resolve the potential rolloff for a route.

check_route

Return a route name after a check.

check_cutoff

Return a positive, finite threshold as a Python float.

ROUTE_NAMES

Route spellings: the Fourier-space route and the real-space route.

DEFAULT_PROJECTED_CUTOFF

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 a volume_cutoff with "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 of ROUTE_NAMES.

Returns:

For "either": "spatial" when multi_device, else "spectral". A route name gives itself.

Return type:

str

Raises:
  • TypeError – If multi_device is not a bool or preference not 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_ROLLOFF for "either", None for None, check_rolloff(w) for a number. "spatial": None for "either" and None.

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:

str

Raises:
  • TypeError – If value is not a str.

  • ValueError – If value is 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:
  • cutoff_level (float) – Threshold [Volt or Volt Angstrom].

  • field_label (str) – Name of the checked field, for the message.

Returns:

The checked threshold.

Return type:

float

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-4 rad/(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#

thin_slice_transmission

Return the thin-slice transmission function of each slice.

phase_from_projection

Return the phase shift phi = sigma(E) V [rad].

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') with sigma = phase_per_potential_at(E). The code evaluates torch.polar(amp, phi) with phi = sigma V and amp = 1 (no absorption) or amp = exp(-sigma V'). So |t| = 1 to 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 of V, because it comes from the same projected build with absorptive form spectra; so no slice length enters. Real; it broadcasts to the shape of V without enlarging it, and moves to the device and dtype of V with 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 (see ellipse_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 reaches V and V'.

Return type:

torch.Tensor

Raises:
  • TypeError – For a non-tensor or non-real V, a complex V' 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. sigma is phase_per_potential_at() [rad / (Volt Angstrom)].

Return type:

torch.Tensor

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#

born_amplitude

Return the electron scattering amplitude f_e(g) of a neutral atom.

born_amplitude_array

Return f_e(g) [Angstrom] as a numpy float64 array.

born_amplitudes

Return f_e(g) [Angstrom] for a list of atomic numbers.

potential_spectra

Return the Fourier transforms of atomic potentials on a 2-D grid.

gamma_wavelength

Return the product of the Lorentz factor and the wavelength.

validated_atomic_number

Return the atomic number as int after a check against Table 1.

POTENTIAL_PER_AMPLITUDE

h^2 / (2 pi m0 e) [Volt Angstrom^2]: the Fourier transform of the atomic potential [Volt Angstrom^3] is this factor times f_e [Angstrom] (Lobato and Van Dyck 2014, eq.

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 gives d f_e / d g through the same float64 graph.

Parameters:
  • frequency (torch.Tensor) – Spatial frequency g [1/Angstrom], real floating tensor of any shape. f_e is even in g, so a negative value gives f_e(|g|).

  • atomic_number (int) – Atomic number Z in 1..103.

Returns:

f_e [Angstrom], with the shape, dtype and device of frequency.

Return type:

torch.Tensor

Raises:
  • TypeError – If frequency is 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 Z in 1..103.

Returns:

f_e [Angstrom], float64, shape np.shape(frequency).

Return type:

numpy.ndarray

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:
Returns:

(S, *shape). Slice k is equal bit for bit to the one-element form for the k-th number.

Return type:

torch.Tensor or numpy.ndarray

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 g is V(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^2 from dft_sample_frequencies(). On a 2-D grid this is the 3-D transform at k_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 area A [Angstrom^2], divide by A and apply the inverse FFT (torch.fft.ifft2 includes the factor 1 / (Ny Nx), so multiply its result by Ny Nx).

Parameters:
  • grid (PeriodicGrid) – A 2-D grid (y, x).

  • atomic_numbers (sequence of int) – S atomic numbers, each in 1..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 with torch.from_numpy(out).to(device, dtype).

Return type:

numpy.ndarray

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 * v with the projected potential v [Volt Angstrom]. When v comes from f_e [Angstrom] through POTENTIAL_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 lambda times a sum of f_e terms, 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:

float

Raises:

ValueError – If kinetic_ev is not positive.

scatterem.physics.atom_amplitudes.validated_atomic_number(atomic_number) → int#

Return the atomic number as int after a check against Table 1.

Parameters:

atomic_number (int) – Atomic number Z. Python and numpy integers are accepted.

Returns:

Z, in 1..103.

Return type:

int

Raises:

ValueError – If Z is not an integer (bool and float are rejected), or if it is outside 1..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 times f_e [Angstrom] (Lobato and Van Dyck 2014, eq. 2). Rest mass m0; about 47.8776.

Sampling grids and pass bands#

PeriodicGrid

A periodic sampling grid: point counts and periods per axis.

dft_sample_frequencies

Return the spatial frequencies that the DFT samples on a grid.

CircularPassBand

Isotropic pass band in physical frequency on a 2-D grid.

apply_pass_band

Return the band-limited real-space field ifft2(fft2(field) * mask).

ellipse_mask

Return a low-pass mask that keeps the frequencies inside an ellipse.

lowpass_ellipse

Return a complex real-space field band-limited by the ellipse mask.

MaskCacheStats

Counters of the mask store.

mask_cache_stats

Return the counters of the mask store.

clear_mask_cache

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:
  • points (tuple of int) – Number of samples N_i per axis, axis order (..., y, x).

  • lengths (tuple of float) – Period L_i of each axis [Angstrom].

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 j by L then gives the correctly rounded j / L. The object is hashable.

classmethod from_pixel_sizes(points, pixel_sizes) → PeriodicGrid#

Make a grid from point counts and pixel sizes.

Parameters:
  • points (sequence of int) – Number of samples per axis.

  • pixel_sizes (sequence of float) – Sample spacing per axis [Angstrom].

Returns:

The grid with L_i = N_i * d_i, rounded once. The stored L_i is the reference for all frequencies.

Return type:

PeriodicGrid

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 N points and period L [Angstrom], the DFT samples the spectrum at j / L for the FFT-order integers j: 0, 1, ..., (N - 1) // 2 and 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 i has length N_i on axis i and length 1 on all other axes, so the arrays broadcast to the full grid. np.broadcast_arrays gives 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:

tuple of numpy.ndarray

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 is w = rim_samples * max(1 / L_y, 1 / L_x) [1/Angstrom], and the flat radius is k_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_c and sin(pi/2 * (k_c - |k|) / w)**2 on 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 of k_f or k_c can round to 1 or 0.

Parameters:
  • band_grid (PeriodicGrid) – A 2-D grid (y, x). Pixel sizes can differ.

  • cut_fraction (float) – k_c as 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 (see ellipse_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:

torch.Tensor

min_crop_shape() → tuple[int, int]#

Return the smallest lossless centred crop box (M_y, M_x).

The centred crop of M points keeps j from -(M // 2) to M - 1 - M // 2. Padding back returns every kept value to its own frequency. With J_i the largest |j_i| where the float64 mask is not zero, the smallest box is M_i = 2 J_i + 1, never above N_i. A mask of lower precision has no more non-zero points, so the box is valid for every dtype.

Returns:

(M_y, M_x) [samples].

Return type:

tuple of int

scatterem.physics.periodic_sampling.apply_pass_band(field: Tensor, mask: Tensor) → Tensor#

Return the band-limited real-space field ifft2(fft2(field) * mask).

Parameters:
Returns:

New field with the shape and dtype of field. Neither input changes; the autograd graph of field stays intact. A complex32 field is computed in complex64 and cast back, so the FFT sum cannot overflow.

Return type:

torch.Tensor

Raises:
  • TypeError – If field is not complex.

  • ValueError – If the mask shape does not match the last two axes of field.

  • OverflowError – If a complex32 result 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 i is rho_i times the Nyquist frequency. In index units it is R_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 if num < den. A point with num >= den (r >= 1, also r exactly 1) gets the value 0. For R_i integer or half-integer below about 2**20 this test is exact.

Alias-free size: let two fields have spectra in the open ellipse E. Their product has its spectrum in E + E = 2E. The DFT wraps frequency j onto j + (m_y N_y, m_x N_x) with integer m. A wrapped copy reaches E only if the shift lies in 2E - E = 3E. The shortest shifts are along one axis, with normalised length N_i / R_i. So no copy reaches E if N_i / R_i >= 3 on both axes, that is rho_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 - r and w = fade_depth > 0, the value is 0 for num >= den, 1 for t >= w, and sin(pi/2 * t / w)**2 between. This is the Hann taper (Harris 1978). It is monotone in t, 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.rfft2 layout (Ny, Nx // 2 + 1); column n holds j_x = n. If False, return the full layout (Ny, Nx).

  • fade_depth (float, optional) – Depth w of 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:

torch.Tensor

Raises:
  • ValueError – If shape, nyquist_fraction or fade_depth is out of range.

  • TypeError – If dtype is 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 of ellipse_mask() for the shape, real dtype and device of field. The arguments and their reasons are those of ellipse_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:

torch.Tensor

Raises:

TypeError – If field is not complex.

class scatterem.physics.periodic_sampling.MaskCacheStats(hits: int, misses: int, entries: int, nbytes: int)#

Counters of the mask store.

Parameters:
  • hits (int) – Number of requests that the store answered without a build.

  • misses (int) – Number of requests that caused a build.

  • entries (int) – Number of masks in the store now.

  • nbytes (int) – Total size of the masks in the store now [bytes].

scatterem.physics.periodic_sampling.mask_cache_stats() → MaskCacheStats#

Return the counters of the mask store.

Returns:

hits, misses (number of builds), entries and nbytes [bytes].

Return type:

MaskCacheStats

scatterem.physics.periodic_sampling.clear_mask_cache() → None#

Remove all stored masks and set the counters to zero.

STEM-EELS and PRISM driver#

PrismEelsSimulator

Core-loss EELS and elastic CBED of a periodic cell with PRISM kernels.

PrismResult

The output of one PrismEelsSimulator call.

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: pixels samples structure.sides[:2]. The scan is a regular raster of scan positions over the cell, half a step from its edges. An ionized site contributes with the weight that its atom has in the elastic potential: its site_fraction when 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) and Z).

  • 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 c uses ThermalJitter(draw_seed=seed + c). Default None: each configuration takes a fresh seed, which ThermalJitter logs at INFO.

  • device (str or torch.device or None, optional) – Device of every tensor. None (default): the CPU, the device of the NumPy AtomSet (simulator convention). Pass "cuda" for the GPU.

  • dtype (torch.dtype, optional) – torch.complex64 (default) or torch.complex128 for the EELS kernels. The elastic CBED runs in the precision of PrismScanOp.

Variables:
  • sampling (wavelength, gridsize,) – Electron wavelength [Angstrom]; cell size sides[:2] and pixel size gridsize / pixels [Angstrom].

  • slice_distance (slice_thickness,) – sides[2] / num_slices, and the propagation distance the EELS kernels take: slice_thickness, but 0.0 for one slice.

  • device (torch.device) – The resolved device. Every other argument is stored under its name.

Raises:

ValueError – If dtype is 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 probe ifft2(probe_q) carries unit total intensity.

Return type:

torch.Tensor

scan_pixels() → Tensor#

Scan positions in grid pixels.

Returns:

(Sy * Sx, 2) float64 (y, x) positions, row-major over the raster.

Return type:

torch.Tensor

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 dtype dtype.

Return type:

torch.Tensor

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:

numpy.ndarray

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:
  • edge (sequence of int) – (Z, n, l) of the ionized subshell, e.g. (22, 2, 1) for Ti L.

  • epsilon (float) – Energy of the ejected electron above the threshold [eV].

  • **transitions (Any) – Passed to subshell_transitions (order, wavefunctions, xc, potential_scale, lprimes).

Returns:

The stack on this grid, in dtype.

Return type:

TransitionPotentials

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 element Z ionizes.

  • 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", data of shape scan.

Return type:

PrismResult

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_axis of prism_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 (see eels_map()).

Returns:

output="qeels", data of shape scan + (n_q,) and the matching q_pixels. Summing data over its last axis gives the map of eels_map() with the same settings.

Return type:

PrismResult

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", data of shape scan + pixels.

Return type:

PrismResult

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 window pixels // interpolation_factor and 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 without n_radial.

Returns:

output="cbed", data of shape scan + window.

Return type:

PrismResult

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 PrismEelsSimulator call.

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 of q_pixels;

    • "cube": scan + pixels, corner-origin diffraction patterns;

    • "cbed": scan + window, corner-origin diffraction patterns on the PRISM window pixels // interpolation_factor.

  • output ({"map", "qeels", "cube", "cbed"}) – What data holds.

  • energy (float) – Probe energy [eV].

  • detector_sampling (tuple of float) – Reciprocal pixel (dky, dkx) of the diffraction axes of data [1/Angstrom]. For "qeels" it converts q_pixels to 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 that prism_eels_image returns with the patterns, in grid pixels. (n_q, 2) in (qy, qx) order for qeels_axis="both", (n_q,) for a one-axis projection. None for the other outputs.

Transition potentials#

subshell_transitions

All channels of one ionised subshell at one continuum energy.

build_transition_potentials

Real-space transition potentials H_n0 on a periodic grid.

Transition

One ionisation channel: bound orbital (l, ml) to continuum (l', ml').

TransitionPotentials

Real-space transition potentials of a set of channels on one grid.

AtomicRadialWavefunction

Radial one-electron state u(r) = r R(r) on a grid in Bohr.

bound_wavefunction

Bound radial state (n, l) of element Z, cached on disk.

continuum_wavefunction

Continuum radial state l' at epsilon eV above threshold, cached.

gpaw_available

Tell if gpaw can be imported, without importing it.

cache_dir

Return the EELS on-disk cache directory and create it if it is missing.

HydrogenicFallbackWarning

wavefunctions="auto" fell back to the analytic hydrogenic family.

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 L edge: Z=26, n=2, l=1).

  • n (int) – Element and the ionized bound orbital (e.g. Fe L edge: Z=26, n=2, l=1).

  • l (int) – Element and the ionized bound orbital (e.g. Fe L edge: Z=26, n=2, l=1).

  • epsilon (float) – Energy of the ejected electron above the ionization threshold [eV]. Selecting different epsilon selects different points along the energy-loss edge.

  • lprimes (list of int, optional) – Continuum angular momenta to include. Default: every l' >= 0 with |l - l'| <= order.

  • order (int) – Maximum change in angular momentum |l - l'| retained when lprimes is not given explicitly. The leading small-K term of a channel has the multipole order |l - l'|, so order = 1 keeps the dipole channels and the l' = l channel.

  • wavefunctions (str) – "auto" (default: GPAW if importable, else hydrogenic with a HydrogenicFallbackWarning), "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 by l', then ml, then mlprime.

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_n0 on a periodic grid.

fft2(array) = H~(2 pi f) / (dy dx) inside the band limit, with H~ = 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 use psi_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 on device, or with device=None on 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:

TransitionPotentials

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. n is None for continuum states.

  • l (int | None) – Principal and orbital angular-momentum quantum numbers. n is None for 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 on r.

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 element Z, 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 a HydrogenicFallbackWarning), "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:

AtomicRadialWavefunction

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' at epsilon eV 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 a HydrogenicFallbackWarning), "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.0 leaves it unchanged. It is ignored by the analytic hydrogenic wavefunctions, whose free-particle continuum has no atomic potential.

Returns:

The continuum radial wavefunction u_lprime(r), normalised per Rydberg (Manson 1972).

Return type:

AtomicRadialWavefunction

Raises:

ValueError – If epsilon <= 0.

scatterem.simulation.eels.gpaw_available() → bool#

Tell if gpaw can be imported, without importing it.

Returns:

True if gpaw is importable, False otherwise.

Return type:

bool

scatterem.simulation.eels.cache_dir() → str#

Return the EELS on-disk cache directory and create it if it is missing.

SCATTEREM_EELS_CACHE overrides the location. Otherwise the directory is $XDG_CACHE_HOME/scatterem/eels, or ~/.cache/scatterem/eels when XDG_CACHE_HOME is not set. The environment is read at call time.

Returns:

Path to the (created if missing) cache directory.

Return type:

str

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#

multislice_transition_potential

Energy-filtered diffraction patterns for a batch of probe positions.

prism_transition_potential

Dual-scattering-matrix PRISM STEM-EELS (Brown & Ophus).

prism_transition_potential_hybrid

Hybrid PRISM/multislice STEM-EELS (single scattering matrix).

prism_eels_image

Double-channeling PRISM STEM-EELS image I(x, y).

ScatteringMatrix

Plane-wave scattering matrix \(\mathcal S\) advanced by multislice.

PartitionedScatteringMatrix

Partitioned-PRISM scattering matrix (Pelz 2021) for STEM-EELS.

DetectorExitSMatrix

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 (element transition_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|^2 with return_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 iz and \(\mathcal S_2\) propagates the inelastically-scattered wave from iz to 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 position p is:

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 Nbeams columns 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 runs Nbeams times per (site, transition) – independent of the number of scan positions P – instead of P times. For P >> 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) to prism_transition_potential_hybrid(); this routine just reorders the work. Energy-filtered 4D output is preserved – S2 is 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 & Ophus I(x, y) image.

Shrinking the column count (two compatible levers).

  • interpolation_factor = f subsamples the aperture beams to Nbeams / f**2 columns – exact within the PRISM aliasing window – shrinking the exact columns of both legs (S1 build and exit) by f**2.

  • partition (e.g. {"n_radial": 4}) builds S1 on Bp << Nbeams parent 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 (Bp parent propagations) and is approximate (natural-neighbor reconstruction error – accurate in-focus / thin / small-aperture, degrading with thickness/aperture); the exit leg still propagates the reconstructed Nbeams / f**2 columns, so the dual-S P-independence is preserved. Note partitioning does not reduce the (usually dominant) exit leg – only the S1 build; interpolation_factor is the lever for the exit. The two compose (partition partitions the already-subsampled aperture). Unlike partitioning S2, this is correct: the reconstruction resolves the position-dependent NNW basis before H_{n0} is applied (see PartitionedScatteringMatrix.reconstruct_columns).

Parameters:
  • probe_q – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • transmissions – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • transition_potentials – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • sites – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • scan_pixels – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • wavelength – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • gridsize – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • slice_distance – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • return_real_space – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • interpolation_factor – As in prism_transition_potential_hybrid(). partition and interpolation_factor may be combined.

  • partition – As in prism_transition_potential_hybrid(). partition and interpolation_factor may 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|^2 with return_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)); see ScatteringMatrix. 1 (default) is exact; f > 1 subsamples the beams to speed up the scattering matrix by f**2 and is accurate while the probe fits in the 1/f window.

  • partition (dict or None) – If given (e.g. {"n_radial": 4}), use a PartitionedScatteringMatrix (partitioned PRISM, Pelz 2021) instead; interpolation_factor is 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|^2 with return_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_crop around each atom (the localized transition). None uses 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/f crop region around it (matches the interpolation-factor periodicity).

  • scan_shape ((int, int), optional) – If given, the flat (P,) image is reshaped to scan_shape.

  • partition (dict, optional) – If given (e.g. {"n_radial": 4}), build S1 on Bp parent beams (PartitionedScatteringMatrix) and reconstruct the exact aperture columns on each atom’s crop window via natural-neighbor interpolation. This cheapens the S1 build/advance + memory (Bp parents) at the cost of the NNW reconstruction error. A "focal_backprop" key overrides the focal_backprop argument for S1. None uses the exact per-pixel S1. When one slice’s windows cover the grid, both partitioned legs reuse one full-grid reconstruction per slice, within the additional workspace that reconstruction_workspace sets; sparse windows and focal referencing stay windowed.

  • partition_s2 (dict, optional) – Same idea for S2 (the detector matrix): build the transpose multislice on Bp parent detector beams and NNW-reconstruct the detector columns on the crop window, shrinking the resident S2 from ndet to Bp columns at a second NNW error. "dechirp" (default True) removes and restores the scalar vacuum beam phase around the interpolation (see DetectorExitSMatrix); "focal_backprop" turns on the Fresnel referencing of S2 (off unless given here). None keeps the full per-beam S2.

  • qeels_axis ({0, 1, "both"}, optional) – Momentum-resolved (qEELS) output. None (default) returns the scalar elemental map. 0 or 1 resolves that detector-momentum axis and projects the perpendicular one away: each beam’s |amp_d|^2 is binned by its signed frequency along qeels_axis rather than summed over all d. "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 with partition / partition_s2 (the binning is post-|amp|^2); for a faithful resolved axis use interpolation_factor == 1 along 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) coupling S2c (H S1c) once per atom and applies the scan coefficients last; it is best when P is 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 the O(n_det B |window|) intermediate and is faster for small crop windows and modest P. "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 S1 and S2 columns: 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. False is the plain complex average. Ignored without partition / partition_s2.

  • focal_backprop (float, "centroid" or None, optional) – Fresnel referencing of the partitioned S1 parents: 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) or 0 disables it. S2 uses referencing only when partition_s2 names 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); None processes 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. None uses the default of 2 GiB. 0 turns 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 without partition / partition_s2.

Returns:

With qeels_axis=None: the STEM-EELS image, (P,) or scan_shape, per incident electron and per eV (independent of the grid and of f). Otherwise (spectrum, q_pixels), where spectrum carries a trailing momentum axis ((P, n_q) or scan_shape + (n_q,)) and q_pixels is each bin’s sorted signed pixel frequency (physical q = q_pixels / gridsize[qeels_axis]). For "both", q_pixels is (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 contract or qeels_axis is not one of the listed values, or if reconstruction_workspace is 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 Bp parent 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 beam b in terms of the parents. In the full-parent limit (every beam its own parent, w the identity) this is algebraically the exact per-pixel probe, so ScatteringMatrix is the Bp -> B limit and serves as the oracle. Presents the advance_to / probe_at_current_plane interface of ScatteringMatrix plus coeffs_at() / reconstruct_columns(), so it can drive either the hybrid path or the dual-scattering-matrix exit (the reconstructed columns are scalar-combinable). Accepts interpolation_factor so 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) or 0 disables 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 to reconstruct_columns_window().

  • wavelength (float, optional) – Electron wavelength in Angstrom. With slice_distance and gridsize it sets the windowed Fresnel step that reconstruct_columns_window() needs when focal_backprop is on.

  • slice_distance (float, optional) – Slice distance in Angstrom (see wavelength).

  • gridsize ((float, float), optional) – Real-space grid extent (Ly, Lx) in Angstrom (see wavelength).

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 wave e_d* from the exit surface back to the current slice, so that for any wave w at that slice sum_r S2_d(r) w(r) == fft(forward_exit(w))[d] – the amplitude reaching detector beam d. Built once covering all slices (slice 0 -> exit) and peel_to() advances the start slice forward (removing front slices) so it is reused across every atom.

With partition the transpose multislice is built on only Bp parent detector beams (a hex-ring subsample); the full detector columns are NNW-reconstructed on a crop window via columns_window(). By reciprocity the de-tilted back-propagated columns are locally similar, so the same partitioned-PRISM interpolation applies – shrinking the resident S2 from ndet to Bp columns.

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": False is the ablation without it. None builds the full ndet columns 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 partition is 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) or 0 disables it. It is skipped in the full-parent limit, where the columns are exact.

  • wavelength (float, optional) – Electron wavelength in Angstrom. With slice_distance and gridsize it sets the windowed Fresnel step that focal_backprop needs.

  • slice_distance (float, optional) – Slice distance in Angstrom (see wavelength).

  • gridsize ((float, float), optional) – Real-space grid extent (Ly, Lx) in Angstrom (see wavelength).

Elastic PRISM#

ScanExitWaveOperator

Map a transmission function, probe and scan positions to exit waves.

PrismScanOp

Scan-time exit-wave operator that projects a partitioned S-matrix.

MultisliceScanOp

Standard per-position multislice.

build_prism_smeta

Synthesize a pure- or partitioned-PRISM, f-lattice SMeta (Ophus 2017).

build_prism_smeta_for_probe

Power-based f-lattice-shell PRISM SMeta from the probe (faithful PRISM).

class scatterem.nn.scan_exit_wave.ScanExitWaveOperator(*args, **kwargs)#

Map a transmission function, probe and scan positions to exit waves.

Two flavours of T input, decided by wants_full_fov:

  • wants_full_fov = False – T is 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 – T is 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 (default None, and None on 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, or None. A plain attribute, not a registered buffer, so it stays out of state_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_project over scan positions.

  • periodic (bool, optional) – Whether prism_project treats 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_WARP environment 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_COLS overrides.

class scatterem.nn.scan_exit_wave.MultisliceScanOp#

Standard per-position multislice.

Two transmission input flavours, selected by inverse_index:

  • inverse_index is None – T is already-gathered per-position patches of shape (NZ_bin, K, M1, M2); each slice is broadcast- multiplied into the waves.

  • inverse_index given – T is the ungathered per-unique-pixel (exponentiated) potential stack of shape (NZ_bin, U); the gather + complex multiply is fused per slice via the Warp fused_transmit kernel.

In both cases inter-slice Fresnel propagation is applied after every slice except the last (matching the model).

exit_antialias_aperture (inherited; default None, and None on every reconstruction path) optionally applies an antialiasing aperture once to the exit wave; see forward().

checkpoint_every (default 0, off) checkpoints the slice loop in segments of that many slices when a gradient is recorded (checkpointed_slice_loop in _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 is N = f * pixels per axis; the detector is N / f = pixels (dk = f·Δq).

  • f (int) – PRISM interpolation factor (>= 1).

  • dx (array-like (2,)) – Real-space pitch Δp = unitcell / pixels per axis (Å). UNCHANGED by f – 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 if f * pixels < FOV. None for a PERIODIC specimen under a periodic crop: the N grid 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 at f = 1 scan 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 by SMeta.make_beamlet_meta(n_radial, n_angular), which selects Bp << B parent beams on n_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 when n_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 / lambda instead, 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’s prism_spec["aperture"] = "kmax_margin".

Returns:

When n_radial is None: a pure-PRISM SMeta on the N grid with an f-lattice BF-disk aperture, identity natural-neighbor weights and one-hot beamlets. When n_radial is set: the partitioned SMeta (parent-beam subset Bp << B, Voronoi NNW (B, Bp), beamlets (Bp, MY, MX)).

Return type:

SMeta

Raises:

ValueError – If f * pixels < FOV (object does not fit) – the message tells the caller to increase pixels so f * 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 SMeta from the probe (faithful PRISM).

Sizes the BF-disk aperture from the incoherent multi-mode probe power spectrum instead of the fixed kmax*1.05 margin of build_prism_smeta(). The f-lattice only has beams at every f-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 reaches power_fraction of 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 the N = f*pixels grid. The incoherent power spectrum P(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 is N = f*pixels.

  • f (int) – PRISM interpolation factor (>= 1).

  • dx (array-like (2,)) – Real-space pitch Delta p per axis (Aa), UNCHANGED by f.

  • wavelength (float) – Electron wavelength (Aa).

  • semiconvergence_angle (float) – Probe semiconvergence angle (rad). kmax = semiconvergence_angle / wavelength sets the kmax*1.2 floor.

  • fov_shape ((int, int)) – Object FOV (NY_fov, NX_fov). Raises if f*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_radial is set), enclosing >= power_fraction of the incoherent probe power and never tighter than kmax*1.2.

Return type:

SMeta

Raises:

ValueError – If f*pixels < FOV (object does not fit), or the probe grid does not match N = f*pixels.

Propagation#

Propagator

Fresnel/angular-spectrum single-slice propagator for multislice simulation.

SubpixShift

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 by slice_thickness and applies it in forward() via an FFT round-trip. The ramp is built by propagator_kernel() (paraxial) or angular_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). Multiplies prop by exp(+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 kernel prop carries it; the reference-plane fresnel_kernel()/fresnel_phase() stay untilted. None or all-zero leaves prop bit-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 dr via 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 forward applies the sub-pixel shift; if False, forward only broadcasts waves to the batch of positions.

  • rdtype (torch.dtype, optional) – Real dtype of the stored frequency ramps. Default is torch.float32.

Slice transmission in ptychography#

multislice_transmit_slice

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 MultisliceScanOp route 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 None to 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_patches is 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#

beamlet_samples

Select PRISM beam coordinates closest to a polar sampling pattern.

natural_neighbor_weights

Interpolation weights of interp_points on the sites known_points.

fftshift_checkerboard

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:

numpy.ndarray

scatterem.utils.stem.natural_neighbor_weights(known_points, interp_points, minimum_weight_cutoff=0.01, method='linear', device=None)#

Interpolation weights of interp_points on the sites known_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 ramp exp(-2 pi i k (n // 2) / n)), so odd sizes are refused here rather than answered with the wrong pattern.

Parameters:
  • ny (int) – Number of rows (must be even).

  • nx (int) – Number of columns (must be even).

Returns:

(ny, nx) array of alternating -1/+1 values, -1 at [0, 0].

Return type:

numpy.ndarray

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#

fourier_shift_stack

physics.fourier.fourier_shift for many shifts -> (P, *waves.shape).

propagate

One Fresnel propagation step (FFT · kernel · IFFT).

propagator_kernel

Fresnel free-space propagator exp(-i π λ Δz |q|²) (corner origin).

propagator_phase

Unwrapped free-space phase phi with kernel = exp(1j * phi).

angular_spectrum_kernel

Exact angular-spectrum free-space propagator exp(i dz (kz - k)).

transfer_phase

Free-space phase phi(|q|^2) of a propagation by dz.

tilt_phase

Per-slice phase 2*pi*dz*(qy*tan(theta_y) + qx*tan(theta_x)) [rad].

scatterem.physics.propagation.fourier_shift_stack(waves: Tensor, shifts: Tensor, phase_bytes: int = 134217728) → Tensor#

physics.fourier.fourier_shift for 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_shift reads each entry of a host shift with float(), 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 to phase_bytes rather than built for all P at once; the output is preallocated instead of torch.stack-ing a list, which halves the peak the loop form needed. The transform then writes into that preallocation via out=: assigning its result with out[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.

fftfreq comes 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 than exp(-2j*pi*t) because the two are the same bits and the second is strictly more work: the exponent’s real part is -0.0 for every element, so a complex exp spends one of its three float64 transcendentals computing exp(-0.0) == 1.0 and then multiplying by it, and the -2j*pi*t operand has to be materialised as a complex128 plane (32 B/element) to say so. polar takes the float64 angle directly and calls only cos/sin – which is what exp reduces to here – so the identity is exact, not approximate: verified torch.equal over 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 as exp(-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 the r7_eels target 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: polar is bound by double-precision sin/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 that sincos() 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 explicit stream=. 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-D waves, that kernel also applies wq * before its store, again with the same bits.

ifft2’s own 1/N normalisation is torch’s, not cuFFT’s – the C2C plan is unnormalised, so norm="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. When ny*nx is an exact power of two, 1/N is an exponent decrement, so it commutes bit-for-bit with every multiply and add in the transform and can ride on wq – 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, so norm="forward" on its own merely turns a fused scalar-multiply into a plain copy_ 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 small and fine rows 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, chunk being 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-two N the pre-scaling rounds where the post-scaling did not, which would move the sha256 contracts r7_eels is 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): waves shifted by each row of shifts.

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 the 1/(MY*MX) folded into the propagator instead: torch applies the default norm="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 into propagator_kernel: that is public API, and _detector_exit._conj_propagate normalises its own inverse transform with the same kernel.

Do NOT try to fold this round trip onto waves with out=. Both torch.fft.fft2(w, out=w) and out= into a distinct buffer are bit-exact, but torch’s CUDA out-variant transforms into a fresh allocation and copies into out, so each one costs a full extra read+write of the stack: at the r7_eels/wide/conventional shape (2048 x 192 x 192 complex128, 1152 MiB) the round trip goes 37.5 -> 41.3 ms for one out= 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 (see propagator_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 phi with kernel = 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) kz is clamped to zero, so the kernel there is exp(-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 by dz.

Parameters:
  • q2 (Tensor) – |q|^2 in 1/Angstrom^2 (q in cycles per Angstrom), float64, any shape and device.

  • wavelength (float) – Electron wavelength, in Angstrom.

  • dz (float) – Propagation distance, in Angstrom (may be negative).

  • method (str, optional) – "fresnel"/"paraxial" or "angular_spectrum"/"asm".

Returns:

Phase in radians, shape, dtype and device of q2; the transfer function is exp(1j * phi).

Return type:

Tensor

Raises:

ValueError – If method is 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 by scatterem.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:

torch.Tensor

Grids#

dual_mesh

Return the DFT sample frequencies of a 2-D grid, both components.

shell_means

Return the mean of a spectrum over shells of constant |q|.

ShellMeans

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) and 1 / (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.float32 or torch.float64. The default is torch.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 the y frequency of row i and entry [1, i, j] is the x frequency of column j. Entry 0 holds the y frequencies and entry 1 the x frequencies. Use torch.fft.fftshift(out, dim=(-2, -1)) to centre it.

Return type:

torch.Tensor

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 (see dual_mesh). The shells are equally spaced in |q| with the spacing D = max_a 1 / (N_a d_a), the coarsest frequency step. Shell k is at q_k = k D.

A sample at |q| = x D with k0 = floor(x) and t = x - k0 gives the weight (1 - t) J to shell k0 and t J to shell k0 + 1 (linear interpolation). The factor J = (D / |q|)^(n - 1) for n axes cancels the growth of the number of samples with |q|, so the effective weight in |q| is a symmetric tent about q_k. The bias for a smooth f(|q|) is then about f''(q_k) D^2 / 12. The sample at |q| = 0 gives the weight 1 to shell 0. The shell mean is sum w v / sum w, so it is linear in the values and a constant array gives that constant.

Outer limit: q_lim is the smallest of the largest positive axis frequencies, min_a floor((N_a - 1) / 2) / (N_a d_a). The output holds the shells k with (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_wavenumber is in [1/length].

Return type:

ShellMeans

Raises:
  • TypeError – If spectrum_samples is complex, bool or not an array, or a pitch is not a real number.

  • ValueError – If spectrum_samples has fewer than two axes, an axis has fewer than 3 points, spectrum_samples holds 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

Show 2D data as one panel or as a grid of panels.

show_2d_array

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_meta of the input if it has one; else the bar reads 1 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 Sampling or a dict of its fields). Default is None: use array.sampling_meta if 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; axes must 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 of figax get the tick, axis-label and spine sizes too. Save the figure inside use_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) and cbar (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. With combine_images, the one row of panels is blended into one image by _show_2d_combined instead.

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. axes is 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, cbar and figsize are accepted in kwargs then.

  • scalebar ("auto", bool, dict, or ScalebarConfig, default="auto") – The scale bar of the panels that scalebar_panel selects.

  • 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 replaces norm.

  • **kwargs (dict) – Passed to every panel, for example norm, cmap, role or cbar. title is 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 figax do not have the grid shape, or if combine_images gets several rows or a per-panel keyword.

  • NotImplementedError – If combine_images is used with cbar=True.

EELS radial states#

resolve_wavefunctions

Resolve a wavefunctions choice to "gpaw" or "hydrogenic".

hydrogenic_bound_wavefunction

Normalised hydrogenic bound state on a uniform grid.

free_continuum_wavefunction

Free continuum state, normalised per Rydberg.

scatterem.simulation.eels.physics.radial.resolve_wavefunctions(wavefunctions: str) → str#

Resolve a wavefunctions choice to "gpaw" or "hydrogenic".

Parameters:

wavefunctions (str) – "auto", "gpaw" or "hydrogenic". "auto" resolves to "gpaw" when GPAW is importable, else to "hydrogenic" with a HydrogenicFallbackWarning.

Returns:

"gpaw" or "hydrogenic".

Return type:

str

Raises:

ValueError – If wavefunctions is 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) and N = sqrt((2Z/n)^3 (n-l-1)! / (2n (n+l)!)), where L is the generalised Laguerre polynomial with L^(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 / Z Bohr, 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 from Z / n as 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:

AtomicRadialWavefunction

Raises:

ValueError – If l is not in 0 <= 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), with k = sqrt(epsilon / Ry) in 1/Bohr. Far out u -> (pi k)^(-1/2) sin(k r - l pi/2), so int u_E u_E' dr = delta(E - E') with E in 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:

AtomicRadialWavefunction

Raises:

ValueError – If epsilon <= 0.

Crystal phases#

Phase

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 (component i along row i of cell). N may 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 in AtomSet.

  • msd (None, float or array_like, optional) – (N,) or scalar, Angstrom^2, >= 0. Isotropic mean-square displacement <u^2> along one direction. None gives DEFAULT_U2.

  • adp (None or array_like, optional) – Shape (N, 3, 3), Angstrom^2. Symmetric anisotropic displacement tensors U, Cartesian in the frame of the cell rows. None (default) means isotropic sites (msd only). A structure factor uses a tensor as exp(-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#

atomic_number

Return the atomic number of an element symbol.

atomic_weight

Return the abridged standard atomic weight of an element.

symbol

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:

int

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:

float

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).

scatterem.crystal.elements.symbol(z: int) → str#

Return the chemical symbol of an atomic number.

Parameters:

z (int) – Atomic number, 1 to 118.

Returns:

The symbol, for example "Si" for 14.

Return type:

str

Raises:

ValueError – If z is not between 1 and 118.

Fourier helpers#

phase_ramp

Build the Fourier phase ramp that shifts a grid of shape by shift.

fourier_shift

Shift x by shift pixels along its last axes (Fourier shift theorem).

fourier_rescale

Resample x to a new pixel size by cropping or zero-padding its spectrum.

dft_center

Return the index of the zero frequency in a spectrum of real-space shape.

fftshift_last2

Return torch.fft.fftshift(x, dim=(-2, -1)), bit-identical, ONE buffer.

fftshift_rfft

Apply fftshift to every spatial axis of an rfft spectrum but the last.

ifftshift_rfft

Undo fftshift_rfft().

rfft_shape

Return the shape of torch.fft.rfftn over every axis of shape.

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 shape by shift.

The ramp is exp(-2j * pi * (k_0 * s_0 + k_1 * s_1 + ...)), summed in axis order, with k_i the fftfreq (cycles per pixel) of axis i. Multiplying a spectrum by it and transforming back moves the content by +shift pixels.

For real x, irfftn(rfftn(x) * phase_ramp(x.shape, s, rfft=True), x.shape) equals fourier_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, because fourier_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 with float()), 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 has n_{D-1} // 2 + 1 non-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 axis n_{D-1} // 2 + 1 when rfft).

Return type:

Tensor

Raises:

ValueError – If shift does not address exactly len(shape) axes.

scatterem.physics.fourier.fourier_shift(x: Tensor, shift: Sequence[float] | Tensor, *, ndim: int | None = None, ramp_dtype: dtype = torch.float64) → Tensor#

Shift x by shift pixels along its last axes (Fourier shift theorem).

Periodic; equals torch.roll for 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 with float() (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 route irfftn(rfftn(x) * phase_ramp(..., rfft=True)) agrees with this function for real x only under the Nyquist condition phase_ramp() states.

Parameters:
  • x (Tensor) – Real or complex (..., n_0, ..., n_{D-1}); the last D axes 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 of x.

  • ndim (int, optional) – Number of shifted axes D. Default: inferred from shift; 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 shift and ndim disagree, D exceeds x.ndim, or the leading shapes of a tensor shift and x do 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 x to 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. taper adds a raised-cosine roll-off below the band edge, which removes the ringing of a hard cut.

Axis i gets round(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 last D axes are resampled.

  • sampling_in (sequence of float) – Pixel size of x per resampled axis.

  • sampling_out (sequence of float) – Requested pixel size per resampled axis.

  • ndim (int, optional) – Number of resampled axes D. Default len(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 - taper and 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, x itself is returned, not a copy.

  • sampling (tuple of float) – The pixel size actually achieved, n_i * sampling_in[i] / n_out_i; exactly sampling_in[i] on an axis whose size did not change.

Raises:

ValueError – If the sampling lengths disagree with ndim, ndim exceeds x.ndim, a sampling is not finite and positive, an axis would get fewer than one sample, or taper is 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:
  • shape (sequence of int) – Real-space shape.

  • rfft (bool) – Whether the spectrum is an rfft half spectrum; its last axis is never shifted, so the zero frequency stays at index 0 there.

  • fftshifted (bool) – Whether the (other) axes were fftshifted, which puts the zero frequency at n // 2.

Returns:

Index of the zero frequency, one entry per axis.

Return type:

tuple of int

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 i of the last two dims is at (i + n//2) % n.

Return type:

Tensor

scatterem.physics.fourier.fftshift_rfft(x: Tensor, ndim: int) → Tensor#

Apply fftshift to 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:

x with its zero frequency moved to n_i // 2 on axes 0 .. 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:

x with its zero frequency back at index 0 on axes 0 .. D-2.

Return type:

Tensor

scatterem.physics.fourier.rfft_shape(shape: Sequence[int]) → tuple[int, ...]#

Return the shape of torch.fft.rfftn over every axis of shape.

Parameters:

shape (sequence of int) – Real-space shape.

Returns:

shape with its last entry replaced by shape[-1] // 2 + 1.

Return type:

tuple of int

Axis-angle rotations#

to_matrix

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 @ v turns a column vector v counter-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.

  • sin and cos of 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_norm raises RuntimeError.

The quaternion route agrees with Rodrigues’ formula cos(angle) I + sin(angle) K + (1 - cos(angle)) u u^T to 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#

from_axis_angle

Build the quaternions of right-handed turns about axes.

from_matrix

Convert rotation matrices to quaternions.

from_rotation_vector

Build the unit quaternions of rotation vectors.

multiply

Compute the Hamilton product q1 ⊗ q2.

to_matrix

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). w is negative for |angle| > pi; the function does not fold the sign.

Return type:

torch.Tensor

Notes

Three dtype rules apply:

  • The output dtype is the type promotion of axis and angle.

  • sin and cos of 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_norm raises RuntimeError.

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), with w >= 0.

Return type:

torch.Tensor

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 is w. The quaternion is (cos(|w| / 2), sin(|w| / 2) w / |w|). The function writes sin(|w| / 2) / |w| as sinc(|w| / 2 pi) / 2, so it is smooth at w = 0 and has a finite gradient there. That is where every gradient refinement of an orientation starts. Unlike from_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_matrix of the result is the rotation matrix exp([w]_x).

Return type:

torch.Tensor

scatterem.rotation.quaternion.multiply(q1: Tensor, q2: Tensor) → Tensor#

Compute the Hamilton product q1 ⊗ q2.

The result applies rotation q2 followed by q1, matching the composition R1 @ R2 of 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:

torch.Tensor

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:

torch.Tensor

Display and animation#

show

Show obj as a good default figure.

show_animated

Show obj as an animation (inline in notebooks, a file when headless).

save_animated

Write obj's animation to path (.mp4 or .gif).

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 obj as 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.show in a GUI.

  • **opts – View-specific options, for example point_group="m-3m".

Returns:

The figure. saved_path is set when a file was written.

Return type:

ShownFigure

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 obj as 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 ValueError for 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.

  • style (str) – As for show().

  • background (str) – As for show().

  • **opts – View-specific options.

Returns:

MP4 (or GIF without the anim extra) with an inline HTML form.

Return type:

Animated

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 to path (.mp4 or .gif).

Parameters:
Returns:

The written file (the .gif when MP4 was not possible).

Return type:

pathlib.Path

Raises:

ValueError – If the suffix is not .mp4 or .gif.

Colour maps and normalisation#

choose_colormap

Choose a colour map by Fig.

colormap_for_role

Choose the colour map for one of the named ROLES.

register_colormaps

Register every Crameri map with matplotlib under its bare name.

ColourChoice

A colour map chosen by choose_colormap(), with its reasons.

DataTraits

The answers to the questions of Fig.

NormalizationConfig

Settings for CustomNormalization.

CustomNormalization

Map data into [0, 1] for display: interval selection, then a stretch.

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:

ColourChoice

Raises:

ValueError – If background is 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:

As choose_colormap().

Return type:

ColourChoice

Raises:

KeyError – If role is 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_2d wraps 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 the lower_quantile/upper_quantile of the finite data, "manual" uses vmin/vmax (falling back to the finite data range for either one left as None), "centered" uses vcenter +/- half_range (half_range defaults to the largest finite deviation from vcenter).

  • stretch_type ({"linear", "power", "logarithmic", "asinh"}) – Which stretch to apply; see _stretch_pair() for the formulas.

  • lower_quantile (float) – Quantiles in [0, 1] with lower < upper, used by "quantile".

  • upper_quantile (float) – Quantiles in [0, 1] with lower < 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 > 0 of the "power" stretch.

  • logarithmic_index (float) – Curvature a > 0 of the "logarithmic" stretch.

  • asinh_linear_range (float) – Linear-range parameter a > 0 of 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/vmax are 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.Normalize compatibility. The result is confined to [0, 1] in any case, because the normalized value is clipped before the stretch is applied.

  • **overrides – Any NormalizationConfig field, 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_style

Use the scatterem style inside a with block.

figure_params

Return the rcParams of a figure style, as show(style=...) uses them.

draw_scale_bar

Draw a scale bar on ax and return the length it represents.

ScalebarConfig

Where and how the plot functions draw a scale bar.

UncalibratedDataWarning

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 with block.

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 to show_2d(..., style="paper"). Save the figure inside the block: savefig.dpi and 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_cycle from line_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:

dict

Raises:

ValueError – If style is 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 ax and 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_pixels must 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 for pixel_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.035 is 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.0 if the geometry was degenerate and nothing was drawn.

Return type:

float

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 AnchoredSizeBar convention). 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. None scales it with the bar thickness.

class scatterem.vis.UncalibratedDataWarning#

An image has no physical calibration, so its scale bar reads “1 a.u.”.

Colour#

complex_to_rgba

Colour an image, using phase as hue when it is given.

phase_wheel

(colors, angles) for a phase colorbar: one full turn of hue.

tile_to_rgba

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 phase as hue when it is given.

Parameters:
  • amplitude – values in [0, 1] (normalise before calling).

  • phase – angles in radians. When None, cmap is applied and the result is an ordinary colormapped image.

  • cmap – matplotlib colormap name, used only when phase is 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.

lightness is 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#

Sampling

Per-axis image calibration.

reconstruction_sampling

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. None means 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 its sampling[:2] the scan step. Its units[: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 of image.

Returns:

The pixel size (dy, dx) and the units of the two real-space axes.

Return type:

Sampling

Raises:

ValueError – If neither image nor shape is given, or the shape is not 2-D.

Saving and loading#

Serializable

Give a declared-schema class save() and load.

load_serializable

Read a file written by Serializable.save(), as one of candidates.

read_schema

The class, version and field list of a file, without constructing anything.

SerializationError

A file cannot be written, or cannot be loaded faithfully.

SCHEMA_VERSION

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() and load.

Subclasses set SERIAL_FIELDS to 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 another Serializable (or a list of them) names the class it holds in SERIAL_NESTED; a tuple there allows any one of several classes.

A subclass that declares neither SERIAL_FIELDS nor _from_fields itself 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 of candidates.

Parameters:
  • path (str or pathlib.Path) – The HDF5 file.

  • candidates (sequence of type) – The classes the caller allows, each a Serializable subclass. 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:

Serializable

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, -1 if absent), class (the stored class name), module (its module, None for files that predate it) and fields (the recorded field list).

Return type:

dict

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 module and __pytype attributes, numbered subgroups for a list of objects) do not bump it.

Supporting modules#

scatterem.data.detector_warp#

as_detector_warp

Validate a detector warp: None, a (2, 2) W or a (T, 2) table.

bright_field_k

The wave vector (ky, kx) each bright-field pixel records, float32.

detector_warp_matrix

The area-preserving stretch W of an elliptical bright-field disk.

polynomial_warp

k + sum_ab c_ab (k_y / k_ref)^a (k_x / k_ref)^b for a (T, 2) table.

warp_table

The (T, 2) polynomial table of a warp; W becomes degree 1.

scatterem.data.detector_warp.as_detector_warp(value: Any) → Tensor | None#

Validate a detector warp: None, a (2, 2) W or 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 triangular T >= 3, an entry is not finite, or det W is 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 sampling dk per detector axis, 1/A per pixel, on the device of centered.

  • meta (object) – The acquisition metadata. Its detector_warp (absent or None: no warp) is applied as k = 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:

torch.Tensor

scatterem.data.detector_warp.detector_warp_matrix(ellipticity: float, tilt_deg: float) → ndarray#

The area-preserving stretch W of an elliptical bright-field disk.

Parameters:
  • ellipticity (float) – 1 - b / a of the disk on the detector, minor over major semi-axis, in [0, 1). 0 is a round disk and gives the identity.

  • tilt_deg (float) – Angle of the major axis from the row (k_y) axis toward the column (k_x) axis, in degrees.

Returns:

(2, 2) float64, (row, col) order. Symmetric, det W = 1. It maps a pixel offset on the major axis to sqrt(1 - e) times that offset, and one on the minor axis to 1 / sqrt(1 - e) times it, so the elliptical disk maps to a round one.

Return type:

numpy.ndarray

Raises:

ValueError – If ellipticity is 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)^b for 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 of k.

Returns:

(..., 2) true k, dtype of k.

Return type:

torch.Tensor

scatterem.data.detector_warp.warp_table(warp: Any, reference: float = 1.0) → Tensor#

The (T, 2) polynomial table of a warp; W becomes degree 1.

Parameters:
  • warp (array_like) – A (2, 2) W or a (T, 2) table (as_detector_warp()).

  • reference (float, optional) – k_ref of the returned table, 1/A (default WARP_REFERENCE). The same field: a degree-d row scales by (reference / WARP_REFERENCE)^d. A k_ref near the detector’s reach keeps a Newton inverse well scaled.

Returns:

(T, 2) float64 on the CPU.

Return type:

torch.Tensor

Raises:

ValueError – If warp is None or not a valid warp.

scatterem.data.geometry#

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 convention R = Rx(psi) @ Ry(theta) @ Rz(phi). R maps lab -> volume.

scatterem.nn.regularizers.tv#

anisotropic_tv_subgradient

Exact (sub)gradient of the mean anisotropic TV loss.

isotropic_tv_subgradient

Exact gradient of the mean isotropic TV loss of total_variation_3d().

mean_abs_forward_diff

Mean absolute forward difference of vol along dim.

total_variation_2d

Mean anisotropic total variation over the last two axes of an image.

total_variation_3d

Mean 3D total variation of a dense [D, H, W] volume (differentiable).

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() with isotropic=False on a [D, H, W] volume. Its derivative is the discrete divergence of sign(grad v) scaled by 1 / numel(diff) of that axis: sign of 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’s abs does. Pure tensor math (no autograd graph, no backward), so it can be injected straight into object.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 interior i in [0, D-1) x [0, H-1) x [0, W-1), with forward differences d.[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. With eps > 0 the 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 by total_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 H and W when 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, so tv_weight in 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#

lens_to_warp

Return a lens vector as a 1-D float32 Warp array in the same order.

lens_wavefront_f32

Return the lens wavefront W [rad] at one frequency point, in float32.

lens_wavefront_focus_f32

Return W [rad] for a lens vector whose sole non-zero slot is 0.

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. None means the device of the tensor, or CPU for a sequence.

Returns:

Shape (12,), dtype wp.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 W32 and the float64 value W64 of 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_j the basis polynomial of slot j. 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_y and k_x [1/Angstrom].

  • fx (wp.float32) – Frequency coordinates k_y and k_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 slot C10). If the other 11 slots are +0.0 or -0.0 and all inputs are finite, it returns the same float32 bits as lens_wavefront_f32(). This needs the default Warp setting without fast-math; fast-math would void it.

Rule: the host picks lens_wavefront_focus_f32 or lens_wavefront_f32 before 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_y and k_x [1/Angstrom].

  • fx (wp.float32) – Frequency coordinates k_y and k_x [1/Angstrom].

  • lambda_a (wp.float32) – Wavelength [Angstrom], larger than zero.

Returns:

Wavefront [rad].

Return type:

wp.float32

scatterem.reconstruction.darkfield.core#

compute_ssnr_from_halfset_images

Estimate the radial spectral SNR from two independent half-set images.

gaussian_blur1d

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/tcDF2 as two independent noise realizations of the same signal (N = (FA - FB) / 2 estimates the noise spectrum, S = (FA + FB) / 2 the signal-plus-noise spectrum), radially bins their power in Fourier space, and forms SSNR(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:

tuple of (torch.Tensor, torch.Tensor, torch.Tensor)

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 <= 0 return x unchanged.

Returns:

The blurred 1D tensor, reflect-padded at the edges.

Return type:

torch.Tensor

scatterem.reconstruction.darkfield.drizzle#

drizzle_resample

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 – many index_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. The N dithered 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. Frame n’s input pixel (i, j) is deposited at HR position (i * U + dy_n, j * U + dx_n): input pixel i maps to HR pixel i * U, matching Fourier zero-pad upsampling, plus the sub-pixel shift. Moved to the device and accumulation dtype of images.

  • upsample (int) – Integer output magnification U; the output is H * U by W * U.

  • pixfrac (float) – Drizzle drop size as a fraction of one input pixel, in (0, 1]. The deposited footprint is a box of side pixfrac * U HR 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 of images. With return_parts=True, the triple (image, accum, hits): accum is the flux grid, which conserves images.sum() for in-frame content, and hits is the summed coverage weight.

Return type:

Tensor or tuple of Tensor

Raises:

ValueError – If images is not 3-dimensional, if shifts is not (N, 2) matching it, if upsample is below 1, or if pixfrac is outside (0, 1].

scatterem.vis.colors#

UnscientificColormapWarning

A plot was asked to use a colour map outside the scientific allow-list.

resolve_display

The colour choice and normalisation for one displayed image.

simulate_cvd

Simulate how a person with a full dichromacy sees sRGB colours.

srgb_to_lab

CIELAB coordinates of sRGB colours.

warn_if_unscientific

Warn when cmap is not on the scientific allow-list.

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), where norm is the caller’s or the role’s.

Return type:

tuple

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:

numpy.ndarray

Raises:

ValueError – If kind is 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 of L*, a*, b*.

Return type:

numpy.ndarray

scatterem.vis.colors.warn_if_unscientific(cmap: str | Colormap, stacklevel: int = 3) → None#

Warn when cmap is not on the scientific allow-list.

The warnings filters decide how often the warning shows, so simplefilter("error") catches every call. show_2d warns once per call, not once per panel. For one warning per process, use warnings.filterwarnings("once", category=UnscientificColormapWarning).

Parameters:

scatterem.vis.normalization#

NORMALIZATION_PRESETS

Preset name -> a callable that returns a new NormalizationConfig.

INTERVAL_TYPES

Built-in immutable sequence.

STRETCH_TYPES

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#

nice_bar_length

Longest 1-2-5 length that fits comfortably across span.

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.0 if span is not a usable positive number – a degenerate axis should produce no bar rather than a NaN one.

scatterem.vis.show#

Animated

An encoded animation that notebooks show inline (once in Jupyter).

FigureContext

Options that every view and panel sees.

FrameSource

The frames of an animated view.

Panel

One panel of a figure: a name, a drawing function and a screen title.

ShownFigure

The figure show returns.

register

Register the panel function decorated by this as the view for target.

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 role is 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.

Parameters:
  • name (str) – Panel name, used by panels=.

  • draw (callable) – draw(ax, ctx) draws the panel into ax.

  • title (str, default="") – Title shown in screen style.

class scatterem.vis.show.ShownFigure(*args: Any, **kwargs: Any)#

The figure show returns.

In Jupyter, show displays 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:
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) -> FrameSource for show_animated.

Returns:

The decorator.

Return type:

callable

scatterem.vis.style#

line_colours

Categorical line colours from batlowS that stand out on background.

style_params

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_DL in L*. Each next colour is the one farthest (in CIELAB) from those already picked.

Return type:

list of str

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 an axes.prop_cycle from line_colours().

Return type:

dict

scatterem.vis.visualization_utils#

add_cbar_to_ax

Draw a colorbar for norm/cmap into an existing axes.

add_colorbars

Add the value colour bar to ax, plus a phase bar for complex data.

special_ticks

Colour-bar ticks for data that round ticks describe badly.

add_scalebar_to_ax

Positional adapter for scatterem.vis.scale_bar.draw_scale_bar().

estimate_scalebar_length

A round bar length for an image n_pixels wide at sampling per pixel.

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/cmap into 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 vmin and vmax must 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:

matplotlib.colorbar.Colorbar

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 labels and 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 and ScalebarConfig already speak it.

Two arguments are reinterpreted on the way through, because their names describe the old AnchoredSizeBar implementation rather than the geometry:

width_px

Bar 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_px

Corner inset. Was in multiples of the label font size despite the name. Now read as a fraction of the axes – 0.5 was 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_bar in 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 AnchoredSizeBar convention).

  • 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_pixels wide at sampling per pixel.

Thin adapter over scatterem.vis.scale_bar.nice_bar_length(), kept because callers want the length in pixels as well.

Parameters:
  • n_pixels (float) – Width of the displayed array, in pixels.

  • sampling (float) – Physical size of one pixel.

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:

tuple