pysofi package

Submodules

pysofi.pysofi module

class pysofi.pysofi.PysofiData(filepath, filename)

Bases: object

Data object contains the information of a dataset (e.g. dimensions, frame numbers), and provides SOFI methods to perform analysis and visualization on the dataset (moments reconstruction, cumulants reconstruction, shrinking kernel deconvolution, etc…).

When loading a tiff file, a PysofiData() object is created and further SOFI analysis can be preformed. All the standard data-attributes are listed below. New data-attributes can be added or updated using ‘.add()’ function.

Parameters
  • filapath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

filename
Type

str

filepath
Type

str

ave

The average image of the image stack / tiff video.

Type

ndarray

finterp_factor

The interpolation factor for Fourier interpolation.

Type

int

morder_lst

All orders of moments-reconstructions that have been calculated.

Type

list

morder_finterp_lst

All orders of moments-reconstructions after Fourier interpolation that have been calculated.

Type

list

moments_set

moment order (int) -> moment-reconstructed image (ndarray) A dictionary of orders and corrensponding moment reconstructions.

Type

dict

moments_set_bc

moment order (int) -> moment-reconstructed image (ndarray) A dictionary of orders and corrensponding moment reconstructions with bleaching correction.

Type

dict

cumulants_set

cumulant order (int) -> cumulant-reconstructed image (ndarray) A dictionary of orders and corrensponding cumulant reconstructions.

Type

dict

cumulants_set_bc

cumulant order (int) -> cumulant-reconstructed image (ndarray) A dictionary of orders and corrensponding cumulant reconstructions with bleaching correction.

Type

dict

morder

The highest order of moment reconstruction that has been calculated.

Type

int

corder

The highest order of cumulant reconstruction that has been calculated.

Type

int

fbc

Bleaching correction factor.

Type

float

n_frames

The number of frames of the image stack / tiff video.

Type

int

xdim

The number of pixels in x dimension.

Type

int

ydim

The number of pixels in y dimension.

Type

int

Notes

For SOFI processing, after loading the tiff video into the Data object, a pipeline of 1) fourier interpolation, 2) moments reconstrtuction or cumulants reconstruction, 3) noise filtering 1, 4) shrinking kernel de- convolution, 5) noise filtering 2, and 6) ldrc. The processed video will be saved into a new tiff file with the colormap user selects.

References

1

Xiyu Yi, Sungho Son, Ryoko Ando, Atsushi Miyawaki, and Shimon Weiss,

“Moments reconstruction and local dynamic range compression of high order superresolution optical fluctuation imaging,” Biomed. Opt. Express 10, 2430-2445 (2019).

add(**kwargs)

Add or update elements (attributes and/or dict entries).

add_filtered(image, filter_name='noise filter')

Add (noise) filtered image as an attribute of the object.

average_image(frames=[])

Calculate average image of the tiff video.

average_image_with_finterp(interp_num)
bleach_correct(fbc=0.04, smooth_kernel=251, save_option=True, return_option=False)

Performs bleaching correction on a tiff image (stack) with a bleaching correction factor.

Parameters
  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease. Only used when bleach correction is True.

  • smooth_kernel (int) – The size of the median filter window.

  • save_option (bool) – Whether to save the corrected images into tiff files.

  • return_option (bool) – Whether to return the corrected image series as a 3d array.

Returns

bc_im – All bleaching-corrected imagee in a 3d array.

Return type

ndarray

calc_moments_set(highest_order=4, frames=[], mean_im=None, bleach_correction=False, smooth_kernel=251, fbc=0.04)

Calculate moment-reconstructed images to the highest order.

Parameters
  • highest_order (int) – The highest order number of moment-reconstructed images.

  • frames (list of int) – The start and end frame number.

  • mean_im (ndarray) – Average image of the tiff stack.

  • bleach_correction (bool) – Whether to use bleaching correction.

  • smooth_kernel (int, optional) – The size of the median filter window. Only used when bleach correction is True.

  • fbc (float, optional) – The fraction of signal decrease within each block compared to the total signal decrease. Only used when bleach correction is True.

Returns

moments_set, moments_set_bc – order number (int) -> image (ndarray) A dictionary of calcualted moment-reconstructed images.

Return type

dict

cumulants_images(highest_order=4, frames=[], m_set=None, bleach_correction=False, smooth_kernel=251, fbc=0.04)

Calculate cumulant-reconstructed images to the highest order.

