proxtoolbox.utils package

This package contains some utilities, mostly for loading and processing data.

proxtoolbox.utils.Laplace_matrix(n)[source]

Discrete Laplace operator with Neumann boundary conditions

This method calculates the Laplacian for a 2-dim. signal (usually an image) of size n x n. The resulting matrix has size (n*n)x(n*n).

Parameters:
n : int - Dimension of input signal of size n x n
Returns:
L : sparse array - Discrete Laplace operator of size (n*n)x(n*n)
proxtoolbox.utils.procrustes(X, Y, scaling=True, reflection='best')[source]

A port of MATLAB’s procrustes function to Numpy.

Procrustes analysis determines a linear transformation (translation, reflection, orthogonal rotation and scaling) of the points in Y to best conform them to the points in matrix X, using the sum of squared errors as the goodness of fit criterion.

d, Z, [tform] = procrustes(X, Y)
Parameters:
X, Y

matrices of target and input coordinates. they must have equal numbers of points (rows), but Y may have fewer dimensions (columns) than X.

scaling

if False, the scaling component of the transformation is forced to 1

reflection

if ‘best’ (default), the transformation solution may or may not include a reflection component, depending on which fits the data best. setting reflection to True or False forces a solution with reflection or no reflection respectively.

Returns:
d

the residual sum of squared errors, normalized according to a measure of the scale of X, ((X - X.mean(0))**2).sum()

Z

the matrix of transformed Y-values

tform

a dict specifying the rotation, translation and scaling that maps X –> Y

proxtoolbox.utils.FFT(f)[source]
proxtoolbox.utils.IFFT(F)[source]
proxtoolbox.utils.Resize(A, Mnew, Nnew)[source]
proxtoolbox.utils.PoissonRan(xm)[source]

Poisson random number generation with mean of xm

See numerical recipe C++ version ref: y(i+1) = xm^i*exp(-xm)/factorial(i); see Leo Breiman Probability

Parameters:
xm : real number

Mean

Returns:
em : real number

Sample from the parameterized Poisson distribution

Notes

This code suffers from numerical precision issues. With big values for xm (for example, xm = 6.910459246361838e+27, as was initially the case with the JWST experiment) the difference with Matlab is substential. In Python, one exponential evalutation gives +inf while it gives zero in Maltab.

proxtoolbox.utils.ZeroPad(m)[source]

Submodules

proxtoolbox.utils.Extracter module

Extracter.py
written on 7. May 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: Extracts a 2x2 image from a zero field INPUT: u, an array with an imbedded image

l, left pixel adjustment r, right pixel adjustment up, upper pixel adjustment dn, lower pixel adjustment

OUTPUT: u, the extracted image USAGE: U=Extracter(u,l,r,up,dn)

proxtoolbox.utils.Extracter.Extracter(u, l, r, up, dn)[source]
proxtoolbox.utils.Extracter.find(Array, ele)[source]

proxtoolbox.utils.FFT module

proxtoolbox.utils.FFT.FFT(f)[source]
proxtoolbox.utils.FFT.fft(a)[source]

Compute the one-dimensional discrete Fourier transform of a the way Matlab does. When a is a vector, the Fourier transform of the vector is returned. When a is a matrix, each column vector of a is transformed individually, and a new matrix containing the transformed column vectors of a is returned.

Parameters:
a : array_like

1-D or 2-D input array (can be complex)

Returns
——-
result : ndarray

1-D or 2-D array of similar shape and type containing the discrete fourier transform of a

See also

ifft

Notes

Using the Numpy function fft on a matrix does not produce results similar to what Matlab does. This helper function uses the Numpy functions to produce a resut that agrees with what Matlab does.

proxtoolbox.utils.FFT.ifft(a)[source]

Compute the one-dimensional inverse discrete Fourier transform the way Matlab does. When a is a vector, the inverse Fourier transform of the vector is returned. When a is a matrix, each column vector of a is transformed individually, and a new matrix containing the transformed column vectors of a is returned.

Parameters:
a : array_like

1-D or 2-D input array (can be complex)

Returns:
out : ndarray

1-D or 2-D array of similar shape and type containing the inverse discrete fourier transform of a

See also

fft

Notes

Using the Numpy function ifft on a matrix does not produce results similar to what Matlab does. This helper function uses the Numpy functions to produce a resut that agrees with what Matlab does.

proxtoolbox.utils.FFT.transformVectors(a, transform)[source]

Transform a according to the given transform function. When a is a vector, it applies the transform function to a and returns the result. When a is a matrix, each column vector of a is transformed individually using the given transform function, and a new matrix containing the transformed column vectors of a is returned.

Parameters:
a : array_like

1-D or 2-D input array

transform : callable function

This function takes a 1-D array as argument and returns a 1-D array of same size. This function is applied to a if it is a vector or to the column vectors of a if a is a matrix.

Returns
——-
out : ndarray

1-D or 2-D array of similar shape and type containing the transformed data

See Also
——–
fft, ifft

Notes

This function is used by fft(a) and ifft(a).

proxtoolbox.utils.FFT.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.Flip module

Flip.py

written on 10. May 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

DESCRIPTION: Flips a 2x2 image INPUT: A, an image to be flipped OUTPUT: B, the flipped image USAGE: B=Flip(A)

NONSTANDARD FUNCTION CALLS: Reorder.py

!!!!!!!!!!! Not sure if it does the job correctly !!!!!!!!!!

proxtoolbox.utils.Flip.Flip(A)[source]

proxtoolbox.utils.IFFT module

proxtoolbox.utils.IFFT.IFFT(F)[source]
proxtoolbox.utils.IFFT.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.IFresnel2 module

proxtoolbox.utils.IFresnel2.IFresnel2(A)[source]
written on 3. May 2019 by
Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: < Description > Input: A, n x m numpy array

Output: E_out, nxm numpy array Usage: E_out = IFresnel2(A)

proxtoolbox.utils.Laplace_matrix module

proxtoolbox.utils.Laplace_matrix.Laplace_matrix(n)[source]

Discrete Laplace operator with Neumann boundary conditions

This method calculates the Laplacian for a 2-dim. signal (usually an image) of size n x n. The resulting matrix has size (n*n)x(n*n).

Parameters:
n : int - Dimension of input signal of size n x n
Returns:
L : sparse array - Discrete Laplace operator of size (n*n)x(n*n)

proxtoolbox.utils.Laplacian module

< Prog Name >
written on Sep 12. by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: Discrete Laplacian Input: f: is the discretized function

l: is the interval length

Output: the value of the discrete Laplacian excluding the boundary Usage: Lf = Laplacian(f, l)

proxtoolbox.utils.Laplacian.Laplacian(f, l)[source]

proxtoolbox.utils.Mgen module

Mgen.py written on 10. May 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Usage: A = Mgen(k,n,s,c) Inputs: rows, k; columns, n; scaling, s; center, c; seed, seed. Output: Random matrix with elements uniformly distributed on [c-s, c+s].
proxtoolbox.utils.Mgen.Mgen(k, n, s, c, seed)[source]
proxtoolbox.utils.Mgen.ran_seed(seed=None)

Seed the generator.

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

Parameters:
seed : int or 1-d array_like, optional

Seed for RandomState. Must be convertible to 32 bit unsigned integers.

See also

RandomState

proxtoolbox.utils.Mgen.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.MgenN module

MgenN.py
written on 9. Sep 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: < Description > Input: rows, k; columns, n; variance, v; mean, m; seed. seed.

Output: Random matrix with normally distributed (mean m, variance v) iid elements. Usage: rand_output = MgenN(k, n, v, m, seed)

proxtoolbox.utils.MgenN.MgenN(k, n, v, m, seed)[source]
proxtoolbox.utils.MgenN.ran_seed(seed=None)

Seed the generator.

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

Parameters:
seed : int or 1-d array_like, optional

Seed for RandomState. Must be convertible to 32 bit unsigned integers.

See also

RandomState

proxtoolbox.utils.MgenN.randn(d0, d1, ..., dn)

Return a sample (or samples) from the “standard normal” distribution.

If positive, int_like or int-convertible arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the \(d_i\) are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.

This is a convenience function. If you want an interface that takes a tuple as the first argument, use numpy.random.standard_normal instead.

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.

Returns:
Z : ndarray or float

