cryolike.stacks

cryolike.stacks.image

class cryolike.stacks.image.Images(phys_data: PhysicalImages | CartesianGrid2D | None = None, fourier_data: FourierImages | PolarGrid | None = None, box_size: float | ndarray[tuple[int, ...], dtype[floating]] | None = None, viewing_angles: ViewingAngles | None = None, ctf: CTF | None = None)

Bases: object

Class representing a collection of (Cartesian-space or Fourier-space) images, with methods for manipulating them.

box_size

Size of the (Cartesian-space) viewing port.

Type:

FloatArrayType

phys_grid

A grid describing the space in which physical images reside.

Type:

CartesianGrid2D

polar_grid

A grid describing the space in which Fourier images reside.

Type:

PolarGrid

images_phys

Cartesian-space images as a pixel-value array of [image x X-index x Y-index].

Type:

torch.Tensor

images_fourier

Fourier-space images as a complex-valued array of [image x shell-index x point-index].

Type:

torch.Tensor

n_images

Count of images in the collection.

Type:

int

ctf

Contrast transfer function associated with the image stack, if any.

Type:

CTF | None

viewing_angles

Optimal viewing angle, if set.

Type:

Optional[ViewingAngles]

displacement_grid_angstrom

Represents the grid of displacements to be searched in image-template comparison, as a tensor of [x=0/y=1, n_displacements]. Defaults to null displacement. Should not be set manually.

Type:

Tensor

displacement_count

The number of displacements in the displacement grid. Defaults to 1.

Type:

int

_translation_matrix

Cached translation kernel that broadcasts the displacement grid over the Fourier images, returning them with an extra “displacement” dimension. Has dimensions of [n_displacements, n_radii, n_inplanes]. Should not be accessed directly.

Type:

torch.Tensor

filename

The name of the file of origin of these images, if they were read from an MRC file.

Type:

str | None

add_noise_fourier(snr: float | ndarray[tuple[int, ...], dtype[floating]] | Tensor = 1.0)

Add random ((0,1) complex normal) noise to Fourier-space images in the collection.

Parameters:

snr (float | FloatArrayType | torch.Tensor, optional) – Signal-to-noise ratio. Defaults to 1.0.

Raises:

ValueError – If Fourier-space images do not exist.

Returns:

The updated images (as also updated in-place), and the

noise applied to them.

Return type:

Tuple[torch.Tensor, torch.Tensor]

add_noise_phys(snr: float | ndarray[tuple[int, ...], dtype[floating]] | Tensor = 1.0)

Add random ((0,1) Gaussian) noise to the Cartesian-space images in the collection.

Parameters:

snr (float | FloatArrayType | torch.Tensor, optional) – Signal-to-noise ratio. Defaults to 1.0.

Raises:

ValueError – If Cartesian-space images do not exist.

Returns:

The updated images (as also updated in-place), and the

noise applied to them.

Return type:

Tuple[torch.Tensor, torch.Tensor]

apply_ctf(ctf: CTF)

Applies a contrast transfer function to the Fourier-space images.

Parameters:

ctf (CTF) – CTF to apply.

Raises:

NotImplementedError – If the Fourier-space images are using a non-uniform polar grid.

Returns:

The updated images (which will also be persisted to the collection).

Return type:

torch.Tensor

center_physical_image_signal(norm_type: NormType = NormType.MAX)

Converts pixel values to 0-mean and unit norm representation.

Parameters:

norm_type (NormType, optional) – Whether to use max-norm or standard-deviation norm. Defaults to NormType.MAX.

Raises:

ValueError – If physical images do not exist in this collection.

Returns:

The computed mean and norm of the images.

Return type:

Tuple[torch.Tensor, torch.Tensor]

change_images_phys_size(n_pixels: int | list[int] | ndarray[tuple[int, ...], dtype[integer]] | None = None, box_size: float | list[float] | ndarray[tuple[int, ...], dtype[floating]] | None = None)

Change the sizes of the physical images in this image collection.

Parameters:
  • n_pixels (Optional[int | list[int] | IntArrayType], optional) – New number of pixels. Defaults to None.

  • box_size (Optional[float | list[float] | FloatArrayType], optional) – New viewing box size. Defaults to None.

Raises:
  • ValueError – If both n_pixels and box_size are set, or if neither is set.

  • ValueError – If physical images do not actually exist in this collection.

displace_fourier_images(x_displacements: ndarray[tuple[int, ...], dtype[floating]] | Tensor | float, y_displacements: ndarray[tuple[int, ...], dtype[floating]] | Tensor | float, displacement_per_image: bool = False)

Apply a displacement to the Fourier-space images in the collection, modifying them in-place. The displacements are assumed to be intended as a fraction of half a viewing box (i.e. they will be multiplied by 2 and divided by the viewing box size)

