aspire.image package

Submodules

aspire.image.image module

class aspire.image.image.BasisImage(basis)

Bases: Image

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

evaluate()
class aspire.image.image.BispecImage(data, pixel_size=None, dtype=None)

Bases: Image

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

expand(basis)
class aspire.image.image.CartesianImage(data, pixel_size=None, dtype=None)

Bases: Image

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

expand(basis)
class aspire.image.image.FBBasisImage(basis)

Bases: BasisImage

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

class aspire.image.image.Image(data, pixel_size=None, dtype=None)

Bases: object

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

property T

Abbreviation for transpose.

Returns:

Image instance.

asnumpy()

Return image data as a (<stack>, resolution, resolution) read-only array view.

Returns:

read-only ndarray view

backproject(rot_matrices, symmetry_group=None, zero_nyquist=True)

Backproject images along rotations. If a symmetry group is provided, images used in back-projection are duplicated (boosted) for symmetric viewing directions. Note, it is assumed that a main axis of symmetry aligns with the z-axis.

Parameters:
  • rot_matrices – An n-by-3-by-3 array of rotation matrices corresponding to viewing directions.

  • symmetry_group – A SymmetryGroup instance or string indicating symmetry, ie. “C3”. If supplied, uses symmetry to increase number of images used in back-projection.

  • zero_nyquist – Option to keep or remove Nyquist frequency for even resolution. Defaults to zero_nyquist=True, removing the Nyquist frequency.

Returns:

Volume instance corresonding to the backprojected images.

copy()
downsample(ds_res, zero_nyquist=True)

Downsample Image to a specific resolution. This method returns a new Image.

Parameters:
  • ds_res – int - new resolution, should be <= the current resolution of this Image

  • zero_nyquist – Option to keep or remove Nyquist frequency for even resolution. Defaults to zero_nyquist=True, removing the Nyquist frequency.

Returns:

The downsampled Image object.

extensions = {'.mrc': <function load_mrc>, '.tif': <function load_tiff>, '.tiff': <function load_tiff>}
filter(filter)

Apply a Filter object to the Image and returns a new Image.

Parameters:

filter – An object of type Filter.

Returns:

A new filtered Image object.

flip(axis=-2)

Flip image stack data along axis using numpy.flip().

Parameters:

axis – Optionally specify axis as integer or tuple. Defaults to axis=-2.

Returns:

Image instance.

frc(other, cutoff=None, method='fft', plot=False)

Compute the Fourier ring correlation between two images.

Images are assumed to be well aligned.

The FRC is defined as:

\[c(i) = \frac{ \operatorname{Re}( \sum_i{ \mathcal{F}_1(i) * {\mathcal{F}^{*}_2(i) } } ) }{\ \sqrt{ \sum_i { | \mathcal{F}_1(i) |^2 } * \sum_i{| \mathcal{F}^{*}_2}(i) |^2 } }\]
Parameters:
  • otherImage instance to compare.

  • cutoff – Cutoff value, traditionally .143. Default None implies cutoff=1 and excludes plotting cutoff line.

  • method – Selects either ‘fft’ (on cartesian grid), or ‘nufft’ (on polar grid). Defaults to ‘fft’.

  • plot – Optionally plot to screen or file. Defaults to False. True plots to screen. Passing a filepath as a string will attempt to save to file.

Returns:

tuple(estimated_resolution, FRC), where estimated_resolution is in angstrom and FRC is a Numpy array of correlations.

static load(filepath, dtype=None)

Load raw data from supported files.

Currently MRC and TIFF are supported.

Parameters:
  • filepath – File path (string).

  • dtype – Optionally force cast to dtype. Default dtype is inferred from the file contents.

Returns:

numpy array of image data.

norm()
project(angles)

Computes the Radon Transform on an Image Stack using Non-Uniform Fast Fourier Transforms. This method projects the Image stack along different angles and returns the Radon Transform.

Parameters:

angles – A 1-D Numpy Array of angles in Radians. This is used to compute the Radon Transform at different angles.

