peri.util

peri.util.Tile

class peri.util.Tile(left, right=None, mins=None, maxs=None, size=None, centered=False, dim=None, dtype=’int’)

Creates a tile element which represents a hyperrectangle in D dimensions. These hyperrectangles may be operated upon to find intersections, bounding tiles, calculate interior coordinates and other common operations.

Parameters:
  • left (number or array-like) – Left side of the tile
  • right ((optional) number or array-like) – If provided along with left, gives the right side of the tile
  • mins ((optional) number or array-like) – Can be provided to clip the sides of the Tile to certain minimum
  • maxs ((optional) number or array-like) – Can be provided to clip the sides of the Tile to certain maximum
  • size ((optional) number or array-like) – If provided along with left gives the size of the tile
  • centered (boolean) –
    • If true: [left] - [size]/2 -> [left] + [size]/2
    • If false: [left] -> [left] + [size]
  • dim (integer) – Number of dimensions for the Tile
  • dtype (string, np.dtype) – Resulting type of number for the Tile coordinates

Notes

These parameters can be combined into many different combinations (where [] indicates an array created from either a single number or any iterable):

  • left : [0,0,0] -> [left]
  • left, right : [left] -> [right]
  • left, size (not centered) : [left] -> [left] + [size]
  • left, size (yes centered) : [left] - [size]/2 -> [left] + [size]/2

Each of these can be limited by using (mins, maxs) which are applied after calculating left, right for each element:

  • left = max(left, [mins])
  • right = min(right, [maxs])

Since tiles are used for array slicing, they only allow integer values, which can truncated without warning from float.

Notes on dimension. The dimensionality is determined first by the shape of left, right, size if provided not as an integer. If it not provided there then it is assumed to be 3D. This can be overridden by setting dim in the arguments. For example:

  • Tile(3) : [0,0,0] -> [3,3,3]
  • Tile(3, dim=2) : [0,0] -> [3,3]
  • Tile([3]) : [0] -> [3]

Examples

>>> Tile(10)
Tile [0, 0, 0] -> [10, 10, 10] ([10, 10, 10])
>>> Tile([1,2])
Tile [0, 0] -> [1, 2] ([1, 2])
>>> Tile(0, size=4, centered=True)
Tile [-2, -2, -2] -> [2, 2, 2] ([4, 4, 4])
>>> Tile([-1, 0, 1], right=10, mins=0)
Tile [0, 0, 1] -> [10, 10, 10] ([10, 10, 9])
>>> Tile(10, dtype='float')
Tile [0.0, 0.0, 0.0] -> [10.0, 10.0, 10.0] ([10.0, 10.0, 10.0])
static boundingtile(tiles, *args)

Convex bounding box of a group of tiles

>>> Tile.boundingtile(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))
Tile [0, 0] -> [5, 5] ([5, 5])
center

Return the center of the tile

>>> Tile(5).center
array([ 2.5,  2.5,  2.5])
contains(items, pad=0)

Test whether coordinates are contained within this tile.

Parameters:
  • items (ndarray [3] or [N, 3]) – N coordinates to check are within the bounds of the tile
  • pad (integer or ndarray [3]) – anisotropic padding to apply in the contain test

Examples

>>> Tile(5, dim=2).contains([[-1, 0], [2, 3], [2, 6]])
array([False,  True, False], dtype=bool)
coords(norm=False, form=’broadcast’)

Returns the coordinate vectors associated with the tile.

Parameters:
  • norm (boolean) – can rescale the coordinates for you. False is no rescaling, True is rescaling so that all coordinates are from 0 -> 1. If a scalar, the same norm is applied uniformally while if an iterable, each scale is applied to each dimension.
  • form (string) –
    In what form to return the vector array. Can be one of:
    ’broadcast’ – return 1D arrays that are broadcasted to be 3D
    ’flat’ – return array without broadcasting so each component
    is 1D and the appropriate length as the tile
    ’meshed’ – arrays are explicitly broadcasted and so all have
    a 3D shape, each the size of the tile.
    ’vector’ – array is meshed and combined into one array with
    the vector components along last dimension [Nz, Ny, Nx, 3]

Examples

