-
Notifications
You must be signed in to change notification settings - Fork 0
/
mystrax.py
executable file
·1903 lines (1379 loc) · 51 KB
/
mystrax.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 sys
import os
from datetime import datetime
from flo_analysis import *
import flo_fancy
import flo_decorators
from threading import Thread, Event
import matplotlib.pyplot as plt
import matplotlib as mpl
import mystrax_corrections as msc
import get_corrections as gc
def now():
return(datetime.now())
mystrax_limporttime = now()
def age():
print(f"strax loaded from \33[1m{straxpath}\33[0m at {mystrax_limporttime} (age: {now() - mystrax_limporttime})")
tcol = "\33[36m"
if "straxpath" in os.environ:
straxpath = os.environ["straxpath"]
print(f"found straxpath envornmental variable: {straxpath}")
else:
straxpath = "/data/workspace/Flo/straxbra_flo"
# import
sys.path.insert(0,f"{straxpath}/strax")
import strax
sys.path.insert(0,f"{straxpath}/straxbra")
import straxbra
eff = straxbra.plugins.eff
context_sp = straxbra.SinglePhaseContext()
context_dp = straxbra.XebraContext()
db = straxbra.utils.db
# database collections
mycol = db["calibration_info"]
corr_coll = db["correction_info"]
labels = gc.labels
fields_df = gc.fields_df
def time_from__id(_id):
return(datetime.fromtimestamp(int(str(_id)[:8], 16)))
def get_field(ds, field, prio_identical = True):
'''
returns the field of ds that start with field
'''
lf = len(field)
if (field in ds.dtype.names) and (prio_identical is True):
return(field)
fields = [n for n in ds.dtype.names if n[:lf]==field]
if len(fields) == 1:
return(fields[0])
else:
return(fields)
def s1_ratios(ds):
field = get_field(ds, "areas")
ratios = ds[field][:,0]/ds[field][:,1]
return(ratios)
def draw_multi_woa_multi(ds, axs, draw_list=False, plugin = "event_fits_summary", titles = False, **kwargs):
'''
wrapper fucntion to draw all three default woa multis of ds into axs
'''
if draw_list is False:
draw_list = ["0123", "45", "67"]
if titles is False:
titles = ["", "", ""]
for ax, draw, title in zip(axs, draw_list, titles):
draw_woa_multi(ds, ax = ax, draw = draw, plugin = plugin, title = title, **kwargs)
def draw_woa_single(
a, w, ax = False,
label = "Signal",
cmap = "Purples",
show_counts = True,
setup = True,
):
'''
cmap:
'Purples', 'Reds', 'Blues','Greens','Oranges'
'''
if not isinstance(ax, plt.Axes):
raise TypeError("ax must be plt.Axes")
count, bca, bcw = fhist.make_2d_hist_plot(a, w)
n_count = np.nansum(count, dtype = int)
count_ = count / n_count
if show_counts is True:
label = f"{label} (N: {n_count})"
im_ = ax.pcolormesh(
bca, bcw,
count_.T,
norm=fhist.LogNorm(),
cmap = cmap,
)
if setup is True:
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel(fhist.defaults["2d_hist_label_area"])
ax.set_ylabel(fhist.defaults["2d_hist_label_width"])
color = mpl.cm.get_cmap(cmap)(.75)
if label != "":
ax.plot(
[],
"o",
color = color,
label = label
)
ax.legend(loc = "upper right")
return(color, n_count)
def draw_woa_scatter(
ds,
ax = False,
draw = "0123",
plugin = "event_fits_summary",
labels_ = False,
field_a = "areas_corrected",
field_w = "widths",
colors = False, alpha = .01,
marker = ".",
rasterized = True,
):
if ax is False:
ax = fhist.ax()
if colors is False:
colors = fhist.default_colors
if labels_ is False:
labels_ = labels[plugin]
for i_draw, field_id_str, color in enumezip(draw, colors):
field_id = int(field_id_str)
label = labels_[field_id]
w = ds[field_w][:, field_id]
a = ds[field_a][:, field_id]
addlabel(ax, f"{label}", marker = "o", color = color )
ax.plot(
a, w,
linestyle = "",
marker = marker, markeredgewidth = 0,
alpha = alpha, color = color,
rasterized = rasterized
)
ax.set_xlim(10,1e5)
ax.set_ylim(10,1e4)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel("area / PE")
ax.set_ylabel("width / ns")
ax.legend(loc = "upper right")
ax.grid()
def draw_woa_multi(
ds, ax = False, draw = "0123", plugin = "event_fits_summary", add_grid = True, show_only_max_count = True,
vmin = 1, global_scale = False, show_counts = True, title = "", show_precut = False,
labels_ = False, field_a = "auto", field_w = "auto", cmaps = False, cmap_cb = False):
'''
draws multiple signals in one width over area plot
each signal get a different color
params:
ds: the dataset that contains the fields "areas" and "widths"
draw: the field indize to draw. must be iteratble (string or list)
default: "0123"
plugin: used to get labels via labels[plugin]
default: event_fits_summary
add_grid: adds a grid to the plot if set to True
default: True
show_only_max_count: If True draws only the max count per bin.
prevents lower values overwriting higher values
default True
vmin: bins with less counts are set to 0
default 2
global_scale: wheter the colorbars should have the same vmax or not
default True
show_counts: wheter the legend shoudl also contain the number of binned datapoints
default True
labels_: alternative to plugin, must be a list
default: False
field_a, field_w: fields that contain area/width
default: "areas", "widths"
ax: where to put the plot into
default: False, creates a new one
cmaps: the colormaps to use, if cmaps run out fall back to cmap_cb
default False uses ['Purples', 'Blues', 'Greens', 'Reds', 'Oranges']
cmap_cb: the colormap for the colorbar
default False uses "Greys"
'''
if field_a == "auto":
field_a = get_field(ds, "areas")
if field_w == "auto":
field_w = get_field(ds, "widths")
if (vmin is False) or (vmin < 1):
vmin = 1
if labels_ is False:
labels_ = labels[plugin]
draw = [int(i) for i in draw if int(i) < len(ds[field_a][0])]
n_draw = len(draw)
counts = [False]*n_draw
labs = [""]*n_draw
for i, j in enumerate(draw):
try:
count, bca, bcw = fhist.make_2d_hist_plot(ds[field_a][:, j], ds[field_w][:, j])
n_precut = np.nansum(count, dtype = int)
count[count < vmin] = 0
n_postcut = np.nansum(count, dtype = int)
counts[i] = count
labs[i] = labels_[j]
if show_counts is True:
if show_precut is True:
str_appendix = f" (N: {n_postcut}/{n_precut})"
else:
str_appendix = f" (N: {n_precut})"
labs[i] = f"{labs[i]}{str_appendix}"
except Exception as e:
print(f"failed at {i} (label: {labs[i]}): {e}")
if ax is False:
ax = fhist.ax()
if title != "":
ax.set_title(title)
vmax = np.nanmax(counts)
if vmax == 0:
ax.set_axis_off()
return(None)
# raise ValueError("maxmimum of counts is zero!")
if cmaps is False:
cmaps = [
'Purples',
'Reds',
'Blues',
'Greens',
'Oranges'
]
if cmap_cb is False:
cmap_cb = "Greys"
if global_scale is True:
im = ax.pcolormesh(
bca, bcw, np.zeros_like(count.T),
norm=fhist.LogNorm(),
cmap = cmap_cb, vmin=vmin, vmax=vmax
)
cb = plt.colorbar(im, ax=ax, label="Counts/bin",)
lims = dict(
vmin = vmin,
vmax = vmax,
)
else:
lims = dict(
vmin = vmin,
)
max_values = np.nanmax(np.array(counts), axis=0)
for count, label in zip(counts, labs):
if (count is not False) and (label != ""):
if len(cmaps) > 0:
cmap = cmaps.pop(0)
else:
cmap = cmap_cb
ax.plot(
[],
"o",
color = mpl.cm.get_cmap(cmap)(.75),
label = label
)
if show_only_max_count is True:
count_ = count * (count >= max_values)
else:
count_ = count
im_ = ax.pcolormesh(
bca, bcw,
count_.T,
norm=fhist.LogNorm(),
cmap = cmap,
**lims
)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel(fhist.defaults["2d_hist_label_area"])
ax.set_ylabel(fhist.defaults["2d_hist_label_width"])
ax.legend(loc = "upper right")
if add_grid is True:
ax.grid()
return(counts, bca, bcw)
def draw_woa(ds, plugin = "event_fits_summary", draw = "all", title = "", ret = False, loc = "upper right", **kwargs):
'''
draws each individual signals if available
'''
titles = labels[plugin]
if draw == "all":
draw = np.array(list(range(len(titles))))
else:
draw = np.array([int(i) for i in draw])
fig, axs = fhist.make_fig(n_tot = -len(draw), axis_off = True)
if title != "":
fig.suptitle(title)
for i, ax, title in zip(draw, axs, titles[draw]):
ax.set_title(title)
ax.set_axis_on()
try:
fhist.make_2d_hist_plot(ds["areas"][:,i],ds["widths"][:,i], ax, loc = loc, **kwargs)
ax.grid()
except Exception:
pass
plt.subplots_adjust(
hspace = .25
)
plt.show()
if ret is True:
return(fig, axs)
def jr(runs, sep = ", "):
'''
joins list of anything (maily ints of runnumbers) to list
'''
return(sep.join(map(str, runs)))
def rs(runs):
'''
turns runs into a list of run strings (zero padded to five digits) to be used when loading data
'''
if isinstance(runs, int):
runs = [runs]
elif isinstance(runs, str):
runs = [runs]
rstrs = [f"{r:0>5}" for r in runs]
return(rstrs)
def find_config(target = ""):
if target[:10] == "sp_krypton":
config = default_config
else:
config = {}
return(config)
def get_correction_for(typ = False, start = False, *_, plugin = False, run = False, limit = 1, v = False):
'''
returns correcions for types various types:
get the types by calling this funciotn witout an argument
parameters:
* typ: type of correction see above
* start (now()): time of run, correction must be older than this
* limit (1): how many entries to return
* v (False): 'verbose', prints query parameters
'''
valid_types = list(msc.corrections)
if typ is True:
print(f"valid types: {valid_types}")
if typ is True or typ is False:
return(valid_types)
if typ not in valid_types:
raise TypeError(f"typ must be in ({valid_types})")
if start is False:
start = datetime.now()
filters = [{"type": typ}]
if run is not False:
filters.append({
"$or": [
{"run":run},
{"$and":[
{"run": {"$exists": False}},
{"date": {"$lte": start}},
]}
]
})
else:
filters.append({"date": {"$lte": start}})
if isinstance(plugin, str):
filters.append({
"$or": [
{"plugin": {"$exists": False}},
{"plugin": plugin},
]
})
filters = {"$and": filters}
correction = list(corr_coll.find(
filters,
sort = [('_id', -1)],
limit = limit,#
))
if (limit == 1) and len(correction) == 1:
correction = correction[0]
return(correction)
def fiduzalize_z(ds, tpc_geometry, id_bool = False, sigmas = 1):
if not isinstance(id_bool, np.ndarray):
id_bool = np.array([True] * len(ds))
if "info" in tpc_geometry:
tpc_geometry = tpc_geometry["info"]
fiducal_dft = (
tpc_geometry["dft_gate"] + sigmas * tpc_geometry["sigma_dft_gate"],
tpc_geometry["dft_cath"] - sigmas * tpc_geometry["sigma_dft_cath"],
)
outside_fid_volume_bool = (
(ds["drifttime"] < fiducal_dft[0])
| (ds["drifttime"] > fiducal_dft[1])
)
set_zero_bool = id_bool * outside_fid_volume_bool
ds["z"][set_zero_bool] = 0
ds = ds[~set_zero_bool]
return(ds)
def check(runs, target, context = False, config = False, cast_int = True, v = True):
if context is False:
context = context_sp
if config is False:
config = find_config(target)
runs = rs(runs)
t0 = now()
if v is True: print(f"checking \33[1m{tcol}{target}\33[0m for {len(runs)} runs...")
runs = [r for r in runs if context.is_stored(r, target, config = config)]
t1 = now()
if cast_int is True:
runs = list(map(int, runs))
if v is True: print(f" found data for {len(runs)} runs in {t1-t0}")
return(runs)
def load(
runs, target,
context = False,
config = False,
mconfig = None,
check_load = True,
v = True,
correct = True,
filters = True,
fidu_z = False,
**kwargs
):
'''
loads data if availabe
parameters:
runs: list of runs to load
(either list or one value; either string or int; doestn't matter)
target: the plugin to load
context: which context to use (mystrax.context_sp or mystrax.context_dp)
default False falls back to mystrax.context_sp
config: custom config to be loaded
default False
if False uses default configs:
- mystrax.default_config for runs that start with sp_krypton
- {} for everythin else
mconfig (None): modifiying automatic config
(overwrites default configs settings if names match)
check load: check if the data is available before attmepting to load it
use a string of a different target to check the existance of that data to load this data
set to false if you want to skip all checks
default True
v: verbose toggle, prints messages
default True
filters (True): if True: looks for fields like OK and clean and returns only fields where these fields are True
if list of strings: uses list entires and checks them
fidu_z (0): if this is a number a fidicilisatzion if z will be done (only if corrections are applied)
the number is the measure for how many sigmas we move inwards to the main volume
(based on drift time position of gate and cathode)
check_load
'''
if context is False:
context = context_sp
if config is False:
config = find_config(target)
if isinstance(mconfig, dict):
config = {**config, **mconfig}
if v is True:
print("config:")
print(config)
runs = rs(runs)
if check_load is not False:
if isinstance(check_load, str):
target_ = check_load
else:
target_ = target
runs = check(runs = runs, target = target_, context = context, config = config, v = v)
if len(runs) == 0:
if v is True: print("no runs to load")
return None
t0 = now()
if v is True: print(f"loading \33[1m{tcol}{target}\33[0m of {len(runs)} runs...")
runs = rs(runs)
data = context.get_array(runs, target, config = config, **kwargs)
t1 = now()
if v is True: print(f" data loaded: {len(data)} entries for {len(runs)} runs in {t1-t0}")
if filters is True:
filters = ["OK", "clean"]
dtype_names = data.dtype.names
if isinstance(filters, list):
filters = [f for f in filters if (isinstance(f, str) and f in dtype_names)]
if v is True: qp(f"filtering: ")
for filter_i in filters:
if v is True: qp(f"{len(data)} -(\33[1m{tcol}{filter_i}\33[0m)-> ")
data = data[data[filter_i] == True]
if v is True: print(f"{len(data)}")
run_ids = list(map(int, runs))
if correct is True:
correct = get_correction_for()
if (target[-8:] == "_summary") and isinstance(correct, list):
print("correcting")
runs_info = list(db.runs.find({
"experiment": context.config["experiment"],
"run_id": {"$in": run_ids}
}))
runs_info = {x["run_id"]:x for x in runs_info}
for run_id in run_ids:
if len(run_ids) == 1:
bool_run = np.array([True]*len(data))
else:
bool_run = data["run_id"] == run_id
start_run = runs_info[run_id]["start"]
qp(f" * {run_id} ({start_run.strftime('%H:%M:%S %d.%m.%Y')}):")
tpc_info = get_correction_for("gate_cathode", start_run)["info"]
pre_string = ""
for corection_type in correct:
qp(f"{pre_string} {corection_type}")
corr = get_correction_for(corection_type, start_run, plugin = target, run = run_id)
if "run" in corr:
qp(f" ({corr['run']})")
info = corr["info"]
msc.corrections[corection_type](data, info, tpc_info, bool_run)
pre_string = ","
# why is bool a subclass of int.......
if not isinstance(fidu_z, bool) and isinstance(fidu_z, (int, float)):
data = fiduzalize_z(data, tpc_info, id_bool = bool_run, sigmas = fidu_z)
qp(f", fidu_z ({len(data)})")
print(", done")
print("correcting done")
print(f"\n\33[1m{tcol}data is ready\33[0m")
return(data)
c = {
"s":context_sp,
"d":context_dp,
}
experiments = {
"s":"xebra_singlephase",
"d": "xebra",
}
default_config = {'split_min_ratio': 1.5, 'split_min_height': 0, 'split_n_smoothing': 4}
energies_signals = {
("combined", "", 41.6),
("first", "1", 9.4),
("second", "2", 32.2),
}
def append_unique(df, fields, sep="__", uname = "unique"):
'''
modifies df directly!!
'''
out = False
for f in fields:
if out is False:
out = df[f].astype(str)
else:
out = out + sep + df[f].astype(str)
df[uname] = out
def make_unique_runs_dict(runs_all, fields):
'''
flattens the given array and merges multiple fields properties
returns a dict where each unique fields combination contains all runs
with this combination
'''
df = make_dV_df(runs_all)
append_unique(df, fields)
uniques = {u:df.loc[df["unique"] == u]["run"].values for u in np.unique(df["unique"])}
return(uniques)
def make_dV_dict(runs_all):
_Vs = np.unique([x["fields"]["dV_Anode"] for x in runs_all.values()])
runs_all_dVs = {dV:[r for r, x in runs_all.items() if x["fields"]["dV_Anode"] == dV] for dV in _Vs}
return(runs_all_dVs)
def make_df(runs_all, dict_types = True, *args, **kwargs):
df = pd.DataFrame()
t0 = min([x["start"] for r, x in runs_all.items()])
for r, d in runs_all.items():
d = {
"run": r,
"t_rel": (d["start"] - t0).total_seconds(),
**flatten_dict(d, *args, **kwargs),
}
df = df.append(d, ignore_index=True)
if dict_types is True:
# add here freely, only existing columns will be renamed
dict_types = {
'run': 'int32',
'N': 'int32',
'fields.adc': 'int32',
}
if isinstance(dict_types, dict):
columns_names = df.columns.values
dict_types = {
n:v
for n, v in dict_types.items()
if n in columns_names
}
df = df.astype(dict_types)
return(df)
def get_all_runs(query = False, *args, **kwargs):
'''
runs_all, runs_all_dVs = mystrax.get_all_runs()
parameter:
- query: database query
'''
if query is False:
query = {}
db = list(mycol.find(query))
runs_all = {db_i["run"]:db_i for db_i in db}
runs_all_df = make_df(runs_all, *args, **kwargs)
return(runs_all, runs_all_df)
# description for sp_krypton exits
DEVELOPER_fails={
0: "no peaks in event",
1: "less than 2 large peaks",
2: "less than 3 large peaks",
3: "first S1 area too large",
4: "second S1 area too large",
5: "decay time limit exceeded",
6: "drift time limit exceeded",
7: "first S2 smaller than first S1 (area)",
8: "first S1 smaller than second S1 (area)",
}
def get_unit_sp(x):
if x[:11] == "time_drift":
return("µs")
elif x[:11] == "time_decay":
return("ns")
elif x[:5] == "width":
return("ns")
elif x[:4] == "area":
return("PE")
elif x[:4] == "energy":
return("keV")
elif x[:2] == "cS":
return("PE")
else:
return("")
folder_cache = "/data/storage/strax/cached/singlephase"
def db_dict():
return(
{f["run"]:f for f in mycol.find({})}
)
def filter_peaks(peaks, sp_krypton_s1_area_min = 25, sp_krypton_max_drifttime_ns=500e3 ):
ps = peaks[peaks["area"] >= sp_krypton_s1_area_min]
idx = np.nonzero(np.diff(ps["time"]) <= sp_krypton_max_drifttime_ns)[0]
idx = np.unique(np.append(idx, idx+1))
return(ps[idx])
def draw_peaks(ax, ps, t0 = False, y_offset = 0, *args, **kwargs):
if t0 is False:
t0 = ps[0]["time"]
elif t0 == "start":
t0 = False
for pi, p in enumerate(ps):
draw_peak(ax, p, t0 = t0, y_offset = y_offset*pi, *args, **kwargs)
def draw_peak(ax, p, t0 = False, label="", show_area = False, label_peaktime = False, show_peaktime = False,
PE_ns = True, y_offset = 0, **kwargs):
if t0 is False:
t0 = p["time"]
t_offs = p["time"]-t0
y = np.trim_zeros(p["data"], trim = "b")
if PE_ns is True:
y = y / p["dt"]
y = y + y_offset
x = t_offs+np.arange(0, len(y))*p["dt"]
props = []
if show_area is True:
props.append(f"{p['area']:.1f} PE")
if label_peaktime is True:
props.append(f"{(p['time']-t0)+p['time_to_midpoint']:.0f} ns")
if len(props) > 0:
props = f" ({', '.join(props)})"
else:
props = ""
plt_i = ax.plot(x, y, label = f"{label}{props}", **kwargs)[0]
if show_peaktime is True:
ax.axvline((p['time']-t0)+p['time_to_midpoint'], color = plt_i.get_color())
def draw_gauss_peak(ax, p, t0 = False, show_pars = True, **kwargs):
if show_pars is False:
show_pars = []
elif show_pars is True:
show_pars = [*straxbra.plugins.GaussfitPeaks.props_fits]
if t0 is False:
t0 = p["time"]
draw_peak(ax=ax, p=p, t0=t0, **kwargs)
if "OK_fits" not in p.dtype.names:
print("\33[31muse peaks of type 'gaussfit_peaks' for this function\33[0m")
return(0)
t_offs = p["time"]-t0
y = np.trim_zeros(p["data"], trim = "b")
x = t_offs+np.arange(0, len(y))*p["dt"]
xp = np.linspace(0, max(x), 1000)
for g, (label, f, fp0, fb, pars, units) in straxbra.plugins.GaussfitPeaks.props_fits.items():
if p[f"OK_fit_{g}"] is np.True_:
yf = f(xp, *p[f"fit_{g}"])
res = p[f'sum_resid_sqr_fit_{g}']
ax.plot(xp, yf, label = f"{label} gauss (res/ndf: {res:.1f})")
if g in show_pars:
for par, v, sv, u in zip(pars, p[f"fit_{g}"], p[f"sfit_{g}"], units):
fhist.add_fit_parameter(ax, par, v, sv, u)
def draw_kr_event(
ax, event,
no_labels = False, show_peaks = "0123", label_area = True,
show_peaktime = False, label_peaktime = False,
PE_ns = True,
leg_loc = False, t_ref = 0, t0 = False,
yoffset = 0,
**kwargs):
'''
plots S1s and S2s into ax
parameters:
- no_labels: prevents the creaation of any labels
- show peaks: string with numbers from 0 to 4 of whuich peaks to draw
(default = "0123") ==> all 4 peaks are shown
- show_peaktime:
show midpoint ime of peak
- PE_ns (True): convert peaks from PE/sample to PE/ns
- label_peaktime:
add midpoint time of peak to legend
- leg_loc: set this to a valid legend_loc value to draw the legend,
leave blank to not draw legend
- t0: which time to use as reference. default False.
if not given fallback to t_ref
- t_ref: which peak to use for time reference
(default: 0, so its the first S1)
- **kwargs: used to format the plots
'''
if t0 is False:
if t_ref in [0, 1, 2, 3]:
t0 = event["time_signals"][t_ref]
else:
t0 = 0
# extra offset in case t0 is not first peaks time
t_offset_abs = event["time_signals"][0]-t0
if event["s2_split"]:
labels = ["first S1", "second S1", "first S2", "second S2"]
else:
labels = ["first S1", "second S1", "S2"]
for peak_i, (p_data, t_peak, t_peak_in_event_time, label) in enumerate(zip(event["data_peaks"], event["time_signals"], event["time_peaks"], labels)):
if str(peak_i) in show_peaks:
t_offs = t_peak-t0
y = np.trim_zeros(p_data, trim = "b")
if PE_ns is True:
y = y/event["dt"][peak_i]
x = t_offs+np.arange(0, len(y))*event["dt"][peak_i]
area = event[f"area_s{(peak_i>1)+1}{peak_i%2+1}"]
props = []
if label_area is True:
props.append(f"{area:.1f} PE")
if label_peaktime is True:
props.append(f'{event["time_peaks"][peak_i]:.0f} ns')
if len(props) > 0:
props = f" ({', '.join(props)})"
else:
props = ""
if no_labels is True:
label_ = ""
else:
label_ = f"{label}{props}"
plt_i = ax.plot(x, y+yoffset, label = label_, **kwargs)[0]
if show_peaktime is True: