aspire.operators package

Submodules

aspire.operators.blk_diag_matrix module

Define a BlkDiagMatrix module which implements operations for block diagonal matrices as used by ASPIRE.

class aspire.operators.blk_diag_matrix.BlkDiagMatrix(partition, dtype=<class 'numpy.float32'>)

Bases: object

Define a BlkDiagMatrix class which implements operations for block diagonal matrices as used by ASPIRE.

Currently BlkDiagMatrix is implemented only for square blocks. While in the future this can be extended, at this time assigning a non square array will raise NotImplementedError.

Instantiate a BlkDiagMatrix.

Parameters:
  • partition – The matrix block partition in the form of a nblock-element list storing all shapes of diagonal matrix blocks, where partition[i] corresponds to the shape (number of rows and columns) of the i matrix block.

  • dtype – Datatype for blocks, defaults to np.float32.

Returns:

BlkDiagMatrix instance.

property T

Syntactic sugar for self.transpose().

abs()

Compute the elementwise absolute value of BlkDiagMatrix instance.

Returns:

A BlkDiagMatrix like self.

add(other, inplace=False)

Define the elementwise addition of BlkDiagMatrix instance.

Parameters:
  • other – The rhs BlkDiagMatrix instance.

  • inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

BlkDiagMatrix instance with elementwise sum equal to self + other.

append(blk)

Append blk to self. Used to incrementally build up a BlkDiagMatrix instance where the number of blocks and/or shapes are derived incrementally.

Parameters:

blk – Block to append (ndarray).

apply(X)

Define the apply option of a block diagonal matrix with a matrix of coefficient vectors.

Parameters:

X – Coefficient matrix, each column is a coefficient vector.

Returns:

A matrix with new coefficient vectors.

check_psd()

Check the positive semidefinite property of all blocks

Returns:

True if all blocks have non-negative eigenvalues.

copy()

Returns new BlkDiagMatrix which is a copy of self.

:return BlkDiagMatrix like self

dense()

Convert list representation of BlkDiagMatrix instance into full matrix.

Parameters:

blk_diag – The BlkDiagMatrix instance.

Returns:

The BlkDiagMatrix instance including the zero elements of

non-diagonal blocks.

diag()

Return the diagonal elements of this BlkDiagMatrix.

eigvals()

Compute the eigenvalues of a BlkDiagMatrix.

Returns:

Array of eigvals, with length equal to the fully expanded matrix diagonal.

static empty(nblocks, dtype=<class 'numpy.float32'>)

Instantiate an empty BlkDiagMatrix with nblocks, where each data block is initially None with size (0,0).

This is used for incrementally building up a BlkDiagMatrix, by using nblocks=0 in conjunction with append method or situations where blocks are immediately assigned in a loop, such as in a copy.

Parameters:

nblocks – Number of diagonal matrix blocks.

Returns:

BlkDiagMatrix instance where each block is None.

static eye(blk_partition, dtype=<class 'numpy.float32'>)

Build a BlkDiagMatrix eye (identity) matrix

Parameters:
  • blk_partition – The matrix block partition in the form of a K-element list storing all shapes of K diagonal matrix blocks, where blk_partition[i] corresponds to the shape (number of rows and columns) of the i diagonal matrix block.

  • dtype – The data type of the diagonal matrix blocks.

Returns:

A BlkDiagMatrix instance consisting of K eye (identity) blocks.

static eye_like(A, dtype=None)

Build a BlkDiagMatrix eye (identity) matrix with the partition structure of BlkDiagMatrix A. Defaults to dtype of A.

Parameters:
  • A – BlkDiagMatrix instance.

  • dtype – Optional, data type of the new diagonal matrix blocks.

Returns:

BlkDiagMatrix instance consisting of K eye (identity) blocks.

static from_dense(A, blk_partition, warn_eps=0.001)

Create BlkDiagMatrix with blk_partition from dense matrix A.

Parameters:
  • A – Dense Numpy array.

  • blk_partition – List of block partition shapes.

  • warn_eps – Optionally warn if off block values from A exceed warn_eps. None disables warnings.

Returns:

BlkDiagMatrix with values from A.

static from_list(blk_diag, dtype=<class 'numpy.float32'>)

