-
Notifications
You must be signed in to change notification settings - Fork 0
/
microscope.py
2455 lines (2175 loc) · 90.8 KB
/
microscope.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
# %%
import numpy as np
from numpy import pi
from scipy.special import jv
import matplotlib.pyplot as plt
from typing import Optional, Union, List, Tuple, Callable
from warnings import warn
from dataclasses import dataclass
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os.path
from scipy import integrate
from matplotlib.widgets import Slider
import re
from hashlib import md5
import mrcfile as mrc
import pandas as pd
from numba import njit, prange
from tqdm import tqdm
M_ELECTRON = 9.1093837e-31
C_LIGHT = 299792458
H_BAR = 1.054571817e-34
E_CHARGE = 1.602176634e-19
EPSILON_ELECTRICITY = 8.8541878128e-12
FINE_STRUCTURE_CONST = E_CHARGE**2 / (
4 * np.pi * EPSILON_ELECTRICITY * H_BAR * C_LIGHT
)
np.seterr(all="raise")
try:
PHASE_MASKS_DF = pd.read_csv(
r"data/phase masks/phase_masks.csv",
index_col=False,
dtype={"ring_cavity": bool},
)
except FileNotFoundError:
PHASE_MASKS_DF = pd.DataFrame(
columns=[
"file_path",
"n_frequencies",
"method",
"lambda_laser_1_nm",
"lambda_laser_2_nm",
"power_1",
"power_2",
"NA_1",
"NA_2",
"alpha_tilt_rads",
"theta_polarization_rads",
"E_0_electron_keV",
"ring_cavity",
"Nx",
"Ny",
"N_t",
"N_z",
"DX",
"DY",
"time_calculated",
]
)
def l_of_E(E: float) -> float:
return 2 * pi / k_of_E(E)
def V_of_E(E: float) -> float:
return E / E_CHARGE
def E_of_V(V: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
return V * E_CHARGE
def k_of_E(E):
return E / (C_LIGHT * H_BAR) * np.sqrt(1 + 2 * M_ELECTRON * C_LIGHT**2 / E)
def beta_of_k(k: float) -> float:
return beta_of_p(k * H_BAR)
def k_of_beta(beta: float) -> float:
return p_of_beta(beta) / H_BAR
def beta_of_E(E: float) -> float:
return beta_of_k(k_of_E(E))
def k_of_V(V0: float, V: Optional[np.ndarray] = None) -> Union[float, np.ndarray]:
if V is None:
V = 0
E = E_of_V(V0 + V)
return k_of_E(E)
def l_of_k(k: float) -> float:
return 2 * pi / k
def k_of_l(lambda_laser: float) -> float:
return 2 * pi / lambda_laser
def w_of_k(k: float, n=1) -> float:
return C_LIGHT * k / n
def k_of_w(w: float, n=1) -> float:
return n * w / C_LIGHT
def w_of_l(lambda_laser: float) -> float:
return w_of_k(k_of_l(lambda_laser))
def l_of_w(w: float) -> float:
return l_of_k(k_of_w(w))
def beta_of_p(p: float) -> float:
return p / (np.sqrt(C_LIGHT**2 * M_ELECTRON**2 + p**2))
def p_of_beta(beta: float) -> float:
return M_ELECTRON * C_LIGHT * beta * np.sqrt(1 - beta**2)
def gamma_of_beta(beta: float) -> float:
return 1 / np.sqrt(1 - beta**2)
def beta_of_gamma(gamma: float) -> float:
return np.sqrt(1 - 1 / gamma**2)
def beta_of_lambdas(l1: float, l2: float):
return (1 - l1 / l2) / (1 + l1 / l2)
def Joules_of_keV(keV: float) -> float:
return keV * 1.602176634e-16
def keV_of_Joules(J: float) -> float:
return J / 1.602176634e-16
def x_R_gaussian(w0: float, lambda_laser: float) -> float:
# l is the wavelength of the laser
return pi * w0**2 / lambda_laser
def w0_of_NA(NA: float, lambda_laser: float) -> float:
return lambda_laser / (np.pi * NA)
def NA_of_w0(w0: float, lambda_laser: float) -> float:
return lambda_laser / (np.pi * w0)
def w_x_gaussian(
w_0: float,
x: Union[float, np.ndarray],
x_R: Optional[float] = None,
l_laser: Optional[float] = None,
):
# l is the wavelength of the laser
if x_R is None:
x_R = x_R_gaussian(w_0, l_laser)
return w_0 * np.sqrt(1 + (x / x_R) ** 2)
def gouy_phase_gaussian(
x: Union[float, np.ndarray],
x_R: Optional[float] = None,
w_0: Optional[float] = None,
l_laser: Optional[float] = None,
):
# l is the wavelength of the laser
if x_R is None:
x_R = x_R_gaussian(w_0, l_laser)
return np.arctan(x / x_R)
def R_x_inverse_gaussian(x, x_R=None, l_laser=None, w_0=None):
if x_R is None:
x_R = x_R_gaussian(w_0, l_laser)
return x / (x**2 + x_R**2)
def manipulate_plot(
imdata_callable: Callable,
values: Tuple[Tuple[float, float, float], ...],
labels: Optional[Tuple[str, ...]] = None,
):
# from matplotlib import use
# use('TkAgg')
N_params = len(values)
if labels is None:
labels = [f"param{i}" for i in range(N_params)]
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=N_params * 0.04 + 0.15)
initial_data = imdata_callable(*[v[0] for v in values])
if initial_data.ndim == 2:
img = plt.imshow(initial_data)
elif initial_data.ndim == 1:
(img,) = plt.plot(initial_data)
else:
raise ValueError("imdata_callable must return 1 or 2 dimensional data")
# axcolor = 'lightgoldenrodyellow'
sliders_axes = [
plt.axes([0.25, 0.04 * (i + 1), 0.65, 0.03], facecolor=(0.97, 0.97, 0.97))
for i in range(N_params)
]
sliders = [
Slider(
ax=sliders_axes[i],
label=labels[i],
valmin=values[i][0],
valmax=values[i][1],
valinit=values[i][0],
valstep=values[i][2],
)
for i in range(N_params)
]
def update(val):
values = [slider.val for slider in sliders]
if initial_data.ndim == 2:
img.set_data(imdata_callable(*values))
else:
img.set_ydata(imdata_callable(*values))
fig.canvas.draw_idle()
for slider in sliders:
slider.on_changed(update)
if initial_data.ndim == 2:
plt.colorbar(ax=ax)
plt.show()
def safe_exponent(a: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
return np.exp(np.clip(a=a, a_min=-200, a_max=None)) # ARBITRARY
def safe_abs_square(a: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
return np.clip(a=np.abs(a), a_min=1e-500, a_max=None) ** 2 # ARBITRARY
def signif(x, p=4):
if pd.isna(x):
return x
else:
x_array = np.asarray(x)
x_positive = np.where(
np.isfinite(x_array) & (x_array != 0), np.abs(x_array), 10 ** (p - 1)
)
mags = 10 ** (p - 1 - np.floor(np.log10(x_positive)))
return np.round(x_array * mags) / mags
@njit(parallel=True)
def gaussian_beam_numba(
x: np.ndarray,
y: np.ndarray,
z: np.ndarray,
E: float,
lambda_laser: float,
NA: float,
t: np.ndarray,
forward_propagation: bool,
standing_wave: bool,
) -> np.ndarray:
w_0 = lambda_laser / (np.pi * NA)
x_R = pi * w_0**2 / lambda_laser
w_x = w_0 * np.sqrt(1 + (x / x_R) ** 2)
gouy_phase = np.arctan(x / x_R)
R_x_inverse = x / (x**2 + x_R**2)
k = 2 * pi / lambda_laser
other_phase = k * x + k * (z**2 + y**2) / 2 * R_x_inverse
potential_factor = 1 / (C_LIGHT * k) # potential_factor = 1/omega
if forward_propagation is True:
propagation_sign = -1
else:
propagation_sign = 1
time_phase = C_LIGHT * k * t
spatial_phase = other_phase - gouy_phase
envelope = (
E
* (w_0 / w_x)
* np.exp(np.clip(a=-(y**2 + z**2) / w_x**2, a_min=-200, a_max=None))
)
if standing_wave:
return (
envelope * potential_factor * np.cos(spatial_phase) * np.cos(time_phase)
) # * 2
else:
return (
envelope
* potential_factor
* np.cos(propagation_sign * spatial_phase + time_phase)
)
@njit(parallel=True)
def gaussian_beam_numba_looped(
x: np.ndarray,
y: np.ndarray,
z: np.ndarray,
E: float,
lambda_laser: float,
NA: float,
t: np.ndarray,
forward_propagation: bool,
standing_wave: bool,
) -> np.ndarray:
result_array = np.zeros_like(x)
w_0 = lambda_laser / (np.pi * NA)
x_R = pi * w_0**2 / lambda_laser
w_x = w_0 * np.sqrt(1 + (x / x_R) ** 2)
gouy_phase = np.arctan(x / x_R)
R_x_inverse = x / (x**2 + x_R**2)
k = 2 * pi / lambda_laser
other_phase = k * x + k * (z**2 + y**2) / 2 * R_x_inverse
potential_factor = 1 / (C_LIGHT * k) # potential_factor = 1/omega
if forward_propagation is True:
propagation_sign = -1
else:
propagation_sign = 1
for i in prange(result_array.shape[0]):
time_phase = C_LIGHT * k * t[i, ...]
spatial_phase = other_phase[i, ...] - gouy_phase[i, ...]
envelope = (
E
* (w_0 / w_x[i, ...])
* np.exp(
np.clip(
a=-(y[i, ...] ** 2 + z[i, ...] ** 2) / w_x[i, ...] ** 2,
a_min=-200,
a_max=None,
)
)
) # The clipping
# is to prevent underflow errors.
if standing_wave:
result_array[i, ...] = (
potential_factor * envelope * np.cos(spatial_phase) * np.cos(time_phase)
)
else:
result_array[i, ...] = (
potential_factor
* envelope
* np.cos(propagation_sign * spatial_phase + time_phase)
)
return result_array
def gaussian_beam(
x: [float, np.ndarray],
y: [float, np.ndarray],
z: Union[float, np.ndarray],
E: float, # The amplitude of the electric field, not the potential A.
lambda_laser: float,
w_0: Optional[float] = None,
NA: Optional[float] = None,
t: Optional[Union[float, np.ndarray]] = None,
mode: str = "intensity",
standing_wave: bool = True,
forward_propagation: bool = True,
complex: bool = True,
) -> Union[np.ndarray, float]:
if w_0 is None:
w_0 = w0_of_NA(NA, lambda_laser)
# Calculates the electric field of a gaussian beam
x_R = x_R_gaussian(w_0, lambda_laser)
w_x = w_x_gaussian(w_0=w_0, x=x, x_R=x_R)
gouy_phase = gouy_phase_gaussian(x, x_R)
R_x_inverse = R_x_inverse_gaussian(x, x_R)
k = k_of_l(lambda_laser)
other_phase = k * x + k * (z**2 + y**2) / 2 * R_x_inverse
envelope = (
E * (w_0 / w_x) * safe_exponent(-(y**2 + z**2) / w_x**2)
) # The clipping
# is to prevent underflow errors.
if forward_propagation is True:
propagation_sign = -1
else:
propagation_sign = 1
if mode == "intensity":
if standing_wave: # No time dependence
return envelope**2 * np.cos(other_phase + gouy_phase) ** 2 # * 4
else:
return envelope**2
elif mode in ["field", "potential"]:
if t is not None:
time_phase = C_LIGHT * k * t
else:
time_phase = 0
spatial_phase = other_phase - gouy_phase
if (
mode == "potential"
): # The ratio between E and A in Gibbs gauge is E=w*A or A=E/w
potential_factor = 1 / (C_LIGHT * k) # potential_factor = 1/omega
else:
potential_factor = 1
if standing_wave:
if complex:
return (
envelope
* potential_factor
* np.cos(spatial_phase)
* np.exp(1j * time_phase)
) # * 2
else:
return (
envelope
* potential_factor
* np.cos(spatial_phase)
* np.cos(time_phase)
) # * 2
else:
if complex:
return (
envelope
* potential_factor
* np.exp(1j * (propagation_sign * spatial_phase + time_phase))
)
else:
return (
envelope
* potential_factor
* np.cos(propagation_sign * spatial_phase + time_phase)
)
elif mode == "phase":
total_phase = propagation_sign * (other_phase - gouy_phase)
if t is not None:
time_phase = C_LIGHT * k * t
else:
time_phase = 0
return total_phase + time_phase
def lower_image_resolution(image: np.ndarray, subsample_rate) -> np.ndarray:
reshaped_image = image.reshape(
image.shape[0] // subsample_rate,
subsample_rate,
image.shape[1] // subsample_rate,
subsample_rate,
)
subsampled_image = reshaped_image.sum(axis=(1, 3))
return subsampled_image
def ASPW_propagation(
U_z0: np.ndarray, dxdydz: tuple[float, ...], k: float
) -> np.ndarray:
dx, dy, dz = dxdydz
U_fft = np.fft.fftn(U_z0)
k_x = np.fft.fftfreq(U_z0.shape[0], d=dx) * 2 * pi
k_y = np.fft.fftfreq(U_z0.shape[1], d=dy) * 2 * pi
k_x, k_y = np.meshgrid(k_x, k_y)
phase_argument = np.exp(1j * np.sqrt(k**2 - k_x**2 - k_y**2) * dz)
U_fft *= phase_argument
U_dz = np.fft.ifftn(U_fft)
return U_dz
def propagate_through_potential_slice(
incoming_wave: np.ndarray, averaged_potential: np.ndarray, dz: float, E0
) -> np.ndarray:
# CHECK THAT THIS my original version CORRESPONDS TO KIRKLAND'S VERSION
# V0 = E_0 / E_CHARGE
# dk = V2k(V0) - V2k(V0, averaged_potential)
# psi_output = incoming_wave * np.exp(-1j * dk * dz)
# KIRKLAND'S VERSION: (TWO VERSION AGREE!)
sigma = (
gamma_of_beta(beta_of_E(E0)) * M_ELECTRON * E_CHARGE / (H_BAR**2 * k_of_E(E0))
)
psi_output = incoming_wave * np.exp(1j * sigma * dz * averaged_potential)
return psi_output
def divide_calculation_to_batches(
f_s: Callable,
list_of_axes: List[np.ndarray],
numel_maximal: int,
print_progress=False,
save_to_file=True,
**kwargs,
):
# This function divides the calculation of a function to batches, so that the maximal number of elements in the
# calculation is numel_maximal. this is needed because when calculating the potential, the number of elements
# goes like N_x * N_y * N_t * N_z, and so the memory might not be enough to calculate the whole potential at once.
dimensions_sizes = [s.size for s in list_of_axes]
output = np.zeros(dimensions_sizes)
numel_per_layer = np.prod(dimensions_sizes[:-1])
if numel_per_layer < numel_maximal:
layers_in_batch = int(np.floor(numel_maximal / numel_per_layer))
layers_done = 0
while layers_done < dimensions_sizes[-1]:
layers_to_do = min(layers_in_batch, dimensions_sizes[-1] - layers_done)
if print_progress:
print(
f"Calculating layers {layers_done + 1}-{layers_done + layers_to_do} out of {len(list_of_axes[-1])} in axis {len(list_of_axes) - 1}"
)
last_axis_temp = list_of_axes[-1][layers_done : layers_done + layers_to_do]
f_s_values = f_s(
list_of_axes[:-1] + [last_axis_temp],
save_to_file=save_to_file,
**kwargs,
)
output[..., layers_done : layers_done + layers_to_do] = f_s_values
layers_done += layers_to_do
save_to_file = False # Save only the first iteration of the innermost loop.
else:
for i in range(dimensions_sizes[-1]):
if print_progress:
print(
f"Calculating layer {i + 1} out of {len(list_of_axes[-1])} in axis {len(list_of_axes) - 1}"
)
def f_s_contracted(l, **kwargs):
return f_s(l + [list_of_axes[-1][i]], **kwargs)[..., 0]
output[..., i] = divide_calculation_to_batches(
f_s=f_s_contracted,
list_of_axes=list_of_axes[:-1],
numel_maximal=numel_maximal,
print_progress=print_progress,
save_to_file=save_to_file,
**kwargs,
)
return output
def find_power_for_phase(
starting_power: float = 1e3,
E_0: float = Joules_of_keV(300),
desired_phase: float = pi / 2,
cavity_type: str = "numerical",
print_progress=False,
mode: str = "analytical",
plot_in_numerical_option: bool = True,
**kwargs,
):
input_coordinate_system = CoordinateSystem(lengths=(0, 0), n_points=(1, 1))
input_wave = WaveFunction(
E_0=E_0, psi=np.ones((1, 1)), coordinates=input_coordinate_system
)
# Based on equation e_41 from the simulation notes:
if mode == "analytical":
x_1 = starting_power
if cavity_type == "numerical":
C_1 = CavityNumericalPropagator(power_1=x_1, print_progress=False, **kwargs)
elif cavity_type == "analytical":
C_1 = CavityAnalyticalPropagator(power_1=x_1, **kwargs)
else:
raise ValueError(
f"Unknown cavity type {cavity_type}. must be either 'numerical' or 'analytical'"
)
mask_1 = C_1.phase_and_amplitude_mask(input_wave=input_wave)
y_1 = np.angle(mask_1[0, 0])
y_2_supposed = -desired_phase
x_2 = y_2_supposed * x_1 / y_1
if cavity_type == "numerical":
C_2 = CavityNumericalPropagator(power_1=x_2, print_progress=False, **kwargs)
else:
C_2 = CavityAnalyticalPropagator(power_1=x_2, **kwargs)
mask_2 = C_2.phase_and_amplitude_mask(input_wave=input_wave)
y_2_resulted = np.real(np.angle(mask_2[0, 0]))
if print_progress:
print(
f"for power_1 = {x_2:.1e} the resulted phase is {y_2_resulted / np.pi:.2f}pi={y_2_resulted:.2f} rads"
)
return x_2
elif mode == "numerical":
# Brute force search:
phases = []
resulted_phase = 0
P = starting_power
Es = []
while resulted_phase + desired_phase > 0:
if cavity_type == "numerical":
C = CavityNumericalPropagator(power_1=P, **kwargs)
elif cavity_type == "analytical":
C = CavityAnalyticalPropagator(power_1=P, **kwargs)
else:
raise ValueError(
"cavity_type must be either 'numerical' or 'analytical'"
)
phase_and_amplitude_mask = C.phase_and_amplitude_mask(input_wave=input_wave)
resulted_phase = np.real(np.angle(phase_and_amplitude_mask[0, 0]))
phases.append(resulted_phase)
if print_progress:
print(
f"For P={P:.2e} the resulted phase is {resulted_phase / np.pi:.2f}pi={resulted_phase:.2f} rads"
)
Es.append(P)
P *= 1.01
if plot_in_numerical_option:
plt.plot(Es, np.real(phases))
plt.axhline(-desired_phase, color="r")
plt.ylabel("Phase [rad]")
plt.xlabel("$power_{1}$ [W]")
plt.title("phase of x=y=0 as a function of power_1")
plt.show()
if print_progress:
print(
f"For P={Es[-1]:.2e} the phase is phi_original_function={resulted_phase:.2f}"
)
return Es[-1]
############################################################################################################
@dataclass
class CoordinateSystem:
def __init__(
self,
axes: Optional[
Tuple[np.ndarray, ...]
] = None, # The axes of the wave function, assumed to be evenly spaced
lengths: Optional[
Tuple[int, ...]
] = None, # the lengths of the sample in the x, y directions
n_points: Optional[
Tuple[int, ...]
] = None, # the number of points in the x, y directions
dxdydz: Optional[
Tuple[float, ...]
] = None, # the step size in the x, y directions
):
if axes is not None:
self.axes: Tuple[np.ndarray, ...] = axes
elif lengths is not None:
dim = len(lengths)
if n_points is not None and dxdydz is not None:
raise (ValueError("You can and only specify one out of n and dxdydz"))
elif n_points is not None:
self.axes: Tuple[np.ndarray, ...] = tuple(
np.linspace(-lengths[i] / 2, lengths[i] / 2, n_points[i])
for i in range(dim)
)
elif dxdydz is not None:
self.axes: Tuple[np.ndarray, ...] = tuple(
np.arange(-lengths[i] / 2, lengths[i] / 2, dxdydz[i])
for i in range(dim)
)
else:
raise (ValueError("You must specify either n or dxdydz"))
elif dxdydz is not None and n_points is not None:
dim = len(dxdydz)
self.axes: Tuple[np.ndarray, ...] = tuple(
np.linspace(
-(n_points[i] - 1) / 2,
(n_points[i] - 1) / 2,
n_points[i],
endpoint=True,
)
* dxdydz[i]
for i in range(dim)
)
else:
raise (
ValueError(
"You must specify either axes or lengths or both dxdydz and n_points"
)
)
@property
def dim(self) -> int:
return len(self.axes)
@property
def lengths(self) -> Tuple[float, ...]:
return tuple(axis[-1] - axis[0] for axis in self.axes)
@property
def n_points(self) -> Tuple[int, ...]:
return tuple(len(axis) for axis in self.axes)
@property
def dxdydz(self) -> Tuple[float, ...]:
return tuple(axis[1] - axis[0] for axis in self.axes)
@property
def grids(self) -> Tuple[np.ndarray, ...]:
return tuple(np.meshgrid(*self.axes, indexing="ij"))
@property
def X_grid(self) -> np.ndarray:
return self.grids[0]
@property
def Y_grid(self) -> np.ndarray:
return self.grids[1]
@property
def Z_grid(self) -> np.ndarray:
if self.dim == 3:
return self.grids[2]
else:
raise (ValueError("This coordinate system is not 3D"))
@property
def x_axis(self) -> np.ndarray:
return self.axes[0]
@property
def y_axis(self) -> np.ndarray:
return self.axes[1]
@property
def z_axis(self) -> np.ndarray:
if self.dim == 3:
return self.axes[2]
else:
raise (ValueError("This coordinate system is not 3D"))
@property
def dx(self) -> float:
return self.dxdydz[0]
@property
def dy(self) -> float:
return self.dxdydz[1]
@property
def dz(self) -> float:
if self.dim == 3:
return self.dxdydz[2]
else:
raise (ValueError("This coordinate system is not 3D"))
@property
def limits(self) -> Tuple[float, ...]:
limits_pairs = tuple((axis[0], axis[-1]) for axis in self.axes)
limits = tuple(lim for t in limits_pairs for lim in t)
return limits
@property
def is_centered(self) -> bool:
centered = True
for axis in [self.x_axis, self.y_axis]:
# if the middle pixel is substantialy different from 0 (with respect to dx, the typical order of magnitude)
# and also the average of the two middle pixels is substantialy different tan 0, then it is not centered.
if len(axis) == 1:
if np.abs(axis[0]) > 1e-100:
centered = False
else:
if len(axis) % 2:
mid_value, mid_adjacent_value = (
axis[axis.size // 2],
axis[axis.size // 2 + 1],
)
else:
mid_value, mid_adjacent_value = (
axis[axis.size // 2],
axis[axis.size // 2 - 1],
)
if np.abs(mid_value) > np.abs(mid_value + mid_adjacent_value) * 1e-10:
# and np.abs(mid_value + mid_adjacent_value) > np.abs(mid_value) * 1e-10 # (This second condition is
# for the case where the array is centered around 0 but like so: ..., -3dx/2, -dx/2, dx/2, 3dx/2, ...
# but actually I am never interested in this case, so I don't consider it as "centered".)
centered = False
return centered
@dataclass
class SpatialFunction:
values: np.ndarray # The values of the function
coordinates: CoordinateSystem # The coordinate system on which it is evaluated
class WaveFunction(SpatialFunction):
def __init__(
self,
E_0: float, # Energy of the particle in Joules
psi: Optional[
np.ndarray
] = None, # The input wave function in one z=const plane
coordinates: Optional[
CoordinateSystem
] = None, # The coordinate system of the input wave
mrc_file_path: Optional[
str
] = None, # Path to a .mrc file containing the wave function
):
if psi is not None and coordinates is not None:
super().__init__(psi, coordinates)
elif mrc_file_path is not None:
mrc_file = mrc.open(mrc_file_path)
if len(mrc_file.data.shape) == 3:
psi = mrc_file.data[:, :, -1]
if mrc_file.data.shape[2] > 1:
warn(
"3D data is not supported in a wave function, taking last slice only"
)
else:
psi = mrc_file.data
C = CoordinateSystem(
dxdydz=np.array(mrc_file.voxel_size.tolist()[0:2]) * 1e-10,
n_points=mrc_file.header[["nx", "ny"]].tolist(),
)
super().__init__(psi, C)
else:
raise (
ValueError(
"Either psi and coordinates or mrc_file_path must be provided"
)
)
self.E_0 = E_0
@property
def psi(self) -> np.ndarray:
return self.values
@property
def beta(self):
return beta_of_E(self.E_0)
def plot(self, fig=None, ax=None, clip=True, title=None, psi_subscript: str = "0"):
if ax is None:
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
intensity = np.abs(self.psi) ** 2
if clip:
intensity = np.clip(intensity, 0, np.percentile(intensity, 99))
im_intensity = ax[0].imshow(intensity)
ax[0].set_title(f"$\\left|\\psi_{psi_subscript}\\right|^{2}$")
divider = make_axes_locatable(ax[0])
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im_intensity, cax=cax, orientation="vertical")
im_argument = ax[1].imshow(np.angle(self.psi))
divider = make_axes_locatable(ax[1])
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im_argument, cax=cax, orientation="vertical")
ax[1].set_title(f"$arg\\left(\\psi_{psi_subscript}\\right)$")
if title is not None:
fig.suptitle(title)
return ax
class Propagator:
def propagate(self, state: WaveFunction) -> WaveFunction:
raise NotImplementedError()
@dataclass
class PropagationStep:
input_wave: WaveFunction
output_wave: WaveFunction
propagator: Propagator
class Microscope:
def __init__(
self,
propagators: List[Propagator],
print_progress: bool = False,
n_electrons_per_square_angstrom=1e1,
):
self.propagators = propagators
self.propagation_steps: List[PropagationStep] = []
self.print_progress = print_progress
self.n_electrons_per_square_angstrom = n_electrons_per_square_angstrom
def take_a_picture(
self, input_wave: WaveFunction, add_shot_noise=True
) -> SpatialFunction:
output_wave = self.propagate(input_wave)
image = self.expose_camera(output_wave, add_shot_noise=add_shot_noise)
return image
def propagate(self, input_wave: WaveFunction) -> WaveFunction:
self.propagation_steps = []
input_wave_psi_normalized = input_wave.psi / np.sqrt(
np.sum(np.abs(input_wave.psi) ** 2)
)
input_wave_psi_normalized *= np.sqrt(
self.n_electrons_per_square_angstrom
* 1e20
* input_wave.coordinates.lengths[0]
* input_wave.coordinates.lengths[1]
)
input_wave = WaveFunction(
input_wave.E_0, input_wave_psi_normalized, input_wave.coordinates
) # Normalized
for propagator in self.propagators:
if self.print_progress:
print(f"Propagating with {propagator.__class__}")
output_wave = propagator.propagate(input_wave)
self.propagation_steps.append(
PropagationStep(input_wave, output_wave, propagator)
)
input_wave = output_wave
return input_wave
def expose_camera(
self, output_wave: Optional[WaveFunction] = None, add_shot_noise=True
) -> SpatialFunction:
if len(self.propagation_steps) == 0:
raise ValueError("You must propagate the wave first")
if output_wave is None:
output_wave = self.propagation_steps[-1].output_wave
output_wave_intensity = np.abs(output_wave.psi) ** 2
# expected_electrons_per_pixel = output_wave_intensity * (
# self.n_electrons_per_square_angstrom * output_wave.psi.size
# )
if (
np.max(output_wave_intensity) > 100000000 or add_shot_noise is False
): # ARBITRARY - this prevents overflow
# of the poisson distribution
output_wave_intensity_shot_noise = output_wave_intensity
else:
output_wave_intensity_shot_noise = np.random.poisson(
output_wave_intensity
) # This actually assumes an
# independent shot noise for each pixel, which is not true, but it's a good approximation for many pixels.
return SpatialFunction(
output_wave_intensity_shot_noise,
self.propagation_steps[-1].output_wave.coordinates,
)
def plot_step(self, propagator: Propagator, clip=True, title=None, file_name=None):
step = self.step_of_propagator(propagator)
input_wave = step.input_wave
output_wave = step.output_wave
fig, ax = plt.subplots(2, 2, figsize=(12, 12))
input_wave.plot(fig, ax[0], clip=clip, psi_subscript="i")
output_wave.plot(fig, ax[1], clip=clip, psi_subscript="o")
if title is not None:
fig.suptitle(title)
if file_name is not None:
fig.savefig("Figures\\" + file_name)
plt.show()
def step_of_propagator(self, propagator: Propagator) -> PropagationStep:
step_idx = self.propagators.index(propagator)
return self.propagation_steps[step_idx]
class SamplePropagator(Propagator):
def __init__(
self,
sample: Optional[SpatialFunction] = None,
path_to_sample_file: Optional[str] = None,
dummy_potential: Optional[str] = None,
coordinates_for_dummy_potential: Optional[CoordinateSystem] = None,
):
if sample is not None:
self.sample: SpatialFunction = sample
# elif path_to_sample_file is not None:
# self.sample: SpatialFunction = np.load(path_to_sample_file)
elif dummy_potential is not None:
self.generate_dummy_potential(
dummy_potential, coordinates_for_dummy_potential
)
else:
raise ValueError(
"You must specify either a sample or a path to a potential file or a dummy potential"
)
def generate_dummy_potential(
self, potential_type: str, coordinates_for_dummy_potential: CoordinateSystem
):
c = coordinates_for_dummy_potential # just abbreviation for the name
if len(c.grids) == 2: