-
Notifications
You must be signed in to change notification settings - Fork 6
/
chx_xpcs_xsvs_jupyter_V1.py
2464 lines (2243 loc) · 85.6 KB
/
chx_xpcs_xsvs_jupyter_V1.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 pandas as pds
from pyCHX.chx_libs import colors, markers
from pyCHX.chx_packages import *
# from pyCHX.chx_generic_functions import get_short_long_labels_from_qval_dict
# RUN_GUI = False
# from pyCHX.chx_libs import markers
# from IPython import get_ipython
# ip = get_ipython()
# ip.run_line_magic(
# "run", "/nsls2/data/chx/shared/CHX_Software/packages/environment_management/chx_analysis_setup.ipynb"
# )
def get_t_iqc_uids(uid_list, setup_pargs, slice_num=10, slice_width=1):
"""Get Iq at different time edge (difined by slice_num and slice_width) for a list of uids
Input:
uid_list: list of string (uid)
setup_pargs: dict, for caculation of Iq, the key of this dict should include
'center': beam center
'dpix': pixel size
'lambda_': X-ray wavelength
slice_num: slice number of the time edge
slice_edge: the width of the time_edge
Output:
qs: dict, with uid as key, with value as q values
iqsts:dict, with uid as key, with value as iq values
tstamp:dict, with uid as key, with value as time values
"""
iqsts = {}
tstamp = {}
qs = {}
label = []
for uid in uid_list:
md = get_meta_data(uid)
luid = md["uid"]
timeperframe = md["cam_acquire_period"]
N = md["cam_num_images"]
filename = "/XF11ID/analysis/Compressed_Data" + "/uid_%s.cmp" % luid
good_start = 5
FD = Multifile(filename, good_start, N)
Nimg = FD.end - FD.beg
time_edge = create_time_slice(Nimg, slice_num=slice_num, slice_width=slice_width, edges=None)
time_edge = np.array(time_edge) + good_start
# print( time_edge )
tstamp[uid] = time_edge[:, 0] * timeperframe
qpt, iqsts[uid], qt = get_t_iqc(FD, time_edge, None, pargs=setup_pargs, nx=1500)
qs[uid] = qt
return qs, iqsts, tstamp
def plot_t_iqtMq2(qt, iqst, tstamp, ax=None, perf=""):
"""plot q2~Iq at differnt time"""
if ax is None:
fig, ax = plt.subplots()
q = qt
for i in range(iqst.shape[0]):
yi = iqst[i] * q**2
time_labeli = perf + "time_%s s" % (round(tstamp[i], 3))
plot1D(
x=q,
y=yi,
legend=time_labeli,
xlabel="Q (A-1)",
ylabel="I(q)*Q^2",
title="I(q)*Q^2 ~ time",
m=markers[i],
c=colors[i],
ax=ax,
ylim=[-0.001, 0.005],
) # , xlim=[0.007,0.1] )
def plot_t_iqc_uids(qs, iqsts, tstamps):
"""plot q2~Iq at differnt time for a uid list"""
keys = list(qs.keys())
fig, ax = plt.subplots()
for uid in keys:
qt = qs[uid]
iqst = iqsts[uid]
tstamp = tstamps[uid]
plot_t_iqtMq2(qt, iqst, tstamp, ax=ax, perf=uid + "_")
def plot_entries_from_csvlist(
csv_list,
uid_list,
inDir,
key="g2",
qth=1,
legend_size=8,
yshift=0.01,
ymulti=1,
xlim=None,
ylim=None,
uid_length=None,
legend=None,
fp_fulluid=True,
):
"""
YG Feb2, 2018, make yshift be also a list
YG June 9, 2017@CHX
YG Sep 29, 2017@CHX.
plot enteries for a list csvs
Input:
csv_list: list, a list of uid (string)
inDir: string, imported folder for saved analysis results
key: string, plot entry, surport
'g2' for one-time,
'iq' for q~iq
'mean_int_sets' for mean intensity of each roi as a function of frame
TODOLIST:#also can plot the following
dict_keys(['qt', 'imgsum', 'qval_dict_v', 'bad_frame_list', 'iqst',
'times_roi', 'iq_saxs', 'g2', 'mask', 'g2_uids', 'taus_uids',
'g2_fit_paras', 'mean_int_sets', 'roi_mask', 'qval_dict', 'taus',
'pixel_mask', 'avg_img', 'qval_dict_p', 'q_saxs', 'md'])
qth: integer, the intesrest q number
yshift: float, values of shift in y direction
xlim: [x1,x2], for plot x limit
ylim: [y1,y2], for plot y limit
Output:
show the plot
Example:
uid_list = ['5492b9', '54c5e0']
plot_entries_from_uids( uid_list, inDir, yshift = 0.01, key= 'g2', ylim=[1, 1.2])
"""
uid_dict = {}
fig, ax = plt.subplots()
for uid in uid_list:
if uid_length is not None:
uid_ = uid[:uid_length]
else:
uid_ = uid
# print(uid_)
uid_dict[uid_] = get_meta_data(uid)["uid"]
# for i, u in enumerate( list( uid_dict.keys() )):
for i, fp in enumerate(list(csv_list)):
u = uid_list[i] # print(u)
inDiru = inDir + u + "/"
if fp_fulluid:
inDiru = inDir + uid_dict[u] + "/"
else:
inDiru = inDir + u + "/"
d = pds.read_csv(inDiru + fp)
# print(d)
if key == "g2":
taus = d["tau"][1:]
col = d.columns[qth + 1]
# print( qth+1, col )
y = d[col][1:]
if legend is None:
leg = u
else:
leg = "uid=%s-->" % u + legend[i]
if isinstance(yshift, list):
yshift_ = yshift[i]
ii = i + 1
else:
yshift_ = yshift
ii = i
plot1D(
x=taus,
y=y + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=True,
legend=leg,
xlabel="t (sec)",
ylabel="g2",
legend_size=legend_size,
)
title = "Q = %s" % (col)
ax.set_title(title)
elif key == "imgsum":
y = total_res[key]
plot1D(
y=d + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
legend=u,
xlabel="Frame",
ylabel="imgsum",
)
elif key == "iq":
x = total_res["q_saxs"]
y = total_res["iq_saxs"]
plot1D(
x=x,
y=y * ymulti[i] + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
logy=True,
legend=u,
xlabel="Q " r"($\AA^{-1}$)",
ylabel="I(q)",
)
else:
d = total_res[key][:, qth]
plot1D(
x=np.arange(len(d)),
y=d + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
legend=u,
xlabel="xx",
ylabel=key,
)
if key == "mean_int_sets":
ax.set_xlabel("frame ")
if xlim is not None:
ax.set_xlim(xlim)
if ylim is not None:
ax.set_ylim(ylim)
return fig, ax
def plot_entries_from_uids(
uid_list,
inDir,
key="g2",
qth=1,
legend_size=8,
yshift=0.01,
ymulti=1,
xlim=None,
ylim=None,
legend=None,
uid_length=None,
filename_list=None,
fp_fulluid=False,
fp_append=None,
): # ,title='' ):
"""
YG Feb2, 2018, make yshift be also a list
YG June 9, 2017@CHX
YG Sep 29, 2017@CHX.
plot enteries for a list uids
Input:
uid_list: list, a list of uid (string)
inDir: string, imported folder for saved analysis results
key: string, plot entry, surport
'g2' for one-time,
'iq' for q~iq
'mean_int_sets' for mean intensity of each roi as a function of frame
TODOLIST:#also can plot the following
dict_keys(['qt', 'imgsum', 'qval_dict_v', 'bad_frame_list', 'iqst',
'times_roi', 'iq_saxs', 'g2', 'mask', 'g2_uids', 'taus_uids',
'g2_fit_paras', 'mean_int_sets', 'roi_mask', 'qval_dict', 'taus',
'pixel_mask', 'avg_img', 'qval_dict_p', 'q_saxs', 'md'])
qth: integer, the intesrest q number
yshift: float, values of shift in y direction
xlim: [x1,x2], for plot x limit
ylim: [y1,y2], for plot y limit
Output:
show the plot
Example:
uid_list = ['5492b9', '54c5e0']
plot_entries_from_uids( uid_list, inDir, yshift = 0.01, key= 'g2', ylim=[1, 1.2])
"""
uid_dict = {}
fig, ax = plt.subplots()
for uid in uid_list:
if uid_length is not None:
uid_ = uid[:uid_length]
else:
uid_ = uid
# print(uid_)
uid_dict[uid_] = get_meta_data(uid)["uid"]
# for i, u in enumerate( list( uid_dict.keys() )):
for i, u in enumerate(list(uid_list)):
# print(u)
if isinstance(yshift, list):
yshift_ = yshift[i]
ii = i + 1
else:
yshift_ = yshift
ii = i
if uid_length is not None:
u = u[:uid_length]
inDiru = inDir + u + "/"
if fp_fulluid:
inDiru = inDir + uid_dict[u] + "/"
else:
inDiru = inDir + u + "/"
if filename_list is None:
if fp_append is not None:
filename = "uid=%s%s_Res.h5" % (uid_dict[u], fp_append)
else:
filename = "uid=%s_Res.h5" % uid_dict[u]
else:
filename = filename_list[i]
total_res = extract_xpcs_results_from_h5(filename=filename, import_dir=inDiru, exclude_keys=["g12b"])
if key == "g2":
d = total_res[key][1:, qth]
taus = total_res["taus"][1:]
if legend is None:
leg = u
else:
leg = "uid=%s-->" % u + legend[i]
plot1D(
x=taus,
y=d + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=True,
legend=leg,
xlabel="t (sec)",
ylabel="g2",
legend_size=legend_size,
)
title = "Q = %s" % (total_res["qval_dict"][qth])
ax.set_title(title)
elif key == "imgsum":
d = total_res[key]
plot1D(
y=d + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
legend=u,
xlabel="Frame",
ylabel="imgsum",
)
elif key == "iq":
x = total_res["q_saxs"]
y = total_res["iq_saxs"]
plot1D(
x=x,
y=y * ymulti[i] + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
logy=True,
legend=u,
xlabel="Q " r"($\AA^{-1}$)",
ylabel="I(q)",
)
else:
d = total_res[key][:, qth]
plot1D(
x=np.arange(len(d)),
y=d + yshift_ * ii,
c=colors[i],
m=markers[i],
ax=ax,
logx=False,
legend=u,
xlabel="xx",
ylabel=key,
)
if key == "mean_int_sets":
ax.set_xlabel("frame ")
if xlim is not None:
ax.set_xlim(xlim)
if ylim is not None:
ax.set_ylim(ylim)
return fig, ax
####################################################################################################
##For real time analysis##
#################################################################################################
def get_iq_from_uids(uids, mask, setup_pargs):
"""Y.G. developed July 17, 2017 @CHX
Get q-Iq of a uids dict, each uid could corrrespond one frame or a time seriers
uids: dict, val: meaningful decription, key: a list of uids
mask: bool-type 2D array
setup_pargs: dict, at least should contains, the following paramters for calculation of I(q)
'Ldet': 4917.50495,
'center': [988, 1120],
'dpix': 0.075000003562308848,
'exposuretime': 0.99998999,
'lambda_': 1.2845441,
'path': '/XF11ID/analysis/2017_2/yuzhang/Results/Yang_Pressure/',
"""
Nuid = len(np.concatenate(np.array(list(uids.values()))))
label = np.zeros([Nuid + 1], dtype=object)
img_data = {} # np.zeros( [ Nuid, avg_img.shape[0], avg_img.shape[1]])
n = 0
for k in list(uids.keys()):
for uid in uids[k]:
uidstr = "uid=%s" % uid
sud = get_sid_filenames(db[uid])
# print(sud)
md = get_meta_data(uid)
imgs = load_data(uid, md["detector"], reverse=True)
md.update(imgs.md)
Nimg = len(imgs)
if Nimg != 1:
filename = "/XF11ID/analysis/Compressed_Data" + "/uid_%s.cmp" % sud[1]
mask0, avg_img, imgsum, bad_frame_list = compress_eigerdata(
imgs,
mask,
md,
filename,
force_compress=False,
para_compress=True,
bad_pixel_threshold=1e14,
bins=1,
num_sub=100,
num_max_para_process=500,
with_pickle=True,
)
else:
avg_img = imgs[0]
show_img(
avg_img,
vmin=0.00001,
vmax=1e1,
logs=True,
aspect=1, # save_format='tif',
image_name=uidstr + "_img_avg",
save=True,
path=setup_pargs["path"],
cmap=cmap_albula,
)
setup_pargs["uid"] = uidstr
qp_saxs, iq_saxs, q_saxs = get_circular_average(avg_img, mask, pargs=setup_pargs, save=True)
if n == 0:
iqs = np.zeros([len(q_saxs), Nuid + 1])
iqs[:, 0] = q_saxs
label[0] = "q"
img_data[k + "_" + uid] = avg_img
iqs[:, n + 1] = iq_saxs
label[n + 1] = k + "_" + uid
n += 1
plot_circular_average(
qp_saxs,
iq_saxs,
q_saxs,
pargs=setup_pargs,
xlim=[q_saxs.min(), q_saxs.max() * 0.9],
ylim=[iq_saxs.min(), iq_saxs.max()],
)
if "filename" in list(setup_pargs.keys()):
filename = setup_pargs["filename"]
else:
filename = "qIq.csv"
pd = save_arrays(iqs, label=label, dtype="array", filename=filename, path=setup_pargs["path"], return_res=True)
return pd, img_data
def wait_func(wait_time=2):
print("Waiting %s secdons for upcoming data..." % wait_time)
time.sleep(wait_time)
# print( 'Starting to do something here...')
def wait_data_acquistion_finish(uid, wait_time=2, max_try_num=3):
"""check the completion of a data uid acquistion
Parameter:
uid:
wait_time: the waiting step in unit of second
check_func: the function to check the completion
max_try_num: the maximum number for waiting
Return:
True: completion
False: not completion (include waiting time exceeds the max_wait_time)
"""
FINISH = False
Fake_FINISH = True
w = 0
sleep_time = 0
while not FINISH:
try:
get_meta_data(uid)
FINISH = True
print("The data acquistion finished.")
print("Starting to do something here...")
except:
wait_func(wait_time=wait_time)
w += 1
print("Try number: %s" % w)
if w > max_try_num:
print("There could be something going wrong with data acquistion.")
print("Force to terminate after %s tries." % w)
FINISH = True
Fake_FINISH = False
sleep_time += wait_time
return FINISH * Fake_FINISH # , sleep_time
def get_uids_by_range(start_uidth=-1, end_uidth=0):
"""Y.G. Dec 22, 2016
A wrap funciton to find uids by giving start and end uid number, i.e. -10, -1
Return:
uids: list, uid with 8 character length
fuids: list, uid with full length
"""
hdrs = list([db[n] for n in range(start_uidth, end_uidth)])
if len(hdrs) != 0:
print("Totally %s uids are found." % (len(hdrs)))
uids = [] # short uid
fuids = [] # full uid
for hdr in hdrs:
fuid = hdr["start"]["uid"]
uids.append(fuid[:8])
fuids.append(fuid)
uids = uids[::-1]
fuids = fuids[::-1]
return np.array(uids), np.array(fuids)
def get_uids_in_time_period(start_time, stop_time):
"""Y.G. Dec 22, 2016
A wrap funciton to find uids by giving start and end time
Return:
uids: list, uid with 8 character length
fuids: list, uid with full length
"""
hdrs = list(db(start_time=start_time, stop_time=stop_time))
if len(hdrs) != 0:
print("Totally %s uids are found." % (len(hdrs)))
uids = [] # short uid
fuids = [] # full uid
for hdr in hdrs:
fuid = hdr["start"]["uid"]
uids.append(fuid[:8])
fuids.append(fuid)
uids = uids[::-1]
fuids = fuids[::-1]
return np.array(uids), np.array(fuids)
def do_compress_on_line(start_time, stop_time, mask_dict=None, mask=None, wait_time=2, max_try_num=3):
"""Y.G. Mar 10, 2017
Do on-line compress by giving start time and stop time
Parameters:
mask_dict: a dict, e.g., {mask1: mask_array1, mask2:mask_array2}
wait_time: search interval time
max_try_num: for each found uid, will try max_try_num*wait_time seconds
Return:
running time
"""
t0 = time.time()
uids, fuids = get_uids_in_time_period(start_time, stop_time)
print(fuids)
if len(fuids):
for uid in fuids:
print("*" * 50)
print("Do compress for %s now..." % uid)
if db[uid]["start"]["plan_name"] == "count":
finish = wait_data_acquistion_finish(uid, wait_time, max_try_num)
if finish:
try:
md = get_meta_data(uid)
compress_multi_uids(
[uid],
mask=mask,
mask_dict=mask_dict,
force_compress=False,
para_compress=True,
bin_frame_number=1,
)
update_olog_uid(uid=md["uid"], text="Data are on-line sparsified!", attachments=None)
except:
print("There are something wrong with this data: %s..." % uid)
print("*" * 50)
return time.time() - t0
def realtime_xpcs_analysis(
start_time, stop_time, run_pargs, md_update=None, wait_time=2, max_try_num=3, emulation=False, clear_plot=False
):
"""Y.G. Mar 10, 2017
Do on-line xpcs by giving start time and stop time
Parameters:
run_pargs: all the run control parameters, including giving roi_mask
md_update: if not None, a dict, will update all the found uid metadata by this md_update
e.g,
md['beam_center_x'] = 1012
md['beam_center_y']= 1020
md['det_distance']= 16718.0
wait_time: search interval time
max_try_num: for each found uid, will try max_try_num*wait_time seconds
emulation: if True, it will only check dataset and not do real analysis
Return:
running time
"""
t0 = time.time()
uids, fuids = get_uids_in_time_period(start_time, stop_time)
# print( fuids )
if len(fuids):
for uid in fuids:
print("*" * 50)
# print('Do compress for %s now...'%uid)
print("Starting analysis for %s now..." % uid)
if db[uid]["start"]["plan_name"] == "count" or db[uid]["start"]["plan_name"] == "manual_count":
# if db[uid]['start']['dtype'] =='xpcs':
finish = wait_data_acquistion_finish(uid, wait_time, max_try_num)
if finish:
try:
md = get_meta_data(uid)
##corect some metadata
if md_update is not None:
md.update(md_update)
# if 'username' in list(md.keys()):
# try:
# md_cor['username'] = md_update['username']
# except:
# md_cor = None
# uid = uid[:8]
# print(md_cor)
if not emulation:
# suid=uid[:6]
run_xpcs_xsvs_single(
uid, run_pargs=run_pargs, md_cor=None, return_res=False, clear_plot=clear_plot
)
# update_olog_uid( uid= md['uid'], text='Data are on-line sparsified!',attachments=None)
except:
print("There are something wrong with this data: %s..." % uid)
else:
print("\nThis is not a XPCS series. We will simiply ignore it.")
print("*" * 50)
# print( 'Sleep 10 sec here!!!')
# time.sleep(10)
return time.time() - t0
####################################################################################################
##compress multi uids, sequential compress for uids, but for each uid, can apply parallel compress##
#################################################################################################
def compress_multi_uids(
uids,
mask,
mask_dict=None,
force_compress=False,
para_compress=True,
bin_frame_number=1,
reverse=True,
rot90=False,
use_local_disk=True,
):
"""Compress time series data for a set of uids
Parameters:
uids: list, a list of uid
mask: bool array, mask array
force_compress: default is False, just load the compresssed data;
if True, will compress it to overwrite the old compressed data
para_compress: apply the parallel compress algorithm
bin_frame_number:
Return:
None, save the compressed data in, by default, /XF11ID/analysis/Compressed_Data with filename as
'/uid_%s.cmp' uid is the full uid string
e.g., compress_multi_uids( uids, mask, force_compress= False, bin_frame_number=1 )
"""
for uid in uids:
print("UID: %s is in processing..." % uid)
if validate_uid(uid):
md = get_meta_data(uid)
imgs = load_data(uid, md["detector"], reverse=reverse, rot90=rot90)
sud = get_sid_filenames(db[uid])
for pa in sud[2]:
if "master.h5" in pa:
data_fullpath = pa
print(imgs, data_fullpath)
if mask_dict is not None:
mask = mask_dict[md["detector"]]
print("The detecotr is: %s" % md["detector"])
md.update(imgs.md)
if not use_local_disk:
cmp_path = "/nsls2/xf11id1/analysis/Compressed_Data"
else:
cmp_path = "/tmp_data/compressed"
cmp_path = "/nsls2/xf11id1/analysis/Compressed_Data"
if bin_frame_number == 1:
cmp_file = "/uid_%s.cmp" % md["uid"]
else:
cmp_file = "/uid_%s_bined--%s.cmp" % (md["uid"], bin_frame_number)
filename = cmp_path + cmp_file
mask, avg_img, imgsum, bad_frame_list = compress_eigerdata(
imgs,
mask,
md,
filename,
force_compress=force_compress,
para_compress=para_compress,
bad_pixel_threshold=1e14,
reverse=reverse,
rot90=rot90,
bins=bin_frame_number,
num_sub=100,
num_max_para_process=500,
with_pickle=True,
direct_load_data=use_local_disk,
data_path=data_fullpath,
)
print("Done!")
####################################################################################################
##get_two_time_mulit_uids, sequential cal for uids, but apply parallel for each uid ##
#################################################################################################
def get_two_time_mulit_uids(
uids,
roi_mask,
norm=None,
bin_frame_number=1,
path=None,
force_generate=False,
md=None,
imgs=None,
direct_load_data=False,
compress_path=None,
):
"""Calculate two time correlation by using auto_two_Arrayc func for a set of uids,
if the two-time resutls are already created, by default (force_generate=False), just pass
Parameters:
uids: list, a list of uid
roi_mask: bool array, roi mask array
norm: the normalization array
path: string, where to save the two time
force_generate: default, False, if the two-time resutls are already created, just pass
if True, will force to calculate two-time no matter exist or not
Return:
None, save the two-time in as path + uid + 'uid=%s_g12b'%uid
e.g.,
get_two_time_mulit_uids( guids, roi_mask, norm= norm,bin_frame_number=1,
path= data_dir,force_generate=False )
"""
qind, pixelist = roi.extract_label_indices(roi_mask)
for uid in uids:
print("UID: %s is in processing..." % uid)
if not direct_load_data:
md = get_meta_data(uid)
imgs = load_data(uid, md["detector"], reverse=True)
else:
pass
N = len(imgs)
# print( N )
if compress_path is None:
compress_path = "/XF11ID/analysis/Compressed_Data/"
if bin_frame_number == 1:
filename = "%s" % compress_path + "uid_%s.cmp" % md["uid"]
else:
filename = "%s" % compress_path + "uid_%s_bined--%s.cmp" % (md["uid"], bin_frame_number)
FD = Multifile(filename, 0, N // bin_frame_number)
# print( FD.beg, FD.end)
uid_ = md["uid"]
os.makedirs(path + uid_ + "/", exist_ok=True)
filename = path + uid_ + "/" + "uid=%s_g12b" % uid
doit = True
if not force_generate:
if os.path.exists(filename + ".npy"):
doit = False
print("The two time correlation function for uid=%s is already calculated. Just pass..." % uid)
if doit:
data_pixel = Get_Pixel_Arrayc(FD, pixelist, norm=norm).get_data()
g12b = auto_two_Arrayc(data_pixel, roi_mask, index=None)
np.save(filename, g12b)
del g12b
print("The two time correlation function for uid={} is saved as {}.".format(uid, filename))
def get_series_g2_from_g12(
g12b, fra_num_by_dose=None, dose_label=None, good_start=0, log_taus=True, num_bufs=8, time_step=1
):
"""
Get a series of one-time function from two-time by giving noframes
Parameters:
g12b: a two time function
good_start: the start frame number
fra_num_by_dose: a list, correlation number starting from index 0,
if this number is larger than g12b length, will give a warning message, and
will use g12b length to replace this number
by default is None, will = [ g12b.shape[0] ]
dose_label: the label of each dose, also is the keys of returned g2, lag
log_taus: if true, will only return a g2 with the correponding tau values
as calculated by multi-tau defined taus
Return:
g2_series, a dict, with keys as dose_label (corrected on if warning message is given)
lag_steps, the corresponding lags
"""
g2 = {}
lag_steps = {}
L, L, qs = g12b.shape
if fra_num_by_dose is None:
fra_num_by_dose = [L]
if dose_label is None:
dose_label = fra_num_by_dose
fra_num_by_dose = sorted(fra_num_by_dose)
dose_label = sorted(dose_label)
for i, good_end in enumerate(fra_num_by_dose):
key = round(dose_label[i], 3)
# print( good_end )
if good_end > L:
warnings.warn(
"Warning: the dose value is too large, and please check the maxium dose in this data set and give a smaller dose value. We will use the maxium dose of the data."
)
good_end = L
if not log_taus:
g2[key] = get_one_time_from_two_time(g12b[good_start:good_end, good_start:good_end, :])
else:
# print( good_end, num_bufs )
lag_step = get_multi_tau_lag_steps(good_end, num_bufs)
lag_step = lag_step[lag_step < good_end - good_start]
# print( len(lag_steps ) )
lag_steps[key] = lag_step * time_step
g2[key] = get_one_time_from_two_time(g12b[good_start:good_end, good_start:good_end, :])[lag_step]
return lag_steps, g2
def get_fra_num_by_dose(exp_dose, exp_time, att=1, dead_time=2):
"""
Calculate the frame number to be correlated by giving a X-ray exposure dose
Paramters:
exp_dose: a list, the exposed dose, e.g., in unit of exp_time(ms)*N(fram num)*att( attenuation)
exp_time: float, the exposure time for a xpcs time sereies
dead_time: dead time for the fast shutter reponse time, CHX = 2ms
Return:
noframes: the frame number to be correlated, exp_dose/( exp_time + dead_time )
e.g.,
no_dose_fra = get_fra_num_by_dose( exp_dose = [ 3.34* 20, 3.34*50, 3.34*100, 3.34*502, 3.34*505 ],
exp_time = 1.34, dead_time = 2)
--> no_dose_fra will be array([ 20, 50, 100, 502, 504])
"""
return np.int_(np.array(exp_dose) / (exp_time + dead_time) / att)
def get_series_one_time_mulit_uids(
uids,
qval_dict,
trans=None,
good_start=0,
path=None,
exposure_dose=None,
dead_time=0,
num_bufs=8,
save_g2=True,
md=None,
imgs=None,
direct_load_data=False,
):
"""Calculate a dose depedent series of one time correlations from two time
Parameters:
uids: list, a list of uid
trans: list, same length as uids, the transmission list
exposure_dose: list, a list x-ray exposure dose;
by default is None, namely, = [ max_frame_number ],
can be [3.34 334, 3340] in unit of ms, in unit of exp_time(ms)*N(fram num)*att( attenuation)
path: string, where to load the two time, if None, ask for it
the real g12 path is two_time_path + uid + '/'
qval_dict: the dictionary for q values
Return:
taus_uids, with keys as uid, and
taus_uids[uid] is also a dict, with keys as dose_frame
g2_uids, with keys as uid, and
g2_uids[uid] is also a dict, with keys as dose_frame
will also save g2 results to the 'path'
"""
if path is None:
print("Please calculate two time function first by using get_two_time_mulit_uids function.")
else:
taus_uids = {}
g2_uids = {}
for i, uid in enumerate(uids):
print("UID: %s is in processing..." % uid)
if not direct_load_data:
md = get_meta_data(uid)
imgs = load_data(uid, md["detector"], reverse=True)
# print(md)
detectors = md["detector"]
if isinstance(detectors, list):
if len(detectors) > 1:
if "_image" in md["detector"]:
pref = md["detector"][:-5]
else:
pref = md["detector"]
for k in [
"beam_center_x",
"beam_center_y",
"cam_acquire_time",
"cam_acquire_period",
"cam_num_images",
"wavelength",
"det_distance",
"photon_energy",
]:
md[k] = md[pref + "%s" % k]
else:
pass
N = len(imgs)
if exposure_dose is None:
exposure_dose = [N]
try:
g2_path = path + uid + "/"
g12b = np.load(g2_path + "uid=%s_g12b.npy" % uid)
except:
g2_path = path + md["uid"] + "/"
g12b = np.load(g2_path + "uid=%s_g12b.npy" % uid)
try:
exp_time = float(md["cam_acquire_time"]) # *1000 #from second to ms
except:
exp_time = float(md["exposure time"]) # * 1000 #from second to ms
if trans is None:
try:
transi = md["transmission"]
except:
transi = [1]
else:
transi = trans[i]
fra_num_by_dose = get_fra_num_by_dose(
exp_dose=exposure_dose, exp_time=exp_time, dead_time=dead_time, att=transi
)
print("uid: %s--> fra_num_by_dose: %s" % (uid, fra_num_by_dose))
taus_uid, g2_uid = get_series_g2_from_g12(
g12b,
fra_num_by_dose=fra_num_by_dose,
dose_label=exposure_dose,
good_start=good_start,
num_bufs=num_bufs,
time_step=exp_time,
) # md['cam_acquire_period'] )
g2_uids["uid_%03d=%s" % (i, uid)] = g2_uid
taus_uids["uid_%03d=%s" % (i, uid)] = taus_uid
if save_g2:
for k in list(g2_uid.keys()):
# print(k)
uid_ = uid + "_fra_%s_%s" % (good_start, k)
save_g2_general(
g2_uid[k],
taus=taus_uid[k],
qr=np.array(list(qval_dict.values()))[:, 0],
uid=uid_ + "_g2.csv",
path=g2_path,
return_res=False,
)
return taus_uids, g2_uids
def plot_dose_g2(
taus_uids,
g2_uids,
qval_dict,
qth_interest=None,
ylim=[0.95, 1.05],