Skip to content

Utilities

leopard_em.utils

Utilities submodule for various data and pre- and post-processing tasks.

FFTPaddingPlan

Immutable record of how one micrograph is padded up to a fast FFT size.

Attributes:

  • original_shape (tuple[int, int]) –

    Real-space (H, W) of the unpadded micrograph.

  • padded_shape (tuple[int, int]) –

    Real-space (H, W) actually handed to the backend.

  • template_shape (tuple[int, int]) –

    Real-space (h, w) of a single template projection.

  • noise_seed (int) –

    Seed for the Gaussian fill, so a plan fully reproduces a padded image.

  • effective_backend (str) –

    Cross-correlation backend actually used. Typically the requested backend, but a requested "zipfft" falls back to the PyTorch "streamed" backend when no compiled zipFFT configuration matches the padded image and template shapes.

Methods:

  • pad –

    Pad a real-space image according to this plan.

is_padded

is_padded: bool

Whether this plan actually changes the image size.

pad_amount

pad_amount: tuple[int, int]

Rows and columns added to the bottom and right, respectively.

area_growth

area_growth: float

Fractional increase in pixel count caused by padding.

unpadded_valid_shape

unpadded_valid_shape: tuple[int, int]

Shape of the "valid" correlation region for the unpadded image.

__post_init__

__post_init__() -> None

Validate that the recorded shapes are mutually consistent.

pad

pad(image: Tensor) -> torch.Tensor

Pad a real-space image according to this plan.

Parameters:

  • image (Tensor) –

    Real-space 2D image matching original_shape.

Returns:

  • Tensor –

    Image padded to padded_shape.

FFTPaddingWarning

Bases: UserWarning

Warning raised when automatic FFT padding changes behavior materially.

handle_correlation_mode

handle_correlation_mode(cross_correlation: Tensor, out_shape: tuple[int, ...], mode: Literal['valid', 'same']) -> torch.Tensor

Handle cropping for cross correlation mode.

NOTE: 'full' mode is not implemented.

Parameters:

  • cross_correlation (Tensor) –

    The cross correlation result.

  • out_shape (tuple[int, ...]) –

    The desired shape of the output.

  • mode (Literal['valid', 'same']) –

    The mode of the cross correlation. Either 'valid' or 'same'. See numpy.correlate for more details.

calculate_ctf_filter_stack

calculate_ctf_filter_stack(template_shape: tuple[int, int], optics_group: OpticsGroup, defocus_offsets: Tensor, pixel_size_offsets: Tensor) -> torch.Tensor

Calculate searched CTF filter values for a given shape and optics group.

Parameters:

  • template_shape (tuple[int, int]) –

    Desired output shape for the filter, in real space.

  • optics_group (OpticsGroup) –

    OpticsGroup object containing the optics defining the CTF parameters.

  • defocus_offsets (Tensor) –

    Tensor of defocus offsets to search over, in Angstroms.

  • pixel_size_offsets (Tensor) –

    Tensor of pixel size offsets to search over, in Angstroms.