Convert full from python list representation into BlkDiagMatrix.

This is to facilitate integration with code that may not be using the BlkDiagMatrix class yet.

:param blk_diag; The blk_diag representation in the form of a

K-element list storing all shapes of K diagonal matrix blocks, where blk_partition[i] corresponds to the shape (number of rows and columns) of the i diagonal matrix block.

Returns:

The BlkDiagMatrix instance.

property is_square

Check if all blocks are square.

Returns:

boolean

property isfinite

Check if all blocks in diag matrix are finite.

Calls numpy.isfinite for every entry in self. This has the effect of checking values are not += inf or `nan`s.

Returns:

Bool.

make_psd()

Convert all blocks to positive semidefinite

Returns:

The BlkDiagMatrix instance with all blocks positive semidefinite

matmul(other, inplace=False)

Compute the matrix multiplication of two BlkDiagMatrix instances.

Parameters:
  • other – The rhs BlkDiagMatrix instance.

  • inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

A BlkDiagMatrix of self @ other.

mul(val, inplace=False)

Compute the numeric multiplication of a BlkDiagMatrix instance and a scalar.

Parameters:
  • other – The rhs BlkDiagMatrix instance.

  • inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

A BlkDiagMatrix of self * other.

neg()

Compute the unary negation of BlkDiagMatrix instance.

Returns:

A BlkDiagMatrix like self.

norm()

Compute the norm of a BlkDiagMatrix instance.

Parameters:

inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

The norm of the BlkDiagMatrix instance.

static ones(blk_partition, dtype=<class 'numpy.float32'>)

Build a BlkDiagMatrix ones matrix.

Parameters:
  • blk_partition – The matrix block partition in the form of a K-element list storing all shapes of K diagonal matrix blocks, where blk_partition[i] corresponds to the shape (number of rows and columns) of the i diagonal matrix block.

  • dtype – The data type to set precision of diagonal matrix block.

Returns:

A BlkDiagMatrix instance consisting of K ones blocks.

property partition

Return the partitions (block sizes) of this BlkDiagMatrix

Returns:

The matrix block partition in the form of a

K-element list storing all shapes of K diagonal matrix blocks, where partition[i] corresponds to the shape (number of rows and columns) of the i diagonal matrix block.

pow(val, inplace=False)

Compute the elementwise power of BlkDiagMatrix instance.

Parameters:

inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

A BlkDiagMatrix like self.

rapply(X)

Right apply. Given a matrix of coefficient vectors, applies the block diagonal matrix on the right hand side. Example, X @ self.

This is the right hand side equivalent to apply.

Parameters:

X – Coefficient matrix, each column is a coefficient vector.

Returns:

A matrix with new coefficient vectors.

reset_cache()

Resets this objects internal cache. This should trigger the cache to be recalculated on the next request (ie lazily).

solve(Y)

Solve a linear system involving a block diagonal matrix.

Parameters:

Y – The right-hand side in the linear system. May be a matrix consisting of coefficient vectors, in which case each column is solved for separately.

Returns:

The result of solving the linear system formed by the matrix.

sub(other, inplace=False)

Define the element subtraction of BlkDiagMatrix instance.

Parameters:
  • other – The rhs BlkDiagMatrix instance.

  • inplace – Boolean, when set to True change values in place, otherwise return a new instance (default).

Returns:

A BlkDiagMatrix instance with elementwise subraction equal to self - other.

transpose()

Get the transpose matrix of a BlkDiagMatrix instance.

Returns:

The corresponding transpose form as a BlkDiagMatrix.

static zeros(blk_partition, dtype=<class 'numpy.float32'>)

Build a BlkDiagMatrix zeros matrix.

Parameters:
  • blk_partition – The matrix block partition in the form of a K-element list storing all shapes of K diagonal matrix blocks, where blk_partition[i] corresponds to the shape (number of rows and columns) of the i diagonal matrix block.

  • dtype – The data type to set precision of diagonal matrix block.

Returns:

A BlkDiagMatrix instance consisting of K zero blocks.

static zeros_like(A, dtype=None)

Build a BlkDiagMatrix zeros matrix with the partition structure of BlkDiagMatrix A. Defaults to dtype of A.