Parameters
  • highest_order (int) – The highest order number of cumulant-reconstructed images.

  • frames (list of int) – The start and end frame number.

  • m_set (dict) – order number (int) -> image (ndarray) A dictionary of calcualted moment-reconstructed images.

  • bleach_correction (bool) – Whether to use bleaching correction.

  • smooth_kernel (int, optional) – The size of the median filter window. Only used when bleach correction is True.

  • fbc (float, optional) – The fraction of signal decrease within each block compared to the total signal decrease. Only used when bleach correction is True.

Returns

cumulants_set, cumulants_set_bc – order number (int) -> image (ndarray) A dictionary of calcualted cumulant-reconstructed images.

Return type

dict

deconvsk(est_psf=array([[0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0], ..., [0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0]]), input_im=None, deconv_lambda=1.5, deconv_iter=20)

Perform serial Richardson-Lucy deconvolution with a series of PSFs on the input image. For details of shrinking kernel deconvolution, refer to deconvsk.py and [1].

Parameters
  • est_psf (ndarray) – Estimated PSF.

  • input_im (ndarray) – Input image that need deconvolution.

  • deconv_lambda (float) – Lambda for the exponent between. It is an empirical parameter within the range of (1,2).

  • deconv_iter (int) – Number of iterations for each deconvolution.

Returns

deconv – Deconvoluted image.

Return type

ndarray

finterp_image(input_im=None, interp_num_lst=[2, 4])

Performs fourier interpolation on an image array.

finterp_tiffstack(interp_num_lst=[2, 4], frames=[], save_option=True, return_option=False)

Performs fourier interpolation on a tiff image (stack) with a list of interpolation factors (the number of pixels to be interpolated between two adjacent pixels).

Parameters
  • interp_num_lst (list (int)) – A list of interpolation factors.

  • frames (list of int) – The start and end frame number.

  • save_option (bool) – Whether to save the interpolated images into tiff files (each interpolation factor seperately).

  • return_option (bool) – Whether to return the interpolated image series as 3d arrays.

Returns

finterps – A list of interpolated image sereis corresponding to the interpolation factor list.

Return type

list (ndarray)

get_dims()

Get dimensions and frame number of the tiff video.

get_frame(frame_num=0)

Get one frame of the tiff video.

Parameters

frame_num (int) – The frame number (e.g. 0 for the first frame).

Returns

frame_im – Frame array.

Return type

ndarray

ldrc(order=6, window_size=[25, 25], mask_im=None, input_im=None)

Compress the dynamic range of moments-/cumulants reconstruced image with ldrc method. For details of ldrc, refer to ldrc.py and [1].

Parameters
  • order (int) – The order of the reconstructed image.

  • window_size ([int, int]) – The [x, y] dimension of the scanning window.

  • mask_im (ndarray) – A reference image. Usually a average/sum image or second-order SOFI image is used.

  • input_im (ndarray) – An input image, usually a high-order moment- or cumulant- reconstructed image.

Returns

ldrc_image – The compressed image with the same dimensions of input_im.

Return type

ndarray

moment_image(order=6, mean_im=None, mvlength=[], finterp=False, interp_num=1)

Calculate the moment-reconstructed image of a defined order.

Parameters
  • order (int) – The order number of the moment-reconstructed image.

  • mean_im (ndarray) – Average image of the tiff stack.

  • mvlength (int) – Length of the video to calculate moments-reconstruction.

  • finterp (bool) – Whether to first conduct Fourier interpolation then calculate moments-reconstructions.

  • interp_num (int) – The interpolation factor.

Returns

moment_im – The calculated moment-reconstructed image.

Return type

ndarray

pysofi.deconvsk module

pysofi.deconvsk.corelucy(image, h)

Make core for the LR estimation. Calculates f to produce the next iteration array that maximizes the likelihood that the entire suite satisfies the Poisson statistics. This is a simplified version of MATLAB corelucy function without damping, weights and externally defined functions.

Parameters
  • image (ndarray) – Input image.

  • h (ndarray) – Zero-padded OTF. h should have the same dimensions as image.

Returns

f – LR extimation core.

Return type

ndarray

References

1

Acceleration of iterative image restoration algorithms, by D.S.C. Biggs

and M. Andrews, Applied Optics, Vol. 36, No. 8, 1997. .. [2] Deconvolutions of Hubble Space Telescope Images and Spectra, R.J. Hanisch, R.L. White, and R.L. Gilliland. in “Deconvolution of Images and Spectra”, Ed. P.A. Jansson, 2nd ed., Academic Press, CA, 1997.

pysofi.deconvsk.deconvsk(est_psf, input_im, deconv_lambda, deconv_iter)

Perform serial Richardson-Lucy deconvolution with shrinking PSFs. U = (U**(l/(l-1))) * (U**(l**2/(l-1))) * … * (U**(l**n/(l-1))). The PSF of the imaging system U can be decomposed into a series a smaller (shrinking) PSF U**r where r > 1, and the image can be deconvolved by these PSFs in sequence. In this way, the result is more similar to the input image, so each individual deconvolution step is a lighter deconcolution task.

Parameters
  • est_psf (ndarray) – Estimated PSF.

  • input_im (ndarray) – Input image that need deconvolution.

  • deconv_lambda (float) – Lambda for the exponent between. It is an empirical parameter within the range of (1,2).

  • deconv_iter (int) – Number of iterations for each deconvolution.

Returns

deconv_im – Deconvoluted image.

Return type

ndarray

Notes

The quality of the deconvolution result is greatly dependent on the initial PSF size instead of the value. We recommend to calibrate PSF of the imaging system and use that as the initial PSF guess. Otherwise, generating a PSF according to the magnification of the imaging system is an option. For more details on the shrinking kernel deconvolution method, please refer to [1].

References

1

Xiyu Yi, Sungho Son, Ryoko Ando, Atsushi Miyawaki, and Shimon Weiss,

“Moments reconstruction and local dynamic range compression of high order superresolution optical fluctuation imaging,” Biomed. Opt. Express 10, 2430-2445 (2019).

pysofi.deconvsk.otf2psf(otf, shape)

Convert optical transfer function (OTF) to point-spread function (PSF). Compute the Inverse Fast Fourier Transform (ifft) of the OTF array and creates the PSF array that is not influenced by the OTF off-centering. By default, the PSF array is the same size as the OTF array. Adapted from MATLAB otf2psf function.

Parameters
  • otf (ndarray) – OTF array.

  • shape (list (int)) – Output shape of the OTF array.

Returns

psf – PSF array.

Return type

ndarray

pysofi.deconvsk.psf2otf(psf, shape)

From https: // github.com/aboucaud/pypher/blob/master/pypher/pypher.py. Convert point-spread function to optical transfer function. Compute the Fast Fourier Transform(FFT) of the point-spread function(PSF) array and creates the optical transfer function(OTF) array that is not influenced by the PSF off-centering. By default, the OTF array is the same size as the PSF array. To ensure that the OTF is not altered due to PSF off-centering, PSF2OTF post-pads the PSF array(down or to the right) with zeros to match dimensions specified in OUTSIZE, then circularly shifts the values of the PSF array up ( or to the left) until the central pixel reaches (1, 1) position. Adapted from MATLAB psf2otf function.

Parameters
  • psf (ndarray) – PSF array.

  • shape (list(int)) – Output shape of the OTF array.

Returns

otf – OTF array.

Return type

ndarray

pysofi.deconvsk.richardson_lucy(image, psf, iterations=10, **kwargs)

Richardson-Lucy deconvolution. It deconvolves image using maximum likelihood algorithm, returning both deblurred image J and a restored point-spread function PSF. This is a simplified version of MATLAB deconvblind function without damping, weights and externally defined functions.

Parameters
  • image (ndarray) – Input degraded image.

  • psf (ndarray) – The point spread function.

  • iterations (int) – Number of iterations.

Returns

  • P (ndarray) – Restored point-spread function PSF.

  • J (ndarray) – Deblurred image.

Examples

>>> import numpy as np
>>> from scipy.ndimage.gaussian_filter
>>> image = np.zeros((8,8),dtype=int)
>>> image[1::2,::2] = 1
>>> image[::2,1::2] = 1
>>> psf = np.zeros((7, 7))
>>> psf[3, 3] = 1
>>> psf = gaussian_filter(psf, sigma=[7,7])
>>> new_psf, deconv_im = richardson_lucy(image, psf, 15)

Notes

The quality of the deconvolution result is greatly dependent on the initial PSF size instead of the value. We recommend to calibrate PSF of the imaging system and use that as the initial PSF guess. Otherwise, generating a PSF according to the magnification of the imaging system is an option.

References

1

http: // en.wikipedia.org/wiki/Richardson % E2 % 80 % 93Lucy_deconvolution

2

Biggs, D. S. C.; Andrews, M. Acceleration of Iterative Image

Restoration Algorithms. Applied Optics 1997, 36 (8), 1766.

pysofi.deconvsk.zero_pad(image, shape, position='center')

From https: // github.com/aboucaud/pypher/blob/master/pypher/pypher.py. Extends image to a certain size with zeros.

Parameters
  • image (real 2d ndarray) – Input image.

  • shape (tuple of list(int)) – Desired output shape of the image.

  • position (str, optional) –

    The position of the input image in the output one:
    • ’corner’

      top-left corner(default)

    • ’center’

      centered

Returns

padded_img – The zero-padded image.

Return type

real ndarray

pysofi.filtering module

pysofi.filtering.filter1d_same(time_series, noise_filter)

Filter original time_series with noise_filter, and return the filtered_series with the same length as the original sereis. Compared to MATLAB results, when the length of the filter and frame number are both even, the filtered result would shift to left by one number. In other cases, results are the same.

pysofi.filtering.med_smooth(ori_signal, kernel_size=251)

Perform a one-dimensional median filter with ‘reflect’ padding. For more information, please check scipy.signal.medfilt.

pysofi.filtering.noise_filter1d(dset, im_set, noise_filter=[], filtername='noise filter after M6', filenames=None, return_option=False, return_type='dict')

Perform noise filtering on a image stack along the time axis for each pixel independently.

Parameters
  • dset (dict) – filename (str) -> Data (object). A dictionary mapping tiff stack filenames to Data object.

  • im_set (dict) – filename (str) -> pre-filtering image (ndarray). A dictionary mapping tiff filenames to images need to be filtered.

  • noise_filter (ndarray) – Noise filtering kernel, e.g. 1D-Gaussian.

  • filtername (str) – Name of the filter for Data.add_filtered.

  • filenames (list (str)) – Sequence of filenames for the filtering.

  • return_option (bool) – Whether to return the results after noise filtering or not.

  • return_type (str) – Choose the format of the returned value. Can use either ‘ndarray’ or ‘dict’

Returns

  • m_filtered (ndarray) – Filtered image stack in the format of a numpy.ndarray.

  • m_filtered (dict) – Filtered image stack in the format of a dictionary.

pysofi.finterp module

This module performs fourier interpolation on a single image or a image stack (tiff file). Interpolated image (stack) can be saved into a new tiff file or return as a numpy array.

Fourier interpolation was implemented with transformation matrix operation, where the Fourier transformation matrix was constructed with the original matrix size without interpolation grids, and the inverse Fourier transformation matrix encodes the extra interpolation position coordinates.

Adapted from https://github.com/xiyuyi/xy_fInterp_forTIFF.

pysofi.finterp.fourier_interp_array(im, interp_num_lst)

Performs fourier interpolation on an image array with a list of interpolation factors.

pysofi.finterp.fourier_interp_tiff(filepath, filename, interp_num_lst, frames=[], save_option=True, return_option=False)

Performs fourier interpolation on a tiff image (stack) with a list of interpolation factors (the number of pixels to be interpolated between two adjacent pixels).

Parameters
  • filepath (str) – The path to the tiff file.

  • filename (str) – The filename of the tiff file without ‘.tif’.

  • interp_num_lst (list (int)) – A list of interpolation factors.

  • frames (list of int) – The start and end frame number.

  • save_option (bool) – Whether to save the interpolated images into tiff files (each interpolation factor seperately).

  • return_option (bool) – Whether to return the interpolated image series as 3d arrays.

Returns

interp_imstack_lst – A list of interpolated image series corresponding to the interpolation factor list.

Return type

list (ndarray)

pysofi.finterp.ft_matrix2d(xrange, yrange)

Calculate fourier transform matrix for x- and y-dimension.

pysofi.finterp.ift_matrix2d(xrange, yrange, interp_num)

Calculate inverse fourier transform matrix without center shift for a given fold of interpolation for x- and y-dimension. Here we use 2 times the x-dimension of a frame image for xrange and 2 times of y for yrange. interp_num is the number of times the resolution enhanced. For instance, when interp_num = 2, the resolution is two times the original one.

pysofi.finterp.interpolate_image(im, fx, fy, ifx, ify, interp_num)