Parameters:
  • x_displacements (FloatArrayType | torch.Tensor | float) – Displacements to apply. May be constant for each pixel, or a set of displacements to apply per-pixel for each image, or a complete tensor of displacements.

  • y_displacements (FloatArrayType | torch.Tensor | float) – Displacements to apply. May be constant for each pixel, or a set of displacements to apply per-pixel for each image, or a complete tensor of displacements.

  • displacement_per_image (bool, optional) – If True, enforce that the displacements are equal-length tensors with one element each per image. Otherwise, assume they are a set of displacements to sum and apply to each image.

downsample_images_phys(downsample_factor: int = 2, type: Literal['mean'] | Literal['max'] = 'mean')

Downsample the physical images in this collection.

Parameters:
  • downsample_factor (int, optional) – Factor by which to downsample the images. Defaults to 2.

  • type (Literal['mean'] | Literal['max']) – Whether to take mean or max of the pool for downsampling. Defaults to mean.

Raises:

ValueError – If physical images do not exist in this collection.

filter_padded_images(rtol=0.1)

Restrict the image collection to the set of images which do not have padding.

classmethod from_mrc(filename: str, pixel_size: float | list[float] | ndarray[tuple[int, ...], dtype[floating]] | None, device: str | device = 'cpu')

Create a new set of physical images from an MRC file.

Parameters:
  • filename (str) – Name of MRC file to load. Must end with a .mrc or .mrcs extension.

  • pixel_size (Optional[float | list[float] | FloatArrayType]) – Sizes of the image pixels in Angstroms. If set, will override the values in the MRC file; if unset, the file values will be used.

  • device (str | torch.device, optional) – Device to use for the resulting image Tensor. Defaults to ‘cpu’.

Raises:
  • ValueError – If a non-MRC file extension is passed.

  • ValueError – If the pixel_size is not set and the existing MRC file has non-positive pixel sizes.

Returns:

An Images image collection, with the physical images and grid populated per the saved data.

Return type:

Images

get_item_size(space: Literal['fourier'] | Literal['physical'] = 'fourier')

Returns the size, in bytes, of one image in the stack.

Parameters:

space ('fourier' | 'physical', optional) – Whether to compute the size of the physical or fourier representation. Defaults to ‘fourier’.

Returns:

Per-image size, in bytes.

Return type:

int

get_power_spectrum()

Gets the power spectrum of the (Fourier-space) images.

Raises:

ValueError – If no Fourier-space images exist in the collection.

Returns:

Tuple of power-spectrum values and the resolutions.

Return type:

Tuple[np.ndarray, np.ndarray]

modify_pixel_size(pixel_size: float | list[float] | ndarray[tuple[int, ...], dtype[floating]])

Update the pixel sizes describing the physical images in this image collection. Note that physical images must exist for this to succeed (or make sense). This will overwrite any existing viewing box size.

Parameters:

pixel_size (float | list[float] | FloatArrayType) – New pixel sizes. If scalar, the same value will be used for the X and Y dimensions; if a list-like is passed, the 0th index will be the X-dimension and the 1st index will be the Y-dimension.

normalize_images_fourier(ord: int = 1, use_max: bool = False)

Normalize the Fourier-space images in the collection.

Parameters:
  • ord (int, optional) – Degree of norm to apply. Defaults to 1.

  • use_max (bool, optional) – Whether to use the max in place of an LP norm. Defaults to False.

Returns:

The norm applied to the images (which are modified in-place).

Return type:

torch.Tensor

normalize_images_phys(ord: int = 1, use_max: bool = False)

Normalize the Cartesian-space images in the collection.

Parameters:
  • ord (int, optional) – Degree of norm to apply. Defaults to 1.

  • use_max (bool, optional) – Whether to use the max in place of an LP norm. Defaults to False.

Returns:

The norm applied to the images (which are modified in-place).

Return type:

torch.Tensor

project_images_over_displacements(range_min: int, range_max_excl: int, device: device | str | None = None)

Returns a tensor of the requested range of the Fourier-space images, projected over the currently configured displacements, stored on the requested device.

Parameters:
  • range_min (int) – Index of first image to return

  • range_max_excl (int) – One more than the index of the last image to be returned

  • device (torch.device | str | None) – Device on which to store the returned tensor. If unset, will default to the device where the current Fourier images reside.

Returns:

A tensor of Fourier-space images, projected over

the configured displacements. This tensor will be indexed as [image, displacement, radius, inplane-value], with the latter two dimensions corresponding to the polar quadrature grid.

Return type:

torch.Tensor

rotate_images_fourier_discrete(inplane_rotations: ndarray | Tensor | float)

Apply an in-plane rotation to the Fourier-space images.

While a continuous value is accepted, the resulting rotated object must align with the points on the polar grid, so the rotation will be discretized.

Assumes a uniform polar grid.

Parameters:

inplane_rotations (np.ndarray | torch.Tensor | float) – Rotation to apply, in revolutions. If an array or tensor, must be of length 1 (in which case it will be applied to all images) or a 1-d array of length equal to the number of images (one rotation per image).