>>> Tile(3, dim=2).coords(form='meshed')[0]
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]])
>>> Tile(3, dim=2).coords(form='meshed')[1]
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]])
>>> Tile([4,5]).coords(form='vector').shape
(4, 5, 2)
>>> [i.shape for i in Tile((4,5), dim=2).coords(form='broadcast')]
[(4, 1), (1, 5)]
corners

Iterate the vector of all corners of the hyperrectangles

>>> Tile(3, dim=2).corners
array([[0, 0],
       [0, 3],
       [3, 0],
       [3, 3]])
static intersection(tiles, *args)

Intersection of tiles, returned as a tile

>>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))
Tile [1, 1] -> [4, 4] ([3, 3])
kcenter

Return the frequency center of the tile (says fftshift)

kvectors(norm=False, form=’broadcast’, real=False, shift=False)

Return the kvectors associated with this tile, given the standard form of -0.5 to 0.5. norm and form arguments arethe same as that passed to Tile.coords.

Parameters:real (boolean) – whether to return kvectors associated with the real fft instead
oslicer(tile)

Opposite slicer, the outer part wrt to a field

overhang(tile)

Get the left and right absolute overflow – the amount of box overhanging tile, can be viewed as self tile (set theory relative complement, but in a bounding sense)

pad(pad)

Pad this tile by an equal amount on each side as specified by pad

>>> Tile(10).pad(2)
Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])
>>> Tile(10).pad([1,2,3])
Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
reflect_overhang(clip)

Compute the overhang and reflect it internally so respect periodic padding rules (see states._tile_from_particle_change). Returns both the inner tile and the inner tile with necessary pad.

slicer

Array slicer object for this tile

>>> Tile((2,3)).slicer
(slice(0, 2, None), slice(0, 3, None))
>>> np.arange(10)[Tile((4,)).slicer]
array([0, 1, 2, 3])
translate(dr)

Translate a tile by an amount dr

>>> Tile(5).translate(1)
Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])
volume

Volume of the tile

>>> Tile(10).volume
1000
>>> Tile(np.sqrt(2), dim=2, dtype='float').volume 
2.0000000000...

peri.util.Image

class peri.util.Image(image, tile=None, filters=None)

Create an image object from a raw np.ndarray.

Parameters:
  • image (ndarray) – The image in float format with dimensions arranged as [z,y,x]
  • tile (peri.util.Tile) – The region of the image to crop out to use for the actual featuring, etc. Coordinates are in pixel-space.
  • filters (list of tuples) – A list of (slice, value) pairs which are Fourier-space domain filters that are to be applied to an image. In Fourier-space, each filter is a numpy slice object and the Fourier values to be subtracted from those slices.
filtered_image(im)

Returns a filtered image after applying the Fourier-space filters

set_filter(slices, values)

Sets Fourier-space filters for the image. The image is filtered by subtracting values from the image at slices.

Parameters:
  • slices (List of indices or slice objects.) – The q-values in Fourier space to filter.
  • values (np.ndarray) – The complete array of Fourier space peaks to subtract off. values should be the same size as the FFT of the image; only the portions of values at slices will be removed.

Examples

To remove a two Fourier peaks in the data at q=(10, 10, 10) & (245, 245, 245), where im is the residuals of a model:

  • slices = [(10,10,10), (245, 245, 245)]
  • values = np.fft.fftn(im)
  • im.set_filter(slices, values)
set_tile(tile)

Sets the current tile of the image to a peri.util.Tile

peri.util.RawImage

class peri.util.RawImage(filename, tile=None, invert=False, exposure=None, float_precision=<class ‘numpy.float64’>)

An image object which stores information about desired region, exposure compensation, color inversion, and filters to remove certain fourier peaks.

Parameters:
  • filename (str) – Path of the image file. Recommended that you supply a relative path so that transfer between computers is possible, i.e. if the file is located at /home/user/data/1.tif then work in the directory /home/user/data and supply the filename 1.tif.
  • tile (peri.util.Tile) – the region of the image to crop out to use for the actual featuring, etc
  • invert (boolean) – Whether to invert the image.
  • exposure (tuple of numbers (min, max) | None) – If set, it is the values used to normalize the image. It is the values which map to 0 and 1 in the loaded version of the image, the default being for 8-bit images, mapping raw values (0, 255) to loaded values (0, 1). This functionality is provided since the noise and exposure may change between images where a common scaling is desired for proper comparison. Setting this values allows a series of images to be initialized with the same ILM, PSF etc. Should be the bit value of the camera.
  • float_precision (numpy float datatype) – One of numpy.float16, numpy.float32, numpy.float64; precision for precomputed arrays. Default is np.float64; make it 16 or 32 to save memory.
