Repository navigation
Expand file tree
/
Copy pathdata_processing.py
More file actions
1933 lines (1800 loc) · 70.2 KB
/
Copy pathdata_processing.py
File metadata and controls
1933 lines (1800 loc) · 70.2 KB
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
# %% Imports et blabla
import contrast
from PIL import Image
from scipy import ndimage
from skimage import restoration
import numpy as np
import matplotlib.pyplot as plt
import pyfftw
import multiprocessing
from cycler import cycler
import tqdm
import time
import cv2
import os
import regex as re
import velocity
import pickle
import faulthandler
import scipy.optimize as opt
from scipy.optimize import curve_fit
from skimage.restoration import unwrap_phase
from scipy.integrate import solve_ivp
from scipy import optimize
# from findpeaks import findpeaks
faulthandler.enable()
# matplotlib.use("Qt5Agg")
pyfftw.interfaces.cache.enable()
pyfftw.config.NUM_THREADS = multiprocessing.cpu_count()
pyfftw.config.PLANNER_EFFORT = "FFTW_MEASURE"
# try to load previous fftw wisdom
try:
with open("fft.wisdom", "rb") as file:
wisdom = pickle.load(file)
pyfftw.import_wisdom(wisdom)
except FileNotFoundError:
print("No FFT wisdom found, starting over ...")
# for dark theme
# plt.style.use("dark_background")
# plt.rcParams["figure.facecolor"] = "#00000080"
# plt.rcParams["axes.facecolor"] = "#00000080"
# plt.rcParams["savefig.facecolor"] = "#00000080"
# plt.rcParams['savefig.transparent'] = True
# plt.rcParams['font.family'] = 'sans-serif'
# plt.rcParams['font.sans-serif'] = ['Liberation Sans']
# for plots
tab_colors = [
"tab:blue",
"tab:orange",
"forestgreen",
"tab:red",
"tab:purple",
"tab:brown",
"tab:pink",
"tab:gray",
"tab:olive",
"teal",
]
fills = [
"lightsteelblue",
"navajowhite",
"darkseagreen",
"lightcoral",
"violet",
"indianred",
"lavenderblush",
"lightgray",
"darkkhaki",
"darkturquoise",
]
edges = tab_colors
custom_cycler = (
(cycler(color=tab_colors))
+ (cycler(markeredgecolor=edges))
+ (cycler(markerfacecolor=fills))
)
plt.rc("axes", prop_cycle=custom_cycler)
# plt.rcParams.update({
# "text.usetex": True,
# "font.family": "serif",
# "font.size": 12
# })
# sshfs taladjidi@patriot.lkb.upmc.fr:/partages/EQ15B/LEON-15B /home/tangui/LEON
# path_leon = "/run/user/1000/gvfs/sftp:host=patriot.lkb.upmc.fr,user=taladjidi/partages/EQ15B/LEON-15B"
# path_leon = "/run/user/1000/gvfs/sftp:host=88.160.142.14,port=16384,user=aladjidi/home/aladjidi/Disk0/LEON"
# %% Paths and parameters
k0 = 2 * np.pi / 780e-9
L = 20e-2
d_slm = 8e-6
d_real = (
3.45e-6 * 2
) # times 2 beacuse of the lose of resolution for amplitude and phase reconstruction
d_def = 1.1e-6
Nx, Ny = 2464, 2056
Nx_def, Ny_def = 2048, 2048
GPU = False # if True, use nvidia GPU for spectral analysis (need cupy package)
if GPU:
import cupy as cp
# %% Functions
def Vortex2D(mn, y_val, x_val, xi) -> np.ndarray:
y, x = mn
# y, x = np.meshgrid(m, n)
# x = x - n / 2.0 + x_val
# y = y - m / 2.0 + y_val
r = np.sqrt((x - x_val) ** 2 + (y - y_val) ** 2)
Psi = r / np.sqrt(r**2 + (2 * xi) ** 2)
Amp = np.abs(Psi)
return Amp.ravel()
def Soliton1D(x, Mach, xi):
Psi = (
np.sqrt(1 - Mach**2) * np.tanh((x / (np.sqrt(2) * xi)) * np.sqrt(1 - Mach**2))
+ 1j * Mach
)
# Amp = np.abs(Psi)
Phase = np.angle(Psi) + np.pi
return Phase
def JRS_2D_ansatz(x, Mach, xi):
c = np.sqrt(2) * np.sqrt(1 - Mach)
denominator = 3 / 2 + c**2 * x**2 / xi**2
fin = -2 * np.sqrt(2) * c * x / xi / denominator
return fin.ravel()
def JRS_padé(x, y):
"""
Compute the density of the rarefaction pulse at U = 0.5.
Parameters:
x (float or np.ndarray): x-coordinate(s).
y (float or np.ndarray): y-coordinate(s).
Returns:
float or np.ndarray: Density rho(x, y).
"""
# Numerator coefficients for u and v
a00 = -0.825937
a10 = -0.114393
a01 = -0.0271467
b00 = -0.737901
b10 = -0.108587
b01 = -0.0542934
# Denominator coefficients (common to both u and v)
c10 = 0.37355
c01 = 0.14235
c20 = 0.03495
c11 = 0.03495
c02 = 0.008737
# Compute u(x, y)
u_num = a00 + a10 * x**2 + a01 * y**2
u_den = 1 + c10 * x**2 + c01 * y**2 + c20 * x**4 + c11 * x**2 * y**2 + c02 * y**4
u = 1 + u_num / u_den
# Compute v(x, y)
v_num = x * (b00 + b10 * x**2 + b01 * y**2)
v = v_num / u_den # Note: same denominator as u
# Compute density rho(x, y)
rho = u**2 + v**2
psi = u + 1j * v
rho = np.abs(psi) ** 2
phase = np.angle(psi)
return rho, phase
def natural_sort(l):
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split("([0-9]+)", key)]
return sorted(l, key=alphanum_key)
def compute_phase_time(scan: str, plot: bool = False):
"""Compute the phase.
Computes the phase from the interferograms for a time scan
dataset.
Args:
scan (str): Path to the dataset
plot (bool, optional): Whether to plot the phase. Defaults to False.
"""
# powers = np.load(f"{path_real}/{scan}/powers.npy")
# N_times = powers.size
input_power = np.load(f"{scan}/input_power.npy")
N_times = input_power.size
N_avg = np.load(f"{scan}/N_avg.npy")
laser_powers = np.load(f"{scan}/laser_settings.npy")
field = np.zeros((N_times, N_avg, Ny // 2, Nx // 2), dtype=np.complex64)
field_ref = np.zeros((N_times, N_avg, Ny // 2, Nx // 2), dtype=np.complex64)
field_vortex = np.zeros((N_times, N_avg, Ny // 2, Nx // 2), dtype=np.complex64)
# ref_arm = np.array(Image.open(
# f"{path_real}/ref.TIF"), dtype=np.uint16).astype(np.float32)
# ref_arm = ndimage.zoom(ref_arm, .5)
taus = np.zeros(N_times)
taus_err = np.zeros(N_times)
# prepare plans
a = pyfftw.empty_aligned((Ny, Nx), dtype=np.float32)
c = pyfftw.empty_aligned((Ny // 2, Nx // 2), dtype=np.complex64)
plan_fft = pyfftw.builders.rfft2(a)
plan_ifft = pyfftw.builders.ifft2(c)
with open("fft.wisdom", "wb") as file:
wisdom = pyfftw.export_wisdom()
pickle.dump(wisdom, file)
plans = (plan_fft, plan_ifft)
# del a, b
pbar = tqdm.tqdm(total=N_times * N_avg, desc="Computing phase", position=1)
for i in range(N_times):
tau = np.zeros(N_avg)
for j in range(N_avg):
im_ref = np.array(
Image.open(f"{scan}/dn_ref_{i}_{j}.tiff"),
dtype=np.float32,
)
im = np.array(
Image.open(f"{scan}/dn_{i}_{j}.tiff"),
dtype=np.float32,
)
im_vortex = np.array(
Image.open(f"{scan}/dn_vortex_{i}_{j}.tiff"),
dtype=np.float32,
)
field_ref[i, j, :, :] = contrast.im_osc_fast_t(
im_ref,
plans=plans,
center=(im_ref.shape[-2] // 2, im_ref.shape[-1] // 4),
radius=im_ref.shape[-2] // 16,
)
field[i, j, :, :] = contrast.im_osc_fast_t(
im,
center=(im_ref.shape[-2] // 2, im_ref.shape[-1] // 4),
radius=im_ref.shape[-2] // 16,
)
field_vortex[i, j, :, :] = contrast.im_osc_fast_t(
im_vortex,
plans=plans,
center=(im_ref.shape[-2] // 2, im_ref.shape[-1] // 4),
radius=im_ref.shape[-2] // 16,
)
# plt.imshow(np.abs(field[i, j, :, :]) ** 2)
# plt.show()
phi_ref = contrast.angle_fast(field_ref[i, j, :, :])
rho_ref = (
field_ref[i, j, :, :].real * field_ref[i, j, :, :].real
+ field_ref[i, j, :, :].imag * field_ref[i, j, :, :].imag
)
threshold = 2e-2
mask = rho_ref < threshold * np.max(rho_ref)
phi_ref_masked = np.ma.array(phi_ref, mask=mask)
phi_ref_unwrapped = restoration.unwrap_phase(
phi_ref_masked, wrap_around=(True, True)
)
tau[j] = np.abs(np.nanmax(phi_ref_unwrapped) - np.nanmin(phi_ref_unwrapped))
pbar.update(1)
taus[i] = np.mean(tau)
taus_err[i] = np.std(tau)
pbar.close()
print("Saving data ...")
t0 = time.perf_counter()
np.save(f"{scan}/field_ref.npy", field_ref)
np.save(f"{scan}/field.npy", field)
np.save(f"{scan}/field_vortex.npy", field_vortex)
np.save(f"{scan}/taus_reproc.npy", taus)
np.save(f"{scan}/taus_err_reproc.npy", taus_err)
t = time.perf_counter() - t0
sz = field_ref.nbytes + field.nbytes + field_vortex.nbytes + taus.nbytes
rate = sz / t
print(f"Saved {sz * 1e-6:.0f} MB of data in {t:.2f} s / {rate * 1e-6:.2f} MB/s")
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(np.abs(field[0, -1, :, :]) ** 2)
ax[1].imshow(np.angle(field[0, -1, :, :]), cmap="twilight_shifted")
fig.savefig(f"{scan}/field.svg", dpi=300)
taus0 = np.load(f"{scan}/taus.npy")
taus0_err = np.load(f"{scan}/taus_err.npy")
fig1, ax1 = plt.subplots()
ax1.errorbar(
laser_powers,
taus0,
yerr=taus0_err,
marker="o",
label="During acquisition",
)
ax1.errorbar(laser_powers, taus, yerr=taus_err, marker="o", label="Reprocessed")
ax1.legend()
ax1.set_xlabel("Power in a.u.")
ax1.set_ylabel(r"$\delta\phi = \tau$ in rad")
ax1.set_title("Phase shift vs power")
fig1.savefig(f"{scan}/taus.svg", dpi=300)
if plot:
plt.show()
plt.close("all")
def compute_n2_Isat(scan: str, plot: bool = False):
"""Compute n2 and Isat from the phase shift vs power and plot the effective refractive index"""
print("Loading data ...")
def delta_n_avg(I, I_sat, n2):
return n2 * I
waist = 1.7e-3
L = 0.2
k0 = 2 * np.pi / 780e-9
taus = np.load(f"{scan}/taus.npy")
delta_n = taus / (k0 * L)
# laser_powers = np.load(f"{scan}/laser_settings.npy")
laser_powers = np.linspace(0.05, 3, len(delta_n))
laser_intensity = 2 * laser_powers / (np.pi * (waist) ** 2)
laser_intensity = laser_intensity[5:]
delta_n = delta_n[5:]
popt, pcov = curve_fit(delta_n_avg, laser_intensity, delta_n, p0=[6e5, 1e-10])
plt.figure()
plt.plot(laser_intensity, delta_n, marker="o")
plt.plot(
laser_intensity,
delta_n_avg(laser_intensity, *popt),
label=f"Isat = {popt[0]:.2e} W/m$^2$ | n2 = {popt[1]:.2e} m$^2$/W",
)
plt.xlabel("Laser intensity (W/m$^2$)")
plt.ylabel(r"$\Delta n$")
plt.legend()
plt.grid()
plt.savefig(f"{scan}/n2_Isat.svg", dpi=300)
plt.show()
def compute_final_xi(scan: str, plot: bool = False):
"""Find final xi value"""
print("Loading data ...")
t0 = time.perf_counter()
fields_ref = np.load(f"{scan}/field_ref.npy")
fields = np.load(f"{scan}/field.npy")
fields_vortex = np.load(f"{scan}/field_vortex.npy")
taus = np.load(f"{scan}/taus.npy")
t = time.perf_counter() - t0
sz = fields_ref.nbytes + fields.nbytes
rate = sz / t
print(f"Loaded {sz * 1e-6:.0f} MB of data in {t:.2f} s / {rate * 1e-6:.2f} MB/s")
window_m = 30
vort_size = []
vort_size_err = []
xi_avg = []
for i in tqdm.tqdm(range(fields.shape[0]), desc="Plotting", position=1):
vort_size_avg = []
for j in range(fields.shape[1]):
field = fields[i, j, :, :]
field_ref = fields_ref[i, j, :, :]
field_vortex = fields_vortex[i, j, :, :]
field = ndimage.gaussian_filter(field, 2)
field_ref = ndimage.gaussian_filter(field_ref, 2)
field_vortex = ndimage.gaussian_filter(field_vortex, 2)
# Compute the phase and density
contrast.exp_angle_fast(field, field_ref)
contrast.exp_angle_fast(field_vortex, field_ref)
phi_vort_flat = contrast.angle_fast(field_vortex)
rho = field.real * field.real + field.imag * field.imag
# rho = ndimage.gaussian_filter(rho, 3)
rho_ref = field_ref.real * field_ref.real + field_ref.imag * field_ref.imag
rho_vort = (
field_vortex.real * field_vortex.real
+ field_vortex.imag * field_vortex.imag
)
rho = np.sqrt(rho)
rho = rho / np.nanmax(rho)
rho_ref = np.sqrt(rho_ref)
rho_ref = rho_ref / np.nanmax(rho_ref)
rho_vort = np.sqrt(rho_vort)
rho_vort = rho_vort / np.nanmax(rho_vort)
# Define a circular mask from the reference field
threshold = 5e-2
mask_ref = rho_ref < threshold * np.max(rho_ref)
mask_fluid = rho_ref >= threshold * np.max(rho_ref)
radius_mask_ref = np.sqrt(np.sum(mask_fluid) / np.pi)
window = int(radius_mask_ref) / 1.5
x, y = np.meshgrid(
np.arange(mask_ref.shape[-1]), np.arange(mask_ref.shape[-2])
)
mask_fluid = np.abs(
(x - mask_ref.shape[-1] // 2) ** 2 + (y - mask_ref.shape[-2] // 2) ** 2
< radius_mask_ref**2
)
mask_fluid = np.logical_not(mask_fluid)
rho_masked = rho
rho_masked[mask_fluid] = np.nan
# plt.figure()
# plt.imshow(rho_masked, cmap='gray')
# plt.show()
####### Compute xi with vortex radius
vortices = np.array([])
vort = velocity.vortex_detection(phi_vort_flat, plot=False, r=1)
vort[:, 0] -= phi_vort_flat.shape[-1] // 2
vort[:, 1] -= phi_vort_flat.shape[-2] // 2
# vort_in_window_x = np.logical_and(vort[:, 0] > -window, vort[:, 0] < window)
# vort_in_window_y = np.logical_and(vort[:, 1] > -window, vort[:, 1] < window)
# vort_select = np.logical_and(vort_in_window_x, vort_in_window_y)
vort_select = np.logical_not(vort[:, 0] ** 2 + vort[:, 1] ** 2 > window**2)
vortices = vort[vort_select, :]
center_x = field.shape[1] // 2 + vortices[0][0]
center_y = field.shape[0] // 2 + vortices[0][1]
# Find the vortex position, and width
rho_zoom = rho_vort[
int(center_y - window_m) : int(center_y + window_m),
int(center_x - window_m) : int(center_x + window_m),
]
x = np.arange(rho_zoom.shape[1])
y = np.arange(rho_zoom.shape[0])
X, Y = np.meshgrid(x, y)
inital_guess = (window_m, window_m, 10)
try:
popt, pcov = opt.curve_fit(
Vortex2D, (Y, X), rho_zoom.ravel(), p0=inital_guess
)
except RuntimeError:
popt = np.array([window_m, window_m, np.nan])
vortex_reshape = Vortex2D((Y, X), *popt).reshape(window_m * 2, window_m * 2)
# plt.figure()
# plt.imshow(vortex_reshape, cmap='inferno')
# plt.show()
vort_rad = popt[2] * d_real
if vort_rad > 150e-6:
vort_rad = np.nan
vort_size_avg += [vort_rad]
vort_size_avg = np.array(vort_size_avg)
vort_size += [np.nanmean(vort_size_avg)]
vort_size_err += [np.nanstd(vort_size_avg)]
xi_avg += [np.sqrt(0.2 / (taus[i] * 8e6))]
vort_size = np.array(vort_size)
vort_size_err = np.array(vort_size_err)
xi_avg = np.array(xi_avg)
np.save(f"{scan}/xis_final.npy", vort_size)
plt.figure()
plt.errorbar(
taus,
vort_size * 1e6,
yerr=vort_size_err * 1e6,
marker="o",
label="Vortex radius",
)
# plt.plot(taus, vort_size*1e6, marker='o', label='Vortex radius')
plt.plot(taus, xi_avg * 1e6, marker="s", label="Average xi")
plt.xlabel(r"$\tau$")
plt.ylabel(r"$\xi$ $(\mu m)$")
plt.grid()
plt.legend()
plt.savefig(f"{scan}/xi_vortex.svg", dpi=300)
if plot:
plt.show()
def plot_fields(scan: str, window: int = 50, plot: bool = False):
"""Plot the fields.
Args:
scan (str): Path to the dataset
plot (bool, optional): Whether to plot the fields. Defaults to False.
"""
print("Loading data ...")
t0 = time.perf_counter()
taus = np.load(f"{scan}/taus.npy")
field_ref = np.load(f"{scan}/field_ref.npy")
field = np.load(f"{scan}/field.npy")
t = time.perf_counter() - t0
sz = field_ref.nbytes + field.nbytes
field = field[:, -1, :, :]
field_ref = field_ref[:, -1, :, :]
rate = sz / t
# if field_ref.shape[-1] == Nx // 2:
print(f"Loaded {sz * 1e-6:.0f} MB of data in {t:.2f} s / {rate * 1e-6:.2f} MB/s")
delta_n = taus / (k0 * L)
# xis = 1 / (k0 * np.sqrt(delta_n))
xis = np.load(f"{scan}/xis_final.npy")
fig, ax = plt.subplots(1, 2, figsize=(10, 5), dpi=300)
im0 = ax[0].imshow(
np.ones(field.shape[1:]),
cmap="gray",
vmin=0,
vmax=1,
interpolation="none",
)
im1 = ax[1].imshow(
np.ones(field.shape[1:]),
cmap="twilight_shifted",
vmin=-np.pi,
vmax=np.pi,
interpolation="none",
)
for a in ax:
a.set_xlabel(r"$x/\xi$")
a.set_ylabel(r"$y/\xi$")
ax[0].set_title("Density")
ax[1].set_title("Normalized phase")
# ax[0].locator_params(axis="both", nbins=5)
# ax[1].locator_params(axis="both", nbins=5)
fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95)
fig.colorbar(im0, ax=ax[0], label=r"$\sqrt{\rho}$ in a.u.", shrink=0.6)
cbar = fig.colorbar(im1, ax=ax[1], label=r"$\phi/\phi_0$ in rad", shrink=0.6)
cbar.set_ticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[
r"$\pi$",
r"$-\frac{\pi}{2}$",
r"$0$",
r"$\frac{\pi}{2}$",
r"$\pi$",
],
)
fig.canvas.draw()
mat = np.array(fig.canvas.renderer._renderer)
mat = cv2.cvtColor(mat, cv2.COLOR_RGB2BGR)
# create folder if it does not exist
if not (os.path.exists(f"{scan}")):
os.mkdir(f"{scan}")
video_writer = cv2.VideoWriter(
f"{scan}/field.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
3,
(mat.shape[1], mat.shape[0]),
)
video_writer1 = cv2.VideoWriter(
f"{scan}/field_rescaled.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
3,
(mat.shape[1], mat.shape[0]),
)
for i in tqdm.tqdm(range(field.shape[0]), desc="Plotting fields", position=1):
fig.suptitle(rf"$\tau$ = {taus[i]:.0f} / $\xi$ = {xis[i] * 1e6:.0f} $\mu m$")
ext_real = [
-field.shape[-1] * d_real / (2 * xis[i]),
field.shape[-1] * d_real / (2 * xis[i]),
-field.shape[-2] * d_real / (2 * xis[i]),
field.shape[-2] * d_real / (2 * xis[i]),
]
contrast.exp_angle_fast(field[i, :, :], field_ref[i, :, :])
phi_flat = contrast.angle_fast(field[i, :, :])
rho = (
field[i, :, :].real * field[i, :, :].real
+ field[i, :, :].imag * field[i, :, :].imag
)
rho = np.sqrt(rho)
rho = rho / np.max(rho)
im0.set_data(rho)
im0.set_clim(np.min(rho), 1.0)
im1.set_data(phi_flat)
im0.set_extent(ext_real)
im1.set_extent(ext_real)
for a in ax:
a.set_xlim((ext_real[0], ext_real[1]))
a.set_ylim((ext_real[2], ext_real[3]))
fig.canvas.draw()
if plot:
plt.show()
mat = np.array(fig.canvas.renderer._renderer)
mat = cv2.cvtColor(mat, cv2.COLOR_RGB2BGR)
video_writer.write(mat)
fig.savefig(f"{scan}/fields_{i}.svg", dpi=300)
window = window
for a in ax:
a.set_xlim((-window, window))
a.set_ylim((-window, window))
fig.canvas.draw()
mat = np.array(fig.canvas.renderer._renderer)
mat = cv2.cvtColor(mat, cv2.COLOR_RGB2BGR)
video_writer1.write(mat)
fig.savefig(f"{scan}/fields_rescaled_{i}.svg", dpi=300)
if plot:
plt.show()
print()
plt.close("all")
video_writer.release()
video_writer1.release()
def energy_time(scan: str, plot: bool = False):
"""Compute the kinetic energy (comp and inc) and the interaction energy.
Args:
scan (str): File path.
plot (bool, optional): Whether to plot. Defaults to False.
"""
print("Loading data ...")
t0 = time.perf_counter()
field_ref = np.load(f"{scan}/field_ref.npy")
N_times = field_ref.shape[0]
N_avg = field_ref.shape[1]
field = np.load(f"{scan}/field.npy")
field_vortex = np.load(f"{scan}/field_vortex.npy")
taus = np.load(f"{scan}/taus.npy")
taus_err = np.load(f"{scan}/taus_err.npy")
t = time.perf_counter() - t0
sz = field_ref.nbytes + field.nbytes + field_vortex.nbytes
rate = sz / t
print(f"Loaded {sz * 1e-6:.0f} MB of data in {t:.2f} s / {rate * 1e-6:.2f} MB/s")
filtering_radius = 4
# field = ndimage.gaussian_filter(field, filtering_radius)
# field_vortex = ndimage.gaussian_filter(field_vortex, filtering_radius)
# compute energies
e_comp = np.zeros(field.shape[:2])
e_inc = np.zeros(field.shape[:2])
e_int = np.zeros(field.shape[:2])
u_inc = np.zeros(
(*field.shape[:2], 2, field.shape[-2], field.shape[-1]),
dtype=np.float32,
)
u_comp = np.zeros(
(*field.shape[:2], 2, field.shape[-2], field.shape[-1]),
dtype=np.float32,
)
e_comp_vortex = np.zeros(field.shape[:2])
e_inc_vortex = np.zeros(field.shape[:2])
e_int_vortex = np.zeros(field.shape[:2])
u_inc_vortex = np.zeros(
(*field.shape[:2], 2, field.shape[-2], field.shape[-1]),
dtype=np.float32,
)
u_comp_vortex = np.zeros(
(*field.shape[:2], 2, field.shape[-2], field.shape[-1]),
dtype=np.float32,
)
for i in tqdm.tqdm(range(N_times), desc="Computing energies", position=1):
# for i in range(30,31):
for j in range(N_avg):
contrast.exp_angle_fast(field[i, j, :, :], field_ref[i, j, :, :])
contrast.exp_angle_fast_scalar(
field[i, j, :, :],
field[i, j, field.shape[-2] // 2, field.shape[-1] // 2],
)
contrast.exp_angle_fast(field_vortex[i, j, :, :], field_ref[i, j, :, :])
contrast.exp_angle_fast_scalar(
field_vortex[i, j, :, :],
field_vortex[
i,
j,
field_vortex.shape[-2] // 2,
field_vortex.shape[-1] // 2,
],
)
rho = (
field[i, j, :, :].real * field[i, j, :, :].real
+ field[i, j, :, :].imag * field[i, j, :, :].imag
)
rho_vortex = (
field_vortex[i, j, :, :].real * field_vortex[i, j, :, :].real
+ field_vortex[i, j, :, :].imag * field_vortex[i, j, :, :].imag
)
rho_ref = (
field_ref[i, j, :, :].real * field_ref[i, j, :, :].real
+ field_ref[i, j, :, :].imag * field_ref[i, j, :, :].imag
)
# Define a circular mask from the reference field
threshold = 5e-2
mask_ref = rho_ref < threshold * np.max(rho_ref)
mask_fluid = rho_ref >= threshold * np.max(rho_ref)
radius_mask_ref = np.sqrt(np.sum(mask_fluid) / np.pi) / 1.6
x, y = np.meshgrid(
np.arange(mask_ref.shape[-1]), np.arange(mask_ref.shape[-2])
)
mask_fluid = (x - mask_ref.shape[-1] // 2) ** 2 + (
y - mask_ref.shape[-2] // 2
) ** 2 < radius_mask_ref**2
mask_fluid = np.logical_not(mask_fluid)
field[i, j, :, :] = ndimage.gaussian_filter(
field[i, j, :, :], filtering_radius
)
(
_,
u_inc[i, j, :, :, :],
u_comp[i, j, :, :, :],
) = velocity.helmholtz_decomp(field[i, j, :, :], dx=d_real, plot=False)
# u_inc[i, j, :, :, :] = ndimage.gaussian_filter(
# u_inc[i, j, :, :, :], filtering_radius
# )
# u_comp[i, j, :, :, :] = ndimage.gaussian_filter(
# u_comp[i, j, :, :, :], filtering_radius
# )
for k in range(u_comp_vortex.shape[2]):
u_comp[i, j, k, :, :][mask_fluid] = 0
u_inc[i, j, k, :, :][mask_fluid] = 0
e_comp[i, j] = np.sum(u_comp[i, j, :, :, :] ** 2)
e_inc[i, j] = np.sum(u_inc[i, j, :, :, :] ** 2)
e_int[i, j] = np.sum(rho * rho)
field_vortex[i, j, :, :] = ndimage.gaussian_filter(
field_vortex[i, j, :, :], filtering_radius
)
(
_,
u_inc_vortex[i, j, :, :, :],
u_comp_vortex[i, j, :, :, :],
) = velocity.helmholtz_decomp(
field_vortex[i, j, :, :], dx=d_real, plot=False
)
# u_inc_vortex[i, j, :, :, :] = ndimage.gaussian_filter(
# u_inc_vortex[i, j, :, :, :], filtering_radius
# )
# u_comp_vortex[i, j, :, :, :] = ndimage.gaussian_filter(
# u_comp_vortex[i, j, :, :, :], filtering_radius
# # )
for jj in range(u_comp_vortex.shape[2]):
u_comp_vortex[i, j, k, :, :][mask_fluid] = 0
u_inc_vortex[i, j, k, :, :][mask_fluid] = 0
e_comp_vortex[i, j] = np.sum(np.abs(u_comp_vortex[i, j, :, :, :]) ** 2)
e_inc_vortex[i, j] = np.sum(np.abs(u_inc_vortex[i, j, :, :, :]) ** 2)
e_int_vortex[i, j] = np.sum(rho_vortex * rho_vortex)
print("\nSaving data ...")
t0 = time.perf_counter()
# np.save(f"{path_dn}/{scan}/e_comp.npy", e_comp)
# np.save(f"{path_dn}/{scan}/e_inc.npy", e_inc)
# np.save(f"{path_dn}/{scan}/e_int.npy", e_int)
np.save(f"{scan}/u_inc.npy", u_inc)
# np.save(f"{path_dn}/{scan}/u_comp.npy", u_comp)
# np.save(f"{path_dn}/{scan}/e_comp_vortex.npy", e_comp_vortex)
# np.save(f"{path_dn}/{scan}/e_inc_vortex.npy", e_inc_vortex)
# np.save(f"{path_dn}/{scan}/e_int_vortex.npy", e_int_vortex)
# np.save(f"{path_dn}/{scan}/u_inc_vortex.npy", u_inc_vortex)
# np.save(f"{path_dn}/{scan}/u_comp_vortex.npy", u_comp_vortex)
t = time.perf_counter() - t0
sz = (
e_comp.nbytes
+ e_inc.nbytes
+ u_inc.nbytes
+ u_comp.nbytes
+ e_comp_vortex.nbytes
+ e_inc_vortex.nbytes
+ u_inc_vortex.nbytes
+ u_comp_vortex.nbytes
)
rate = sz / t
print(f"Saved {sz * 1e-6:.0f} MB of data in {t:.2f} s / {rate * 1e-6:.2f} MB/s")
fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].set_title(r"$E_{two}$")
ax[0].errorbar(
taus,
np.mean(e_comp, axis=-1),
xerr=taus_err,
yerr=np.std(e_comp, axis=-1),
label="Compressible",
marker="o",
)
ax[0].errorbar(
taus,
np.mean(e_inc, axis=-1),
xerr=taus_err,
yerr=np.std(e_inc, axis=-1),
label="Incompressible",
marker="^",
)
# ax[0].errorbar(
# taus,
# np.mean(e_int, axis=-1),
# xerr=taus_err,
# yerr=np.std(e_int, axis=-1),
# label="Interaction",
# marker="^",
# )
ax[1].set_title(r"$E_{one}$")
ax[1].errorbar(
taus,
np.mean(e_comp_vortex, axis=-1),
xerr=taus_err,
yerr=np.std(e_comp_vortex, axis=-1),
label="Compressible",
marker="o",
)
ax[1].errorbar(
taus,
np.mean(e_inc_vortex, axis=-1),
xerr=taus_err,
yerr=np.std(e_inc_vortex, axis=-1),
label="Incompressible",
marker="^",
)
# ax[1].errorbar(
# taus,
# np.mean(e_int_vortex, axis=-1),
# xerr=taus_err,
# yerr=np.std(e_int_vortex, axis=-1),
# label="Interaction",
# marker="^",
# )
ax[2].set_title(r"$E_{two}/E_{one}$")
ax[2].errorbar(
taus,
np.mean(e_comp, axis=-1) / np.mean(e_comp_vortex, axis=-1),
yerr=np.std(e_comp / e_comp_vortex, axis=-1),
xerr=taus_err,
label="Compressible",
marker="o",
)
ax[2].errorbar(
taus,
np.mean(e_inc, axis=-1) / np.mean(e_inc_vortex, axis=-1),
yerr=np.std(e_inc / e_inc_vortex, axis=-1),
xerr=taus_err,
label="Incompressible",
marker="^",
)
ax[2].errorbar(
taus,
np.mean(e_int, axis=-1) / np.mean(e_int_vortex, axis=-1),
yerr=np.std(e_int / e_int_vortex, axis=-1),
xerr=taus_err,
label="Interaction",
marker="s",
)
for a in ax:
a.set_xlabel(r"$\tau$ in rad")
a.set_ylabel(r"$E$ in a.u.")
a.legend()
ax[2].axhline(1, color="grey", linestyle="--")
ax[2].set_ylim(bottom=-0.05)
fig.savefig(f"{scan}/energies.svg", dpi=300)
if plot:
plt.show()
plt.close("all")
def spectral_analysis(
scan: str,
which: str = "vortex",
img_nbr: int = 1,
plot: bool = False,
debug: bool = False,
):
"""Compute the energy spectra for a given time with the new spectral analysis."""
print("Loading data ...")
xi = 40e-6
im = Image.open(f"{scan}/ref/fluid.tif")
im_ref = Image.open(f"{scan}/ref/ref.tif")
fluid = np.array(im)
ref = np.array(im_ref)
## Choose image size
# h, w = (206, 206)
# h, w = (512, 512)
h, w = (1024, 1024)
e_inc_fields = []
e_comp_fields = []
g_inc_fields = []
g_comp_fields = []
filtering_radius = 2 # If no smooth set to 0
exponent = 8 # Hypergaussian for beam edge smoothing
scale = 4 # Oversampling factor
field_ref = contrast.im_osc_fast_t(
fluid / ref,
center=(fluid.shape[-2] // 2, fluid.shape[-1] // 4),
radius=fluid.shape[-2] // 8,
)
rho_ref = field_ref.real * field_ref.real + field_ref.imag * field_ref.imag
# Define a circular mask from the reference field
threshold = 5e-2
mask_ref = rho_ref < threshold * np.max(rho_ref)
mask_fluid = rho_ref >= threshold * np.max(rho_ref)
radius_mask_ref = np.sqrt(np.sum(mask_fluid) / np.pi) / 1.05
x, y = np.meshgrid(np.arange(mask_ref.shape[-1]), np.arange(mask_ref.shape[-2]))
x = x - mask_ref.shape[-1] // 2
y = y - mask_ref.shape[-2] // 2
## Hypergaussian
E0 = np.exp(-(((x**2 + y**2) / radius_mask_ref**2) ** exponent))
for i in np.arange(1, img_nbr + 1):
dn = Image.open(f"{scan}/{which}/{which}_{i}.tif")
im_field = np.array(dn)
field = contrast.im_osc_fast_t(
im_field / ref,
center=(im_field.shape[-2] // 2, im_field.shape[-1] // 4),
radius=im_field.shape[-2] // 8,
)
contrast.exp_angle_fast(field, field_ref)
field = ndimage.gaussian_filter(field, filtering_radius)
center = (field.shape[-2] // 2, field.shape[-1] // 2)
roi = (
slice(center[0] - h // 2, center[0] + h // 2),
slice(center[1] - w // 2, center[1] + w // 2),
)
field = field * np.abs(E0) # Smooth edges
field = field[roi]
if debug:
figure, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(np.abs(field), cmap="gray", interpolation="none")
ax[1].imshow(np.angle(field), cmap="twilight_shifted", interpolation="none")
plt.show()
ks = 2 * np.pi * np.fft.fftfreq(field.shape[-1] * scale, d=d_real)
ks = ks[0 : field.shape[0] // 2]
rs = np.linspace(0, field.shape[0] // 2 * d_real * scale, ks.size)
# if no nvidia GPU set cp=False
g_inc_field, g_comp_field = velocity.corr_spectra(
k=ks, r=rs, psi=field, d=d_real, cp=GPU
)
e_inc_field, e_comp_field = velocity.comp_incomp_spectrum(
k=ks, psi=field, d=d_real, cp=GPU
)
e_inc_fields += [e_inc_field]
e_comp_fields += [e_comp_field]
g_inc_fields += [g_inc_field]
g_comp_fields += [g_comp_field]
e_inc_fields = np.array(e_inc_fields)
e_inc_fields_mean = np.nanmean(e_inc_fields, axis=0)
e_inc_fields_err = np.nanstd(e_inc_fields, axis=0)
e_comp_fields = np.array(e_comp_fields)
e_comp_fields_mean = np.nanmean(e_comp_fields, axis=0)
e_comp_fields_err = np.nanstd(e_comp_fields, axis=0)
g_inc_fields = np.array(g_inc_fields)
g_inc_fields_mean = np.nanmean(g_inc_fields, axis=0)
g_inc_fields_err = np.nanstd(g_inc_fields, axis=0)
g_comp_fields = np.array(g_comp_fields)
g_comp_fields_mean = np.nanmean(g_comp_fields, axis=0)
g_comp_fields_err = np.nanstd(g_comp_fields, axis=0)
R = radius_mask_ref * d_real
Rx = R / xi
if plot:
rx = rs / xi
plt.figure(figsize=(2, 5))
plt.errorbar(
rx,
g_comp_fields_mean,
yerr=g_comp_fields_err,
marker="o",
label="Compressible",
)
plt.errorbar(
rx,
g_inc_fields_mean,
yerr=g_inc_fields_err,
marker="^",
label="Incompressible",
)
plt.xlabel(r"$r/\xi$")
plt.ylabel(r"$g^{i}_{kin}$")
plt.xlim(-2, 80)
plt.axvline(Rx)
plt.grid()
plt.legend()
plt.savefig(f"{scan}/{which}/g.svg", dpi=300)
plt.show()
np.save(f"{scan}/{which}/g_inc_fields_mean.npy", g_inc_fields_mean)
np.save(f"{scan}/{which}/g_inc_fields_err.npy", g_inc_fields_err)
np.save(f"{scan}/{which}/g_comp_fields_mean.npy", g_comp_fields_mean)
np.save(f"{scan}/{which}/g_comp_fields_err.npy", g_comp_fields_err)
np.save(f"{scan}/{which}/rx.npy", rx)
if plot:
kx = ks * xi
plt.figure(figsize=(5, 3))
plt.errorbar(
kx,
e_comp_fields_mean,
yerr=e_comp_fields_err,
marker="o",
label="Compressible",
)
plt.errorbar(
kx,
e_inc_fields_mean,
yerr=e_inc_fields_err,
marker="^",
label="Incompressible",
)
plt.xlabel(r"$k\xi$")
plt.ylabel(r"$E^{c,i}_{kin}$")
plt.yscale("log")
plt.xscale("log")
plt.tick_params(axis="both", direction="in", which="major", labelsize=13)
plt.tick_params(axis="both", direction="in", which="minor", labelsize=13)
plt.legend()
plt.axvline(1, color="grey", linestyle="-")
plt.axvline(2 * np.pi / Rx)
plt.grid()
plt.savefig(f"{scan}/{which}/e.svg", dpi=300)