acryo package

Subpackages

Submodules

acryo.simulator module

class acryo.simulator.Component(molecules: Molecules, image: NDArray[np.float32] | ImageProvider)[source]

Bases: NamedTuple

A component of tomogram.

image: numpy.ndarray[Any, numpy.dtype[numpy.float32]] | acryo.pipe._classes.ImageProvider

Alias for field number 1

molecules: acryo.molecules.core.Molecules

Alias for field number 0

class acryo.simulator.TomogramSimulator(order: Literal[0, 1, 3] = 3, scale: nm = 1.0, corner_safe: bool = False)[source]

Bases: object

An object for tomogram simulation

A TomogramSimulator contains set(s) of molecules and their corresponding density and additional information for tomogram generation. For instance, to simulate a tomogram with two sets of molecules, you can do

>>> sim = TomogramSimulator()
>>> sim.add_molecules(molecules_a, image_a, name="Molecule-A")
>>> sim.add_molecules(molecules_b, image_b, name="Molecule-B")
>>> img = sim.simulate(shape=(128, 128, 128))
Parameters
  • order (int, default is 3) – Interpolation order for density image. - 0 = Nearest neighbor - 1 = Linear interpolation - 3 = Cubic interpolation

  • scale (float, default is 1.0) – Scale of the pixel. This value is used to determine the position of the molecules.

  • corner_safe (bool, default is False) – Not implemented yet.

add_molecules(molecules: Molecules, image: NDArray[np.float32] | ImageProvider, *, name: str | None = None, overwrite: bool = False) Self[source]

Add molecules to the tomogram.

Parameters
  • molecules (Molecules) – Molecules object that defines the coordinates and orientations of the input molecules.

  • image (np.ndarray or ImageProvider) – Density image of the input molecules, or an image provider.

  • name (str, optional) – Name of the molecules., by default None

  • overwrite (bool, default is False) – If true, allow overwriting existing component.

Returns

Same object.

Return type

TomogramSimulator

collect_molecules() acryo.molecules.core.Molecules[source]
property components: mappingproxy[str, acryo.simulator.Component]

Return all the components in the tomogram.

copy() Self[source]

Create a shallow copy of the loader.

property corner_safe: bool
property order: Literal[0, 1, 3]

Return the interpolation order.

replace(order: Literal[0, 1, 3] | None = None, scale: float | None = None, corner_safe: bool | None = None) Self[source]

Return a new instance with different parameter(s).

property scale: float

The physical scale of the tomogram.

simulate(shape: tuple[pixel, pixel, pixel], colormap: Callable[[pl.DataFrame], ColorType] | NDArray[np.float32] | None = None) NDArray[np.float32][source]

Simulate a tomogram.

Parameters
  • shape (tuple of int) – Shape of the tomogram.

  • colormap (callable, optional) – Colormap used to generate the colored tomogram. The input is a polars row vector of features of each molecule.

Returns

Simulated tomogram image.

Return type

np.ndarray