A (d0, d1, ..., dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.

See also

standard_normal
Similar, but takes a tuple as its argument.

Notes

For random samples from \(N(\mu, \sigma^2)\), use:

sigma * np.random.randn(...) + mu

Examples

>>> np.random.randn()
2.1923875335537315 #random

Two-by-four array of samples from N(3, 6.25):

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random

proxtoolbox.utils.OnesPad2 module

OnesPad.py
written on September 2. 1019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen
Description: Function for padding an array with ones.
Automatically resizes the array to the next largest diad by adding zeros symmetrically to the array and again symmetrically doubles the size of the array. Takes one or two dimensional arrays.

Input: m = numpy data array

Output: padded_m = the ones padded numpy array Usage: padded_m = OnesPad(m)

proxtoolbox.utils.OnesPad2.OnesPad(arr)[source]

proxtoolbox.utils.PoissonRan module

proxtoolbox.utils.PoissonRan.PoissonRan(xm)[source]

Poisson random number generation with mean of xm

See numerical recipe C++ version ref: y(i+1) = xm^i*exp(-xm)/factorial(i); see Leo Breiman Probability

Parameters:
xm : real number

Mean

Returns:
em : real number

Sample from the parameterized Poisson distribution

Notes

This code suffers from numerical precision issues. With big values for xm (for example, xm = 6.910459246361838e+27, as was initially the case with the JWST experiment) the difference with Matlab is substential. In Python, one exponential evalutation gives +inf while it gives zero in Maltab.

proxtoolbox.utils.PoissonRan.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.Procrustes module

proxtoolbox.utils.Procrustes.procrustes(X, Y, scaling=True, reflection='best')[source]

A port of MATLAB’s procrustes function to Numpy.

Procrustes analysis determines a linear transformation (translation, reflection, orthogonal rotation and scaling) of the points in Y to best conform them to the points in matrix X, using the sum of squared errors as the goodness of fit criterion.

d, Z, [tform] = procrustes(X, Y)
Parameters:
X, Y

matrices of target and input coordinates. they must have equal numbers of points (rows), but Y may have fewer dimensions (columns) than X.

scaling

if False, the scaling component of the transformation is forced to 1

reflection

if ‘best’ (default), the transformation solution may or may not include a reflection component, depending on which fits the data best. setting reflection to True or False forces a solution with reflection or no reflection respectively.

Returns:
d

the residual sum of squared errors, normalized according to a measure of the scale of X, ((X - X.mean(0))**2).sum()

Z

the matrix of transformed Y-values

tform

a dict specifying the rotation, translation and scaling that maps X –> Y

proxtoolbox.utils.RANDsrc module

RANDsrc.py
written on September 2. 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: < Description > Input: m,n: shape of return numpy array

alphabet: array of two values state: propability for values in alphabet

Output: random numpy array of shape m,n Usage: randMatrix = RANDsrc(m ,n ,alphabet=[1,-1], state=[0.5, 0.5] )

!!!!!!!!!!!!!!!!!!! has no error handling !!!!!!!!!!!!!!!

proxtoolbox.utils.RANDsrc.RANDsrc(m, n, alphabet=[1, -1], state=[0.5, 0.5])[source]
proxtoolbox.utils.RANDsrc.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.Rbin module

Rbin.py
written on Sep 2. 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: .npz-file or .npz for reading binary files into python. Input: ‘filename’ must specify the entire directory path

‘Type’ is either “npy” or “npz”

Output: reads data from ‘filename’ Usage: data=Rbin(‘filename’,’Type’)

proxtoolbox.utils.Rbin.Rbin(file, Type)[source]

proxtoolbox.utils.Reorder module

Reorder.py written on 10. May 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

DESCRIPTION: Reorders a 2x2 image INPUT: A, an image to be reordered OUTPUT: B, the reordered image USAGE: B=Reorder(A)
proxtoolbox.utils.Reorder.Reorder(B)[source]

proxtoolbox.utils.Resize module

proxtoolbox.utils.Resize.Resize(A, Mnew, Nnew)[source]
proxtoolbox.utils.Resize.rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Parameters:
d0, d1, …, dn : int, optional

The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:
out : ndarray, shape (d0, d1, ..., dn)

Random values.

See also

random

Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

Examples

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

proxtoolbox.utils.Unwrapper module

Unwrapper.py
written on Sep 9 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: < Description > Input: Xi_A : numpy array

theta: skalar variable (float or int)

Output: numpy array Usage: res = Unwrapper(Xi_A, theta)

proxtoolbox.utils.Unwrapper.Unwrapper(Xi_A, theta)[source]
proxtoolbox.utils.Unwrapper.find(Array, ele=0, operator='==')[source]
proxtoolbox.utils.Unwrapper.length(arr)[source]

proxtoolbox.utils.Wbin module

Wbin.py
written on 7 Sep by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen
Description: Saves data in .npz and nd creates a companion .info file
with information about the size and class of the data
Input: data: array of numpy matrices OR a dictionary {“name of array”: numpy_array, “second_array”: sec_array, …….}
filename: path to file in which the data should be saved info: ????????????????????????????????

Output: filename.npz : a zip file containing the data Usage: Wbin(data, filename, info)

proxtoolbox.utils.Wbin.Wbin(data, filename, info)[source]

proxtoolbox.utils.ZeroPad module

proxtoolbox.utils.ZeroPad.ZeroPad(m)[source]

proxtoolbox.utils.cell module

class proxtoolbox.utils.cell.Cell[source]

Bases: numpy.ndarray

Array containing any kind of object (inherits from ndarray). The data type is defined as numpy.object. This is similar to cells in Matlab.

proxtoolbox.utils.cell.isCell(u)[source]

Test if object u is an instance of Cell class.

Parameters:
u : any object
Returns:
bool

True if ‘u’ is an instance of Cell class, False otherwise.

proxtoolbox.utils.dftregistration module

dftregistration
written on Sep 4. 2019 by Constantin Höing Inst. Fuer Numerische und Angewandte Mathematik Universität Göttingen

Description: COPIED FROM MATLAB

% function [output Greg] = dftregistration(buf1ft,buf2ft,usfac); % Efficient subpixel image registration by crosscorrelation. This code % gives the same precision as the FFT upsampled cross correlation in a % small fraction of the computation time and with reduced memory % requirements. It obtains an initial estimate of the crosscorrelation peak % by an FFT and then refines the shift estimation by upsampling the DFT % only in a small neighborhood of that estimate by means of a % matrix-multiply DFT. With this procedure all the image points are used to % compute the upsampled crosscorrelation. % Manuel Guizar - Dec 13, 2007

% Portions of this code were taken from code written by Ann M. Kowalczyk % and James R. Fienup. % J.R. Fienup and A.M. Kowalczyk, “Phase retrieval for a complex-valued % object by using a low-resolution image,” J. Opt. Soc. Am. A 7, 450-458 % (1990).

% Citation for this algorithm: % Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, % “Efficient subpixel image registration algorithms,” Opt. Lett. 33, % 156-158 (2008).

Input: buf1ft Fourier transform of reference image,
DC in (1,1) [DO NOT FFTSHIFT]
buf2ft Fourier transform of image to register,
DC in (1,1) [DO NOT FFTSHIFT]
usfac Upsampling factor (integer). Images will be registered to
within 1/usfac of a pixel. For example usfac = 20 means the images will be registered within 1/20 of a pixel. (default = 1)
Output: output = [error,diffphase,net_row_shift,net_col_shift]

error Translation invariant normalized RMS error between f and g diffphase Global phase difference between the two images (should be

zero if images are non-negative).

net_row_shift net_col_shift Pixel shifts between images Greg (Optional) Fourier transform of registered version of buf2ft,

the global phase difference is compensated for.

Usage: [output, Greg] = dftregistration(buf1ft,buf2ft,usfac=1)

proxtoolbox.utils.dftregistration.dftregistration(buf1ft, buf2ft, usfac=1)[source]
proxtoolbox.utils.dftregistration.dftups(In, nor=None, noc=None, usfac=1, roff=0, coff=0)[source]

COPIED FROM MATLAB

% function out=dftups(in,nor,noc,usfac,roff,coff);

% Upsampled DFT by matrix multiplies, can compute an upsampled DFT in just % a small region. % usfac Upsampling factor (default usfac = 1) % [nor,noc] Number of pixels in the output upsampled DFT, in % units of upsampled pixels (default = size(in)) % roff, coff Row and column offsets, allow to shift the output array to % a region of interest on the DFT (default = 0) % Recieves DC in upper left corner, image center must be in (1,1) % Manuel Guizar - Dec 13, 2007 % Modified from dftus, by J.R. Fienup 7/31/06

% This code is intended to provide the same result as if the following % operations were performed % - Embed the array “in” in an array that is usfac times larger in each % dimension. ifftshift to bring the center of the image to (1,1). % - Take the FFT of the larger array % - Extract an [nor, noc] region of the result. Starting with the % [roff+1 coff+1] element.

% It achieves this result by computing the DFT in the output array without % the need to zeropad. Much faster and memory efficient than the % zero-padded FFT approach if [nor noc] are much smaller than [nr*usfac nc*usfac]

proxtoolbox.utils.dftregistration.nargout()[source]

proxtoolbox.utils.gaussian module

proxtoolbox.utils.gaussian.gaussian(points, var, center_index)[source]

proxtoolbox.utils.loadMatFile module

proxtoolbox.utils.mypoissonrnd module

proxtoolbox.utils.mypoissonrnd.mypoissonrnd(lambd)[source]

proxtoolbox.utils.size module

proxtoolbox.utils.size.size_matlab(u)[source]

This utility function mimics what the Matlab function size does. Works with multidimensional arrays and returns the length of the data corresponding to the first 4 dimensions. It returns 1 when the dimension does not exist. Although this does not make a lot of sense in Python, this is done here to insure compatibility with Matlab and previous Python code.

Parameters:
u : array_like
Returns:
n, m, p, q: tuple of integers

Size of each of the first 4 dimensions of ‘u’. Returns 1 when dimension does not exist (for compatibility with Matlab)