Raises:

ValueError – If the inplane_rotations is multi-dimensional, or cannot be obviously broadcast to the number of images.

save_to_mrc(filename: str)

Write the physical images to an MRC file. Will overwrite any existing file with that name.

Parameters:

filename (str) – Name of the file to save.

select_images(indices: list[int] | ndarray[tuple[int, ...], dtype[integer]] | Tensor)

Restrict this collection’s images to the specified indices.

Parameters:

indices (_type_) – The indices to keep.

set_displacement_grid(max_displacement_pixels: float, n_displacements_x: int, n_displacements_y: int, pixel_size_angstrom: float | None = None)

Sets the displacement grid (the set of displacements to search in cross-comparison) for this object. This will also set the translation kernel that enables broadcasting the images over the displacements. The resulting grid will be square in shape, with a maximum displacement in both X and Y of max_displacement_pixels, but the number of displacements in either direction will vary. The original image (a displacement of (0, 0)) will always be included.

Parameters:
  • max_displacement_pixels (float) – Maximum displacement value

  • n_displacements_x (int) – Number of displacements in the x-direction

  • n_displacements_y (int) – Number of displacements in the y-direction

  • pixel_size_angstrom (float | None, optional) – Size of each pixel, in angstrom. Needed to interpret the max_displacement_pixels. Only required if this image stack does not have a physical grid set.

transform_to_fourier(polar_grid: PolarGrid | None = None, nufft_eps: float = 1e-12, precision: Precision = Precision.DEFAULT, device: str | device | None = 'cuda')

Transform the physical images in this collection to Fourier-space representation. Existing physical images are kept. The new Fourier-space images will be placed on the same device as the physical images.

Parameters:
  • polar_grid (Optional[PolarGrid], optional) – The polar grid for the Fourier-space image representation. If unset, there must be a pre-existing one. Defaults to None.

  • nufft_eps (float, optional) – Tolerance for non-uniform FFT. Defaults to 1e-12.

  • precision (Precision, optional) – Whether to use 64- or 128-bit representation. (Note that the Fourier-space representation uses complex numbers, so the bit counts are twice the corresponding precision for reals.) Defaults to Precision.DEFAULT, which matches the precision of the physical representation.

  • use_cuda (bool, optional) – Whether to use a cuda device. Defaults to True.

Raises:

ValueError – If no polar grid exists on the collection already, and none is passed.

transform_to_spatial(grid: CartesianGrid2D | tuple[int | list[int] | numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.integer]], float | list[float] | numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.floating]]] | None = None, nufft_eps: float = 1e-12, precision: Precision = Precision.DEFAULT, max_to_transform: int = -1, device: device | str | None = None) Tensor

Transform the Fourier-space images in this collection to a Cartesian-space representation. Existing Fourier-space images are kept. The new images will be placed on the same device as the Fourier-space images.

Parameters:
  • grid (Optional[Cartesian_grid_descriptor], optional) – Cartesian grid describing the new physical images. Defaults to None. If None is passed, the collection’s existing grid will be used. If None is passed and no existing grid exists, this operation will fail.

  • nufft_eps (float, optional) – Tolerance for the non-uniform FFT. Defaults to 1e-12.

  • precision (Precision, optional) – Whether to use 32- or 64-bit representation. Defaults to Precision.DEFAULT (which matches the current Fourier precision).

  • use_cuda (bool, optional) – Whether to use a cuda device. Defaults to True.

Raises:

ValueError – If no existing Cartesian grid was set, and no new one was passed.

cryolike.stacks.template

class cryolike.stacks.template.Templates(*, phys_data: PhysicalImages | CartesianGrid2D | None = None, fourier_data: FourierImages | PolarGrid | None = None, box_size: float | ndarray[tuple[int, ...], dtype[floating]] | None = None, viewing_angles: ViewingAngles, ctf: CTF | None = None)

Bases: Images

Class representing a collection of (Cartesian-space and/or Fourier-space) templates, with methods for manipulating them.

box_size

Size of the (Cartesian-space) viewing port

Type:

FloatArrayType

phys_grid

A grid describing the physical space in which the (physical-representation) templates reside

Type:

CartesianGrid2D

polar_grid

A grid describing the polar space in which the Fourier templates reside

Type:

PolarGrid

templates_phys

Cartesian-space template images as pixel-value array of [template x X-index x Y-index]

Type:

torch.Tensor | None

templates_fourier

Fourier-space template images as complex-valued array of [template x radius x angle]

Type:

torch.Tensor | None

n_templates

Count of templates in the collection

Type:

int

ctf

Contrast transfer function to be applied to templates, if any

Type:

CTF | None

viewing_angles

Viewing angle which generated each template in the stack

Type:

ViewingAngles

filename

If set, the name of the file from which the templates were loaded

Type:

str | None