simulate_2d(shape: tuple[int, int]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a grayscale tomogram.

simulate_projection(shape: tuple[int, int], center: tuple[float, float, float], xaxis: tuple[float, float, float], yaxis: tuple[float, float, float]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a projection of the tomogram in any direction.

Projection plane and the projection range are defined by the given parameters. shape and center define the range of the projection plane. Technically, center will be the scale-considered center of the assumed 3D tomogram image. xaxis and yaxis define the coordinate system of the projection plane.

Parameters
  • shape ((int, int)) – Output shape of the projection.

  • center ((float, float, float)) – Center of the projection plane in world coordinate system.

  • xaxis ((float, float, float)) – X-axis of the projection plane in world coordinate system.

  • yaxis ((float, float, float)) – Y-axis of the projection plane in world coordinate system.

Returns

Simulated projection image.

Return type

2D array

simulate_tilt_series(degrees: Iterable[float], shape: tuple[int, int, int]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a tilt series of the tomogram.

This method is a simplified version of simulate_projection(). Projection angles are restricted to the rotation around the y-axis of the world coordinate and the tomogram will be projected parallel to the z-axis.

Parameters
  • degrees (iterable of float) – Rotation angles.

  • shape ((int, int, int)) – Tomogram shape.

Returns

Tilting series image.

Return type

(N, Y, X) array

subset(names: str | Sequence[str]) Self[source]

Construct a simulator composed of a subset of the components.

Parameters

names (str or sequence of str) – Component names that will be included in the subset.

Returns

New simulator object.

Return type

TomogramSimulator

acryo.simulator.cross(x: numpy.ndarray, y: numpy.ndarray, axis=None) numpy.ndarray[source]

Vector outer product in zyx coordinate.

Module contents

class acryo.BatchLoader(order: int = 3, scale: float = 1.0, output_shape: int | tuple[int, int, int] | acryo.loader._base.Unset = Unset, corner_safe: bool = False)[source]

Bases: acryo.loader._base.LoaderBase

Collection of tomograms and their molecules.

A BatchLoader is similar to a list of SubtomogramLoader objects, but with better consistency in loader parameters and more convenient access to the molecules. This class is useful for processing many tomograms at once, especially when you want to get the average of all the molecules available.

add_loader(loader: SubtomogramLoader | BatchLoader) Self[source]

Add a subtomogram loader or a batch loader to the collection.

add_tomogram(image: np.ndarray | da.Array, molecules: Molecules, image_id: Hashable | None = None) Self[source]

Add a tomogram and its molecules to the collection.

Parameters
  • image (np.ndarray or da.Array) – Tomogram image. This argument is passed directly to the SubtomogramLoader constructor.

  • molecules (Molecules) – Molecules in the tomogram (corresponding to the image argument). This argument is passed directly to the SubtomogramLoader constructor.

  • image_id (Hashable, optional) – Identifier for the tomogram. If not provided, a unique identifier will be generated. This identifier is used to tag molecules with the tomogram they reside in.

binning(binsize: int, *, compute: bool = False) Self[source]

Return a new instance with binned images.

construct_loading_tasks(output_shape: _ShapeType = None, backend: Backend | None = None) DaskArrayList[source]

Construct batch loading tasks.

classmethod from_loaders(loaders: Iterable[SubtomogramLoader], order: int = 3, scale: nm = 1.0, output_shape: pixel | tuple[pixel, pixel, pixel] | Unset = Unset, corner_safe: bool = False) Self[source]

Construct a loader from a list of loaders.

property images: mappingproxy

All the images in the collection.

property loaders: acryo.loader._batch.LoaderAccessor

Interface to access the subtomogram loaders.

property molecules: acryo.molecules.core.Molecules

Collect all the molecules from all the loaders

replace(molecules: Molecules | None = None, output_shape: _ShapeType | Unset = None, order: int | None = None, scale: float | None = None, corner_safe: bool | None = None) Self[source]

Return a new instance with different parameter(s).

class acryo.MockLoader(template: numpy.ndarray[Any, numpy.dtype[numpy.float32]] | acryo.pipe._classes.ImageProvider, molecules: acryo.molecules.core.Molecules, noise: float = 0.0, degrees: Optional[Union[Sequence[float], numpy.ndarray[Any, numpy.dtype[numpy.float32]]]] = None, central_axis: tuple[float, float, float] = (0.0, 1.0, 0.0), order: int = 3, scale: float = 1.0, corner_safe: bool = False)[source]

Bases: acryo.loader._base.LoaderBase

A subtomogram loader from a virtual tomogram.

This loader is for testing purpose only. The tomogram does not actually exist but subtomograms are generated on the fly based on the template image. The true center of the molecules is always at (0, 0, 0) and the true rotation is always the identity rotation. Thus, given molecule positions/rotations will directly be the values to be tested.

Parameters
  • template (3D array, ImageProvider) – The template image.

  • molecules (Molecules) – The molecules to be loaded. Note that the true center/rotation is always (0, 0, 0) and the identity rotation, respectively.

  • noise (float, optional) – Standard deviation of the Gaussian noise to be added to the subtomograms projection slices.

  • degrees (array-like, optional) – The rotation angles in degrees. If not provided, projection/back-projection will not be simulated.

  • central_axis (tuple, default is (0.0, 1.0, 0.0)) – The central axis of the rotation during tomogram acquisition.

construct_loading_tasks(output_shape: _ShapeType = None, backend: Backend | None = None) DaskArrayList[source]
property molecules: acryo.molecules.core.Molecules

All the molecules

replace(molecules: Molecules | None = None, output_shape: None = None, order: int | None = None, scale: float | None = None, corner_safe: bool | None = None) Self[source]
class acryo.Molecules(pos: Union[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]], rot: scipy.spatial.transform._rotation.Rotation | None = None, features: Optional[Union[polars.dataframe.frame.DataFrame, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]], dict[str, Union[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[Union[bool, int, float, complex, str, bytes]]]]]] = None)[source]

Bases: object

Object that represents position- and orientation-defined molecules.

Positions are represented by a (N, 3) np.ndarray and orientations are represented by a scipy.spatial.transform.Rotation object. Features of each molecule can also be recorded by the features property.

Parameters
  • pos (ArrayLike) – Moleculs positions.

  • rot (scipy.spatial.transform.Rotation object) – Molecule orientations.

  • features (dataframe, optional) – Molecule features.

affine_matrix(src: numpy.ndarray, dst: numpy.ndarray | None = None, inverse: bool = False) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Construct affine matrices using positions and angles of molecules.

Parameters
  • src (np.ndarray) – Source coordinates.

  • dst (np.ndarray, optional) – Destination coordinates. By default the coordinates of molecules will be used.

  • inverse (bool, default is False) – Return inverse mapping if true.

Returns

Array of concatenated affine matrices.

Return type

(N, 4, 4) array

append(other: Molecules) Self[source]

Mutably append molecules.

Parameters

other (Molecules) – Molecules to be appended. They must only have the subset of features, otherwise this method will raise ValueError.

Returns

Same instance with updated values.

Return type

Molecules

classmethod concat(moles: Iterable[Molecules], concat_features: bool = True, nullable: bool = True) Self[source]

Concatenate Molecules objects.

concat_with(other: Molecules, /, nullable: bool = True) Self[source]

Concatenate the molecules with the others.

Parameters
  • other (Molecules) – Molecules to be concatenated.

  • nullable (bool, default is True) – If true, missing features in either of the molecules will be filled with null. Raise error otherwise.

copy() Self[source]

Make a copy of the object.

count() int[source]

Return the number of molecules.

cutby(by: str, bins: list[float]) acryo.molecules._cut.MoleculeCutGroup[source]

Cut molecules into sub-groups by binning.

drop_features(columns: str | Sequence[str], *more_columns: str) Self[source]

Return a new instance with updated features.

classmethod empty(feature_labels: Iterable[str] = ())[source]
euler_angle(seq: str = 'ZXZ', degrees: bool = False) numpy.ndarray[Any, numpy.dtype[numpy.float64]][source]

Calculate Euler angles that transforms a source vector to vectors that belong to the object.

Parameters
  • seq (str, default is "ZXZ") – Copy of scipy.spatial.transform.Rotation.as_euler. 3 characters belonging to the set {“X”, “Y”, “Z”} for intrinsic rotations, or {“x”, “y”, “z”} for extrinsic rotations. Adjacent axes cannot be the same. Extrinsic and intrinsic rotations cannot be mixed in one function call.

  • degrees (bool, default is False) – Copy of scipy.spatial.transform.Rotation.as_euler. Returned angles are in degrees if this flag is True, else they are in radians.

Returns

Euler angles.

Return type

(N, 3) ndarray

property features: polars.dataframe.frame.DataFrame

Molecules features.

filter(predicate: pl.Expr | str | pl.Series | list[bool] | np.ndarray) Self[source]

Filter molecules by its features.

classmethod from_axes(pos: np.ndarray, z: np.ndarray | None = None, y: np.ndarray | None = None, x: np.ndarray | None = None) Self[source]

Construct molecule cloud with orientation from two of their local axes.

classmethod from_csv(path: PathLike, pos_cols: list[str] = ['z', 'y', 'x'], rot_cols: list[str] = ['zvec', 'yvec', 'xvec'], **pl_kwargs) Self[source]

Load csv as a Molecules object.

classmethod from_dataframe(df: pl.DataFrame, pos_cols: list[str] = ['z', 'y', 'x'], rot_cols: list[str] = ['zvec', 'yvec', 'xvec']) Self[source]

Construct Molecules object from a DataFrame.

classmethod from_euler(pos: np.ndarray, angles: ArrayLike, seq: str = 'ZXZ', degrees: bool = False, order: str = 'xyz', features: pl.DataFrame | None = None) Self[source]

Create molecules from Euler angles.

classmethod from_file(path: PathLike, pos_cols: list[str] = ['z', 'y', 'x'], rot_cols: list[str] = ['zvec', 'yvec', 'xvec']) Self[source]

Load a file as a Molecules object using proper reader.

classmethod from_matrix(pos: np.ndarray, matrix: np.ndarray, features: pl.DataFrame | None = None) Self[source]

Create molecules from rotation matrices.

classmethod from_parquet(path: PathLike, pos_cols: list[str] = ['z', 'y', 'x'], rot_cols: list[str] = ['zvec', 'yvec', 'xvec']) Self[source]

Load parquet as a Molecules object.

classmethod from_quat(pos: np.ndarray, quat: ArrayLike, features: pl.DataFrame | None = None) Self[source]

Create molecules from quaternions.

classmethod from_random(pos: np.ndarray, seed: int | None = None, features: pl.DataFrame | None = None) Self[source]

Create randomly oriented molecules from given positions.

classmethod from_rotvec(pos: np.ndarray, vec: ArrayLike, features: pl.DataFrame | None = None) Self[source]

Create molecules from rotation vectors.

group_by(by, *more_by)

Group molecules into sub-groups.

groupby(by: Union[str, polars.expr.expr.Expr]) acryo.molecules._group.MoleculeGroup[str][source]
groupby(by: Union[Sequence[Union[str, polars.expr.expr.Expr]], tuple[Union[str, polars.expr.expr.Expr], ...]]) acryo.molecules._group.MoleculeGroup[tuple[str, ...]]
groupby(by: Union[str, polars.expr.expr.Expr], *more_by: Union[str, polars.expr.expr.Expr]) acryo.molecules._group.MoleculeGroup[tuple[str, ...]]

Group molecules into sub-groups.

head(n: int = 10) Self[source]

Return the first n molecules.

linear_transform(shift: ArrayLike, rotator: Rotation, inv: bool = False) Self[source]

Shift and rotate molecules around their own coordinate.

local_coordinates(shape: tuple[int, int, int], scale: float = 1.0, *, squeeze: bool = True) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Generate local coordinates at the neighborhood of each molecule.

Parameters
  • shape ((int, int, int)) – Shape of the local coordinates.

  • scale (float, default is 1.0) – Scale of the local coordinates.

  • squeeze (bool, default is True) – If ture and the number of molecules is 1, the first axis will be removed.

Returns

World coordinates. array[i] can be directly used as the coordinates for ndi.map_coordinates.

Return type

(N, D, Z, Y, X) array

matrix() numpy.ndarray[Any, numpy.dtype[numpy.float64]][source]

Calculate rotation matrices that align molecules in such orientations that vec belong to the object.

Returns

Rotation matrices. Rotations represented by these matrices transform molecules to the same orientations, i.e., align all the molecules.

Return type

(N, 3, 3) ndarray

property pos: numpy.ndarray[Any, numpy.dtype[numpy.float32]]

Positions of molecules.

quaternion(canonical: bool = False) numpy.ndarray[Any, numpy.dtype[numpy.float64]][source]

Calculate quaternions that transforms a source vector to vectors that belong to the object.

Returns

Quaternions.

Return type

(N, 4) ndarray

rotate_by(rotator: Rotation, copy: bool = True) Self[source]

Rotate molecule with a Rotation object.

Note that Rotation object satisfies following equation.

>>> rot1.apply(rot2.apply(v)) == (rot1*rot2).apply(v)
Parameters
  • rotator (Rotation) – Molecules will be rotated by this object.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated orientation.

Return type

Molecules

rotate_by_euler_angle(angles: ArrayLike, seq: str = 'ZXZ', degrees: bool = False, order: Literal['xyz', 'zyx'] = 'xyz', copy: bool = True) Self[source]

Rotate molecules using Euler angles, with their position unchanged.

Parameters
  • angles (array-like) – Euler angles of rotation.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated orientation.

Return type

Molecules

rotate_by_matrix(matrix: ArrayLike, copy: bool = True) Self[source]

Rotate molecules using rotation matrices, with their position unchanged.

Parameters
  • matrix (ArrayLike) – Rotation matrices, whose length must be same as the number of molecules.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated orientation.

Return type

Molecules

rotate_by_quaternion(quat: ArrayLike, copy: bool = True) Self[source]

Rotate molecules using quaternions, with their position unchanged.

Parameters
  • quat (ArrayLike) – Rotation quaternion.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated orientation.

Return type

Molecules

rotate_by_rotvec(vector: ArrayLike, copy: bool = True) Self[source]

Rotate molecules using rotation vectors, with their position unchanged.

Parameters
  • vector (array-like) – Rotation vectors.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated orientation.

Return type

Molecules

rotate_by_rotvec_internal(vector: ArrayLike, copy: bool = True) Self[source]

Rotate molecules using internal rotation vector.

Vector components are calculated in the molecule-coordinate.

Parameters
  • vector (ArrayLike) – Rotation vector(s).

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated angles.

Return type

Molecules

rotate_random(copy: bool = True, seed: int | None = None) Self[source]

Rotate molecules randomly.

Parameters
  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

  • seed (int, default is None) – Random seed to generate randomized rotators.

Returns

Instance with updated orientation.

Return type

Molecules

property rotator: scipy.spatial.transform._rotation.Rotation

Return scipy.spatial.transform.Rotation object

rotvec() numpy.ndarray[Any, numpy.dtype[numpy.float64]][source]

Calculate rotation vectors that transforms a source vector to vectors that belong to the object.

Returns

Rotation vectors.

Return type

(N, 3) ndarray

sample(n: int = 10, seed: int | None = None) Self[source]

Return n randomly sampled molecules.

sort(by: IntoExpr | Iterable[IntoExpr], *more_by: IntoExpr, descending: bool = False) Self[source]

Return a new instance with sorted molecules and features.

Parameters
  • by (str or Expr or sequence of them) – Column name or expression to sort by.

  • descending (bool, default is False) – If true, sort in descending order.

subset(spec: int | slice | list[int] | NDArray[np.bool_] | NDArray[np.integer]) Self[source]

Create a subset of molecules by slicing.

Any slicing supported in numpy.ndarray, except for integer, can be used here. Molecule positions and angles are sliced at the same time.

Parameters

spec (int, slice, list of int, or ndarray) – Specifier that defines which molecule will be used. Any objects that numpy slicing are defined are supported. For instance, [2, 3, 5] means the 2nd, 3rd and 5th molecules will be used (zero-indexed), and slice(10, 20) means the 10th to 19th molecules will be used.

Returns

Molecule subset.

Return type

Molecules

tail(n: int = 10) Self[source]

Return the last n molecules.

to_csv(save_path: Union[str, pathlib.Path], float_precision: int | None = 4) None[source]

Save molecules as a csv file.

Parameters
  • save_path (PathLike) – Save path.

  • float_precision (int, default is 4) – Float precision.

to_dataframe() polars.dataframe.frame.DataFrame[source]

Convert coordinates, rotation and features into a single data frame.

to_file(save_path: Union[str, pathlib.Path]) None[source]

Save molecules as a file.

to_parquet(save_path: PathLike, *, compression: ParquetCompression = 'zstd', compression_level: int | None = 10) None[source]

Save molecules as a parquet file.

Parameters
  • save_path (PathLike) – Save path.

  • compression (str, default is "zstd") – Compression method, by default “zstd”.

translate(shifts: ArrayLike, copy: bool = True) Self[source]

Translate molecule positions by shifts.

Shifts are applied in world coordinates, not internal coordinates of every molecules. If molecules should be translated in their own coordinates, such as translating toward y-direction of each molecules by 1.0 nm, use translate_internal instead. Translation operation does not convert molecule orientations.

Parameters
  • shifts ((3,) or (N, 3) array) – Spatial shift of molecules.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated positional coordinates.

Return type

Molecules

translate_internal(shifts: ArrayLike, *, copy: bool = True) Self[source]

Translate molecule positions internally by shifts.

Shifts are applied in the coordinates of each molecule. If molecules should be translated in world coordinates use translate instead.

