Utilities¶
PtyLab.utils
¶
alignment
¶
show_alignment(reconstruction, data, params, engine)
¶
Show a viewer which gives information about the alignment of the probe and the object
Source code in PtyLab/utils/alignment.py
downloader
¶
download_with_progress(url, filename)
¶
Download a file and show a progress bar while doing so.
Parameters¶
url: URL of data filename: path to save it
Returns¶
None
Source code in PtyLab/utils/downloader.py
fsvd
¶
============================================================================= Randomized SVD. See Halko, Martinsson, Tropp's 2011 SIAM paper:
This file has been adopted to fit in PtyLab by making it GPU-aware by Dirk Boonzajer
"Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions" =============================================================================
rsvd(A, rank, n_oversamples=None, n_subspace_iters=None, return_range=False)
¶
Randomized SVD (p. 227 of Halko et al).
:param A: (m x n) matrix.
:param rank: Desired rank approximation.
:param n_oversamples: Oversampling parameter for Gaussian random samples.
:param n_subspace_iters: Number of power iterations.
:param return_range: If True, return basis for approximate range of A.
:return: U, S, and Vt as in truncated SVD.
Source code in PtyLab/utils/fsvd.py
find_range(A, n_samples, n_subspace_iters=None)
¶
Algorithm 4.1: Randomized range finder (p. 240 of Halko et al).
Given a matrix A and a number of samples, computes an orthonormal matrix that approximates the range of A.
:param A: (m x n) matrix. :param n_samples: Number of Gaussian random samples. :param n_subspace_iters: Number of subspace iterations. :return: Orthonormal basis for approximate range of A.
Source code in PtyLab/utils/fsvd.py
subspace_iter(A, Y0, n_iters)
¶
Algorithm 4.4: Randomized subspace iteration (p. 244 of Halko et al).
Uses a numerically stable subspace iteration algorithm to down-weight smaller singular values.
:param A: (m x n) matrix. :param Y0: Initial approximate range of A. :param n_iters: Number of subspace iterations. :return: Orthonormalized approximate range of A after power iterations.
Source code in PtyLab/utils/fsvd.py
ortho_basis(M)
¶
Computes an orthonormal basis for a matrix.
:param M: (m x n) matrix. :return: An orthonormal basis for M.
gpuUtils
¶
getArrayModule(*args, **kwargs)
¶
Return a numerical array processing module based on wether the array lives on the CPU or on the GPU.
See cupy.getArrayModule for details. :param args: :param kwargs: :return:
Source code in PtyLab/utils/gpuUtils.py
asNumpyArray(ary)
¶
Return a numpy.ndarray version of ary.
:param ary: numpy or cupy ndarray :return: cpu-version of ary
transfer_fields_to_gpu(self, fields, logger, dtype='auto')
¶
Move any fields defined in fields to the CPU. Fields has to be a list of strings with field names :param self: :param fields: :param logger: :param dtype: data type. If 'auto', will be set to np.float32 for real-valued data and np.complex64 for complex :return:
Source code in PtyLab/utils/gpuUtils.py
transfer_fields_to_cpu(self, fields, logger)
¶
Move any fields defined in fields to the CPU. Fields has to be a list of strings with field names :param self: :param fields: :param logger: :return:
Source code in PtyLab/utils/gpuUtils.py
initializationFunctions
¶
initialProbeOrObject(shape, type_of_init, data, logger=None)
¶
Initialization objects are created for the reconstruction. Currently implemented: ones - every element is set to 1 + random noise circ - same as 'ones' but with a circular boundary constraint upsampled - upsampled low-resolution estimate (used for FPM)
Random noise is added to the arrays to enforce linear independence required for orthogonalization of modes
:return:
Source code in PtyLab/utils/initializationFunctions.py
scanGrids
¶
tsp_ga
¶
genetic algorithm for traveling salesman problem.
Source code in PtyLab/utils/scanGrids.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
GenerateNonUniformFermat(n, radius=1000, power=1)
¶
generate spiral patterns :param n: number of points generated :param radius: radius in micrometer :param power = 1 is standard Fermat, power>1 yields more points towards the center of grid :return: R: row C: column
Source code in PtyLab/utils/scanGrids.py
GenerateFermatSpiral(n, c)
¶
generate Fermat Spiral :param n: number of points generated :param c: optional argument that controls scaling of spiral :return: R: row C: column
Source code in PtyLab/utils/scanGrids.py
GenerateConcentricGrid(Nr, s, rend)
¶
generate concentric circles :param Nr: number of circles (or shells) :param s: number of pixels between points on each circle, roughly calculated as rend/Nr :param rend: end radius size (in pixel units) :return: R: row C: column
Source code in PtyLab/utils/scanGrids.py
GenerateRasterGrid(n, ds, randomOffset=False, amplitude=1)
¶
generate a raster grid containing n*n points with a period of ds in pixelsize, with the option of adding randomOffsets. :param n: number of points per dimension :param ds: period (# of pixels) per dimension :param randomOffset: optional to add random offsets, default: False :param amplitude: amplitude for the random offsets, default: 1 :return: R: row C: column
Source code in PtyLab/utils/scanGrids.py
utils
¶
fft2c(field, fftshiftSwitch=False, *args, **kwargs)
¶
performs 2 - dimensional unitary Fourier transformation, where energy is preserved sum( abs(g)2 ) == sum( abs(fft2c(g))2 ) if g is two - dimensional, fft2c(g) yields the 2D DFT of g if g is multi - dimensional, fft2c(g) yields the 2D DFT of g along the last two axes :param array: :return:
Source code in PtyLab/utils/utils.py
ifft2c(field, fftshiftSwitch=False)
¶
performs 2 - dimensional inverse Fourier transformation, where energy is preserved sum( abs(G)2 ) == sum( abs(fft2c(g))2 ) if G is two - dimensional, fft2c(G) yields the 2D iDFT of G if G is multi - dimensional, fft2c(G) yields the 2D iDFT of G along the last two axes :param array: :return:
Source code in PtyLab/utils/utils.py
circ(x, y, D)
¶
generate a binary array containing a circle on a 2D grid :param x: 2D x coordinate, normally calculated from meshgrid: x,y = np.meshgird((,)) :param y: 2D y coordinate, normally calculated from meshgrid: x,y = np.meshgird((,)) :param D: diameter :return: a binary 2D array
Source code in PtyLab/utils/utils.py
rect(arr, threshold=0.5)
¶
generate a binary array containing a rectangle on a 2D grid :param x: 2D x coordinate, normally calculated from meshgrid: x,y = np.meshgird((,)) :param threshold: threshold value to binarilize the input array, default value 0.5 :return: a binary array
Source code in PtyLab/utils/utils.py
posit(x)
¶
fraccircshift(A, shiftsize)
¶
fraccircshift expands numpy.roll to fractional shifts values, using linear interpolation. :param A: ndarray :param shiftsize: shift size in each dimension of A, len(shiftsize)==A.ndim.
Source code in PtyLab/utils/utils.py
cart2pol(x, y)
¶
orthogonalizeModes(p, method=None)
¶
Imposes orthogonality through singular value decomposition :return:
Source code in PtyLab/utils/utils.py
zernikeAberrations(Xp, Yp, D, z_coeff)
¶
Compute the first 19 Zernike aberrations based on Zernike polynomials Based on https://en.wikipedia.org/wiki/Zernike_polynomials#OSA/ANSI_standard_indices
Xp,Yp - meshgrid coordinates D - radius within which to generate the zernike aberrations z_coeff - 19 element long list containing coefficients.
minimal example:
import matplotlib.pyplot as plt
import numpy as np
# create the circular dimensions which will define the size
# of a unit circle used for zernike aberration calculations
Xp,Yp = np.mgrid[-128:128, -128:128]
D = 128
# Get defocus aberration (4th index)
z_coeff = np.zeros(19)
z_coeff[4] = 3
Z = zernikeAberrations(Xp,Yp,D,z_coeff)
# plot the polynoial
plt.figure(1)
plt.imshow(np.angle(Z))
plt.show()
Source code in PtyLab/utils/utils.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
p2bin(im, binningFactor)
¶
perform binning at a factor of power of 2, return binned image and the indices for before and after binning. :Params im: input image for binning :Params binningFactor: must be power of 2 in the current implementation :return:
Source code in PtyLab/utils/utils.py
bin2(X)
¶
perform 2-by-2 binning. :Params X: input 2D image for binning return: Y: output 2D image after 2-by-2 binning
Source code in PtyLab/utils/utils.py
visualisation
¶
hsv2rgb(hsv)
¶
Convert a 3D hsv np.ndarray to rgb (5 times faster than colorsys). https://stackoverflow.com/questions/27041559/rgb-to-hsv-python-change-hue-continuously h,s should be a numpy arrays with values between 0.0 and 1.0 v should be a numpy array with values between 0.0 and 255.0 :param hsv: np.ndarray of shape (x,y,3) :return: hsv2rgb returns an array of uints between 0 and 255.
Source code in PtyLab/utils/visualisation.py
complex2rgb(u, amplitudeScalingFactor=1, force_numpy=True, center_phase=False)
¶
Preparation function for a complex plot, converting a 2D complex array into an rgb array :param u: a 2D complex array :return: an rgb array for complex plot
Source code in PtyLab/utils/visualisation.py
complex2rgb_vectorized(probe, **kwargs)
¶
Turn complex image into rgb for every line.
The individual images are all autoscaled, so you cannot compare them.
Source code in PtyLab/utils/visualisation.py
plotExtent(pixelSize, axisUnit, shape)
¶
Extent for imshow, expressed in axisUnit.
Real-space axes run from zero, as they always have. Reciprocal axes are centred on zero frequency instead, which is where the pupil sits.
:param pixelSize: sample spacing of the array, in SI units :param str axisUnit: any key of unitRatio :param shape: shape of the array that is plotted :return: [left, right, bottom, top] for imshow
Source code in PtyLab/utils/visualisation.py
complexPlot(rgb, ax=None, pixelSize=1, axisUnit='pixel')
¶
Plot a 2D complex plot (hue for phase, brightness for amplitude). Input array need to be prepared by using the complex2rgb function. :param rgb: a rgb array that is converted from a 2D complex np.ndarray by using complex2rgb :param ax: Optional axis to plot in :param pixelSize: pixelSize in x and y, to display the physical dimension of the plot :param str axisUnit: Options: default 'pixel', 'm', 'cm', 'mm', 'um', and the reciprocal '1/m', '1/mm', '1/um' for Fourier-space quantities :return: An hsv plot
Source code in PtyLab/utils/visualisation.py
modeTile(P, normalize=True)
¶
Tile 3D data into a single 2D array :param P: A complex np.ndarray :param normalize: normalize each mode individually :param pixelSize: pixelSize in x and y, to display the physical dimension of the plot :return: A big array with flattened modes
Source code in PtyLab/utils/visualisation.py
hsvplot(u, ax=None, pixelSize=1, axisUnit='pixel', amplitudeScalingFactor=1)
¶
perform complex plot :param ax :param pixelSize, default 1 :param axisUnit, default 'pixel', options: 'm', 'cm', 'mm', 'um' return: a complex plot
Source code in PtyLab/utils/visualisation.py
hsvmodeplot(P, ax=None, normalize=True, pixelSize=1, axisUnit='pixel', amplitudeScalingFactor=1)
¶
Place multi complex images in a square grid and use hsvplot to display :param P: A complex np.ndarray :param normalize: normalize each mode individually :param pixelSize: pixelSize in x and y, to display the physical dimension of the plot :return: a tiled complex plot
Source code in PtyLab/utils/visualisation.py
setColorMap()
¶
create the colormap for diffraction data (the same as matlab) return: customized matplotlib colormap
Source code in PtyLab/utils/visualisation.py
show3Dslider(A, colormap='diffraction')
¶
show a 3D plot with a slider.
In a Jupyter notebook an inline ipywidgets slider is used. In a script the interactive pyqtgraph viewer is used.
:param A: a 3D array :param colormap: matplotlib colormap, default, customized colormap for plotting diffraction data return: a pyqtgraph plot