Returns:

  • Tensor –

    Tensor of CTF filter values for the specified shape and optics group. Will have shape (num_pixel_sizes, num_defocus_offsets, h, w // 2 + 1)

load_mrc_image

load_mrc_image(file_path: str | PathLike | Path) -> torch.Tensor

Helper function for loading an two-dimensional MRC image into a tensor.

Parameters:

  • file_path (str | PathLike | Path) –

    Path to the MRC file.

Returns:

  • Tensor –

    The MRC image as a tensor, converted to float32 for FFT compatibility.

Raises:

  • ValueError –

    If the MRC file is not two-dimensional.

load_mrc_volume

load_mrc_volume(file_path: str | PathLike | Path) -> torch.Tensor

Helper function for loading an three-dimensional MRC volume into a tensor.

Parameters:

  • file_path (str | PathLike | Path) –

    Path to the MRC file.

Returns:

  • Tensor –

    The MRC volume as a tensor, converted to float32 for FFT compatibility.

Raises:

  • ValueError –

    If the MRC file is not three-dimensional.

load_template_tensor

load_template_tensor(template_volume: Tensor | Any | None = None, template_volume_path: str | PathLike | Path | None = None) -> torch.Tensor

Load and convert template volume to a torch.Tensor.

This function ensures that the template volume is a torch.Tensor. If template_volume is None, it loads the volume from template_volume_path. If template_volume is not a torch.Tensor, it converts it to one.

Parameters:

  • template_volume (Optional[Union[Tensor, Any]], default: None ) –

    The template volume object, by default None

  • template_volume_path (Optional[Union[str, PathLike, Path]], default: None ) –

    Path to the template volume file, by default None

Returns:

  • Tensor –

    The template volume as a torch.Tensor

Raises:

  • ValueError –

    If both template_volume and template_volume_path are None

read_mrc_to_numpy

read_mrc_to_numpy(mrc_path: str | PathLike | Path) -> np.ndarray

Reads an MRC file and returns the data as a numpy array.

Attributes:

  • mrc_path (str | PathLike | Path) –

    Path to the MRC file.

Returns:

  • ndarray –

    The MRC data as a numpy array, copied.

read_mrc_to_tensor

read_mrc_to_tensor(mrc_path: str | PathLike | Path) -> torch.Tensor

Reads an MRC file and returns the data as a torch tensor.

Attributes:

  • mrc_path (str | PathLike | Path) –

    Path to the MRC file.

Returns:

  • Tensor –

    The MRC data as a tensor, copied and converted to float32 if needed.

write_mrc_from_numpy

write_mrc_from_numpy(data: ndarray, mrc_path: str | PathLike | Path, mrc_header: dict | None = None, overwrite: bool = False) -> None

Writes a numpy array to an MRC file.

NOTE: Writing header information is not currently implemented.

Attributes:

  • data (ndarray) –

    The data to write to the MRC file.

  • mrc_path (str | PathLike | Path) –

    Path to the MRC file.

  • mrc_header (Optional[dict]) –

    Dictionary containing header information. Default is None.

  • overwrite (bool) –

    Overwrite argument passed to mrcfile.new. Default is False.

write_mrc_from_tensor

write_mrc_from_tensor(data: Tensor, mrc_path: str | PathLike | Path, mrc_header: dict | None = None, overwrite: bool = False) -> None

Writes a tensor array to an MRC file.

NOTE: Not currently implemented.

Attributes:

  • data (ndarray) –

    The data to write to the MRC file.

  • mrc_path (str | PathLike | Path) –

    Path to the MRC file.

  • mrc_header (Optional[dict]) –

    Dictionary containing header information. Default is None.

  • overwrite (bool) –

    Overwrite argument passed to mrcfile.new. Default is False.

next_even_fft_shape

next_even_fft_shape(image_shape: tuple[int, int], factors: tuple[int, ...] = DEFAULT_FFT_FACTORS) -> tuple[int, int]

Apply :func:next_even_fft_size independently to each image dimension.

next_even_fft_size

next_even_fft_size(n: int, factors: tuple[int, ...] = DEFAULT_FFT_FACTORS) -> int

Smallest even integer >= n whose prime factors all lie in factors.

Parameters:

  • n (int) –

    Minimum required size, typically a micrograph edge length.

  • factors (tuple[int, ...], default: DEFAULT_FFT_FACTORS ) –

    Allowed prime factors. Must contain 2. Default is (2, 3).

Returns:

  • int –

    The smallest even factors-smooth integer greater than or equal to n.

Raises:

  • ValueError –

    If 2 is not present in factors, in which case no even size could ever satisfy the smoothness constraint.

Examples:

>>> next_even_fft_size(4000)
4096
>>> next_even_fft_size(2050)  # plain next_fft_size would return an odd 2187
2304

pad_image_gaussian

pad_image_gaussian(image: Tensor, padded_shape: tuple[int, int], seed: int = 0) -> torch.Tensor

Pad a 2D image at the bottom and right with Gaussian noise.

Parameters:

  • image (Tensor) –

    Real-space 2D image of shape (h, w).

  • padded_shape (tuple[int, int]) –

    Target real-space shape (H, W). Must be at least image.shape in both dimensions.

  • seed (int, default: 0 ) –

    Seed for the noise. A local :class:torch.Generator is used so the global RNG state is left untouched. Default is 0.

Returns:

  • Tensor –

    Padded image of shape padded_shape, with the same dtype and device as image. Returned unchanged (not copied) when no padding is required.

Raises:

  • ValueError –

    If image is not 2D, or padded_shape is smaller than the image in either dimension.

volume_to_rfft_fourier_slice

volume_to_rfft_fourier_slice(volume: Tensor) -> torch.Tensor

Prepares a 3D volume for Fourier slice extraction.

Parameters:

  • volume (Tensor) –

    The input volume.

Returns:

  • Tensor –

    The prepared volume in Fourier space ready for slice extraction.

preprocess_image

preprocess_image(image_rfft: Tensor, cumulative_fourier_filters: Tensor, bandpass_filter: Tensor, full_image_shape: tuple[int, int], extracted_box_shape: tuple[int, int]) -> torch.Tensor

Preprocess and normalize image FFTs with computed normalization factors.

Parameters:

  • image_rfft (Tensor) –

    The real Fourier-transformed image (unshifted).

  • cumulative_fourier_filters (Tensor) –

    The cumulative Fourier filters. Multiplication of the whitening filter, phase randomization filter, bandpass filter, and arbitrary curve filter.

  • bandpass_filter (Tensor) –

    The bandpass filter used for the image. Used for dimensionality normalization.

  • full_image_shape (tuple[int, int]) –

    The shape of the full image.

  • extracted_box_shape (tuple[int, int]) –

    The shape of the extracted box.

Returns:

  • Tensor –

    Preprocessed and normalized image in Fourier space.

cs_to_pixel_size

cs_to_pixel_size(cs_vals: Tensor, nominal_pixel_size: float, nominal_cs: float = 2.7) -> torch.Tensor

Convert Cs values to pixel sizes.

Parameters:

  • cs_vals (Tensor) –

    The Cs (spherical aberration) values.

  • nominal_pixel_size (float) –

    The nominal pixel size.

  • nominal_cs (float, default: 2.7 ) –

    The nominal Cs value, by default 2.7.

Returns:

  • Tensor –

    The pixel sizes.

get_cs_range

get_cs_range(pixel_size: float, pixel_size_offsets: Tensor, cs: float = 2.7) -> torch.Tensor

Get the Cs values for a range of pixel sizes.

Parameters:

  • pixel_size (float) –

    The nominal pixel size.

  • pixel_size_offsets (Tensor) –

    The pixel size offsets.

  • cs (float, default: 2.7 ) –

    The Cs (spherical aberration) value, by default 2.7.

Returns:

  • Tensor –

    The Cs values for the range of pixel sizes.

get_search_tensors

get_search_tensors(min_val: float, max_val: float, step_size: float, skip_enforce_zero: bool = False) -> torch.Tensor

Get the search tensors (pixel or defocus) for a given range and step size.

Parameters:

  • min_val (float) –

    The minimum value.

  • max_val (float) –

    The maximum value.

  • step_size (float) –

    The step size.

  • skip_enforce_zero (bool, default: False ) –

    Whether to skip enforcing a zero value, by default False.

Returns:

  • Tensor –

    The search tensors.