Parameters
  • shifts ((3,) or (N, 3) array) – Spatial shift of molecules.

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Instance with updated positional coordinates.

Return type

Molecules

translate_random(max_distance: nm, *, seed: int | None = None, copy: bool = True) Self[source]

Apply random translation to each molecule.

Translation range is restricted by a maximum distance and translation values are uniformly distributed in this region. Different translations will be applied to different molecules.

Parameters
  • max_distance (nm) – Maximum distance of translation.

  • seed (int, optional) – Random seed, by default None

  • copy (bool, default is True) – If true, create a new instance, otherwise overwrite the existing instance.

Returns

Translated molecules.

Return type

Molecules

with_features(exprs: IntoExpr | Iterable[IntoExpr], *more_exprs: IntoExpr, **named_exprs: IntoExpr) Self[source]

Return a new instance with updated features.

property x: numpy.ndarray[Any, numpy.dtype[numpy.float64]]

Vectors of x-axis.

property y: numpy.ndarray[Any, numpy.dtype[numpy.float64]]

Vectors of y-axis.

property z: numpy.ndarray[Any, numpy.dtype[numpy.float64]]

Vectors of z-axis.

class acryo.SubtomogramLoader(image: numpy.ndarray | dask.array.core.Array, molecules: acryo.molecules.core.Molecules, order: int = 3, scale: float = 1.0, output_shape: int | tuple[int, int, int] | acryo.loader._base.Unset = Unset, corner_safe: bool = False)[source]

Bases: acryo.loader._base.LoaderBase

A class for efficient loading of subtomograms.

A SubtomogramLoader instance is basically composed of two elements, an image and a Molecules object. A subtomogram is loaded by creating a local rotated Cartesian coordinate at a molecule and calculating mapping from the image to the subtomogram.

Parameters
  • image (np.ndarray or da.Array) – Tomogram image. Must be 3-D.

  • molecules (Molecules) – Molecules object that represents positions and orientations of subtomograms.

  • order (int, default is 3) – Interpolation order of subtomogram sampling. - 0 = Nearest neighbor - 1 = Linear interpolation - 3 = Cubic interpolation

  • scale (float, default is 1.0) – Physical scale of pixel, such as nm. This value does not affect averaging/alignment results but molecule coordinates are multiplied by this value. This parameter is useful when another loader with binned image is created.

  • output_shape (int or tuple of int, optional) – Shape of output subtomogram in pixel. This parameter is not required if template (or mask) image is available immediately.

  • corner_safe (bool, default is False) – If true, regions around molecules will be cropped at a volume larger than output_shape so that densities at the corners will not be lost due to rotation. If target density is globular, this parameter should be set false to save computation time.

binning(binsize: pixel = 2, *, compute: bool = True) Self[source]

Return a new instance with binned image.

This method also properly translates the molecule coordinates.

Parameters
  • binsize (int, default is 2) – Bin size.

  • compute (bool, default is True) – If true, the image is computed immediately to a numpy array.

Returns

A new instance with binned image.

Return type

SubtomogramLoader

construct_loading_tasks(output_shape: Optional[Union[int, tuple[int, ...]]] = None, backend: acryo.backend._api.Backend | None = None) acryo._dask.DaskArrayList[source]

Construct a list of subtomogram lazy loader.

Returns

Each object returns a subtomogram on execution by da.compute.

Return type

list of Delayed object

property image: NDArray[np.float32] | da.Array

Return tomogram image.

classmethod imread(path: str, molecules: acryo.molecules.core.Molecules, order: int = 3, scale: float | None = None, output_shape: int | tuple[int, int, int] | acryo.loader._base.Unset = Unset, corner_safe: bool = False, chunks: Any = 'auto')[source]
property molecules: acryo.molecules.core.Molecules

Return the molecules of the subtomogram loader.

replace(molecules: Molecules | None = None, output_shape: pixel | tuple[pixel, pixel, pixel] | Unset | None = None, order: int | None = None, scale: float | None = None, corner_safe: bool | None = None) Self[source]

Return a new instance with different parameter(s).

class acryo.TomogramSimulator(order: Literal[0, 1, 3] = 3, scale: nm = 1.0, corner_safe: bool = False)[source]

Bases: object

An object for tomogram simulation

