-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathafterpulse.py
1714 lines (1483 loc) · 64.8 KB
/
afterpulse.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 functools
import numpy as np
from matplotlib import pyplot as plt, colors
import runsliced
from single_filter_analysis import single_filter_analysis
import textbox
import breaklines
import meanmedian
import correlate
import firstbelowthreshold
import argminrelmin
import maxprominencedip
import npzload
import peaksampl
def maxdiff_boundaries(x, pe):
"""
Compute the 'maxdiff' boudaries for AfterPulse.npeboundaries.
Parameters
----------
x : 1D array
The height values.
pe : array (M,)
The heights of the peaks.
Return
------
values : array (M - 1,)
The midpoint between the two most distant consecutive height samples
between each pair of peaks.
"""
x = np.sort(x)
pe = np.sort(pe)
pepos = 1 + np.searchsorted(x, pe)
values = []
for start, end in zip(pepos, pepos[1:]):
y = x[start:end]
i = np.argmax(np.diff(y))
values.append(np.mean(y[i:i+2]))
assert len(values) == len(pe) - 1, len(values)
return np.array(values)
def _posampl1(x):
return x / x[np.argmax(np.abs(x))]
def figmethod(*args, figparams=['fig']):
"""
Decorator for plotting methods/functions.
Assumes that the method requires a keyword argument `fig` which is a
matplotlib figure. When `fig` is not provided or None, generate a figure
with the method name as window title.
If the original method returns None (or does not return), the decorated
method returns the figure.
"""
def decorator(meth):
@functools.wraps(meth)
def newmeth(*args, **kw):
figs = []
for i, param in enumerate(figparams):
fig = kw.get(param, None)
if fig is None:
title = meth.__qualname__
if len(figparams) > 1:
title += str(i + 1)
fig = plt.figure(num=title, clear=True)
figs.append(fig)
kw[param] = fig
rt = meth(*args, **kw)
return (fig if len(figparams) == 1 else tuple(figs)) if rt is None else rt
return newmeth
if len(args) == 0:
return decorator
elif len(args) == 1:
return decorator(args[0])
else:
raise ValueError(len(args))
class AfterPulse(npzload.NPZLoad):
# TODO (long)
# Add a parameter `npeaks`
# Search `npeaks` peaks in the whole filtered waveform using prominence
# Save in a field 'peak' with shape filtlengths.shape + (npeaks,)
# Use a single variable in `getexpr` for each peak property
# The common shape is filtlenghts.shape + (npeaks, nevents)
# `hist` and `scatter` flatten over npeaks
# A boolean variable 'laser' for the closest to trigger + offset
# Boolean variables 'pre' and 'post' for before/after the trigger
# Do the fingerplot using 'laser' with a cut on the position
# Compute the amplitudes, filter away 0 pe again afterward
# 'apre', 'apost' indices for sorting by amplitude (reversed)
# 'tpre', 'tpost' indices for sorting by position
# TODO
# Instead of using correlate.correlate, use directly
# signal.fftconvolve(waveform - baseline, templ[None, ::-1], mode='full')
# and then subtract len(templ) - 1 from the indices
def __init__(self,
wavdata,
template,
filtlengths=None,
batch=10,
pbar=False,
lowsample=700,
trigger=None,
badvalue=-1000,
mainsearchrange=60,
):
"""
Analyze LNGS laser data.
The analysis is appropriate for studying afterpulses but it can be
used as a general purpose tool.
Parameters
----------
wavdata : array (nevents, nchannels, eventlength)
Data as returned by readwav.readwav(). The first channel is the
waveform, the second channel is the trigger. If there is only one
channel, the trigger position can be specified with `trigger`. If
`trigger` is not specified, the trigger position is constant and
taken from `template`.
template : template.Template
A template object used for the cross correlation filter. Should be
generated using the same wav file.
filtlengths : array, optional
A series of template lengths for the cross correlation filters, in
unit of 1 GSa/s samples. If not specified, a logarithmically spaced
range from 16 ns to 1024 ns is used.
batch : int
The events batch size, default 10.
pbar : bool
If True, print a progressbar during the computation (1 tick per
batch). Default False.
lowsample : scalar
Threshold on single samples in the pre-trigger region to switch to
a default baseline instead of computing it from the event, default
700.
trigger : int array (nevents,), optional
The trigger leading edge position, used if there's no trigger
information in `wavdata`.
badvalue : scalar
Filler used for missing values, default -1000.
mainsearchrange : int
The width of the interval where the main peak is searched. It is
centered on the trigger, plus an offset to keep into account filter
template truncation.
Methods
-------
filtertempl : get a cross correlation filter template.
closept : find pre-trigger peaks close to the trigger.
npeboundaries : divide peak heights in pe bins.
npe : assign heights to pe bins.
fingerplot : plot fingerplot used to determine pe bins.
computenpe : assign height to pe bins for all filters at once.
computenpeboundaries : get the pe bins used by `computenpe`.
signal : compute the filtered signal shape.
signals : compute the filtered signal shape for all filters.
peaksampl : compute the peak amplitude subtracting other peaks.
apheight : correct the amplitude to be constant for afterpulses.
plotevent : plot the analysis of a single event.
getexpr : compute the value of an expression on all events.
setvar : set a variable accessible from `getexpr`.
eventswhere : get the list of events satisfying a condition.
hist : plot the histogram of a variable.
scatter : plot two variables.
hist2d : plot the histogram of two variables.
catindex : map event index to object in a concatenation.
subindex : map global event index to event index in concatenated object.
Class methods
-------------
concatenate : create an instance by concatenating instances.
Members
-------
lowsample, badvalue, mainsearchrange : scalar
The arguments given at initialization.
filtlengths : array
The cross correlation filter lengths.
eventlength : int
The size of the last axis of `wavdata`.
trigger : int array (nevents,)
The `trigger` parameter, if specified.
output : array (nevents,)
A structured array containing the information for each event with
these fields:
'trigger' : int
The index of the trigger leading edge.
'saturated' : bool
If there's at least one sample with value 0 in the event.
'lowbaseline' : bool
If there's at least one sample below `lowsample` before the
trigger.
'baseline' : float
The mean of the medians of the pre-trigger region divided in 8
parts with stride 8. Copied from another event if 'lowbaseline'.
'mainpeak' : array filtlengths.shape
A structured field for the signal identified by the trigger
for each filter length with subfields:
'pos' : int
The peak position.
'height' : float
The peak height (positive) relative to the baseline.
'minorpeak' : array filtlengths.shape
A structured field for the maximum prominence peak after the
main peak for each filter length with these fields:
'pos' : int
The peak position.
'height' : float
The peak height (positive) relative to the baseline.
'prominence' : float
The prominence, computed only looking at samples after the
main peak position (even if it is lower than the secondary
peak), and capping maxima to the baseline.
'minorpeak2' : array filtlengths.shape
Analogous to the 'minorpeak' field, but for the second highest
prominence peak.
'ptpeak', 'ptpeak2' : array filtlengths.shape
Analogous to 'minorpeak' and 'minorpeak2' for the two highest
prominence peaks in the region before the trigger.
'internals' : structured field
Internals used by the object.
'done' : bool
True.
templates : array filtlengths.shape
A structured array containing the cross correlation filter
templates with these fields:
'template' : 1D array
The template, padded to the right with zeros.
'length' : int
The length of the nonzero part of 'template'.
'offset' : float
The number of samples from the trigger to the beginning of
the truncated template.
template : 1D array
The full signal template. If the object is a concatenation, the
`templates` and `template` arrays have an additional first axis
that runs over concatenated objects.
"""
if filtlengths is None:
self.filtlengths = 2 ** np.arange(4, 10 + 1)
else:
self.filtlengths = np.array(filtlengths, int)
self.lowsample = lowsample
self.eventlength = wavdata.shape[-1]
assert badvalue < 0, badvalue
self.badvalue = badvalue
self.mainsearchrange = mainsearchrange
peakdtype = [
('pos', int),
('height', float),
('prominence', float),
]
self.output = np.empty(len(wavdata), dtype=[
('trigger', int),
('baseline', float),
('mainpeak', [
('pos', int),
('height', float),
], self.filtlengths.shape),
('minorpeak', peakdtype, self.filtlengths.shape),
('minorpeak2', peakdtype, self.filtlengths.shape),
('ptpeak', peakdtype, self.filtlengths.shape),
('ptpeak2', peakdtype, self.filtlengths.shape),
('internals', [
# left:right is the main peak search range
('left', int, self.filtlengths.shape),
('right', int, self.filtlengths.shape),
('bsevent', int), # event from which the baseline was copied
('lpad', int), # left padding on pre-trigger region
]),
('saturated', bool),
('lowbaseline', bool),
('done', bool),
])
self.output['internals']['bsevent'] = -1
self.output['done'] = False
if trigger is not None:
trigger = np.asarray(trigger)
assert trigger.shape == self.output.shape, trigger.shape
self.trigger = trigger
elif wavdata.shape[1] == 1:
self.trigger = np.full(len(wavdata), int(template.trigger_median))
# tuple (event from which I copy the baseline, baseline)
self._default_baseline = (-1, template.baseline)
self._maketemplates(template)
func = lambda s: self._run(wavdata[s], self.output[s], s)
runsliced.runsliced(func, len(wavdata), batch, pbar)
self.output.flags['WRITEABLE'] = False
def _maketemplates(self, template):
"""
Fill the `templates` and `template` members.
"""
kw = dict(timebase=1, aligned=True)
def templates(lengths):
templates = np.zeros(lengths.shape, dtype=[
('template', float, (np.max(lengths),)),
('length', int),
('offset', int),
])
templates['length'] = lengths
for _, entry in np.ndenumerate(templates):
templ, offset = template.matched_filter_template(entry['length'], **kw)
assert len(templ) == entry['length']
entry['template'][:len(templ)] = templ
entry['length'] = len(templ)
entry['offset'] = offset
return templates
self.templates = templates(self.filtlengths)
kw.update(randampl=False)
self.template, = template.generate(template.template_length, [0], **kw)
def _max_ilength(self):
"""
Return index of longest filter.
"""
ilength_flat = np.argmax(self.filtlengths)
return np.unravel_index(ilength_flat, self.filtlengths.shape)
def filtertempl(self, ilength=None, ievent=None):
"""
Return a cross correlation filter template.
Parameters
----------
ilength : {int, tuple, None}
The index of the filter length in `filtlengths`. If not specified,
use the longest filter.
ievent : {int, None}
To be specified when the object is a concatenation to get the
template used for the specific event.
Return
------
templ : 1D array
The normalized template.
offset : scalar
The offset of the template start relative to the original
untruncated template.
"""
if ilength is None:
ilength = self._max_ilength()
elif not isinstance(ilength, tuple):
ilength = (ilength,)
if self.templates.shape == self.filtlengths.shape:
entry = self.templates[ilength]
elif ievent is not None:
idx = self.catindex(ievent)
entry = self.templates[(idx,) + ilength]
else:
raise ValueError('the object is a concatenation, specify the event')
templ = entry['template'][:entry['length']]
offset = entry['offset']
return templ, offset
@functools.cached_property
def _offset(self):
if self.templates.shape == self.filtlengths.shape:
offset = self.templates['offset'][..., None]
else:
offset = np.empty(self.filtlengths.shape + self.output.shape, int)
cumlen = np.pad(np.cumsum(self._catlengths), (1, 0))
for start, end, x in zip(cumlen, cumlen[1:], self.templates['offset']):
offset[..., start:end] = x[..., None]
return offset
def _run(self, wavdata, output, slic):
"""
Process a batch of events, filling `output`.
"""
# find trigger
if wavdata.shape[1] == 2:
trigger = firstbelowthreshold.firstbelowthreshold(wavdata[:, 1], 600)
assert np.all(trigger >= 0)
else:
trigger = self.trigger[slic]
# find saturated events
saturated = np.any(wavdata[:, 0] == 0, axis=-1)
# compute the baseline, handling spurious pre-trigger signals
margin = self.mainsearchrange // 2
bsend = np.min(trigger) - margin
bszone = wavdata[:, 0, :bsend]
lowbaseline = np.any(bszone < self.lowsample, axis=-1)
baseline = meanmedian.meanmedian(bszone, 8)
okbs = np.flatnonzero(~lowbaseline)
if len(okbs) > 0:
ibs = okbs[-1]
self._default_baseline = (slic.start + ibs, baseline[ibs])
baseline[lowbaseline] = self._default_baseline[1]
mean_baseline = np.mean(baseline)
for ilength, _ in np.ndenumerate(self.filtlengths):
templ, offset = self.filtertempl(ilength)
# filter
lpad = 100
filtered = correlate.correlate(wavdata[:, 0], templ, boundary=mean_baseline, lpad=lpad)
# divide the waveform in regions
center = int(np.median(trigger)) + int(offset)
left = center - margin
right = center + margin
poststart = lpad + left
# find the main peak as the minimum local minimum near the trigger
searchrange = filtered[:, poststart:lpad + right]
mainpos = argminrelmin.argminrelmin(searchrange, axis=-1)
mainheight = searchrange[np.arange(len(mainpos)), mainpos]
# find two other peaks with high prominence after the main one
posttrigger = filtered[:, poststart:]
minorstart = np.maximum(0, mainpos)
minorend = np.full(*posttrigger.shape)
minorpos, minorprom = maxprominencedip.maxprominencedip(posttrigger, minorstart, minorend, baseline, 2)
minorheight = posttrigger[np.arange(len(minorpos))[:, None], minorpos]
# find peaks in pre-trigger region
ptstart = np.zeros(len(filtered))
ptend = poststart + minorstart + 1
ptpos, ptprom = maxprominencedip.maxprominencedip(filtered, ptstart, ptend, baseline, 2)
ptheight = filtered[np.arange(len(ptpos))[:, None], ptpos]
idx = np.s_[:,] + ilength
badvalue = self.badvalue
# fill main peak
peak = output['mainpeak'][idx]
bad = mainpos < 0
peak['pos'] = np.where(bad, badvalue, left + mainpos)
peak['height'] = np.where(bad, badvalue, baseline - mainheight)
# fill other peaks
peaks = [
('minorpeak', minorpos, minorheight, minorprom, left ),
('ptpeak' , ptpos , ptheight , ptprom , -lpad),
]
for prefix, peakpos, height, prom, offset in peaks:
for ipeak, s in [(1, ''), (0, '2')]:
peak = output[prefix + s][idx]
pos = peakpos[:, ipeak]
bad = pos < 0
peak['pos'] = np.where(bad, badvalue, np.maximum(0, offset + pos))
peak['height'] = np.where(bad, badvalue, baseline - height[:, ipeak])
peak['prominence'] = np.where(bad, badvalue, prom[:, ipeak])
output['internals']['left'][idx] = left
output['internals']['right'][idx] = right
output['trigger'] = trigger
output['baseline'] = baseline
output['saturated'] = saturated
output['lowbaseline'] = lowbaseline
output['internals']['bsevent'][lowbaseline] = self._default_baseline[0]
output['internals']['lpad'] = lpad
output['done'] = True
def closept(self, safedist=2500, safeheight=8):
"""
Find events where there are pre-trigger peaks close to the trigger.
The pre-trigger pulses are identified using the longest filter.
Parameters
----------
safedist : scalar
Distance from a peak in the pre-trigger region to the trigger above
which the peak is not considered close, default 2500.
safeheight : scalar
The maximum height for peaks within `safedist` to be still
considered negligible, default 8.
Return
------
closept : bool array (nevents,)
True where there's a peak.
"""
idx = np.s_[:,] + self._max_ilength()
closept = None
for s in ['', '2']:
peak = self.output['ptpeak' + s][idx]
pos = peak['pos']
height = peak['height']
ptlength = self.output['internals']['left'][idx]
close = pos >= 0
close &= ptlength - pos < safedist
close &= height > safeheight
if closept is None:
closept = close
else:
closept |= close
return closept
@functools.cached_property
def _closept(self):
return self.closept()
@functools.cached_property
def _good(self):
return ~self.output['saturated'] & ~self._closept
def npeboundaries(self, height, plot=False, algorithm='maxdiff'):
"""
Determine boundaries to divide peak heights by number of pe.
Parameters
----------
height : 1D array
The heights.
plot : bool
If True, plot the fingerplot used separate the peaks.
algorithm : {'maxdiff', 'midpoints'}
The algorithm used to place the boundaries. 'midpoints' uses the
midpoints between the peaks. 'maxdiff' (default) uses the midpoint
between the two most distant consecutive samples between two peaks.
Return
------
boundaries : array
The height boundaries separating different pe. boundaries[0]
divides 0 pe from 1 pe, boundaries[-1] divides the maximum pe
from the overflow.
fig : matplotlib figure
Returned only if `plot` is True.
"""
height = np.asarray(height)
assert height.ndim == 1, height.ndim
kw = dict(return_full=True)
if plot:
fig = plt.figure(num='afterpulse.AfterPulse.npeboundaries', clear=True)
kw.update(fig1=fig)
_, center, _ = single_filter_analysis(height, **kw)
if algorithm == 'midpoints':
last = center[-1] + (center[-1] - center[-2])
center = np.pad(center, (0, 1), constant_values=last)
boundaries = (center[1:] + center[:-1]) / 2
elif algorithm == 'maxdiff':
boundaries = maxdiff_boundaries(height, center)
if plot:
ax, = fig.get_axes()
ylim = ax.get_ylim()
ax.vlines(boundaries, *ylim, linestyle='-.', label='final boundaries')
ax.legend(loc='upper right')
else:
raise KeyError(algorithm)
if plot:
return boundaries, fig
else:
return boundaries
def npe(self, height, boundaries, overflow=1000):
"""
Compute the number of photoelectrons from a fingerplot.
Parameters
----------
height : array
The heights.
boundaries : 1D array
The height boundaries separating different pe. boundaries[0]
divides 0 pe from 1 pe, boundaries[-1] divides the maximum pe
from the overflow.
overflow : int
The value used for heights after the last boundary.
Return
------
npe : int array
The number of pe assigned to each height. The array has the same
shape of `height`
"""
npe = np.digitize(height, boundaries)
if np.isscalar(npe):
npe = np.array(npe)
npe[npe >= len(boundaries)] = overflow
return npe
def fingerplot(self, ilength=None):
"""
Plot the fingerplot of the main peak height used to count the pe.
Parameters
----------
ilength : {int, tuple of int, None}, optional
The index in `filtlengths` of the filter length. If not specified,
use the longest filter.
Return
------
fig : matplotlib figure
The plot.
"""
if ilength is None:
ilength = self._max_ilength()
elif not isinstance(ilength, tuple):
ilength = (ilength,)
idx = np.s_[:,] + ilength
peak = self.output['mainpeak'][idx]
height = peak['height']
valid = peak['pos'] >= 0
value = height[valid & self._good]
if len(value) >= 100:
boundaries, fig = self.npeboundaries(value, plot=True)
ax, = fig.get_axes()
length = self.filtlengths[ilength]
textbox.textbox(ax, f'filter length = {length} ns', loc='center right', fontsize='small')
fig.tight_layout()
return fig
@functools.cached_property
def _computenpe_boundaries_height(self):
boundaries = np.empty(self.filtlengths.shape, object)
mainpeak = self.output['mainpeak']
good = self._good
for ilength, _ in np.ndenumerate(self.filtlengths):
idx = np.s_[:,] + ilength
peak = mainpeak[idx]
height = peak['height']
valid = peak['pos'] >= 0
boundaries[ilength] = self.npeboundaries(height[valid & good])
return boundaries
@functools.cached_property
def _computenpe_boundaries_ampl(self):
boundaries = np.empty(self.filtlengths.shape, object)
mainampl = self._peaksampl[..., 0]
mainpeak = self.output['mainpeak']
notsaturated = ~self.output['saturated']
good = self._good
for ilength, _ in np.ndenumerate(self.filtlengths):
ampl = mainampl[ilength + np.s_[:,]]
peak = mainpeak[np.s_[:,] + ilength]
height = peak['height']
pos = peak['pos']
cond = ampl >= 0
x = np.where(cond, ampl, height)
valid = (pos >= 0) & np.where(cond, notsaturated, good)
boundaries[ilength] = self.npeboundaries(height[valid])
return boundaries
def _computenpe_boundaries(self, ampl):
if ampl:
return self._computenpe_boundaries_ampl
else:
return self._computenpe_boundaries_height
def computenpe(self, height, ampl=True):
"""
Compute the number of pe of peaks.
The pe bin boundaries are computed automatically from laser peaks
fingerplots.
Parameters
----------
height : array filtlengths.shape + (nevents,)
The height of a peak.
ampl : bool
If True (default), compute the pe bins using the amplitude
computed by `peaksampl`. If False, use the height.
Return
------
npe : int array filtlengths.shape + (nevents,)
The pe assigned to each peak height. 1000 for height larger than
the highest classified pe. Negative heights are assigned 0 pe.
"""
boundaries = self._computenpe_boundaries(ampl)
npe = np.empty(self.filtlengths.shape + self.output.shape, int)
for ilength, _ in np.ndenumerate(self.filtlengths):
npe[ilength] = self.npe(height[ilength], boundaries[ilength])
return npe
def computenpeboundaries(self, ilength, ampl=True):
"""
Get the pe height bins used by `computenpe`.
Parameters
----------
ilength : {int, tuple}
The index of the filter length in `filtlengths`.
ampl : bool
If True (default), compute the pe bins using the amplitude
computed by `peaksampl`. If False, use the height.
Return
------
boundaries : 1D array
See `npeboundaries` for a detailed description.
"""
return self._computenpe_boundaries(ampl)[ilength]
@functools.cached_property
def _0to1peboundaries(self):
boundaries = self._computenpe_boundaries_ampl
out = np.empty(self.filtlengths.shape)
for idx, array in np.ndenumerate(boundaries):
out[idx] = array[0]
return out
def signal(self, ilength):
"""
Filter the signal template.
If the object is a concatenation, use the first template.
Parameters
----------
ilength : {int, tuple of ints}
The index of the filter length.
Return
------
s : 1D array
The filtered signal waveform. It is positive and the amplitude is 1.
"""
# TODO align and average the templates if the object is a concatenation.
templ, _ = self.filtertempl(ilength, 0)
signal = self.template if self.template.ndim == 1 else self.template[0]
s = np.correlate(signal, templ, 'full')
return _posampl1(s)
def signals(self):
"""
Filter the signal template with all filters.
Equivalent to calling `signal` for each filter length.
Return
------
signals : array filtlengths.shape + (N,)
An array with the filtered signals. The length of the last axis is
the maximum signal length. Shorter signals are padded with zeros.
"""
maxflen = np.max(self.filtlengths)
maxlen = self.template.shape[-1] + maxflen - 1
signal = np.zeros(self.filtlengths.shape + (maxlen,))
for ilength, _ in np.ndenumerate(self.filtlengths):
s = self.signal(ilength)
signal[ilength][:len(s)] = s
return signal
def peaksampl(self, minheight='auto', minprom=0, fillignore=None):
"""
Compute the amplitude of filtered signals.
The amplitude is the height that the peak in the filter output would
have if there were not other signals nearby.
Parameters
----------
minheight : {array_like, 'auto'}
Minimum height of a peak to be considered a signal. If 'auto'
(default), use the boundary between 0 and 1 pe returned by
`computenpeboundaries(..., ampl=False)`. If an array it must
broadcast against `filtlengths`.
minprom : array_like
The minimum prominence (does not apply to the laser peak). Default
0.
fillignore : scalar, optional
The value used for ignored peaks, `badvalue` if not specified.
Return
------
ampl : array filtlengths.shape + (nevents, 5)
The amplitude (positive). The last axis runs over peaks 'mainpeak',
'minorpeak', 'minorpeak2', 'ptpeak', 'ptpeak2'.
"""
if minheight == 'auto':
minheight = np.reshape([
self.computenpeboundaries(ilength, ampl=False)[0]
for ilength, _ in np.ndenumerate(self.filtlengths)
], self.filtlengths.shape)
minheight = np.broadcast_to(minheight, self.filtlengths.shape)
minprom = np.broadcast_to(minprom, self.filtlengths.shape)
signal = self.signals()[..., None, :]
peaks = ['mainpeak', 'minorpeak', 'minorpeak2', 'ptpeak', 'ptpeak2']
pos, height, prom = [
np.stack([
np.moveaxis(self.output[peak][label], 0, -1)
if not (label == 'prominence' and peak == 'mainpeak')
else np.broadcast_to(np.inf, self.filtlengths.shape + self.output.shape)
for peak in peaks
], axis=-1)
for label in ['pos', 'height', 'prominence']
]
missing = pos < 0
ignore = height < minheight[..., None, None]
ignore |= prom < minprom[..., None, None]
cond = missing | ignore
height[cond] = 0
pos[cond] = 0
ampl = peaksampl.peaksampl(signal, height, pos)
ampl[ignore] = self.badvalue if fillignore is None else fillignore
ampl[missing] = self.badvalue
return ampl
@functools.cached_property
def _peaksampl(self):
return self.peaksampl()
def posbackup(self, pos):
# TODO does not work if filtlengths is not 1D
cond = pos >= 0
idx = np.argmax(cond, axis=0)[None]
offset = self._offset
return np.where(cond, pos, offset + np.take_along_axis(pos - offset, idx, 0))
def apheight(self, ampl, correction='height', offset='peak'):
"""
Compute the afterpulse height.
The afterpulse amplitude is increased by a quantity which decreases
with the delay, to put all afterpulses at the same height.
Parameters
----------
ampl : array filtlengths.shape + (nevents, 5)
The amplitude as returned by `peaksampl`.
correction : {'height', 'area'}
The kind of correction. 'height' (default) uses the signal height,
'area' uses the survival function of the signal.
offset : {int, 'peak', 'edge'}:
The offset added to the delay when evaluating the correction.
'peak' (default) starts from the peak of signal template, 'edge'
from the point at 10 % the maximum amplitude of the rising edge. If
an integer it is used directly. Can be negative (the template is
extended with zeros if necessary).
Return
------
height : array filtlengths.shape + (nevents, 2)
The last axis correspond to peaks 'minorpeak' and 'minorpeak2'.
"""
mainpos, pos1, pos2 = [
np.moveaxis(self.output[peak]['pos'], 0, -1)
for peak in ['mainpeak', 'minorpeak', 'minorpeak2']
]
mainpos = self.posbackup(mainpos)
peampl = np.empty(self.filtlengths.shape)
for ilength, _ in np.ndenumerate(self.filtlengths):
height = ampl[ilength + np.s_[:, 0]]
l, r = self.computenpeboundaries(ilength)[:2]
cond = (height >= l) & (height < r)
peampl[ilength] = np.median(height[cond])
signal = self.template if self.template.ndim == 1 else self.template[0]
signal = _posampl1(signal)
signal = np.pad(signal, 1)
if offset == 'peak':
offset = np.argmax(signal)
elif offset == 'edge':
offset = np.flatnonzero(signal >= 0.1)[0]
elif int(offset) == offset:
offset = offset + 1
else:
raise ValueError(offset)
if correction == 'height':
pass
elif correction == 'area':
signal = np.cumsum(signal[::-1])[::-1] / np.sum(signal)
else:
raise KeyError(correction)
signal = peampl[..., None] * signal
signal = signal[..., None, :]
height = np.empty(self.filtlengths.shape + self.output.shape + (2,))
for i, pos in enumerate([pos1, pos2]):
indices = pos - mainpos + offset
indices = np.maximum(indices, 0)
indices = np.minimum(indices, signal.shape[-1] - 1)
base = np.take_along_axis(signal, indices[..., None], -1)
amp = ampl[..., i + 1]
height[..., i] = amp + np.squeeze(base, -1)
ignore = (pos < 0) | (mainpos < 0) | (amp < 0)
height[..., i][ignore] = self.badvalue
return height
@functools.cached_property
def _apheight(self):
return self.apheight(self._peaksampl)
@figmethod
def plotevent(self, wavdata, ievent, ilength=None, zoom='posttrigger', debug=False, fig=None, apampl=True):
"""
Plot a single event.
Parameters
----------
wavdata : array (nevents, 2, 15001) or list
The same array passed at initialization. If the object is
a concatenation, the data passed to the object where the event
originates from. Use `catindex()` to map the event to the object.
If a list, it must be the ordered list of arrays passed at
initialization to the concatenated objects.
ievent : int
The event index.
ilength : int, optional
The index of the filter length in `filtlengths`. If not specified,
use the longest filter.
zoom : {'all', 'posttrigger', 'main', 'pretrigger'}
The x-axis extension.
debug : bool
If False (default), reduce the amount of information showed.
fig : matplotlib figure or axis, optional
A matplotlib figure or axis where the plot is drawn.
apampl : bool
If True (default), use the corrected afterpulse amplitude for
post-trigger pulses.
Return
------
fig : matplotlib figure
The figure.
"""
if ilength is None:
ilength = self._max_ilength()
elif not isinstance(ilength, tuple):
ilength = (ilength,)
if hasattr(fig, 'get_axes'):
ax = fig.subplots()
else:
ax = fig
fig = ax.get_figure()
if not hasattr(wavdata, 'astype'):
wavdata = wavdata[self.catindex(ievent)]
wf = wavdata[self.subindex(ievent), 0]
ax.plot(wf, color='#f55')
entry = self.output[ievent]
ax.axvline(entry['trigger'], color='#000', linestyle='--', label='trigger')
baseline = entry['baseline']
ax.axhline(baseline, color='#000', linestyle=':', label='baseline')
templ, _ = self.filtertempl(ilength, ievent)
lpad = entry['internals']['lpad']
filtered = correlate.correlate(wf, templ, boundary=baseline, lpad=lpad)
length = self.filtlengths[ilength]
ax.plot(-lpad + np.arange(len(filtered)), filtered, color='#000', label=f'filtered ({length} ns templ)')
left = entry['internals']['left'][ilength]
right = entry['internals']['right'][ilength]
offset = -0.5
ax.axvspan(offset + left, offset + right, color='#ddd', label='laser peak search range')
markerkw = dict(
linestyle = '',