Parameters:
  • A – BlkDiagMatrix instance.

  • dtype – Optional, data type of the new diagonal matrix blocks.

Returns:

BlkDiagMatrix instance consisting of K zeros blocks.

aspire.operators.blk_diag_matrix.is_scalar_type(x)

Helper function checking scalar-ness for elementwise ops.

Essentially we are checking for a single numeric object, as opposed to something like an ndarray or BlkDiagMatrix. We do this by checking numpy.isscalar(x).

In the future this check may require extension to include ASPIRE or other third party types beyond what is provided by numpy, so we implement it now as a method.

Parameters:

x – Value to check

Returns:

bool.

aspire.operators.diag_matrix module

Implements operations for diagonal matrices as used by ASPIRE.

class aspire.operators.diag_matrix.DiagMatrix(data, dtype=None)

Bases: object

Implements operations for diagonal matrices as used by ASPIRE.

Currently DiagMatrix is implemented as the equivalent of square matrices. In the future it can be extended to support applications with rectangular shapes.

Instantiate a DiagMatrix with Numpy data shaped (…., self.count), where self.count is the length of one diagonal vector.

Slower axes (if present) are taken to be stack axes.

Parameters:
  • data – Diagonal matrix entries.

  • dtype – Datatype. Default of None will attempt passthrough of data.dtype. When explicitly provided, will attempt casting data as needed.

Returns:

DiagMatrix instance.

property T

Syntactic sugar for self.transpose().

abs()

Compute the elementwise absolute value of DiagMatrix instance.

Returns:

A DiagMatrix like self.

add(other)

Define elementwise addition of DiagMatrix instances with scalars, BlkDiagMatrix, and DiagMatrix.

Parameters:

other – scalar, BlkDiagMatrix or `DiagMatrix.

Returns:

DiagMatrix instance with elementwise sum equal to self + other. In the case of BlkDiagMatrix a BlkDiagMatrix is returned.

apply(X)

Define the apply option of a diagonal matrix with a matrix of coefficient column vectors.

Parameters:

X – Coefficient matrix (ndarray), each column is a coefficient vector.

Returns:

A matrix with new coefficient column vectors.

as_blk_diag(partition)

Express DiagMatrix as a BlkDiagMatrix using partition.

Parameters:

partition – BlkDiagMatrix partition.

Returns:

BlkDiagMatrix

asnumpy()

Return data as Numpy array.

Note this is a read-only view.

Returns:

Numpy array of self.dtype.

copy()

Returns new DiagMatrix which is a copy of self.

:return DiagMatrix like self

dense()

Convert DiagMatrix instance into full matrix.

Returns:

The DiagMatrix instance including the zero elements of

non-diagonal elements.

eigvals()

Compute the eigenvalues of a DiagMatrix.

Returns:

Array of eigvals, with length equal to the fully expanded matrix diagonal.

static empty(shape, dtype=<class 'numpy.float32'>)

Instantiate an empty DiagMatrix with shape. When shape is an integer, this corresponds to the diag(A) where A is (n,n). Note, like Numpy, empty values are uninitialized.

Parameters:
  • shape – Shape of matrix. When integer, corresponds to len(diag(A)). Otherwise, when a tuple (…, n), the last dimension n defines the length of diagonal, while prior dimensions define any stack axes.

  • dtype – Datatype, defaults to np.float32.

Returns:

DiagMatrix instance.

static eye(shape, dtype=<class 'numpy.float32'>)

Build a DiagMatrix eye (identity) matrix. This is simply an alias for ones.

Parameters:
  • shape – Shape of matrix. When integer, corresponds to len(diag(A)). Otherwise, when a tuple (…, n), the last dimension n defines the length of diagonal, while prior dimensions define any stack axes.

  • dtype – Datatype, defaults to np.float32.

Returns:

DiagMatrix instance.

matmul(other)

Compute the matrix multiplication of two DiagMatrix instances.

Parameters:

other – The rhs DiagMatrix, BlkDiagMatrix or 2d dense Numpy array.

Returns:

Returns self @ other, as type of other

mul(other)

Compute the elementwise multiplication of a DiagMatrix instance and a scalar or DiagMatrix.

Parameters:

other – The rhs in the multiplication..

Returns:

A self * other as type of other.

neg()

Compute the unary negation of DiagMatrix instance.

Returns:

A DiagMatrix like self.

property norm

Compute the 2-norm of a DiagMatrix instance.

Returns:

The 2-norm of the DiagMatrix instance.

static ones(shape, dtype=<class 'numpy.float32'>)

Instantiate ones intialized DiagMatrix. When shape is an integer, this corresponds to the diag(A) where A is (n,n).

Parameters:
  • shape – Shape of matrix. When integer, corresponds to len(diag(A)). Otherwise, when a tuple (…, n), the last dimension n defines the length of diagonal, while prior dimensions define any stack axes.

  • dtype – Datatype, defaults to np.float32.

Returns:

DiagMatrix instance.

pow(val)

Compute the elementwise power of DiagMatrix instance.

Parameters:

val – Value to exponentiate by.

Returns:

A DiagMatrix like self.

rapply(X)

Right apply. Given a matrix of coefficient vectors, applies the diagonal matrix on the right hand side. Example, X @ self.

This is the right hand side equivalent to apply, which due to being diagonal, is the same as apply. This method exists purely for interoperability with code originally targeting BlkDiagMatrix.

Parameters:

X – Coefficient matrix, each column is a coefficient vector.

Returns:

A matrix with new coefficient vectors.

solve(b)

For this DiagMatrix a and vector b. solve a x = b for x.

Parameters:

b – Right hand side, Numpy array.

Returns:

DiagMatrix, solution x.

stack_reshape(*args)

Reshape the stack axis.

*argsargs:

Integer(s) or tuple describing the intended shape.

Returns:

DiagMatrix instance.

sub(other)

Define elementwise subtraction of DiagMatrix instances by scalars, BlkDiagMatrix, and DiagMatrix.

Parameters:

other – scalar, BlkDiagMatrix or `DiagMatrix.

Returns:

DiagMatrix instance with elementwise sub equal to self - other. In the case of BlkDiagMatrix a BlkDiagMatrix is returned.

transpose()

Get the transpose matrix of a DiagMatrix instance.

Returns:

The corresponding transpose form as a DiagMatrix.

static zeros(shape, dtype=<class 'numpy.float32'>)

Instantiate a zero intialized DiagMatrix. When shape is an integer, this corresponds to the diag(A) where A is (n,n).

Parameters:
  • shape – Shape of matrix. When integer, corresponds to len(diag(A)). Otherwise, when a tuple (…, n), the last dimension n defines the length of diagonal, while prior dimensions define any stack axes.

  • dtype – Datatype, defaults to np.float32.

Returns:

DiagMatrix instance.

aspire.operators.filters module

class aspire.operators.filters.ArrayFilter(xfer_fn_array)

Bases: Filter

A Filter corresponding to the filter with the specified transfer function.

Parameters:

xfer_fn_array – The transfer function of the filter in the form of an array of one or two dimensions.

evaluate_grid(L, *args, dtype=<class 'numpy.float32'>, **kwargs)

Optimized evaluate_grid method for ArrayFilter.

If evaluate_grid is called with a resolution L that matches the transfer function xfer_fn_array resolution, we do not need to generate a grid, setup interpolation, and evaluate by interpolation. We can instead use the transfer function directly.

In the case the grid is not a match, we fall back to the base evaluate_grid implementation.

See Filter.evaluate_grid for usage.

class aspire.operators.filters.BlueFilter(dim=None, var=1)

Bases: Filter

Filter where power increases with frequency.

class aspire.operators.filters.CTFFilter(pixel_size=10, voltage=200, defocus_u=15000, defocus_v=15000, defocus_ang=0, Cs=2.26, alpha=0.07, B=0)

Bases: Filter

A CTF (Contrast Transfer Function) Filter

Parameters:
  • pixel_size – Pixel size in angstrom

  • voltage – Electron voltage in kV

  • defocus_u – Defocus depth along the u-axis in angstrom

  • defocus_v – Defocus depth along the v-axis in angstrom

  • defocus_ang – Angle between the x-axis and the u-axis in radians

  • Cs – Spherical aberration constant

  • alpha – Amplitude contrast phase in radians

  • B – Envelope decay in inverse square angstrom (default 0)