A TomogramSimulator contains set(s) of molecules and their corresponding density and additional information for tomogram generation. For instance, to simulate a tomogram with two sets of molecules, you can do

>>> sim = TomogramSimulator()
>>> sim.add_molecules(molecules_a, image_a, name="Molecule-A")
>>> sim.add_molecules(molecules_b, image_b, name="Molecule-B")
>>> img = sim.simulate(shape=(128, 128, 128))
Parameters
  • order (int, default is 3) – Interpolation order for density image. - 0 = Nearest neighbor - 1 = Linear interpolation - 3 = Cubic interpolation

  • scale (float, default is 1.0) – Scale of the pixel. This value is used to determine the position of the molecules.

  • corner_safe (bool, default is False) – Not implemented yet.

add_molecules(molecules: Molecules, image: NDArray[np.float32] | ImageProvider, *, name: str | None = None, overwrite: bool = False) Self[source]

Add molecules to the tomogram.

Parameters
  • molecules (Molecules) – Molecules object that defines the coordinates and orientations of the input molecules.

  • image (np.ndarray or ImageProvider) – Density image of the input molecules, or an image provider.

  • name (str, optional) – Name of the molecules., by default None

  • overwrite (bool, default is False) – If true, allow overwriting existing component.

Returns

Same object.

Return type

TomogramSimulator

collect_molecules() acryo.molecules.core.Molecules[source]
property components: mappingproxy[str, acryo.simulator.Component]

Return all the components in the tomogram.

copy() Self[source]

Create a shallow copy of the loader.

property corner_safe: bool
property order: Literal[0, 1, 3]

Return the interpolation order.

replace(order: Literal[0, 1, 3] | None = None, scale: float | None = None, corner_safe: bool | None = None) Self[source]

Return a new instance with different parameter(s).

property scale: float

The physical scale of the tomogram.

simulate(shape: tuple[pixel, pixel, pixel], colormap: Callable[[pl.DataFrame], ColorType] | NDArray[np.float32] | None = None) NDArray[np.float32][source]

Simulate a tomogram.

Parameters
  • shape (tuple of int) – Shape of the tomogram.

  • colormap (callable, optional) – Colormap used to generate the colored tomogram. The input is a polars row vector of features of each molecule.

Returns

Simulated tomogram image.

Return type

np.ndarray

simulate_2d(shape: tuple[int, int]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a grayscale tomogram.

simulate_projection(shape: tuple[int, int], center: tuple[float, float, float], xaxis: tuple[float, float, float], yaxis: tuple[float, float, float]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a projection of the tomogram in any direction.

Projection plane and the projection range are defined by the given parameters. shape and center define the range of the projection plane. Technically, center will be the scale-considered center of the assumed 3D tomogram image. xaxis and yaxis define the coordinate system of the projection plane.

Parameters
  • shape ((int, int)) – Output shape of the projection.

  • center ((float, float, float)) – Center of the projection plane in world coordinate system.

  • xaxis ((float, float, float)) – X-axis of the projection plane in world coordinate system.

  • yaxis ((float, float, float)) – Y-axis of the projection plane in world coordinate system.

Returns

Simulated projection image.

Return type

2D array

simulate_tilt_series(degrees: Iterable[float], shape: tuple[int, int, int]) numpy.ndarray[Any, numpy.dtype[numpy.float32]][source]

Simulate a tilt series of the tomogram.

This method is a simplified version of simulate_projection(). Projection angles are restricted to the rotation around the y-axis of the world coordinate and the tomogram will be projected parallel to the z-axis.

Parameters
  • degrees (iterable of float) – Rotation angles.

  • shape ((int, int, int)) – Tomogram shape.

Returns

Tilting series image.

Return type

(N, Y, X) array

subset(names: str | Sequence[str]) Self[source]

Construct a simulator composed of a subset of the components.

Parameters

names (str or sequence of str) – Component names that will be included in the subset.

Returns

New simulator object.

Return type

TomogramSimulator

acryo.imread(path: str, molecules: acryo.molecules.core.Molecules, order: int = 3, scale: float | None = None, output_shape: int | tuple[int, int, int] | acryo.loader._base.Unset = Unset, corner_safe: bool = False, chunks: Any = 'auto')