Returns:

Radon transform of the Image Stack.

Return type:

Ndarray (stack size, number of angles, image resolution)

property res
rotate()
save(mrcs_filepath, overwrite=False)
shift(shifts)

Translate image by shifts. This method returns a new Image.

Parameters:

shifts – An array of size n-by-2 specifying the shifts in pixels. Alternatively, it can be a column vector of length 2, in which case the same shifts is applied to each image.

Returns:

The Image translated by the shifts, with periodic boundaries.

show(columns=5, figsize=(20, 10), colorbar=True)

Plotting Utility Function.

Parameters:
  • columns – Number of columns in a row of plots.

  • figsize – Figure size in inches, consult matplotlib.figure.

  • colorbar – Optionally plot colorbar to show scale. Defaults to True. Accepts bool or dictionary, where the dictionary is passed to matplotlib.pyplot.colorbar.

property size
sqrt()
stack_reshape(*args)

Reshape the stack axis.

*argsargs:

Integer(s) or tuple describing the intended shape.

Returns:

Image instance

transpose()

Returns a new Image instance with image data axes transposed.

Returns:

Image instance.

class aspire.image.image.PolarImage(data, pixel_size=None, dtype=None)

Bases: Image

A stack of one or more images.

This is a wrapper of numpy.ndarray which provides methods for common processing tasks.

The stack can be multidimensional with n_images equal to the product of the stack dimensions. Singletons will be expanded into a stack with one entry.

The last two axes represent the image size, and are checked to be square.

Parameters:
  • data – Numpy array containing image data with shape (…, resolution, resolution).

  • pixel_size – Optional pixel size in angstroms. When provided will be saved with mrc metadata. Default of None will not write to file, but will be considered unit pixels (1) for FSC.

  • dtype – Optionally cast data to this dtype. Defaults to data.dtype.

Returns:

Image instance holding data.

expand(basis)
aspire.image.image.load_mrc(filepath)

Load raw data from .mrc into an array.

Parameters:

filepath – File path (string).

Returns:

(numpy array of image data, pixel_size)

aspire.image.image.load_tiff(filepath)

Load raw data from .tiff into an array.

Note, TIFF does not natively provide equivalent to pixel/voxel_size, so users of TIFF files may need to manually assign pixel_size to Image instances when required. Defaults to pixel_size=None.

Parameters:

filepath – File path (string).

Returns:

(numpy array of image data, pixel_size=None)

aspire.image.image.normalize_bg(imgs, bg_radius=1.0, do_ramp=True)

Normalize backgrounds and apply to a stack of images

Parameters:
  • imgs – A stack of images in N-by-L-by-L array

  • bg_radius – Radius cutoff to be considered as background (in image size)

  • do_ramp – When it is True, fit a ramping background to the data and subtract. Namely perform normalization based on values from each image. Otherwise, a constant background level from all images is used.

Returns:

The modified images

aspire.image.image_stacker module

class aspire.image.image_stacker.ImageStacker

Bases: ABC

Interface for image and coefficient stacking classes.

It is assumed that provided images are already aligned. Instances of Stacker act like functions.

stacker = ImageStacker(…) stacker(images_to_stack).

Initialize ImageStacker instance.

class aspire.image.image_stacker.MeanImageStacker

Bases: ImageStacker

Stack using mean.

Initialize ImageStacker instance.

class aspire.image.image_stacker.MedianImageStacker

Bases: ImageStacker

Stack using median.

Initialize ImageStacker instance.

class aspire.image.image_stacker.PoissonRejectionImageStacker

Bases: ImageStacker

Stack using Poisson Rejection.

Initialize ImageStacker instance.

class aspire.image.image_stacker.RobustChauvenetRejectionImageStacker

Bases: ImageStacker

Stack using Robust Chauvenet Outlier Rejection.

Initialize ImageStacker instance.

class aspire.image.image_stacker.SigmaRejectionImageStacker(rejection_sigma=3)

Bases: ImageStacker

Stack using Sigma Rejection.