Performs fourier interpolation to increase the resolution of the image. The interpolated image can be further processed by SOFI for super-resolution imaging.

Parameters
  • im (ndarray) – Input image.

  • fx (ndarray) – Fourier transform matrix in x generated from ft_matrix2d function.

  • fy (ndarray) – Fourier transform matrix in y generated from ft_matrix2d function.

  • ifx (ndarray) – Inverse fourier transform matrix in x from ift_matrix2d function.

  • ify (ndarray) – Inverse fourier transform matrix in y from ift_matrix2d function.

  • interp_num (int) – The number of pixels to be interpolated between two adjacent pixels.

Returns

interp_im – Interpolated image with new dimensions.

Return type

ndarray

Notes

Please note here that interpolation doesn’ extend over the edgeo f the matrix, therefore the total number of pixels in the resulting matrix is not an integer fold of the original size of the matrix. For example, if the original matrix size of each frame is xdim and ydim for x and y dimensions respectively. After interpolation, the size of the resulting matrix will be ((xdim-1)*f + 1) for x dimension, and ((ydim-1)*f + 1) for y dimension.

Example

import numpy as np
import matplotlib.pyplot as plt
xdim, ydim, sigma, mu = 10, 10, 0.5, 0
x, y = np.meshgrid(np.linspace(-1, 1, xdim), np.linspace(-1, 1, xdim))
im = np.exp(-((np.sqrt(x*x + y*y) - mu)**2 / (2*sigma**2)))
xrange, yrange, interp_num = 2 * xdim, 2 * ydim, 3
fx, fy = ft_matrix2d(xrange, yrange)
ifx, ify = ift_matrix2d(xrange, yrange, interp_num)
interp_im = interpolate_image(im, fx, fy, ifx, ify, interp_num)

pysofi.ldrc module

pysofi.ldrc.ldrc(mask_im, input_im, order=1, window_size=[25, 25])

Process the image array with “local dynamic range compression” (ldrc).

Parameters
  • mask_im (ndarray) – A reference image. Usually a average/sum image or second-order SOFI image is used.

  • input_im (ndarray) – An input image, usually a high-order moment- or cumulant- reconstructed image.

  • order (int) – The order of the reconstructed image.

  • window_size ([int, int]) – The [x, y] dimension of the scanning window.

Returns

ldrc_im – The compressed image with the same dimensions of input_im.

Return type

ndarray

Notes

High-order cumulants or moments reconstructions result-in images with a large dynamic range of pixel intensities. This ldrc algorithm compresses the dynamic range of these reconstructions with respect to a reference image while retaining resolution enhancement. The compression is performed locally in a small window that is scanned across the image. For details of the ldrc method, see [1].

References

1

Xiyu Yi, Sungho Son, Ryoko Ando, Atsushi Miyawaki, and Shimon Weiss,

“Moments reconstruction and local dynamic range compression of high order superresolution optical fluctuation imaging,” Biomed. Opt. Express 10, 2430-2445 (2019).

pysofi.masks module

pysofi.masks.gauss1d_mask(shape=(1, 3), sigma=0.5)

Generate a 1D gaussian mask.

pysofi.masks.gauss2d_mask(shape=(3, 3), sigma=0.5)

Generate a 2D gaussian mask - should give the same result as MATLAB’s fspecial(‘gaussian’,[shape],[sigma]).

pysofi.reconstruction module

pysofi.reconstruction.average_image(filepath, filename, frames=[])

Get the average image for a video file (tiff stack), either for the whole video or for user defined frames.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • frames (list of int, optional) – Start and end frame number if not the whole video is used.

Returns

mean_im – The average image.

Return type

ndarray

pysofi.reconstruction.average_image_with_finterp(filepath, filename, interp_num)

Get the average image with fourier interpolation for a video file.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • interp_num (int) – Interpolation factor.

Returns

  • mean_im (ndarray) – The average image after fourier interpolation. Interpolated

  • images can be further used for SOFI processing.

pysofi.reconstruction.block_ave_cumulants(filepath, filename, highest_order, smooth_kernel=251, fbc=0.04)

Get average cumulant-reconstructed images of all blocks determined by user-defined noise filtering and bleaching correction factor (fbc).

Within each block, the amount of signal decrease is identical. This amount of signal decrease is characterized by the bleaching correction factor, fbc, which is the fractional signal decrease within each block (as compared to the total signal decrease over the whole signal plot).

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • highest_order (int) – The highest order number of moment-reconstructed images.

  • smooth_kernel (int) – The size of the median filter (‘filtering.med_smooth’) window.

  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease.

