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
cli
¶
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
examples
¶
Build the example pages in docs/examples/ from the scripts in docs/examples/scripts/.
Each example is a percent-format script (# %% code cells, # %% [markdown]
text cells). Only the scripts and the outputs of their code cells are committed:
docs/examples/scripts/<name>.py the script, written by hand
docs/examples/outputs/<name>/ outputs.json (code hash + output of each
code cell) and the figures, from `render`
docs/examples/<name>.md, <name>.ipynb the page and download notebook, from
`build` (git-ignored)
docs/examples/thumbnails/<name>.png the gallery image on index.md: the last
figure, copied by `build` (git-ignored)
render executes a script in a Jupyter kernel and stores its outputs. build
joins the current text of each script with the stored outputs, without running
anything, so a text-only change needs no render. The outputs are valid as long
as the code cells are unchanged, which the code hash in outputs.json records.
uv run ptylab examples render # run examples whose code changed, then write all pages
uv run ptylab examples render example_CPM # one, always run
uv run ptylab examples render --all # all
uv run ptylab examples build # write all pages, never runs anything (CI)
uv run ptylab examples check # CI
Only works in a git checkout of PtyLab.py, which has the docs/ folder.
PageClient
¶
Bases: NotebookClient
Executes a notebook so that each cell keeps the figures it drew.
The PtyLab Monitor reuses one figure across engines and updates it through a display id. In Jupyter that rewrites the output of the cell that first showed it; on a static page the later cell would then show nothing. Here an update that only targets earlier cells becomes a new output of the running cell, and the earlier cell keeps the figure as it was when that cell finished.
Source code in PtyLab/utils/examples.py
shown(cell)
¶
code_hash(notebook)
¶
Hash of the code cells only, so text edits keep the stored outputs valid.
stored_outputs(script, notebook)
¶
The stored output of each shown code cell, or None if missing or for older code.
Source code in PtyLab/utils/examples.py
notebook_text(script)
¶
The downloadable notebook: the script's cells, no outputs.
Source code in PtyLab/utils/examples.py
execute(notebook, stem, timeout)
¶
Run the notebook; return the rendered outputs of each code cell and rewrite the figures.
Source code in PtyLab/utils/examples.py
render(script, timeout=3600)
¶
Run the script and store the outputs of its code cells.
Source code in PtyLab/utils/examples.py
page_text(script, notebook, outputs)
¶
The page: the script's text and code, each code cell followed by its output.
Source code in PtyLab/utils/examples.py
write_thumbnail(script)
¶
Copy the last figure of the example, usually the result, as its gallery image.
Source code in PtyLab/utils/examples.py
build(script)
¶
Write the page and notebook from the stored outputs; False if they are out of date.
Source code in PtyLab/utils/examples.py
problems()
¶
Everything that is not in sync between the scripts, their outputs and the nav.
Source code in PtyLab/utils/examples.py
confirm(question)
¶
Ask a yes/no question; only "y" or "yes" counts as yes (Enter, or no terminal, is no).
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
correctGlobalPhase(estimate, reference, weight=None, ramp=False)
¶
Align the phase of a reconstruction to a reference, such as the ground truth.
A reconstruction \(\hat{x}\) matches the reference \(x\) only up to a constant phase. The best phase is
which solves \(\min_\theta \| e^{i\theta} \hat{x} - x \|_w^2\). The result is \(e^{i\theta} \hat{x}\); the amplitude is not changed.
In blind ptychography \(\hat{x}\) can also carry a linear phase ramp
\(e^{-i\mathbf{k}\cdot\mathbf{r}}\), traded with the probe. With
ramp=True, \(\mathbf{k}\) is first taken as the mean phase step between
neighbouring pixels of \(c = \hat{x}^* x\) (no unwrapping needed),
likewise along columns, and \(\theta\) is then found as above for \(e^{i\mathbf{k}\cdot\mathbf{r}} \hat{x}\).
Each frame on the last two axes gets its own phase (and ramp).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimate
|
ndarray
|
Complex reconstruction, NumPy or CuPy, with frames on the last two axes. |
required |
reference
|
ndarray
|
Complex reference, broadcastable to |
required |
weight
|
ndarray
|
Real weight \(w\) over the frame, for example the illumination or a mask of the scanned area. Defaults to 1 everywhere. |
None
|
ramp
|
bool
|
Also remove the relative linear phase ramp. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The aligned estimate, with the shape and dtype of |
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
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. If pyqtgraph is not importable or there is no display (e.g. ssh without X11 forwarding), it falls back to a matplotlib slider.
:param A: a 3D array :param colormap: matplotlib colormap, default, customized colormap for plotting diffraction data return: a pyqtgraph plot
Source code in PtyLab/utils/visualisation.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | |