-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoneParticle_v.a.12.py
1863 lines (1473 loc) · 64 KB
/
oneParticle_v.a.12.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
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.16.1
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# + [markdown] editable=true slideshow={"slide_type": ""}
# # One Particle
# -
# ## Setup
# !python -V
# + editable=true jupyter={"is_executing": true} slideshow={"slide_type": ""}
import matplotlib.pyplot as plt
import numpy as np
from math import *
from uncertainties import *
from scipy.stats import chi2
import scipy
from matplotlib import gridspec
import matplotlib
from matplotlib.colors import ListedColormap
import pandas as pd
import sys
import statsmodels.api as sm
import warnings ## statsmodels.api is too old ... -_-#
import pickle
import pgzip
import os
import platform
import logging
# import sys
from joblib import Parallel, delayed
from tqdm.notebook import tqdm
from datetime import datetime, timedelta
import time
import pyfftw
# %config InlineBackend.figure_format = 'retina'
# %matplotlib inline
plt.rcParams["figure.figsize"] = (8, 5)
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"
plt.close("all") # close all existing matplotlib plots
# +
# from numba import njit, jit, prange, objmode, vectorize
# import numba
# numba.set_num_threads(8)
# -
N_JOBS=7
N_JOB2=5
nthreads=2
import gc
gc.enable()
# +
use_cache = False
save_cache = False
save_debug = True
datetime_init = datetime.now()
# os.makedirs('output/oneParticleSim', exist_ok=True)
output_prefix = "output/oneParticleSim/"+\
datetime_init.strftime("%Y%m%d-%H%M%S") + "-" + \
str("T" if save_debug else "F") + \
str("T" if use_cache else "F") + \
str("T" if save_cache else "F") + \
"/"
output_ext = ".pgz.pkl"
os.makedirs(output_prefix, exist_ok=True)
print(output_prefix)
# -
plt.set_loglevel("warning")
l = logging.getLogger()
l.setLevel(logging.NOTSET)
l_formatter = logging.Formatter('%(asctime)s - %(levelname)s - \n%(message)s')
l_file_handler = logging.FileHandler(f'{output_prefix}/logs.log', encoding='utf-8')
l_file_handler.setFormatter(l_formatter)
l.addHandler(l_file_handler)
l_console_handler = logging.StreamHandler(sys.stdout)
l_console_handler.setLevel(logging.INFO)
l_console_handler.setFormatter(logging.Formatter('%(message)s'))
l.addHandler(l_console_handler)
# if save_debug:
# with open(output_prefix + "session_info.txt", "wt") as file:
s = ""
s += ("="*20 + "Session System Information" + "="*20) + "\n"
uname = platform.uname()
s += f"Python Version: {platform.python_version()}\n"
s += f"Platform: {platform.platform()}\n"
s += (f"System: {uname.system}")+ "\n"
s += (f"Node Name: {uname.node}")+ "\n"
s += (f"Release: {uname.release}")+ "\n"
s += (f"Version: {uname.version}")+ "\n"
s += (f"Machine: {uname.machine}")+ "\n"
s += (f"Processor: {uname.processor}")+ "\n"
s += f"CPU Counts: {os.cpu_count()} \n"
# print(string)
# file.write(string)
# print(string)
l.info(s)
l.info(f"This file is {output_prefix}logs.log")
#
l.info(f"""nthreads = {nthreads}
N_JOBS = {N_JOBS}
N_JOB2 = {N_JOB2}""")
# +
def sizeof_fmt(num, suffix='B'):
''' by Fred Cirera, https://stackoverflow.com/a/1094933/1870254, modified'''
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
def print_ram_usage(items=globals().items(), cutoff=10):
for name, size in sorted(((name, sys.getsizeof(value)) for name, value in list(items))
, key= lambda x: -x[1])[:cutoff]:
print("{:>30}: {:>8}".format(name, sizeof_fmt(size)))
# -
print_ram_usage()
# +
#test 4
# +
# np.show_config()
# +
nx = 1500+1
nz = 1500+1
xmax = 50 #Micrometers
# zmax = (nz/nx)*xmax
zmax = xmax
dt = 1e-4 # Milliseconds
dx = 2*xmax/(nx-1)
dz = 2*zmax/(nz-1)
hb = 63.5078 #("AtomicMassUnit" ("Micrometers")^2)/("Milliseconds")
m3 = 3 # AtomicMassUnit
m4 = 4
pxmax = 2*pi*hb/dx/2
pzmax = 2*pi*hb/dz/2
# pxmax= (nx+1)/2 * 2*pi/(2*xmax)*hb # want this to be greater than p
# pzmax= (nz+1)/2 * 2*pi/(2*zmax)*hb
# -
s = f"""nx = {nx}
nz = {nz}
xmax = {xmax}
zmax = {zmax}
dt = {dt}
dx = {dx}
dz = {dz}
hb = {hb}
m3 = {m3}
m4 = {m4}
pxmax = {pxmax}
pymax = {pzmax}
"""
l.info(s)
# + editable=true slideshow={"slide_type": ""}
l.info(f"""rotate phase per dt for m3 = {1j*hb*dt/(2*m3*dx*dz)} \t #want this to be small
rotate phase per dt for m4 = {1j*hb*dt/(2*m4*dx*dz)}
number of grid points = {round(nx*nz/1000/1000,3)} (million)
minutes per grid op = {round((nx*nz)*0.001*0.001/60, 3)} \t(for 1μs/element_op)
""")
# + editable=true slideshow={"slide_type": ""}
wavelength = 1.083 #Micrometers
beam_angle = 90
k = sin(beam_angle*pi/180/2) * 2*pi / wavelength # effective wavelength
klab = k
#alternatively
# k = pi / (4*dx)
# Nk = 4
# k = pi / (Nk*dx)
# beam_angle = np.arcsin(k/(2*pi/wavelength))*180/pi
kx = 0
kz = k
# print("k =", k, " is 45 degree Bragg")
# k = 2*pi / wavelength
# k = pi / (2*dz)
# k = pi / (4*dx)
# dopd = 60.1025 # 1/ms Doppler detuning (?)
p = hb*k
# print("k =",k,"1/µm")
# print("p =",p, "u*µm/ms")
v4 = 2*hb*k/m4
v3 = 2*hb*k/m3
# print("v3 =",v3, "µm/ms")
# print("v4 =",v4, "µm/ms")
# sanity check
# assert (pxmax > p*2.5 or pzmax > p*2.5), "momentum resolution too small"
# dopd = 60.1025 # 1/ms Doppler detuning (?)
# dopd = v3**2 * m3 / hb
dopd = v4**2 * m4 / hb /2
# -
xmax**2 * m3 * 6 / (hb*pi*(nx-1))
# + editable=true slideshow={"slide_type": ""}
l.info(f"""wavelength = {wavelength} µm
beam_angle = {beam_angle}
k = {k} 1/µm
klab = {klab}
kx = {kx} 1/µm
kz = {kz} 1/µm
p = {p} u*µm/ms
pxmax/p = {pxmax/p}
pzmax/p = {pzmax/p}
2p = {2*p} u*µm/ms
v3 = {v3} µm/ms
v4 = {v4} µm/ms
dopd = {dopd} 1/ms
2*pi/(2*k)/dx = {2*pi/(2*k)/dx} this should be larger than 4 (grids) and bigger the better
""")
if not (pxmax > p*2.5): l.warning(f"p={p} not << pmax={pxmax} momentum resolution too small!")
if not 2*pi/(2*k)/dx > 1: l.warning(f"2*pi/(2*k)/dx = {2*pi/(2*k)/dx} aliasing will happen")
# -
hb*pi*(nx-1) / (2*m3*xmax*6)
# + editable=true slideshow={"slide_type": ""}
l.info(f"""xmax/v3 = {xmax/v3} ms is the time to reach boundary
zmax/v3 = {zmax/v3}
""")
# -
# V00 = 50000
# dt=0.01
# VxExpGrid = np.exp(-(1j/hb) * 0.5*dt * V00 * cosGrid )
dpx = 2*pi/(2*xmax)*hb
dpz = 2*pi/(2*zmax)*hb
pxlin = np.linspace(-pxmax,+pxmax,nx)
pzlin = np.linspace(-pzmax,+pzmax,nz)
# print("(dpx,dpz) = ", (dpx, dpz))
if abs(dpx - (pxlin[1]-pxlin[0])) > 0.0001: l.error("AHHHHH px is messed up (?!)")
if abs(dpz - (pzlin[1]-pzlin[0])) > 0.0001: l.error("AHHHHH pz")
l.info(f"""dpx = {dpx} uµm/m
dpz = {dpz} """)
# + editable=true slideshow={"slide_type": ""}
# +
#### WARNING:
### These frequencies are in Hz,
#### This simulation uses time in ms, 1Hz = 0.001 /ms
a4 = 0.007512 # scattering length µm
intensity1 = 1 # mW/mm^2 of beam 1
intensity2 = intensity1
intenSat = 0.0017 # mW/mm^2
linewidth = 2*pi*1.6e6 # rad * Hz
omega1 = linewidth * sqrt(intensity1/intenSat/2)
omega2 = linewidth * sqrt(intensity2/intenSat/2)
detuning = 2*pi*3e9 # rad*Hz
omegaRabi = omega1*omega2/2/detuning # rad/s
VR = 2*hb*(omegaRabi*0.001) # Bragg lattice amplitude # USE THIS ONE!
omega = 50 # two photon Rabi frequency # https://doi.org/10.1038/s41598-020-78859-1
V0 = 2*hb*omega # Bragg lattice amplitude
# tBraggPi = np.sqrt(2*pi*hb)/V0
tBraggPi = 2*pi/omegaRabi*1000
tBraggCenter = tBraggPi * 5
tBraggEnd = tBraggPi * 10
V0F = 50*1000
# + editable=true slideshow={"slide_type": ""}
l.info(f"""a4 = {a4} µm
intensity1 = {intensity1} # mW/mm^2 of beam 1
intensity2 = {intensity2}
intenSat = {intenSat} # mW/mm^2 Saturation intensity
linewidth = {linewidth/1e6} # rad * MHz
omega1 = {omega1/1e6} # rad * MHz
omega2 = {omega2/1e6}
detuning = {detuning/1e6} # rad * MHz
omegaRabi = {omegaRabi/1e6} # rad * MHz
omega = {omega}
VR = {VR}
V0 = {V0}
V0F = {V0F}
tBraggPi = {tBraggPi} ms
tBraggCenter = {tBraggCenter} ms
tBraggEnd = {tBraggEnd} ms
""")
# -
l.info(f"""hb*k**2/(2*m3) = {hb*k**2/(2*m3)} \t/ms
hb*k**2/(2*m4) = {hb*k**2/(2*m4)}
(hb*k**2/(2*m3))**-1 = {(hb*k**2/(2*m3))**-1} \tms
(hb*k**2/(2*m4))**-1 = {(hb*k**2/(2*m4))**-1}
2*pi*hb*k**2/(2*m3) = {2*pi*hb*k**2/(2*m3)} \t rad/ms
2*pi*hb*k**2/(2*m4) = {2*pi*hb*k**2/(2*m4)}
omegaRabi = {omegaRabi*0.001} \t/ms
tBraggPi = {tBraggPi} ms
""")
# + editable=true slideshow={"slide_type": ""}
def V(t):
return V0 * (2*pi)**-0.5 * tBraggPi**-1 * np.exp(-0.5*(t-tBraggCenter)**2 * tBraggPi**-2)
def VB(t, tauMid, tauPi):
return V0 * (2*pi)**-0.5 * tauPi**-1 * np.exp(-0.5*(t-tauMid)**2 * tauPi**-2)
V0F = 50*1000
def VBF(t, tauMid, tauPi, V0FArg=V0F):
return V0FArg * (2*pi)**-0.5 * np.exp(-0.5*(t-tauMid)**2 * tauPi**-2)
# + editable=true slideshow={"slide_type": ""}
l.info(f"term infront of Bragg potential {1j*(dt/hb)}")
l.info(f"max(V) {1j*(dt/hb)*V(tBraggCenter)}")
# -
# @njit(cache=True)
def VS(ttt, mid, wid, V0=VR):
return V0 * 0.5 * (1 + np.cos(2*np.pi/wid*(ttt-mid))) * \
(-0.5*wid+mid<ttt) * (ttt<0.5*wid+mid)
tbtest = np.arange(tBraggCenter-5*tBraggPi,tBraggCenter+5*tBraggPi,dt)
plt.plot(tbtest, VBF(tbtest,tBraggPi*5,tBraggPi))
plt.plot(tbtest, VS(tbtest,tBraggPi/2,tBraggPi,0.3*V0F))
plt.plot(tbtest, VS(tbtest,tBraggPi/2+0.4,tBraggPi,0.3*VR))
plt.show()
l.info(f"max(V) {1j*(dt/hb)*VBF(tBraggCenter,tBraggPi*5,tBraggPi)}")
tBraggPi
# + editable=true slideshow={"slide_type": ""}
V(tBraggCenter)
# -
VBF(tBraggCenter,tBraggPi*5,tBraggPi)
np.trapz(V(tbtest),tbtest) # this should be V0
xlin = np.linspace(-xmax,+xmax, nx)
zlin = np.linspace(-zmax,+zmax, nz)
psi=np.zeros((nx,nz),dtype=complex)
zones = np.ones(nz)
xgrid = np.tensordot(xlin,zones,axes=0)
# cosGrid = np.cos(2*k*xgrid)
cosGrid = np.cos(2 * kx * xlin[:, np.newaxis] + 2 * kz * zlin)
l.info(f"""2*kz*dx = {2*kz*dx}
dopd*dt {dopd*dt}""")
plt.plot(zlin, np.cos(2*kz*zlin))
plt.plot(zlin, np.cos(2*kz*zlin + dopd*dt*1))
plt.plot(zlin, np.cos(2*kz*zlin + dopd*dt*2))
plt.plot(zlin, np.cos(2*kz*zlin + dopd*dt*3))
plt.xlim(-1,1)
plt.show()
if abs(dx - (xlin[1]-xlin[0])) > 0.0001: l.error("AHHHHx")
if abs(dz - (zlin[1]-zlin[0])) > 0.0001: l.error("AHHHHz")
# + editable=true slideshow={"slide_type": ""}
l.info(f"{round(psi.nbytes/1000/1000 ,3)} MB of data used to store psi")
# + editable=true slideshow={"slide_type": ""}
ncrop = 30
plt.figure(figsize=(10,10))
plt.subplot(2,2,1)
plt.imshow(cosGrid.T,aspect=1)
plt.title("bragg potential grid smooth?")
plt.subplot(2,2,2)
plt.imshow(cosGrid[:ncrop,:ncrop].T,aspect=1)
plt.title("grid zoomed in")
plt.subplot(2,2,3)
plt.plot(cosGrid[0,:],alpha=0.9,linewidth=0.1)
plt.subplot(2,2,4)
plt.plot(xlin[:ncrop],cosGrid[0,:ncrop],alpha=0.9,linewidth=0.5)
plt.plot(xlin[:ncrop],cosGrid[0,1:ncrop+1],alpha=0.9,linewidth=0.5)
plt.plot(xlin[:ncrop],cosGrid[0,10:ncrop+10],alpha=0.9,linewidth=0.5)
title="bragg_potential_grid"
# plt.savefig("output/"+title+".pdf", dpi=600)
# plt.savefig("output/"+title+".png", dpi=600)
plt.show()
# + editable=true slideshow={"slide_type": ""}
dopd*dt/dx
# + editable=true slideshow={"slide_type": ""}
def plot_psi(psi, plt_show=True):
"""Plots $\psi$ of position wavefunction
Args:
psi (ndarray 2d): wavefunction dtype=complex
"""
plt.figure(figsize=(12, 4))
extent = np.array([-xmax, +xmax, -zmax, +zmax])
plt.subplot(1, 3, 1)
plt.imshow(np.flipud(np.abs(psi.T)**2), extent=extent, interpolation='none')
plt.ylabel("$z$ (µm)")
plt.xlabel("$x$ (µm)")
plt.title("Position $|\psi|^2$")
plt.subplot(1, 3, 2)
plt.imshow(np.flipud(np.real(psi.T)), extent=extent, interpolation='none')
plt.xlabel("$x$ (µm)")
plt.title("$\mathrm{Re}(\psi)$")
plt.subplot(1, 3, 3)
plt.imshow(np.flipud(np.imag(psi.T)), extent=extent, interpolation='none')
plt.xlabel("$x$ (µm)")
plt.title("$\mathrm{Im}(\psi)$")
if plt_show: plt.show()
# +
def plot_mom(psi, zoom_div2=15, zoom_div3=6, plt_show=True):
"""Plots momentum wavefunction
Args:
psi (ndarray 2d): complex position wavefunction
"""
plt.figure(figsize=(12,3))
pspace = np.fft.fftfreq(nx)
extent = np.array([-pxmax,+pxmax,-pzmax,+pzmax])/(hb*k)
# psifft = np.fft.fftshift(np.fft.fft2(psi))
psifft = np.fliplr(np.fft.fftshift(pyfftw.interfaces.numpy_fft.fft2(psi,threads=nthreads,norm='ortho')))
psiAbsSqUnNorm = np.abs(psifft)**2
swnf = sqrt(np.sum(psiAbsSqUnNorm)*dpx*dpz)
psiAbsSq = psiAbsSqUnNorm / swnf
# print(np.sum(psiAbsSq)*dpx*dpz)
# plotdata = np.flipud(psiAbsSq.T)
plotdata = (psiAbsSq.T)
plt.subplot(1,3,1)
plt.imshow(plotdata,extent=extent, interpolation='none')
plt.ylabel("$p_z \ (\hbar k)$")
plt.xlabel("$p_x \ (\hbar k)$")
plt.title("Momentum $|\phi|^2$")
plt.subplot(1,3,2)
nxm = int((nx-1)/2)
nzm = int((nz-1)/2)
nx2 = int((nx-1)/zoom_div2)
nz2 = int((nz-1)/zoom_div2)
plotdata = (psiAbsSq[nxm-nx2:nxm+nx2,nzm-nz2:nzm+nz2].T)
plt.imshow(plotdata,
extent=np.array([pxlin[nxm-nx2],pxlin[nxm+nx2],pzlin[nzm-nz2],pzlin[nzm+nz2]])/(hb*k),
interpolation='none')
plt.xlabel("$p_x \ (\hbar k)$")
plt.title("zoomed in")
plt.subplot(1,3,3)
# nx3 = int((nx-1)/200)
# nz3 = int((nz-1)/200)
# plotdata = np.flipud(psiAbsSq[nxm-nx3:nxm+nx3,nzm-nz3:nzm+nz3].T)
# plt.imshow(plotdata,extent=extent*0.01)
# # print(nx2,nz2,nx3,nz3)
# nxm = int((nx-1)/2)
# nzm = int((nz-1)/2)
nx2 = int((nx-1)/zoom_div3)
# nz2 = int((nz-1)/zoom_div3)
plt.plot((pxlin[nxm-nx2:nxm+nx2])/(hb*k), np.trapz(psiAbsSq,axis=1)[nxm-nx2:nxm+nx2])
plt.axvline(x= 0,color='r',alpha=0.2)
plt.axvline(x=+2,color='r',alpha=0.2)
plt.axvline(x=-2,color='r',alpha=0.2)
# plt.axvline(x=+4,color='r',alpha=0.2)
# plt.axvline(x=-4,color='r',alpha=0.2)
# plt.xlabel("$p (u\cdot \mu m/ms)$")
# plt.ylabel("$|\phi(p)|^2$")
plt.xlabel("$p_x \ (\hbar k)$")
plt.title("integrated over $p_z$")
# plt.savefig("output/"+title+".pdf", dpi = 300)
# plt.savefig("output/"+title+".png", dpi = 300)
# plt.show()
if plt_show: plt.show()
# +
sg=0.2
def psi0(x,z,sx=sg,sz=sg,px=0,pz=0):
return (1/np.sqrt(pi*sx*sz)) \
* np.exp(-0.5*x**2/sx**2) \
* np.exp(-0.5*z**2/sz**2) \
* np.exp(+(1j/hb)*(px*x + pz*z))
def psi0ringUnNorm(x,z,pr=p,mur=10,sg=sg):
# return (pi**1.5 * sg * (1 + scipy.special.erf(mur/sg)))**-1 \
return 1 \
* np.exp(-0.5*( mur - np.sqrt(x**2 + z**2) )**2 / sg**2) \
* np.exp(+(1j/hb) * (x**2 + z**2)**0.5 * pr)
# -
expPGrid = np.zeros((nx,nz),dtype=complex)
for indx in range(nx):
expPGrid[indx, :] = np.exp(-(1j/hb) * (0.5/m3) * (dt) * (pxlin[indx]**2 + pzlin**2))
def psi0np(mux=10,muz=10,p0x=0,p0z=0):
psi=np.zeros((nx,nz),dtype=complex)
for ix in range(1,nx-1):
x = xlin[ix]
psi[ix][1:-1] = psi0(x,zlin[1:-1],mux,muz,p0x,p0z)
return psi
def psi0ringNp(mur=1,sg=1,pr=p):
psi = np.zeros((nx,nz),dtype=complex)
for ix in range(1,nx-1):
x = xlin[ix]
psi[ix][1:-1] = psi0ringUnNorm(x,zlin[1:-1],pr,mur,sg)
norm = np.sum(np.abs(psi)**2)*dx*dz
psi *= 1/sqrt(norm)
return psi
# + editable=true slideshow={"slide_type": ""}
def psi0ringUnNormOffset(x,z,pr=p,mur=10,sg=sg,xo=0,zo=0,pxo=0,pzo=0):
return 1 \
* np.exp(-0.5*( mur - np.sqrt((x-xo)**2 + (z-zo)**2) )**2 / sg**2) \
* np.exp(+(1j/hb) * (((x-xo)**2 + (z-zo)**2)**0.5 * pr + x*pxo+z*pzo))
def psi0ringNpOffset(mur=1,sg=1,pr=p,xo=0,zo=0,pxo=0,pzo=0):
psi = np.zeros((nx,nz),dtype=np.complex128)
for ix in range(0,nx):
x = xlin[ix]
psi[ix,:] = psi0ringUnNormOffset(x,zlin,pr,mur,sg,xo,zo,pxo,pzo)
norm = np.sum(np.abs(psi)**2)*dx*dz
psi *= 1/sqrt(norm)
return psi
# -
# + editable=true slideshow={"slide_type": ""}
# + editable=true slideshow={"slide_type": ""}
# psi = psi0np(5,5,0,0)
# psi = psi0np(5,5,-0.5*p,0)
# psi = psi0np(1,1,p,p)
# psi = psi0np(1,1,0,0)
# @jit(cache=True, forceobj=True)
def phiAndSWNF(psi):
phiUN = np.fliplr(np.fft.fftshift(pyfftw.interfaces.numpy_fft.fft2(psi,threads=nthreads,norm='ortho')))
# superWeirdNormalisationFactorSq = np.trapz(np.trapz(np.abs(phiUN)**2, pxlin, axis=0), pzlin)
superWeirdNormalisationFactorSq = np.sum(np.abs(phiUN)**2)*dpx*dpz
swnf = sqrt(superWeirdNormalisationFactorSq)
phi = phiUN/swnf
return (swnf, phi)
# psi = psi0ringNp(4,2,p)
# psi = psi0ringNpOffset(5,3,p,0,5,0,p)
# psi = psi0np(2,2,0.5*p*np.cos(0),0.5*p*np.sin(0))
# psi = psi0np(mux=3,muz=3,p0x=0,p0z=0)
# psi = psi0ringNpOffset(5,3,p,0,5,0,p)
psi = psi0ringNpOffset(10,3,p,0,20,0,p)
(swnf, phi) = phiAndSWNF(psi)
t = 0
print("Super weird normalisation factor, swnf =",swnf)
print(np.sum(np.abs(phi)**2)*dpx*dpz, "|phi|**2 normalisation check")
print(np.sum(np.abs(psi)**2)*dx*dz, "|psi|**2 normalisation check")
plot_psi(psi,False)
title="init_ring_psi"
# plt.savefig("output/"+title+".pdf", dpi=600)
# plt.savefig("output/"+title+".png", dpi=600)
plt.show()
plot_mom(psi,10,10,False)
title="init_ring_phi"
# plt.savefig("output/"+title+".pdf", dpi=600)
# plt.savefig("output/"+title+".png", dpi=600)
plt.show()
# -
5/v4
v4*0.2
# + editable=true slideshow={"slide_type": ""}
# @jit(cache=True, forceobj=True)
def toMomentum(psi, swnf):
return np.fliplr(np.fft.fftshift(pyfftw.interfaces.numpy_fft.fft2(psi,threads=nthreads,norm='ortho')))/swnf
# @jit(cache=True, forceobj=True)
def toPosition(phi, swnf):
return pyfftw.interfaces.numpy_fft.ifft2(np.fft.ifftshift(np.fliplr(phi*swnf)),threads=nthreads,norm='ortho')
# + editable=true slideshow={"slide_type": ""}
def plotNow(t, psi):
print("time =", round(t*1000,4), "µs")
print(np.sum(np.abs(psi)**2)*dx*dz,"|psi|^2")
print(np.sum(np.abs(phi)**2)*dpx*dpz,"|phi|^2")
plot_psi(psi)
plot_mom(psi)
# @jit(forceobj=True, cache=True)
def numericalEvolve(
t_init,
psi_init,
t_final,
tauPi = tBraggPi,
tauMid = tBraggPi*5,
phase = 0,
doppd=dopd,
print_every_t=-1,
final_plot=True,
progress_bar=True,
V0FArg=V0F,
kkx=kx,
kkz=kz
):
assert (print_every_t > dt or print_every_t <= 0), "print_every_t cannot be smaller than dt"
steps = ceil((t_final - t_init) / dt)
t = t_init
psi = psi_init.copy()
(swnf, phi) = phiAndSWNF(psi)
# tauMid = tauPi * 5
# tauEnd = tauPi * 10
def loop():
nonlocal t
nonlocal psi
nonlocal phi
# cosGrid = np.cos(2*k*xgrid + doppd*(t-tBraggCenter) + phase)
cosGrid = np.cos(2*kkx*xlin[:,np.newaxis] + 2*kkz*zlin + doppd*(t-tauMid) + phase)
VxExpGrid = np.exp(-(1j/hb) * 0.5*dt * VS(t,tauMid,tauPi,V0FArg) * cosGrid )
# VxExpGrid = np.exp(-(1j/hb) * 0.5*dt * V0FArg *
# np.cos(2*kkx*xlin[:,np.newaxis] + 2*kkz*zlin + doppd*(t-tauMid) + phase))
psi *= VxExpGrid
phi = toMomentum(psi,swnf)
phi *= expPGrid
psi = toPosition(phi,swnf)
psi *= VxExpGrid
if print_every_t > 0 and step % round(print_every_t / dt) == 0:
plotNow(t,psi)
t += dt
if progress_bar:
for step in tqdm(range(steps)):
loop()
else:
for step in range(steps):
loop()
if final_plot:
print("ALL DONE")
plotNow(t,psi)
return (t,psi,phi)
# -
# %timeit _ = numericalEvolve(0, psi0np(1,1,0,0), dt, final_plot=False, progress_bar=False)
# + active=""
# # @njit
# # @jit(cache=True, forceobj=True)
# def numericalEvolveNumba(
# t_init = 0,
# psi_init = np.array([]),
# t_final =0,
# tauPi = tBraggPi,
# tauMid = tBraggPi*5,
# phase = 0,
# doppd=dopd,
# print_every_t=-1,
# final_plot=True,
# progress_bar=True,
# V0FArg=V0F,
# kkx=kx,
# kkz=kz
# ):
# assert (print_every_t > dt or print_every_t <= 0), "print_every_t cannot be smaller than dt"
# steps = ceil((t_final - t_init) / dt)
# t = t_init
# psi = psi_init.copy()
# (swnf, phi) = phiAndSWNF(psi)
#
# for step in range(steps):
# # cosGrid = np.cos(2*kkx*xlin[:,np.newaxis] + 2*kkz*zlin + doppd*(t-tauMid) + phase)
# VxExpGrid = np.exp(-(1j/hb) * 0.5*dt * VS(t,tauMid,tauPi,V0FArg) *
# np.cos(2*kkx*xlin[:,np.newaxis] + 2*kkz*zlin + doppd*(t-tauMid) + phase))
# # VxExpGrid = np.exp(-(1j/hb) * 0.5*dt * V0FArg *
# # np.cos(2*kkx*xlin[:,np.newaxis] + 2*kkz*zlin + doppd*(t-tauMid) + phase))
# psi *= VxExpGrid
# phi = toMomentum(psi,swnf)
# phi *= expPGrid
# psi = toPosition(phi,swnf)
# psi *= VxExpGrid
#
# return (t,psi,phi)
# + active=""
# %timeit _ = numericalEvolveNumba(0, psi0np(1,1,0,0), dt, final_plot=False, progress_bar=False)
# -
def freeEvolve(
t_init,
psi,
t_final,
final_plot=True,
logging=False,
):
Dt = t_final-t_init
(swnf, phi) = phiAndSWNF(psi)
if logging: print("checking this value is small ", -(1j/hb) * (0.5/m3) * (Dt)*pxmax)
expPGridLong = np.zeros((nx,nz),dtype=complex)
for indx in range(nx):
expPGridLong[indx, :] = np.exp(-(1j/hb) * (0.5/m3) * (Dt) * (pxlin[indx]**2 + pzlin**2))
phi *= expPGridLong
psi = toPosition(phi,swnf)
if final_plot:
plotNow(t_final,psi)
return (t_final, psi, phi)
_ = freeEvolve(0,psi0np(1,1,0,0),0.1,final_plot=False,logging=True)
(tBraggCenter,tBraggEnd,tBraggPi)
# ## Pulse Scan Test Run
# short test run
_ = numericalEvolve(0, psi0np(3,3,0.5*p,0), 2*dt,progress_bar=False,final_plot=False)
# + editable=true slideshow={"slide_type": ""}
def scanTauPiInnerEval(tPi,
logging=True, progress_bar=True,
ang=0, pmom=p, doppd=dopd, V0FArg=V0F, kkx=kx, kkz=kz,
halo_xr=10
):
tauPi = tPi
tauMid = tauPi / 2
tauEnd = tauPi
if logging:
print("Testing parameters")
print("tauPi =", round(tPi,6), " \t tauMid =", round(tauMid,6), " \t tauEnd = ", round(tauEnd,6))
# output = numericalEvolve(0, psi0np(2,2,pmom*np.cos(ang),pmom*np.sin(ang)),
output = numericalEvolve(0,
# psi0np(mux=3,muz=3,p0x=0,p0z=0),
# psi0ringNpOffset(5,3,pmom,0,5,0,pmom),
psi0ringNpOffset(halo_xr,3,pmom,0,halo_xr,0,pmom),
tauEnd, tauPi, tauMid, doppd=doppd,
final_plot=logging,progress_bar=progress_bar,
V0FArg=V0FArg,kkx=kkx,kkz=kkz
)
# if pbar != None: pbar.update(1)
gc.collect()
return output
# -
tPiScanTime1usStart = datetime.now()
_ = scanTauPiInnerEval(0.001, False, True,0,p,0*dopd,VR)
tPiScanTime1usEnd = datetime.now()
tPiScanTime1usDelta = tPiScanTime1usEnd - tPiScanTime1usStart
l.info(f"""Time to simulate 1us: {tPiScanTime1usDelta}""")
# +
tPDelta = 2*dt # positive +, note I want tPiTest in decending order
# tPiTest = np.append(np.arange(0.5,0.1,-tPDelta), 0) # note this is decending
tPiTest = np.arange(0.03,0.0006-tPDelta,-tPDelta)
# tPiTest = np.arange(dt,3*dt,dt)
l.info(f"#tPiTest = {len(tPiTest)}, max={tPiTest[0]*1000}, min={tPiTest[-1]*1000} us")
l.info(f"tPiTest: {tPiTest}")
plt.figure(figsize=(12,5))
def plot_inner_helper():
tPiScanTotalSimUS = 0
for (i, tauPi) in enumerate(tPiTest):
if tauPi == 0: continue
tauMid = tauPi / 2
tauEnd = tauPi * 1
tPiScanTotalSimUS += tauEnd
tlinspace = np.arange(0,tauEnd,dt)
# plt.plot(tlinspace, VBF(tlinspace, tauMid, tauPi),
# linewidth=0.5,alpha=0.9
# )
plt.plot(tlinspace, VS(tlinspace, tauMid, tauPi),
linewidth=0.5,alpha=0.9
)
return tPiScanTotalSimUS
plt.subplot(2,1,1)
tPiScanTotalSimUS = plot_inner_helper()
plt.ylabel("$V(t)$")
plt.subplot(2,1,2)
plot_inner_helper()
plt.xlim([0,0.002])
plt.xlabel("$t \ (ms)$ ")
plt.ylabel("$V(t)$")
title="bragg_strength_V0"
# plt.savefig("output/"+title+".pdf", dpi=600)
# plt.savefig("output/"+title+".png", dpi=600)
# -
l.info(f"roughtly can finish in {round((tPiScanTime1usDelta*tPiScanTotalSimUS*1000).total_seconds()/3600, 3)} hours")
l.info(f"""psi size is {round(sys.getsizeof(psi)/1024**2,3)} MB
need {round(sys.getsizeof(psi)/1024**3 * len(tPiTest),3)} GB RAM to tPiOutput""")
0.25*dopd
# + editable=true slideshow={"slide_type": ""}
tPiScanTimeStart = datetime.now()
tPiOutput = Parallel(n_jobs=N_JOB2)(
delayed(lambda i: (i, scanTauPiInnerEval(i, False, False,0,p,0.5*dopd,VR)[:2]) )(i)
for i in tqdm(tPiTest)
)
tPiScanTimeEnd = datetime.now()
tPiScanTimeDelta = tPiScanTimeEnd-tPiScanTimeStart
l.info(f"""Time to run one scan: {tPiScanTimeDelta}""")
# -
os.makedirs(output_prefix+"tPiScan", exist_ok=True)
with pgzip.open(output_prefix+"tPiScan/"+f"tPiOutput"+output_ext,'wb', thread=4, blocksize=2*10**8) as file:
pickle.dump(tPiOutput, file)
gc.collect()
tPiOutput[70][0]
tPiOutput[10][1][0]
tPiTest[10]
tPiTest[10]
# + editable=true slideshow={"slide_type": ""}
# psi = tPiOutput[-30][1][1]
ind = 80
psi = tPiOutput[ind][1][1]
print(round(tPiOutput[ind][0]*1000, 3))
# psi = tPiTestRun[1]L
# psi = testFreeEv1[1]
# plot_psi(psi)
(swnf, phi) = phiAndSWNF(psi)
plot_mom(psi,8,8)
# + editable=true slideshow={"slide_type": ""}
# + editable=true slideshow={"slide_type": ""}
# hbar_k_transfers = np.arange(-4,4+1,+2)
hbar_k_transfers = np.arange(-10-1,10+2,+2)
# pzlinIndexSet = np.zeros((len(hbar_k_transfers), len(pxlin)), dtype=bool)
pxlinIndexSet = np.zeros((len(hbar_k_transfers), len(pzlin)), dtype=bool)
cut_p_width = 5*dpz/p
for (j, hbar_k) in enumerate(hbar_k_transfers):
# pzlinIndexSet[j] = abs(pxlin/(hb*k) - hbar_k) <= cut_p_width
pxlinIndexSet[j] = abs(pzlin/p + hbar_k) <= cut_p_width
# print(i,hbar_k)
l.info(f"""hbar_k_transfers = {hbar_k_transfers}
np.sum(pxlinIndexSet,axis=1) = {np.sum(pxlinIndexSet,axis=1)}""")
# + editable=true slideshow={"slide_type": ""}
plt.figure(figsize=(4,4))
plt.imshow(pxlinIndexSet.T,interpolation='none',aspect=0.1,extent=[-2,2,-pzmax/p,pzmax/p])
# plt.imshow(pzlinIndexSet,interpolation='none',aspect=5)
# plt.axvline(x=1001, linewidth=1, alpha=0.7)
title="hbar_k_pxlin_integration_range"
# plt.savefig("output/"+title+".pdf", dpi=600)
# plt.savefig("output/"+title+".png", dpi=600)
plt.show()
# + editable=true slideshow={"slide_type": ""}
# phiDensityGrid = np.zeros((len(tPiTest), pxlin.size))
phiDensityGrid = np.zeros((len(tPiTest), pzlin.size))
phiDensityGrid_hbark = np.zeros((len(tPiTest),len(hbar_k_transfers)))
for i in tqdm(range(len(tPiTest))):
item = tPiOutput[i]
(swnf, phi) = phiAndSWNF(item[1][1])
phiAbsSq = np.abs(phi)**2
# phiX = np.trapz(phiAbsSq, pzlin,axis=1)
phiZ = np.trapz(phiAbsSq, pzlin,axis=0)
# phiDensityGrid[i] = phiX
phiDensityGrid[i] = phiZ
for (j, hbar_k) in enumerate(hbar_k_transfers):
# index = pzlinIndexSet[j]
index = pxlinIndexSet[j]
# phiDensityGrid_hbark[i,j] = np.trapz(phiX[index], pxlin[index])
# phiDensityGrid_hbark[i,j] = np.trapz(phiZ[index], pzlin[index])
phiDensityGrid_hbark[i,j] = np.sum(phiZ[index])
# + editable=true slideshow={"slide_type": ""}
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
nxm = int((nx-1)/2)
nx2 = int((nx-1)/2)
mom_dist_at_diff_angle_phi_asss=(2*pxmax/p)/len(tPiOutput)
mom_dist_at_diff_angle_den_asss=(hbar_k_transfers[-1]-hbar_k_transfers[0])/len(tPiOutput)
plt.imshow(#phiDensityGrid[:,nxm-nx2:nxm+nx2],
phiDensityGrid,
# extent=[pxlin[nxm-nx2]/(hb*k),pxlin[nxm+nx2]/(hb*k),0,len(tPiTest)],
extent=[pzlin[nxm-nx2]/(hb*k),pzlin[nxm+nx2]/(hb*k),0,len(tPiTest)],
interpolation='none',aspect=mom_dist_at_diff_angle_phi_asss)
# plt.imshow(phiDensityGrid,
# extent=[-pxmax/(hb*k),pxmax/(hb*k),1,len(tPiTest)+1],
# interpolation='none',aspect=1)
# ax = plt.gca()
# for t in tPiTest:
# plt.axhline(y=t/dt,color='white',alpha=1,linewidth=0.05,linestyle='-')
ax = plt.gca()
ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))
plt.ylabel("$dt =$"+str(dt*1000) + "$\mu \mathrm{s}$")
# plt.xlabel("$p_x \ (\hbar k)$")
plt.xlabel("$p_z \ (\hbar k)$")
plt.subplot(1,2,2)
plt.imshow(phiDensityGrid_hbark,
extent=[hbar_k_transfers[0],hbar_k_transfers[-1],0,len(tPiTest)],
interpolation='none',aspect=mom_dist_at_diff_angle_den_asss)
# plt.xlabel("$p_x \ (\hbar k)$ integrated block")
plt.xlabel("$p_z \ (\hbar k)$ integrated block")
title="mom_dist_at_diff_angle"
plt.savefig("output/"+title+".pdf", dpi=600)
plt.savefig("output/"+title+".png", dpi=600)