scale(c=1)

Scale filter by a constant factor

Parameters:

c – The scaling factor. For c < 1, it dilates the filter(s) in frequency, while for c > 1, it compresses (default 1).

Returns:

A ScaledFilter object

class aspire.operators.filters.DualFilter(filter_in)

Bases: Filter

A Filter object that is dual to origin one, namely g(w)=f(-w)

evaluate(omega)

Evaluate the filter at specified frequencies.

Parameters:

omega – A vector of size n (for 1d filters), or an array of size 2-by-n, representing the spatial frequencies at which the filter is to be evaluated. These are normalized so that pi is equal to the Nyquist frequency.

Returns:

The value of the filter at the specified frequencies.

class aspire.operators.filters.Filter(dim=None, radial=False)

Bases: object

basis_mat(basis)

Represent the filter in basis.

Parameters:

basis – 2D Basis.

Returns:

basis representation of this filter. Return type will depend on basis.

dual()
evaluate(omega)

Evaluate the filter at specified frequencies.

Parameters:

omega – A vector of size n (for 1d filters), or an array of size 2-by-n, representing the spatial frequencies at which the filter is to be evaluated. These are normalized so that pi is equal to the Nyquist frequency.

Returns:

The value of the filter at the specified frequencies.

evaluate_grid(L, *args, dtype=<class 'numpy.float32'>, **kwargs)

Generates a two dimensional grid with prescribed dtype, yielding the values (omega) which are then evaluated by the filter’s evaluate method.

Passes arbritrary args and kwargs down to self.evaluate method.

Parameters:
  • L – Number of grid points (L by L).

  • dtype – dtype of grid, defaults np.float32.

Returns:

Filter values at omega’s points.

scale(c=1)

Scale filter by a constant factor

Parameters:

c – The scaling factor. For c < 1, it dilates the filter(s) in frequency, while for c > 1, it compresses (default 1).

Returns:

A ScaledFilter object

property sign

A Filter object to evaluate the signs of the underlying filter.

class aspire.operators.filters.FunctionFilter(f, dim=None)

Bases: Filter

A Filter object that is instantiated directly using a 1D or 2D function, which is then directly used for evaluating the filter.

class aspire.operators.filters.IdentityFilter(dim=None)

Bases: ScalarFilter

class aspire.operators.filters.LambdaFilter(filter, f)

Bases: Filter

A Filter object to evaluate lambda function of a regular Filter.

class aspire.operators.filters.MultiplicativeFilter(*args)

Bases: Filter

A Filter object that returns the product of the evaluation of its individual filters

class aspire.operators.filters.PinkFilter(dim=None, var=1)

Bases: Filter

Filter where power decreases with frequency.

class aspire.operators.filters.PowerFilter(filter, power=1)

Bases: Filter

A Filter object that is composed of a regular Filter object, but evaluates it to a specified power.

evaluate_grid(L, *args, dtype=<class 'numpy.float32'>, **kwargs)

Calls the provided filter’s evaluate_grid method in case there is an optimization.

If no optimized method is provided, falls back to base evaluate_grid.

See Filter.evaluate_grid for usage.

class aspire.operators.filters.RadialCTFFilter(pixel_size=10, voltage=200, defocus=15000, Cs=2.26, alpha=0.07, B=0)

Bases: CTFFilter

A CTF (Contrast Transfer Function) Filter

Parameters:
  • pixel_size – Pixel size in angstrom

  • voltage – Electron voltage in kV

  • defocus_u – Defocus depth along the u-axis in angstrom

  • defocus_v – Defocus depth along the v-axis in angstrom

  • defocus_ang – Angle between the x-axis and the u-axis in radians

  • Cs – Spherical aberration constant

  • alpha – Amplitude contrast phase in radians

  • B – Envelope decay in inverse square angstrom (default 0)

class aspire.operators.filters.ScalarFilter(dim=None, value=1)

Bases: Filter

class aspire.operators.filters.ScaledFilter(filt, scale)

Bases: Filter

