-
Notifications
You must be signed in to change notification settings - Fork 5
/
optsim.py
2300 lines (2037 loc) · 78.8 KB
/
optsim.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Collection of functions useful for general optical propagation simulations.
Also generating speckle, and some light field / wavefront sensing routines.
***************************************************************************
cbasedlf/optsim is licensed under the
MIT License
***************************************************************************
If you found it useful, please cite the repo in your projects.
F. Soldevila (@cbasedlf on Github). November 10th, 2022.
"""
#%% General use
import numpy as np
from numpy.fft import fft as fft, fft2 as fft2
from numpy.fft import ifft as ifft, ifft2 as ifft2
from numpy.fft import fftshift as fftshift, ifftshift as ifftshift
import scipy as sc
import cv2
#plotting
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
#%% Classes
'''
Honestly I do not know why I defined the scattering layer as a class. It was
probably my first week learning python and I just wanted to try. You can define
a function that returns a matrix with [thin_scat] and forget about the rest I
guess.
'''
class thin_scatter():
def __init__(self, size, pxnum, corr_width, strength):
'''
[corr_width] controls the 'correlation width' of the scattering layer.
The lower, the bigger the detail of the layer. IN LENGTH UNITS
[strength] controls the amount of balistic photons that go through the
layer (controls if the phase jumps introduced by the thin layer are
bigger or smaller than one wavelength)
'''
delta = size / pxnum #mesh spacing (spatial domain)
delta_f = 1 / (pxnum*delta) #mesh spacing (frequency domain)
corr_width_px = int(corr_width / delta) #calculate corr_width in pixels
#Build gaussian in spatial domain, with the desired width
lowpass = buildGauss(px = pxnum,sigma = (corr_width_px,corr_width_px),
center = (int(pxnum/2),int(pxnum/2)),
phi = 0)
#Convert to frequency domain (to do the filtering)
lowpass_ft = ft2(lowpass, delta)
self.size = size
self.pxnum = pxnum
self.delta = delta
self.seed = np.random.rand(self.pxnum,self.pxnum)
#Filter in frequency domain so detail size corresponds to corr_width
self.phase = np.real(ift2(ft2(self.seed,delta)*lowpass_ft,delta_f))
#shift between -0.5 and 0.5
self.phase = (self.phase - np.min(self.phase)) / (np.max(self.phase) - np.min(self.phase)) - 0.5
#build final phase mask (no wrap here)
self.phase = self.phase*2*np.pi*strength
#build 'field' (wrapped phase)
self.thin_scat = np.exp(1j*self.phase)
pass
pass
#%% Optical propagation functions (and related)
'''
Derived from:
Numerical Simulation of Optical Wave Propagation with Examples in MATLAB
Author(s): Jason D. Schmidt
https://spie.org/Publications/Book/866274?SSO=1
'''
###############################################################################
####### For generating fields that arise from 'point' sources #################
###############################################################################
def build_point(xpos, ypos, pxsize, delta):
'''
build_point generates the field of a point source at the plane of the
point source. Useful for propagation simulations
Parameters
----------
xpos, ypos : position of the source (length units)
pxsize : number of pixels of the grid
delta : grid spacing at the source plane (length units)
Returns
-------
source_field : field of the point source
'''
x = np.arange(-pxsize/2, pxsize/2, 1)*delta
X,Y = np.meshgrid(x,-x)
exp1 = np.exp(-np.sqrt((X-xpos)**2 + (Y-ypos)**2)**2 / (2*delta**2))
exp2 = np.exp(-1j*np.sqrt((X-xpos)**2 + (Y-ypos)**2)**2 / (2*delta**2))
source_field = exp1 * exp2
return source_field
def build_source(xpos, ypos, pxsize, delta, source_size):
'''
build_source generates the field of a point source at the plane of the
point source. Useful for propagation simulations
Parameters
----------
xpos, ypos : position of the source (length units)
pxsize : number of pixels of the grid
delta : grid spacing at the source plane (length units)
source_size : size of the source (length units). Needs to be bigger than
delta
Returns
-------
source_field : field of the point source
'''
gauss_width = source_size/4
x = np.arange(-pxsize/2, pxsize/2, 1)*delta
X,Y = np.meshgrid(x,-x)
exp1 = np.exp(-np.sqrt((X-xpos)**2 + (Y-ypos)**2)**2 / (2*gauss_width**2))
exp2 = np.exp(-1j*np.sqrt((X-xpos)**2 + (Y-ypos)**2)**2 / (2*gauss_width**2))
source_field = exp1 * exp2
return source_field
def build_point_sinc(xpos, ypos, N, apsize, wvl, z):
'''
build_point_sinc generates the field of a point source
at the plane of the point source. Useful for propagation simulations.
Uses a different model than build_point (here we model the source
as a sinc function)
Parameters
----------
xpos, ypos : position of the source (length units)
N : number of grid points
apsize : physical size of the aperture at the observation plane
(length units)
wvl : wavelength of the source (length units)
z : propagation distance (length units)
Returns
-------
source_field : field of the point source
delta : grid spacing at the propagated plane (length units)
'''
k = 2*np.pi / wvl
arg = apsize / (wvl*z)
delta = 1 / (100*arg)
x = np.arange(-N/2, N/2, 1) * delta
x1,y1 = np.meshgrid(x,-x)
def cart2pol(x, y):
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return phi, rho
theta1, r1 = cart2pol(x1, y1)
thetapos, rpos = cart2pol(xpos,ypos)
A = wvl*apsize #sets field amplitude to 1 in obs plane
E1 = np.exp(-1j*k/(2*z)*np.sqrt((x1-xpos)**2+(y1-ypos)**2)**2)
E2 = 1
source_field = A*E1*E2*arg**2*np.sinc(arg*(xpos-x1))*np.sinc(arg*(ypos-y1))
return source_field, delta
def build_point_circ(xpos, ypos, r, N, apsize):
'''
build_point_circ generates a point source with the simplest model:
just a circular aperture as the irradiance, no phase
Parameters
----------
xpos, ypos : position of the source
r : radius of the source
N : number of grid points
apsize : size of the grid
Returns
-------
source_field : amplitude mask representing the source
'''
delta = apsize/N #grid spacing
#Generate grid
x = np.arange(-N/2, N/2, 1)*delta
X,Y = np.meshgrid(x,-x)
#Generate radius (polar)
rho = np.abs((X-xpos) + 1j*(Y-ypos))
#Generate mask with circular aperture of given size, centered at source pos
mask = rho<r
#Build the source
source_field = np.ones((N,N)) * mask
return source_field
def build_delta(xpos, ypos, pxsize, delta):
'''
build_delta generates a point source that is a delta function
(a single pixel)
Parameters
----------
xpos, ypos : position of the source
pxsize : number of pixels of the grid
delta : grid spacing at the source plane (length units)
Returns
-------
source_field : amplitude mask representing the source
'''
#Generate grid
x = np.arange(-pxsize/2, pxsize/2, 1)*delta
X,Y = np.meshgrid(x,-x)
#find position of the source (in pixel index, finds the closest one)
xidx = np.abs(x-xpos).argmin()
yidx = np.abs(-x-ypos).argmin()
#Generate source amplitude (all zeros)
source_field = np.zeros((pxsize,pxsize))
#Build the source
source_field[yidx,xidx] = 1
return source_field
###############################################################################
###Optical propagation routines (Fresnel, Fraunhoffer, Rayleigh-Sommerfeld)####
###############################################################################
def ft(g, delta):
'''
ft performs a discretized version of a Fourier Transform by using DFT
Parameters
----------
g : input signal (sampled discretely) on the spatial(temporal) domain
delta : grid spacing spatial(temporal) domain. length(time) units
Returns
-------
G : Fourier Transform
'''
G = fftshift(fft(ifftshift(g)))*delta
return G
def ift(G, delta_f):
'''
ift performs a discretized version of an Inverse Fourier Transform
by using DFT
Parameters
----------
G : input signal (sampled discretely) on the frequency domain
delta_f : grid spacing frequency domain. 1/length(1/time) units
Returns
-------
g : Inverse Fourier Transform
'''
n = G.shape[0]
g = ifftshift(ifft(fftshift(G)))*(n*delta_f)
return g
def ft2(g, delta):
'''
ft2 performs a discretized version of a Fourier Transform by using DFT
Parameters
----------
g : input field (sampled discretely) on the spatial domain
delta : grid spacing spatial domain (length units)
Returns
-------
G : Fourier Transform
'''
G = fftshift(fft2(ifftshift(g)))*delta**2
return G
def ift2(G, delta_f):
'''
ift2 performs a discretized version of an Inverse Fourier Transform
by using DFT
Parameters
----------
G : input field (sampled discretely) on the frequency domain
delta_f : grid spacing frequency domain (1/length units)
Returns
-------
g : Inverse Fourier Transform
'''
n = G.shape[0]
g = ifftshift(ifft2(fftshift(G)))*(n*delta_f)**2
return g
def fraunhofer_prop(Uin, wvl, delta, z, padsize = False):
'''
franhofer_prop evaluates the Fraunhofer diffraction integral for an
optical field between two planes.
Parameters
----------
Uin : Input field
wvl : wavelength of the field
delta : grid spacing on the input plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted)
Returns
-------
Uout : Output field after propagation
x2 : x-grid on the output plane
y2 : y-grid on the output plane
'''
N = Uin.shape[0]
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl #wavenumber
#spatial frequencies at source plane
delta_f = 1/(N*delta)
f_x1 = np.arange(-N/2, N/2, step = 1)*delta_f #frequency axis
#generate observation plane coordinates
x2, y2 = np.meshgrid(f_x1*z*wvl,-f_x1*z*wvl)
#Calculate field at the output
Uout = 1/(1j*wvl*z)*np.exp(1j*k/(2*z)*(x2**2+y2**2))*ft2(Uin,delta)
return Uout, x2, y2
def fresnel_one_step(Uin,wvl,delta,z,padsize=False):
'''
fresnel_one_step evaluates the Fresel diffraction integral for an
optical field between two planes. It does it in a single step, which
does not allow for controlling the grid spacing at the output (observation)
plane
Parameters
----------
Uin : Input field
wvl : wavelength of the field
delta : grid spacing on the input plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted)
Returns
-------
Uout : Output field after propagation
x2 : x-grid on the output plane
y2 : y-grid on the output plane
'''
N = Uin.shape[0]
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl
#Build source-plane coords
x = np.arange(-N/2, N/2, step = 1)*delta #x-axis
x1,y1 = np.meshgrid(x,-x) #generate grid
#Calculate output plane coords (delta_f scaled by the geometry wvl*z)
x2 = np.arange(-N/2, N/2, step = 1)*wvl*z/(N*delta)
x2,y2 = np.meshgrid(x2,-x2)
#evaluate the Fresnel-Kirchhoff integral
Uout = 1/(1j*wvl*z)*np.exp(1j*k/(2*z)*(x2**2+y2**2))*ft2(Uin*np.exp(1j*k/(2*z)*(x1**2+y1**2)),delta)
return Uout,x2,y2
def fresnel_two_steps(Uin,wvl,delta1,delta2,z,padsize=False):
'''
fresnel_two_steps evaluates the Fresel diffraction integral for an
optical field between two planes. It does it in two steps, which
allows for controlling the grid spacing at the output (observation)
plane
Parameters
----------
Uin : Input field
wvl : wavelength of the field
delta1 : grid spacing on the input plane (spatial domain)
delta2 : grid spacing on the output plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted)
Returns
-------
Uout : Output field (observation plane) after propagation
x2 : x-grid on the output plane
y2 : y-grid on the output plane
'''
N = Uin.shape[0] #Number of gridpoints
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl #wavenumber
#magnification
m = delta2/delta1
#Build source-plane coords
x = np.arange(-N/2, N/2, step = 1)*delta1 #x-axis
x1, y1 = np.meshgrid(x,-x) #generate grid
### Popagate to intermediate plane ###
z1 = z/(1-m) #intermediate propagation distance
#grid spacing on the auxiliary plane
delta_aux = wvl*np.abs(z1)/(N*delta1)
#Build source-plane coords
x_aux = np.arange(-N/2,N/2,step=1)*delta_aux #x-axis
x_aux, y_aux = np.meshgrid(x_aux,-x_aux) #generate auxiliary grid
#Evaluate Fresnel-Kirchoff integral
Uaux = 1/(1j*wvl*z1)*np.exp(1j*k/(2*z1)*(x_aux**2+y_aux**2))*ft2(Uin*np.exp(1j*k/(2*z1)*(x1**2+y1**2)),delta1)
### Propagate to observation plane ###
z2 = z - z1
#Build source-plane coords
x2 = np.arange(-N/2,N/2,step=1)*delta2 #x-axis
x2, y2 = np.meshgrid(x2,-x2) #generate observation plane grid
#Evaluate the Fresnel-Kirchhoff integral
Uout = 1/(1j*wvl*z2)*np.exp(1j*k/(2*z2)*(x2**2+y2**2))*ft2(Uaux*np.exp(1j*k/(2*z2)*(x_aux**2+y_aux**2)),delta_aux)
return Uout,x2,y2
def ang_spec_prop(Uin, wvl, delta1, delta2, z, padsize = False):
'''
ang_spec_prop evaluates the Fresel diffraction integral for an
optical field between two planes using the angular-spectrum method
Assumes paraxial approximation!
Parameters
----------
Uin : Input field (source plane)
wvl : wavelength of the field
delta1 : grid spacing on the input plane (spatial domain)
delta2 : grid spacing on the output plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted). False by default
Returns
-------
Uout : Output field (observation plane)
x2 : x-grid on the output plane
y2 : y-grid on the output plane
'''
N = Uin.shape[0] #number of pixels (assume square grid)
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl #wavenumber
#Build source-plane coords
x = np.arange(-N/2, N/2, step = 1)*delta1 #x-axis
x1, y1 = np.meshgrid(x,-x) #generate grid
r1sq = x1**2 + y1**2
#Spatial frequencies at source plane
delta_f1 = 1/(N*delta1)
f_x1 = np.arange(-N/2, N/2, step = 1)*delta_f1 #frequency axis
#Generate mesh
f_x1, f_y1 = np.meshgrid(f_x1,-f_x1)
fsq = f_x1**2 + f_y1**2
#Scaling parameter
m = delta2/delta1
#Spatial grid at observation plane
x = np.arange(-N/2, N/2, step = 1)*delta2 #x-axis
x2, y2 = np.meshgrid(x,-x) #generate grid
r2sq = x2**2 + y2**2
#Quadratic phase factors
Q1 = np.exp(1j*k/2*(1-m)/z*r1sq)
Q2 = np.exp(-1j*2*np.pi**2*z/m/k*fsq)
Q3 = np.exp(1j*k/2*(m-1)/(m*z)*r2sq)
#Calculate propagated field
Uout = Q3*ift2(Q2*ft2(Q1*Uin/m,delta1),delta_f1)
return Uout, x2, y2
def rs_ang_spec_prop(Uin, wvl, delta, z, padsize = False):
'''
rs_ang_spec_prop evaluates the diffraction integral for an
optical field between two planes using the angular-spectrum method.
Does not use paraxial approximation (equivalent to Rayleigh-Sommerfeld
theory).
Does not take into account evanescent waves (so, you can propagate back
and forth between two planes and you will get the same field)
Parameters
----------
Uin : Input field (source plane)
wvl : wavelength of the field
delta : grid spacing on the input plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted). False by default
Returns
-------
Uout : Output field (observation plane)
'''
N = Uin.shape[0] #number of pixels (assume square grid)
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl #wavenumber
#Build source-plane coords
x = np.arange(-N/2, N/2, step = 1)*delta #x-axis
x1, y1 = np.meshgrid(x,-x) #generate grid
#Spatial frequencies at source plane
delta_f = 1/(N*delta)
f_x = np.arange(-N/2, N/2, step = 1)*delta_f #frequency axis
#Generate mesh
f_x, f_y = np.meshgrid(f_x,-f_x)
#Transfer function
#Term inside the square root
sr = 1 - (wvl*f_x)**2 - (wvl*f_y)**2
#see where the factor inside the square root is positive. Travelling waves
sr_prop = sr*(sr > 0)
#Calculate transfer functions
H = np.exp(1j*k*z*np.sqrt(sr_prop)) #for traveling waves
#apply frequency cut (only where the frequency is lower
#than the frequency cut of the system)
H = H*(sr > 0)
#Calculate propagated field
Uout = ift2(ft2(Uin,delta)*H, delta_f)
return Uout
def rs_ang_spec_prop_evanescent(Uin, wvl, delta, z, padsize = False):
'''
rs_ang_spec_prop_evanescent evaluates the diffraction integral for an
optical field between two planes using the angular-spectrum method.
Does not use paraxial approximation (equivalent to Rayleigh-Sommerfeld
theory)
Takes into account evanescent waves (so, you cannot go back and forth
between two planes with the same result)
Parameters
----------
Uin : Input field (source plane)
wvl : wavelength of the field
delta : grid spacing on the input plane (spatial domain)
z : propagation distance
padsize : size of the padding (if wanted). False by default
Returns
-------
Uout : Output field (observation plane)
'''
N = Uin.shape[0] #number of pixels (assume square grid)
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
pass
k = 2*np.pi/wvl #wavenumber
#Build source-plane coords
x = np.arange(-N/2, N/2, step = 1)*delta #x-axis
x1, y1 = np.meshgrid(x,-x) #generate grid
#Spatial frequencies at source plane
delta_f = 1/(N*delta)
f_x = np.arange(-N/2, N/2, step = 1)*delta_f #frequency axis
#Generate mesh
f_x, f_y = np.meshgrid(f_x,-f_x)
#Transfer function
#Term inside the square root
sr = 1 - (wvl*f_x)**2 - (wvl*f_y)**2
#see where the factor inside the square root is positive. Travelling waves
sr_prop = sr*(sr>0)
#see where the factor inside the square root is negative. Evanescent waves
sr_evanescent = sr * (sr < 0)
#Calculate transfer functions
H_prop = np.exp(1j*k*z*np.sqrt(sr_prop)) #for traveling waves
#apply frequency cut (only where the frequency is lower than
#the frequency cut of the system)
H_prop = H_prop * (sr > 0)
H_evanescent = np.exp(-k*z*np.sqrt(-sr_evanescent)) #For evanescent waves
H_evanescent = H_evanescent*(sr < 0)
#Combine into full transfer function
H = H_prop + H_evanescent
#Calculate propagated field
Uout = ift2(ft2(Uin,delta)*H, delta_f)
return Uout
def rs_ang_spec_prop_multistep(Uin, wvl, delta, z, zsteps,
padsize = False, resample_period = False):
'''
rs_ang_spec_prop_multistep evaluates the diffraction integral for an
optical field between two planes using the angular-spectrum method.
Does not use paraxial approximation (equivalent to Rayleigh-Sommerfeld
theory).
Does the propagation in N steps, in order to avoid aliasing.
After every propagation, uses absorbing boundaries
It can resample the field after resample_period propagations, thus
increasing the mesh spacing and providing bigger FoVs at the output than
the FoV at the input.
Parameters
----------
Uin : Input field (source plane)
wvl : wavelength of the field
delta : grid spacing on the input plane (spatial domain)
z : propagation distance
zsteps : number of propagation steps
padsize : size of the padding (if wanted). False by default
resample_period : if true, resample the field after N propagations.
Resample is done by merging 2x2 pixels into a single
pixel (nearest neighbors)
Returns
-------
Uout : Output field (observation plane)
delta : mesh spacing on the observation plane. Same as
input if resample_period = False
'''
N = Uin.shape[0] #number of pixels (assume square grid)
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
#Define FoV size
FoV = N*delta
#Define absorbing window
window = buildSuperGauss(N, delta, (0,0), (0.35*FoV,0.35*FoV), 4)
#Define step length
zSTEP = z/zsteps
#Load phase unwrap + resample methods
if resample_period != False:
from skimage.restoration import unwrap_phase
from PIL import Image
Uout = Uin.copy()
for idx in range(zsteps):
#Propagation
Uout = rs_ang_spec_prop(Uin = Uout, wvl = wvl, delta = delta,
z = zSTEP, padsize = False)
#Apply absorbing window
Uout *= window
#Resample (if needed)
if resample_period != False:
if (idx > 0) and (idx % resample_period == 0):
#Calculate new size
M = int(N/2)
padsize = int((N-M)/2)
#Take amplitude and phase
amp = np.abs(Uout)
phase = np.angle(Uout)
#Resample amplitude
amp = Image.fromarray(amp).resize((M,M),
resample=Image.NEAREST)
amp = np.array(amp)
#Unwrap phase, then resample it
phase = unwrap_phase(phase)
phase = Image.fromarray(phase).resize((M,M),
resample=Image.NEAREST)
phase = np.array(phase)
#Build field again, pad it to have same size as before
Uout = amp*np.exp(1j*phase)
Uout = np.pad(Uout,
((padsize,padsize),(padsize,padsize)),
'constant')
#Update delta
delta *= 2
#Update FoV size
FoV = N*delta
#Update absorbing window
window = buildSuperGauss(N, delta, (0,0),
(0.35*FoV,0.35*FoV), 4)
return Uout, delta
def lens_in_front_ft(Uin, wvl, delta, focal, distance, padsize = False):
'''
lens_in_front_ft performs propagation of an optical field from a plane
in front of a lens, to the focal plane after the lens
Parameters
----------
Uin : Input field
wvl : wavelength of the field
delta : grid spacing input plane
focal : focal length of the lens
distance : distance between the objet plane and the plane the lens is placed
padsize : padding size. The default is False.
Returns
-------
Uout : Field at the focal plane after the lens
u : x-grid on the output plane
v : y-grid on the output plane
'''
N = Uin.shape[0] #number of pixels (assume square grid)
#Padding (if specified)
if padsize != False:
#pad the input
Uin = np.pad(Uin, ((padsize,padsize),(padsize,padsize)), 'constant')
#Calculate new size in pixels
N = Uin.shape[0]
k = 2*np.pi/wvl #wavenumber
f_x = np.arange(-N/2, N/2, step = 1) / (N*delta) #frequency axis
#Generate mesh
x2, y2 = np.meshgrid(f_x*wvl*focal,-f_x*wvl*focal)
Uout = 1/(1j*wvl*focal)*np.exp(1j*k/(2*focal)*(1-distance/focal)
*(x2**2+y2**2))*ft2(Uin,delta)
return Uout, x2, y2
#%% Plotting functions + display/saving.
'''
This works nice with Spyder to visualize stuff. Not sure at all what will
happen in other IDEs, but the code should be easily patched for those I guess.
'''
def show_img(img, fig_size = False, colormap = 'viridis'):
'''
show_img plots a single matrix as an image
Parameters
----------
img : matrix to plot
fig_size: size of the figure (inches)
colormap: colormap of the plot
Returns
-------
ax : ax object (so you have access to it in the workspace)
'''
if fig_size == False:
fig_size = (5,5)
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = fig_size)
im1 = ax.imshow(img, interpolation = "nearest", cmap = colormap)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.1)
plt.colorbar(im1, cax = cax, ax = ax)
ax.set_aspect(1)
return ax
def show_2img(img1, img2, fig_size = False, colormap = 'viridis'):
'''
show_2img plots two images, side by side
Parameters
----------
img1 : image #1
img2 : image #2
colormap : colormap of the plots
fig_size : size of the plot window (inches)
'''
if fig_size == False:
fig_size = (10,4)
fig,(ax1,ax2) = plt.subplots(nrows = 1, ncols = 2, figsize = fig_size)
im1 = ax1.imshow(img1,interpolation="nearest",cmap = colormap)
ax1.set_aspect(1)
ax1_divider = make_axes_locatable(ax1)
cax1 = ax1_divider.append_axes('right', size='5%', pad=0.1)
fig.colorbar(im1, cax = cax1)
im2 = ax2.imshow(img2,interpolation="nearest",cmap = colormap)
ax2.set_aspect(1)
ax2_divider = make_axes_locatable(ax2)
cax2 = ax2_divider.append_axes('right', size='5%', pad=0.1)
fig.colorbar(im2, cax = cax2)
pass
def show_Nimg(hypercube, fig_size = False, colormap = 'viridis'):
'''
show_Nimg generates a grid plot from a set of 2D images.
Parameters
----------
hypercube : Set of 2D images. Third axis should be the image number
fig_size : size of the figure
colormap : colormap of the plots
'''
if fig_size == False:
fig_size = (8,8)
Nimg = hypercube.shape[2]
nrows = int(np.ceil(np.sqrt(Nimg)))
fig, ax = plt.subplots(nrows = nrows, ncols = nrows, figsize = fig_size)
counter = 0
for rowidx in range(0,nrows):
for colidx in range(0,nrows):
if counter < Nimg:
im = ax[rowidx,colidx].imshow(hypercube[:,:,counter],
cmap = colormap)
ax[rowidx,colidx].set_aspect(1)
divider = make_axes_locatable(ax[rowidx,colidx])
cax = divider.append_axes('right', size='5%', pad = 0.1)
fig.colorbar(im, cax = cax, ax = ax[rowidx,colidx])
counter += 1
plt.tight_layout()
plt.show()
pass
def show_vid(hypercube, rate, fig_size = False, colormap='viridis',
cbarfix = False, loop = False):
'''
show_vid creates an animation showing the frames of a video.
The input is a 3D array, where the third dimension corresponds to time
Parameters
----------
hypercube : input array, third axis is the frames
rate : frame rate (in ms)
fig_size : size of the plot
colormap : colormap of the plots
cbarfix : option to have the same colorbar range for all frames (True)
or not (False)
Returns
-------
anim : animation object (so you have access to it in the workspace, useful
for exporting as .mpg or .gif or whatever)
'''
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable
if fig_size == False:
fig_size = (6,6)
fig , ax = plt.subplots(nrows = 1, ncols = 1, figsize = fig_size)
if cbarfix == True:
cmin = np.min(hypercube)
cmax = np.max(hypercube)
cbarlimits = np.linspace(cmin,cmax,10,endpoint=True)
def plot_img(i):
plt.clf()
plt.suptitle('Frame #' + str(i))
if cbarfix == True:
im1 = plt.imshow(hypercube[:,:,i],vmin = cmin, vmax = cmax,
cmap = colormap)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.6)
ax.set_aspect(1)
plt.colorbar(im1,cax = cax, ax = ax, ticks = cbarlimits)
else:
im1 = plt.imshow(hypercube[:,:,i], cmap = colormap)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.6)
ax.set_aspect(1)
plt.colorbar(im1,cax = cax, ax = ax)
plt.show()
anim = animation.FuncAnimation(fig, plot_img, frames = hypercube.shape[2],
interval = rate, repeat = loop)
return anim
def plot_scatter2d(data, fig_size = False):
'''
plot_scatter plots a 2D scatter plot
Parameters
----------
data : matrix to plot (row_number is number of points, colum is X and Y)
fig_size: size of the figure (inches)
Returns
-------
ax : ax object (so you have access to it in the workspace)
'''
if fig_size == False:
fig_size = (5,5)
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = fig_size)
ax.scatter(data[:,0],data[:,1])
ax.set_aspect(1)
plt.show()
return ax
def plot_lineplot(data, fig_size = False, xlabel = 'x', ylabel = 'y',
title = False, **plot_args):
'''
plot_lineplot plots a 2D line plot
Parameters
----------
data : matrix to plot (row_number is number of points, colum is X and Y)
fig_size: size of the figure (inches)
xlabel: name for X axis
ylabel: name for Y axis
title: plot title
**plot_args: kwargs for the plot options (color, markers, whatever u want)
Returns
-------
fig: fig object (so you have access to it in the workspace)
ax : ax object (so you have access to it in the workspace)
'''
if fig_size == False:
fig_size = (5,5)
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = fig_size)
ax.plot(data[:,0], data[:,1], **plot_args)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if title:
ax.set_title(title)
plt.show()
return fig, ax
def plot_stemplot(data, fig_size = False, xlabel = 'x', ylabel = 'y',
title = False, linefmt = 'teal', markerfmt = 'D',
markersize = 3):
'''
plot_stemplot plots a 2D stem plot (each point has a line going vertically
to the horizontal axis)
Parameters
----------
data : matrix to plot (row_number is number of points, colums are X and Y
values)
fig_size: size of the figure (inches)
xlabel: name for X axis
ylabel: name for Y axis
title: plot title
linefmt: color of the stem lines
markerfmt: marker to use for the data points
markersize: marker size
Returns
-------
fig: fig object (so you have access to it in the workspace)
ax : ax object (so you have access to it in the workspace)
'''
if fig_size == False:
fig_size = (5,5)
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = fig_size)
markerline, stemlines, baseline = ax.stem(data[:,0], data[:,1],
linefmt = linefmt,
markerfmt = markerfmt)
markerline.set_markerfacecolor('none')
markerline.set_markersize(markersize)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if title:
ax.set_title(title)
plt.show()
return fig, ax
def z2rgb(Z, theme = 'light'):
'''Takes an array of complex numbers (z) and converts
it to an array of [r, g, b]. Before it converts z to hsv (makes
more sense / easier to understand). Phase is encoded in
hue and saturaton/value are given by the absolute value,
depeding if you want zero amplitude to be white or black.
https://en.wikipedia.org/wiki/HSL_and_HSV
Last step is to convert the HSV color into RGB for representation.
Useful for representing complex fields (amplitude and phase) in a single
image
'''
absmax = np.abs(Z).max() #calculate maximum amplitude
Y = np.zeros(Z.shape + (3,), dtype='float') #preallocate rgb image
Y[..., 0] = np.angle(Z) / (2 * np.pi) % 1 #calculate hue (phase)
#choose either 0 amplitude to be dark or bright
if theme == 'light':
#map amplitude to saturation
Y[..., 1] = np.clip(np.abs(Z) / absmax, 0, 1)
Y[..., 2] = 1
elif theme == 'dark':
Y[..., 1] = 1
#map amplitude to value
Y[..., 2] = np.clip(np.abs(Z) / absmax, 0, 1)
#convert HSV colors to RGB
Y = matplotlib.colors.hsv_to_rgb(Y)
return Y
def show_field(Z, mode = 'light'):
'''
show_field plots a complex array (usually a wavefront).
Uses amplitude as hue/value, and phase is encoded in color
Parameters
----------
Z : input field
mode : map minimum amplitude to black or white (light/dark modes)
'''
fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (5,5))
img = z2rgb(Z, theme = mode)
im1 = ax.imshow(img, cmap = 'hsv', aspect = Z.shape[1]/Z.shape[0])
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad = 0.1)
cbar = plt.colorbar(im1, cax = cax, ax = ax, ticks = [0,1])
cbar.ax.set_yticklabels(['0','2$\pi$'])
pass
def nparray2png(im_array):
'''
nparray2png takes a numPy array and converts it to a
grayscale image object. Useful for saving results to images