Returns

ave_k_set – order number (int) -> image (ndarray) A dictionary of avereage cumulant-reconstructed images of all blocks.

Return type

dict

Notes

For more information on noise filtering and bleaching corrextion, please see appendix 3 of [1].

References

1
  1. Yi, and S. Weiss. “Cusp-artifacts in high order superresolution

optical fluctuation imaging.” bioRxiv: 545574 (2019).

pysofi.reconstruction.block_ave_moments(filepath, filename, highest_order, smooth_kernel=251, fbc=0.04)

Get average moment-reconstructed images of all blocks determined by user-defined noise filtering and bleaching correction factor (fbc). Similar to ‘block_ave_cumulants’.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • highest_order (int) – The highest order number of moment-reconstructed images.

  • smooth_kernel (int) – The size of the median filter (‘filtering.med_smooth’) window.

  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease.

Returns

ave_m_set – order number (int) -> image (ndarray) A dictionary of avereage moment-reconstructed images of all blocks.

Return type

dict

pysofi.reconstruction.calc_block_moments(filepath, filename, highest_order, frames=[])

Get moment-reconstructed images for user-defined frames (block) of a video file(tiff stack).

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • highest_order (int) – The highest order number of moment-reconstructed images.

  • frames (list of int) – Start and end frame number.

Returns

m_set – order number (int) -> image (ndarray) A dictionary of calcualted moment-reconstructed images.

Return type

dict

Notes

Similar to ‘calc_moments’. Here we omit previously calculated m_set and mean_im as inputs since a block usually has much fewer number of frames and takes shorter calculation time.

pysofi.reconstruction.calc_cumulants_from_moments(moment_set)

Calculate cumulant images from moment images using the recursive relation.

Parameters

moment_set (dict) – order number (int) -> image (ndarray) A dictionary of calcualted moment- images.

Returns

k_set – order number (int) -> image (ndarray) A dictionary of calcualted cumulant-reconstructed images.

Return type

dict

pysofi.reconstruction.calc_cumulants_from_moments_with_lag(m_set, tauSeries)

Calculate cumulant-reconstructed images from moment-reconstructed images with time lags.

Parameters
  • m_set (dict) – order (int) -> dict (partition (tuple) -> image (ndarray)) A nested dictionary of moment-reconstructions of all partitions that calculated from ‘calc_moments_with_lag’.

  • tauSeries (list of int) – A list of time lags for frames contribute to moment reconstruction. The first element is recommended to be 0, and there should be seven elements in the list. The values should be the same as the input for ‘calc_moments_with_lag’.

Returns

k_set – order number (int) -> image (ndarray) A dictionary of calcualted cumulant-reconstructed images with time lags.

Return type

dict

pysofi.reconstruction.calc_moment_im(filepath, filename, order, frames=[], mean_im=None)

Get one moment-reconstructed image of a defined order for a video file.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • order (int) – The order number of moment-reconstructed image.

  • frames (list of int) – The start and end frame number.

  • mean_im (ndarray) – Average image of the tiff stack.

Returns

moment_im – The moments-reconstructed image.

Return type

ndarray

pysofi.reconstruction.calc_moments(filepath, filename, highest_order, frames=None, m_set=None, mean_im=None)

Get all moment-reconstructed images to the user-defined highest order for a video file(tiff stack).

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • highest_order (int) – The highest order number of moment-reconstructed images.

  • frames (list of int) – The start and end frame number.

  • m_set (dict) – order number (int) -> image (ndarray) A dictionary of previously calcualted moment-reconstructed images.

  • mean_im (ndarray) – Average image of the tiff stack.

Returns

m_set – order number (int) -> image (ndarray) A dictionary of calcualted moment-reconstructed images.

Return type

dict

pysofi.reconstruction.calc_moments_with_lag(filepath, filename, tauSeries, frames=[])

Get moment-reconnstructed images with defined time lags.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • tauSeries (list of int) – A list of time lags for frames contribute to moment reconstruction. The first element is recommended to be 0, and there should seven elements in the list.

  • frames (list of int) – The start and end frame number.

Returns

m_set – order (int) -> dict (partition (tuple) -> image (ndarray)) A nested dictionary of moment-reconstructions of all partitions.

Return type

dict

pysofi.reconstruction.calc_total_signal(filepath, filename)

Calculate the total signal intensity of each frame for the whole video (tiff stack).

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

Returns

total_signal – Signal intensity of each frame ordered by the frame number.

Return type

1darray

pysofi.reconstruction.calc_xc_im(filepath, filename, ri_range, frames=[])

Get cross-cumulant image with different pixel combinations.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • ri_range (int) – Maximium distance (# pixels) between the original the selected pixel.

  • frames (list of int) – The start and end frame number.

Returns

xc – pixel (tuple) -> image (ndarray) A dictionary of reconstructed images with pixel index as keys.

Return type

dict

pysofi.reconstruction.correct_bleaching(filepath, filename, fbc=0.04, smooth_kernel=251, save_option=True, return_option=False)

Performs bleaching correction on a tiff image (stack).

Parameters
  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease. Only used when bleach correction is True.

  • smooth_kernel (int) – The size of the median filter window.

  • save_option (bool) – Whether to save the corrected images into tiff files.

  • return_option (bool) – Whether to return the corrected image series as a 3d array.

Returns

bc_im – All bleaching-corrected imagee in a 3d array.

Return type

ndarray

pysofi.reconstruction.cumulants_all_blocks(m_set_all_blocks)

Calculate cumulant-reconstructed images from moment-reconstructed images of each block. Similar to ‘calc_cumulants_from_moments’.

pysofi.reconstruction.cut_frames(signal_level, fbc=0.04)

Find the list of frame number to cut the whole signal plot into seperate blocks based on the change of total signal intensity.

Parameters
  • signal_level (1darray) – Signal change over time (can be derived from ‘calc_total_signal’).

  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease.

Returns

  • bounds (list of int) – Signal intensities on the boundary of each block.

  • frame_lst (list of int) – Frame number where to cut the whole signal plot into blocks.

Notes

The number of blocks is the inverse of the bleaching correction factor, fbc. For instance, if fbc=0.04, it means that in each block, the decrease in signal intensity is 4% if the total decrease, and the whole plot / video is cut into 25 blocks. For some data, it is possible that the maximun signal intensity does not appear at the beginning of the signal plot. Here, we consider all frames before the maximum in the same block as the maximum frame / intensity since usually the number of frames is not too large. The user can add in extra blocks if the initial intensity is much smaller than the maximum.

pysofi.reconstruction.min_image(filepath, filename, frames=[])

Get the minimum image for a video file (tiff stack), either for the whole video or for user defined frames.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • frames (list of int, optional) – Start and end frame number if not the whole video is used.

Returns

min_im – The minimum image.

Return type

ndarray

pysofi.reconstruction.moment_im_with_finterp(filepath, filename, order, interp_num, frames=[], mean_im=None)

Get one moment-reconstructed image of a defined order for a video file.

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • order (int) – The order number of moment-reconstructed image.

  • interp_num (int) – The interpolation factor.

  • mvlength (int) – The length of video for the reconstruction.

  • mean_im (ndarray) – Average image of the tiff stack.

Returns

moment_im – The moments-reconstructed image.

Return type

ndarray

pysofi.reconstruction.moments_all_blocks(filepath, filename, highest_order, smooth_kernel=251, fbc=0.04)

Get moment-reconstructed images for seperate blocks with user-defined noise filtering and bleaching correction factor (fbc).

Within each block, the amount of signal decrease is identical. This amount of signal decrease is characterized by the bleaching correction factor, fbc, which is the fractional signal decrease within each block (as compared to the total signal decrease over the whole signal plot).

Parameters
  • filepath (str) – Path to the tiff file.

  • filename (str) – Name of the tiff file.

  • highest_order (int) – The highest order number of moment-reconstructed images.

  • smooth_kernel (int) – The size of the median filter (‘filtering.med_smooth’) window.

  • fbc (float) – The fraction of signal decrease within each block compared to the total signal decrease.

Returns

m_set_all_blocks – block_number (int) -> {order number (int) -> image (ndarray)} A dictionary of moment-reconstructed images of each block.

Return type

dict

Notes

Similar to ‘calc_moments’. Here we omit previously calculated m_set and mean_im as inputs since a block usually has much fewer number of frames and takes shorter calculation time.

pysofi.reconstruction.sorted_k_partitions(seq, k)

Returns a list of all unique k-partitions of seq. Each partition is a list of parts, and each part is a tuple.

pysofi.visualization module

Module contents