A Filter object that is composed of a regular Filter object, but evaluates it on a scaled omega.

class aspire.operators.filters.ZeroFilter(dim=None)

Bases: ScalarFilter

aspire.operators.filters.evaluate_src_filters_on_grid(src, indices=None)

Given an ImageSource object, compute the source’s unique filters at the filter_indices specified in its metadata.

Parameters:
  • src – Source instance

  • indices – Optional, subset of src indices to compute. Defaults to the entire src.

Returns:

an src.L x src.L x len(src.filter_indices) array containing the evaluated filters at each gridpoint

aspire.operators.polar_ft module

class aspire.operators.polar_ft.PolarFT(size, nrad=None, ntheta=None, dtype=<class 'numpy.float32'>)

Bases: object

Define a derived class for polar Fourier representation for 2D images

Initialize an object for the polar Fourier transform class. PolarFT expects that images are real and uses only half of the ntheta values.

Parameters:
  • size – The shape of the vectors for which to define the transform. May be a 2-tuple or an integer, in which case a square basis is assumed. Currently only square images are supported.

  • nrad – The number of points in the radial dimension. Default is resolution // 2.

  • ntheta – The number of points in the angular dimension. Default is 8 * nrad.

  • dtype – dtype used to compute a polar frequency grid for evaluating the transform..

static half_to_full(pf)

Use the conjugate symmetry of pf to construct the full polar Fourier transform over all rays in [0, 360).

Parameters:

pf – The precomputed half polar Fourier transform with shape (*stack_shape, ntheta//2, nrad)

Returns:

The full polar Fourier transform with shape (*stack_shape, ntheta, nrad)

transform(x)

Evaluate coefficient in polar Fourier grid from those in standard 2D coordinate basis

Parameters:

x – The Image instance representing coefficient array in the standard 2D coordinate basis to be evaluated.

Returns:

The evaluation of the coefficient array x in the polar Fourier grid. This is an array of vectors whose first dimension corresponds to x.shape[0], and last dimension equals self.count.

aspire.operators.wemd module

Wavelet-based approximate Earthmover’s distance (EMD) for n-dimensional signals.

This code is based on the following paper:

Sameer Shirdhonkar and David W. Jacobs. “Approximate earth mover’s distance in linear time.” 2008 IEEE Conference on Computer Vision and Pattern Recognition (CVPR).

More details are available in their technical report:

CAR-TR-1025 CS-TR-4908 UMIACS-TR-2008-06.

aspire.operators.wemd.wemd_embed(arr, wavelet='coif3', level=None)

This function computes an embedding of Numpy arrays such that for non-negative arrays that sum to one, the L1 distance between the resulting embeddings is strongly equivalent to the Earthmover distance of the arrays.

Parameters:
  • arr – Numpy array

  • level – Decomposition level of the wavelets.

Larger levels yield more coefficients and more accurate results. If no level is given, we take the the log2 of the side-length of the domain. :param wavelet: Either the name of a wavelet supported by PyWavelets (e.g. ‘coif3’, ‘sym3’, ‘sym5’, etc.) or a pywt.Wavelet object See https://pywavelets.readthedocs.io/en/latest/ref/wavelets.html#built-in-wavelets-wavelist The default is ‘coif3’, because it seems to work well empirically. :returns: One-dimensional numpy array containing weighted details coefficients.

aspire.operators.wemd.wemd_norm(arr, wavelet='coif3', level=None)

Wavelet-based norm used to approximate the Earthmover’s distance between mass distributions specified as Numpy arrays (typically images or volumes).

Parameters:
  • arr – Numpy array of the difference between the two mass distributions.

  • level – Decomposition level of the wavelets.

Larger levels yield more coefficients and more accurate results. If no level is given, we take the the log2 of the side-length of the domain. Larger levels yield more coefficients and more accurate results :param wavelet: Either the name of a wavelet supported by PyWavelets (e.g. ‘coif3’, ‘sym3’, ‘sym5’, etc.) or a pywt.Wavelet object See https://pywavelets.readthedocs.io/en/latest/ref/wavelets.html#built-in-wavelets-wavelist The default is ‘coif3’, because it seems to work well empirically. :return: Approximated Earthmover’s Distance

Module contents