-
Notifications
You must be signed in to change notification settings - Fork 11
/
phase.py
583 lines (479 loc) · 21.5 KB
/
phase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
"""
Repository of common analytic phase patterns.
"""
import numpy as np
from scipy import special
from math import factorial
from slmsuite.misc.math import REAL_TYPES
from slmsuite.holography.toolbox import _process_grid
def blaze(grid, vector=(0, 0), offset=0):
r"""
Returns a simple `blaze <https://en.wikipedia.org/wiki/Blazed_grating>`_,
a linear phase ramp, toward a given vector in :math:`k`-space.
.. math:: \phi(\vec{x}) = 2\pi \cdot \vec{k}_{norm} \cdot \vec{x}_{norm} + o
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
:math:`\vec{x}_{norm}`. Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
vector : (float, float)
:math:`\vec{k}_{norm}`. Blaze vector in normalized :math:`\frac{k_x}{k}` units.
See :meth:`~slmsuite.holography.toolbox.convert_blaze_vector()`
offset :
Phase offset for this blaze.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
# Optimize phase construction based on context.
if vector[0] == 0 and vector[1] == 0:
return np.zeros_like(x_grid) + offset
elif vector[0] == 0:
return 2 * np.pi * (vector[1] * y_grid) + offset
elif vector[1] == 0:
return 2 * np.pi * (vector[0] * x_grid) + offset
else:
return 2 * np.pi * (vector[0] * x_grid + vector[1] * y_grid) + offset
def lens(grid, f=(np.inf, np.inf)):
r"""
Returns a simple
`thin parabolic lens <https://en.wikipedia.org/wiki/Thin_lens#Physical_optics>`_.
When ``f`` is isotropic,
.. math:: \phi(\vec{x}) = \frac{\pi}{f}|\vec{x}|^2
Otherwise,
.. math:: \phi(x, y) = \pi \left[\frac{x^2}{f_x} + \frac{y^2}{f_y} \right]
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
f : float OR (float, float)
Focus in normalized :math:`\frac{x}{\lambda}` units.
Scalars are interpreted as a non-cylindrical isotropic lens.
Future: add a ``convert_focal_length`` method to parallel
:meth:`.convert_blaze_vector()`
Defaults to infinity (no lens).
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
# Parse focal length.
if isinstance(f, REAL_TYPES):
f = [f, f]
if isinstance(f, (list, tuple, np.ndarray)):
f = np.squeeze(f)
assert f.shape == (2,)
assert not np.any(f == 0), "Cannot interpret a focal length of zero."
# Optimize phase construction based on context (for speed, to avoid square, etc).
if np.isfinite(f[0]) and np.isfinite(f[1]):
return (np.pi / f[0]) * np.square(x_grid) + (np.pi / f[1]) * np.square(y_grid)
elif np.isfinite(f[0]) and np.isfinite(f[1]):
return (np.pi / f[0]) * np.square(x_grid)
elif np.isfinite(f[1]):
return (np.pi / f[1]) * np.square(y_grid)
else:
return np.zeros_like(x_grid)
def axicon(grid, f=(np.inf, np.inf), w=None):
r"""
Returns an `axicon <https://en.wikipedia.org/wiki/Axicon>`_ lens, the phase farfield for a Bessel beam.
A (elliptically)-cylindrical axicon blazes according to :math:`\vec{k}_g = w / \vec{f} / 2` where
:math:`w` is the radius of the axicon. With a flat input amplitude over
:math:`[-w, w]`, this will produce a Bessel beam centered at :math:`z = \vec{f}`.
.. math:: \phi(\vec{x}) = 2\pi \cdot \vec{k}_g \cdot |\vec{x}|
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
f : float OR (float, float)
Focal length (center of the axicon diamond) in normalized :math:`\frac{x}{\lambda}` units.
Scalars are interpreted as a non-cylindrical isotropic axicon.
Defaults to infinity (no axicon).
w : float OR None
See :meth:`~slmsuite.holography.toolbox._determine_source_radius()`.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
w = _determine_source_radius(grid, w)
if isinstance(f, REAL_TYPES):
f = [f, f]
if isinstance(f, (list, tuple, np.ndarray)):
f = np.squeeze(f)
assert f.shape == (2,)
assert not np.any(f == 0), "Cannot interpret a focal length of zero."
angle = [w / f[0] / 2, w / f[1] / 2] # Notice that this fraction is in radians.
# Optimize phase construction based on context (for speed, to avoid sqrt, etc).
if angle[0] == 0 and angle[1] == 0:
return np.zeros_like(x_grid)
elif angle[0] == 0:
return 2 * np.pi * np.abs(y_grid) * angle[1]
elif angle[1] == 0:
return 2 * np.pi * np.abs(x_grid) * angle[0]
else:
return 2 * np.pi * np.sqrt(np.square(x_grid * angle[0]) + np.square(y_grid * angle[1]))
def zernike(grid, n, m, aperture=None):
r"""
Returns a single real `Zernike polynomial <https://en.wikipedia.org/wiki/Zernike_polynomials>`_.
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
n, m : int
Cartesian Zernike index defining the polynomial.
aperture : {"circular", "elliptical", "cropped"} OR (float, float) OR None
See :meth:`.zernike_sum()`.
Returns
-------
numpy.ndarray
The phase for this function.
"""
return zernike_sum(grid, (((n, m), 1), ), aperture=aperture)
def zernike_sum(grid, weights, aperture=None):
r"""
Returns a summation of
`Zernike polynomial <https://en.wikipedia.org/wiki/Zernike_polynomials>`_
in a computationally-efficient manner. To improve performance, especially for higher
order polynomials, we store a cache of Zernike coefficients to avoid regeneration.
See the below example to generate :math:`Z_{20} - Z_{21} + Z_{31}`.
.. highlight:: python
.. code-block:: python
zernike_sum_phase = toolbox.phase.zernike_sum(
grid=slm,
weights=( ((2, 0), 1), # Z_20
((2, 1), -1), # Z_21
((3, 1), 1) ), # Z_31
aperture="circular"
)
Note
~~~~
There are different schemes to index Zernike polynomials.
We use the indexing defined in `this paper <https://doi.org/10.1117/12.294412>`_,
along with the algorithm defined there.
Other packages use different schemes, sometimes defining
:math:`m' = l = n - 2m`. Take care to avoid confusion.
Important
~~~~~~~~~
Zernike polynomials are canonically defined on a circular aperture. However, we may
want to use these polynomials on other apertures (e.g. a rectangular SLM).
Cropping this aperture breaks the orthogonality and normalization of the set, but
this is fine for many applications. While it is possible to orthonormalize the
cropped set, we do not do so in :mod:`slmsuite`, as this is not critical for target
applications such as aberration correction.
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
weights : list of ((int, int), float)
Which Zernike polynomials to sum. The ``(int, int)`` is the index ``(n, m)``,
which correspond to the azimuthal degree and order of the polynomial.
The ``float`` is the weight for the given index.
aperture : {"circular", "elliptical", "cropped"} OR (float, float) OR None
How to scale the polynomials relative to the grid shape. This is relative
to the :math:`R = 1` edge of a standard Zernike pupil.
``"circular"``, ``None``
The circle is scaled isotropically until the pupil edge touches the grid edge.
This is the default aperture.
``"elliptical"``
The circle is scaled anisotropically until each cartesian pupil edge touches a grid
edge. Generally produces and ellipse.
``"cropped"``
The circle is scaled isotropically until the rectangle of the grid is
circumscribed by the circle.
``(float, float)``
Custom scaling. These values are multiplied to the ``x_grid`` and ``y_grid``
directly, respectively. The edge of the pupil corresponds to where
``x_grid**2 + y_grid**2 = 1``.
Returns
-------
numpy.ndarray
The phase for this function.
"""
# Parse passed values
(x_grid, y_grid) = _process_grid(grid)
if aperture is None:
aperture = "circular"
if isinstance(aperture, str):
if aperture == "elliptical":
x_scale = 1 / np.nanmax(x_grid)
y_scale = 1 / np.nanmax(y_grid)
elif aperture == "circular":
x_scale = y_scale = 1 / np.amin([np.nanmax(x_grid), np.nanmax(y_grid)])
elif aperture == "cropped":
x_scale = y_scale = 1 / np.sqrt(np.nanmax(np.square(x_grid) + np.square(y_grid)))
else:
raise ValueError("NotImplemented")
elif isinstance(aperture, (list, tuple)) and len(aperture) == 2:
x_scale = aperture[0]
y_scale = aperture[1]
else:
raise ValueError("Type {} not recognized.".format(type(aperture)))
# At the end, we're going to set the values outside the aperture to zero.
# Make a mask for this if it's necessary.
mask = np.square(x_grid * x_scale) + np.square(y_grid * y_scale) <= 1
use_mask = np.any(mask == 0)
if use_mask:
x_grid_scaled = x_grid[mask] * x_scale
y_grid_scaled = y_grid[mask] * y_scale
else:
x_grid_scaled = x_grid * x_scale
y_grid_scaled = y_grid * y_scale
# Now find the coefficients for polynomial terms x^ay^b. We want to only compute
# x^ay^b once because this is an operation on a large array. In contrast, summing
# the coefficients of the same terms is simple and fast scalar operations.
summed_coefficients = {}
for (key, weight) in weights:
coefficients = _zernike_coefficients(key[0], key[1])
for power_key, factor in coefficients.items():
power_factor = factor * weight
if power_key in summed_coefficients:
summed_coefficients[power_key] += power_factor
else:
summed_coefficients[power_key] = power_factor
# Finally, build the polynomial.
canvas = np.zeros(x_grid.shape)
for power_key, factor in summed_coefficients.items():
if factor != 0:
if power_key == (0,0):
if use_mask:
canvas[mask] += factor
else:
canvas += factor
else:
if use_mask:
canvas[mask] += factor * np.power(x_grid_scaled, power_key[0]) * np.power(y_grid_scaled, power_key[1])
else:
canvas += factor * np.power(x_grid_scaled, power_key[0]) * np.power(y_grid_scaled, power_key[1])
return canvas
_zernike_cache = {}
def _zernike_coefficients(n, m):
"""
Returns the coefficients for the :math:`x^ay^b` terms of the real cartesian Zernike polynomial
of index `(`n, m)``. This is returned as a dictionary of form ``{(a,b) : coefficient}``.
Uses the algorithm and indexing given in `this paper <https://doi.org/10.1117/12.294412>`_.
"""
n = int(n)
m = int(m)
assert 0 <= m <= n, "Invalid cartesian Zernike index."
# Generate coefficients only if we have not already generated.
key = (n, m)
if not key in _zernike_cache:
zernike_this = {}
# Define helper variables.
l = n - 2 * m
if l % 2: # If even
q = int((abs(l) - 1) / 2)
else:
if l > 0:
q = int(abs(l)/2 - 1)
else:
q = int(abs(l)/2)
if l <= 0:
p = 0
else:
p = 1
l = abs(l)
m = int((n-l)/2)
# Helper function
def comb(n, k):
return factorial(n) / (factorial(k) * factorial(n-k))
# Finding the coefficients is a summed combinatorial search.
# This is why we cache: so we don't have to do this many times,
# especially for higher order polynomials and the corresponding cubic scaling.
for i in range(q+1):
for j in range(m+1):
for k in range(m-j+1):
factor = -1 if (i + j) % 2 else 1
factor *= comb(l, 2 * i + p)
factor *= comb(m - j, k)
factor *= (float(factorial(n - j))
/ (factorial(j) * factorial(m - j) * factorial(n - m - j)))
power_key = (n - 2*(i + j + k) - p, 2 * (i + k) + p)
# Add this coefficient to the element in the dictionary
# corresponding to the right power.
if power_key in zernike_this:
zernike_this[power_key] += factor
else:
zernike_this[power_key] = factor
# Update the cache. Remove all factors that have cancelled out (== 0).
_zernike_cache[key] = {power_key: factor for power_key, factor in zernike_this.items() if factor != 0}
return _zernike_cache[key]
# Structured light
def _determine_source_radius(grid, w=None):
r"""
Helper function to determine the assumed Gaussian source radius for various
structured light conversion functions. This is important because structured light
conversions need knowledge of the size of the incident Gaussian beam.
For example, see the ``w`` parameter in
:meth:`~slmsuite.holography.toolbox.phase.laguerre_gaussian()`.
Note
~~~~
Future work: when ``grid`` is a :class:`~slmsuite.hardware.slms.slm.SLM` which has completed
:meth:`~slmsuite.hardware.cameraslm.FourierSLM.fourier_calibration()`, this function should fit
(and cache?) :attr:`~slmsuite.hardware.slms.slm.amplitude_measured` to a Gaussian
and use the resulting width (and center?).
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
w : float OR None
The radius of the phase pattern in normalized :math:`\frac{x}{\lambda}` units.
To produce perfect structured beams, this radius is equal to the radius of
the gaussian profile of the source (ideally not clipped by the SLM).
If ``w`` is left as ``None``, ``w`` is set to a quarter of the smallest normalized screen dimension.
Returns
-------
float
Determined radius. In normalized units.
"""
(x_grid, y_grid) = _process_grid(grid)
if w is None:
return np.min([np.amax(x_grid), np.amax(y_grid)]) / 4
else:
return w
def laguerre_gaussian(grid, l, p, w=None):
r"""
Returns the phase farfield for a
`Laguerre-Gaussian <https://en.wikipedia.org/wiki/Gaussian_beam#Laguerre-Gaussian_modes>`_
beam.
This function is especially useful to hone and validate SLM alignment. Perfect alignment will
result in concentric and uniform fringes for higher order beams. Focusing issues, aberration,
or pointing misalignment will mitigate this.
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
l : int
The azimuthal wavenumber, or orbital angular momentum. Can be negative.
p : int
The radial wavenumber. Should be non-negative.
w : float OR None
See :meth:`~slmsuite.holography.toolbox._determine_source_radius()`.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
w = _determine_source_radius(grid, w)
theta_grid = np.arctan2(x_grid, y_grid)
radius_grid = y_grid * y_grid + x_grid * x_grid
return np.mod(
l * theta_grid
+ np.pi
* np.heaviside(-special.genlaguerre(p, np.abs(l))(2 * radius_grid / w / w), 0)
+ np.pi,
2 * np.pi,
)
def hermite_gaussian(grid, n, m, w=None):
r"""
Returns the phase farfield for a
`Hermite-Gaussian <https://en.wikipedia.org/wiki/Gaussian_beam#Hermite-Gaussian_modes>`_
beam. Uses the formalism described by `this paper <https://doi.org/10.1364/AO.54.008444>`_.
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
n, m : int
The horizontal (``n``) and vertical (``m``) wavenumbers. ``n = m = 0`` yields a flat
phase or a standard Gaussian beam.
w : float
See :meth:`~slmsuite.holography.toolbox._determine_source_radius()`.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
w = _determine_source_radius(grid, w)
factor = np.sqrt(2) / w
# Generate the amplitude of a Hermite-Gaussian mode.
phase = special.hermite(n)(factor * x_grid) * special.hermite(m)(factor * y_grid)
# This is real, so the phase is just the sign of the mode. This produces a
# checkerboard pattern. Probably could make this faster by bitflipping rows and columns.
phase[phase < 0] = 0
phase[phase > 0] = np.pi
return phase
def ince_gaussian(grid, p, m, parity=1, ellipticity=1, w=None):
r"""
**(NotImplemented)** Returns the phase farfield for an
`Ince-Gaussian <https://en.wikipedia.org/wiki/Gaussian_beam#Ince-Gaussian_modes>`_
beam.
`Consider <https://doi.org/10.1364/OL.29.000144>`_
`using <https://doi.org/10.1364/AO.54.008444>`_
`these <https://doi.org/10.3390/jimaging8050144>`_
`references <https://en.wikipedia.org/wiki/Elliptic_coordinate_system>`_.
Parameters
----------
grid : (array_like, array_like) OR :class:`~slmsuite.hardware.slms.slm.SLM`
Meshgrids of normalized :math:`\frac{x}{\lambda}` coordinates
corresponding to SLM pixels, in ``(x_grid, y_grid)`` form.
These are precalculated and stored in any :class:`~slmsuite.hardware.slms.slm.SLM`, so
such a class can be passed instead of the grids directly.
p : int
Ince polynomial order.
m : int
Ince polynomial degree.
parity : {1, -1, 0}
Whether to produce an even (1), odd (-1), or helical (0) Ince polynomial. A helical
polynomial is the linear combination of even and odd polynomials.
.. math:: IG^h_{p,m} = IG^e_{p,m} + iIG^o_{p,m}
ellipticity : float
Ellipticity of the beam. The semifocal distance is equal to ``ellipticity * w``,
where the foci are the points which define the elliptical coordinate system.
w : float
See :meth:`~slmsuite.holography.toolbox._determine_source_radius()`.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
w = _determine_source_radius(grid, w)
if parity == 1:
assert 0 <= m <= p
else:
assert 1 <= m <= p
complex_grid = x_grid + 1j * y_grid
factor = 1 / (w * np.sqrt(ellipticity / 2))
elliptic_grid = np.arccosh(complex_grid * factor)
raise NotImplementedError()
def matheui_gaussian(grid, r, q, w=None):
"""
**(NotImplemented)** Returns the phase farfield for a
`Matheui-Gaussian <https://doi.org/10.1364/AO.49.006903>`_ beam.
Returns
-------
numpy.ndarray
The phase for this function.
"""
(x_grid, y_grid) = _process_grid(grid)
w = _determine_source_radius(grid, w)
raise NotImplementedError()