get_scale()

If exposure was not set in the __init__, get the exposure associated with this RawImage so that it may be used in other RawImage. This is useful for transferring exposure parameters to a series of images.

Returns:exposure – The (emin, emax) which get mapped to (0, 1)
Return type:tuple of floats
static get_scale_from_raw(raw, scaled)

When given a raw image and the scaled version of the same image, it extracts the exposure parameters associated with those images. This is useful when

Parameters:
  • raw (array_like) – The image loaded fresh from a file
  • scaled (array_like) – Image scaled using peri.initializers.normalize()
Returns:

exposure – Returns the exposure parameters (emin, emax) which get mapped to (0, 1) in the scaled image. Can be passed to __init__()

Return type:

tuple of numbers

load_image()

Read the file and perform any transforms to get a loaded image

set_scale(exposure)

Set the exposure parameter for this image, which determines the values which get mapped to (0,1) in the output image.

class peri.util.NullImage(image=None, shape=None)

An image object that doesn’t actual store any information so that small save states can be created for pure model states

Parameters:shape (tuple) – Size of the image which will be mocked

peri.util.{*}

class peri.util.ProgressBar(num, label=’Progress’, value=0, screen=79, time_remaining=True, bar=True, bar_symbol=’=’, bar_caps=’[]’, bar_decimals=2, display=True)

ProgressBar class which creates a dynamic ASCII progress bar of two different varieties:

  1. A bar chart that looks like the following:
    Progress [================      ]  63.00%
  2. A simple number completed look:
    Progress :   17 / 289
Parameters:
  • num (integer) – The number of tasks that need to be completed
  • label (string [default: 'Progress']) – The label for this particular progress indicator,
  • value (integer [default: 0]) – Starting value
  • screen (integer [default: 79]) – Size the screen to use for the progress bar
  • time_remaining (boolean [default: True]) – Display estimated time remaining
  • bar (boolean [default: True]) – Whether or not to display the bar chart
  • bar_symbol (char [default: '=']) – The character to use to fill in the bar chart
  • bar_caps (string [default: '[]']) – Characters to use as the end caps of the. The string will be split in half and each half put on a side of the chart
  • bar_decimals (integer [default: 2]) – Number of decimal places to include in the percentage
  • display (boolean [default: True]) – a crutch so that we don’t have a lot of ``if“s later. display or don’t display the progress bar
peri.util.oddify(num)

Return the next odd number if num is even.

Examples

>>> oddify(1)
1
>>> oddify(4)
5
peri.util.listify(a)

Convert a scalar a to a list and all iterables to list as well.

Examples

>>> listify(0)
[0]
>>> listify([1,2,3])
[1, 2, 3]
>>> listify('a')
['a']
>>> listify(np.array([1,2,3]))
[1, 2, 3]
>>> listify('string')
['string']
peri.util.delistify(a, b=None)

If a single element list, extract the element as an object, otherwise leave as it is.

Examples

>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delistify(np.array([1.0]))
1.0
>>> delistify([1, 2, 3])
[1, 2, 3]
peri.util.aN(a, dim=3, dtype=’int’)

Convert an integer or iterable list to numpy array of length dim. This func is used to allow other methods to take both scalars non-numpy arrays with flexibility.

Parameters:
  • a (number, iterable, array-like) – The object to convert to numpy array
  • dim (integer) – The length of the resulting array
  • dtype (string or np.dtype) – Type which the resulting array should be, e.g. ‘float’, np.int8
Returns:

arr – Resulting numpy array of length dim and type dtype

Return type:

numpy array

Examples

>>> aN(1, dim=2, dtype='float')
array([ 1.,  1.])
>>> aN(1, dtype='int')
array([1, 1, 1])
>>> aN(np.array([1,2,3]), dtype='float')
array([ 1.,  2.,  3.])
peri.util.patch_docs(subclass, superclass)

Apply the documentation from superclass to subclass by filling in all overridden member function docstrings with those from the parent class

peri.util.indir(path)

Context manager for switching the current path of the process. Can be used:

with indir(‘/tmp’):
<do something in tmp>