When no outliers exist, sigma rejection is equivalent to mean. In the presence of outliers, pixels outside of rejection_sigma from the per-pixel-mean are discarded before the mean is performed.

For potentially less Gaussian distributions, ‘FWHM’ and ‘FWTM’ methods are also provided. These will take the mean of all values laying above half the maximum and tenth maximum respectively. Essentially this is the same wing clipping procedure, but the location of the clip is determined by the peak intensity instead of standard deviation.

Note, in both cases, users are responsible for ensuring methods are called on reasonable data (in FW* cases we should be probably be using intensities). No corrections or pedestals are incorporated at this time, but could easily be added in the future.

Instantiates with presribed rejection_sigma.

Parameters:

rejection_sigma – Values falling outside rejection_sigma standard deviations are rejected. Defaults to 3. Also accepts ‘FWHM’ and ‘FWTM’ corresponding to per-pixel full width at half maximum and tenth maximum respectively.

class aspire.image.image_stacker.WinsorizedImageStacker(percentile=0.1)

Bases: ImageStacker

Stack using Winsorization.

Winsorizing is similar to SigmaRejectionImageStacker, except it admits a percentile and replaces rejected values with values at +/- percentile.

Instantiates WinsorizedImageStacker instance with prescribed percentile.

See scipy docs for more details: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mstats.winsorize.html

Parameters:

percentile – Float or tuple of floats. Values must be [0,1] and represent the percentile used for trimming. A tuple allows different lower and upper percentiles respectively. Example (0.1, 0.2) would Winsorize the lower 10% and upper 20% of values. In the case of a single value, the same value will be used for both upper and lower percentiles.

aspire.image.xform module

class aspire.image.xform.Add(addend)

Bases: Xform

A Xform that add the density of a stack of 2D images (in the form of an Image object) by an offset value.

Initialize an Add Xform using a Numpy array of predefined values.

Parameters:

addend – An float/int or an ndarray of shape (n,)

class aspire.image.xform.Downsample(resolution)

Bases: LinearXform

A Xform that downsamples an Image object to a resolution specified by this Xform’s resolution.

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

class aspire.image.xform.FilterXform(filter)

Bases: SymmetricXform

A Xform that applies a single Filter object to a stack of 2D images (as an Image object).

Initialize the Filter Xform using a Filter object

Parameters:

filter – An object of type aspire.operators.Filter

class aspire.image.xform.IndexedXform(unique_xforms, indices=None)

Bases: Xform

An IndexedXform is a Xform where individual Xform objects are used at specific indices of the incoming Image object.

This extra layer of abstraction is used because individual Xform objects are typically capable of dealing with a stack of images (an Image object) in an efficient manner. The IndexedXform class groups the invocation of each of its unique Xform objects, so that calls to individual Xform objects within it is minimized, and equals the number of unique Xforms found.

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

class aspire.image.xform.LambdaXform(lambda_fun, *args, **kwargs)

Bases: Xform

A Xform that applies a predefined function to a stack of 2D images (as an Image object).

Initialize the LambdaXform using a lambda function

Parameters:
  • lambda_fun – Predefine lambda function

  • *args

    Positional arguments

  • **kwargs

    Keyword arguments

class aspire.image.xform.LinearIndexedXform(unique_xforms, indices=None)

Bases: IndexedXform, LinearXform

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

class aspire.image.xform.LinearPipeline(xforms=None, memory=None)

Bases: Pipeline, LinearXform

Initialize a Pipeline with Xform objects.

Parameters:
  • xforms – An iterable of Xform objects to use in the Pipeline.

  • memory – None for no caching (default), or the location of a directory to use to cache steps of the pipeline.

class aspire.image.xform.LinearXform(active=True)

Bases: Xform

A LinearXform is a Xform that additionally provides an adjoint method, similar to the forward method.

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

adjoint(im, indices=None)

Apply adjoint transformation for this Xform object to an Image object.

Parameters:
  • im – The incoming Image object of depth n, on which to apply the adjoint transformation.

  • indices – The indices to use within this Xform. If unspecified, [0..n) is used.

Returns:

An Image object after applying the adjoint transformation.

class aspire.image.xform.Multiply(factor)

Bases: SymmetricXform

A Xform that changes the amplitudes of a stack of 2D images (in the form of an Image object) by multiplying all pixels of a single 2D image by a constant factor.

Initialize a Multiply Xform using specified factors

Parameters:

factor – A float/int or an ndarray of scalar factors to use for amplitude multiplication.

class aspire.image.xform.Pipeline(xforms=None, memory=None)

Bases: Xform

A Pipeline is a Xform made up of individual transformation steps (i.e. multiple Xform objects). The Pipeline, just like any other Xform, can be run in the forward (or adjoint mode, in the case of a LinearPipeline.

In addition to keeping client-side code clean, a major advantage of Pipeline is that individual steps of the pipeline can be cached transparently by the Pipeline, providing significant performance advantages for steps that are performed repeatedly (especially during development while setting up these pipelines) on any Image/Xform pair. This caching uses joblib.Memory object behind the scenes, but is disabled by default.

Initialize a Pipeline with Xform objects.

Parameters:
  • xforms – An iterable of Xform objects to use in the Pipeline.

  • memory – None for no caching (default), or the location of a directory to use to cache steps of the pipeline.

add_xform(xform)

Add a single Xform object at the end of the pipeline.

Parameters:

xform – A Xform object.

Returns:

None

add_xforms(xforms)

Add multiple Xform objects at the end of the pipeline.

Parameters:

xform – An iterable of Xform objects.

Returns:

None

reset()

Reset the pipeline by removing all `Xform`s.

Returns:

None

class aspire.image.xform.Shift(shifts)

Bases: LinearXform

A Xform that shifts pixels of a stack of 2D images (in the form of an Image object)by offsetting all pixels of a single 2D image by constant x/y offsets.

Initialize a Shift Xform using a Numpy array of shift values.

Parameters:

shifts – An ndarray of shape (2) or (n, 2)

class aspire.image.xform.SymmetricXform(active=True)

Bases: LinearXform

A Symmetric Xform is a LinearXform where the forward/adjoint operations are identical.

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

class aspire.image.xform.Xform(active=True)

Bases: ABC

An Xform is anything that implements a forward method (and an adjoint method, in the case of a LinearXform), that takes in a square Image object and spits out a square Image object corresponding to forward/adjoint operations.

It does this by setting up whatever internal data structures it needs to set up in its constructor. Xform objects usually set up data structures that are typically larger than the depth of the Image object that they expect to encounter during any invocation of forward or adjoint.

At runtime, it gets an Image object (a thin wrapper on a n x L x L ndarray), as well as numeric indices (a numpy array of index values) that correspond to index values (the ‘window’) of the incoming Image object within the context of all images (i.e. an Image object of N x L x L, where N represents the number of total images that can ever pass through this Xform.

At runtime, The Xform object may choose to ignore indices altogether (e.g. a Xform that downsamples all incoming images to a constant resolution won’t care what indices they correspond to), or may do something with it (e.g. a Xform that shifts images by varying offsets depending on their indices).

Create a Xform object that works at a specific resolution.

Parameters:

active – A boolean indicating whether the Xform is active. True by default.

class XformActiveContextManager(xform, active)

Bases: object

This inner class allows us to temporarily enable/disable a Xform object, by tweaking its active attribute on enter/exit.

disabled()

Disable this Xform in a context manager, regardless of its active attribute value.

Returns:

A context manager in which this Xform is disabled.

enabled()

Enable this Xform in a context manager, regardless of its active attribute value.

Returns:

A context manager in which this Xform is enabled.

forward(im, indices=None)

Apply forward transformation for this Xform object to an Image object.

Parameters:
  • im – The incoming Image object of depth n, on which to apply the forward transformation.

  • indices – The indices to use within this Xform. If unspecified, [0..n) is used.

Returns:

An Image object after applying the forward transformation.

Module contents