-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathafterpulse_tile21.py
1395 lines (1203 loc) · 45.8 KB
/
afterpulse_tile21.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 os
import glob
import re
import pickle
import collections
import functools
import itertools
import numpy as np
from scipy import stats, special
from matplotlib import pyplot as plt
import matplotlib
import lsqfit
import gvar
import afterpulse
import readwav
import template as _template
import textbox
import breaklines
import savetemplate
def upoisson(k):
return gvar.gvar(k, np.sqrt(np.maximum(k, 1)))
def ubinom(k, n):
p = k / n
s = np.sqrt(n * p * (1 - p))
return gvar.gvar(k, s)
def usamples(x):
return gvar.gvar(np.mean(x), np.std(x, ddof=1))
def hspan(ax, y0=None, y1=None):
ylim = ax.get_ylim()
margin = 1000 * (ylim[1] - ylim[0])
if y0 is None:
y0 = ylim[0] - margin
if y1 is None:
y1 = ylim[1] + margin
ax.axhspan(y0, y1, color='#0002')
ax.set_ylim(ylim)
def vspan(ax, x0=None, x1=None):
xlim = ax.get_xlim()
if x0 is None:
x0 = xlim[0]
if x1 is None:
x1 = xlim[1]
ax.axvspan(x0, x1, color='#0002')
ax.set_xlim(xlim)
def vlines(ax, x, y0=None, y1=None, **kw):
ylim = ax.get_ylim()
margin = 1000 * (ylim[1] - ylim[0])
if y0 is None:
y0 = ylim[0] - margin
if y1 is None:
y1 = ylim[1] + margin
ax.vlines(x, y0, y1, **kw)
ax.set_ylim(ylim)
def hlines(ax, y, x0=None, x1=None, **kw):
xlim = ax.get_xlim()
if x0 is None:
x0 = xlim[0]
if x1 is None:
x1 = xlim[1]
ax.hlines(y, x0, x1, **kw)
ax.set_xlim(xlim)
def uerrorbar(ax, x, y, **kw):
ym = gvar.mean(y)
ys = gvar.sdev(y)
kwargs = dict(yerr=ys)
kwargs.update(kw)
return ax.errorbar(x, ym, **kwargs)
def exponinteg(x1, x2, scale):
return np.exp(-x1 / scale) - np.exp(-x2 / scale)
def borelpmf(n, params):
mu = params['mu_borel']
effmu = mu * n
return np.exp(-effmu) * effmu ** (n - 1) / special.factorial(n)
def geompmf(k, params):
# p is 1 - p respect to the conventional definition to match the borel mu
p = params['p_geom']
return p ** (k - 1) * (1 - p)
def genpoissonpmf(k, params):
# P(k;mu,lambda) = mu (mu + k lambda)^(k - 1) exp(-(mu + k lambda)) / k!
mu = params['mu_poisson']
lamda = params['mu_borel']
effmu = mu + k * lamda
return np.exp(-effmu) * mu * effmu ** (k - 1) / special.factorial(k)
def geompoissonpmf_nv(k, params):
# Nuel 2008, "Cumulative distribution function of a geometric Poisson distribution", proposition 7 (pag 5)
lamda = params['mu_poisson']
theta = 1 - params['p_geom']
z = lamda * theta / (1 - theta)
P = [
np.exp(-lamda),
np.exp(-lamda) * (1 - theta) * z,
]
assert int(k) == k, k
k = int(k)
for n in range(2, k + 1):
t1 = (2 * n - 2 + z) / n * (1 - theta) * P[n - 1]
t2 = (2 - n) / n * (1 - theta) ** 2 * P[n - 2]
P.append(t1 + t2)
assert len(P) == max(k, 1) + 1, (len(P), k)
return P[k]
def geompoissonpmf(ks, params):
out = None
for i, k in np.ndenumerate(ks):
r = geompoissonpmf_nv(k, params)
if out is None:
out = np.empty_like(ks, dtype=np.array(r).dtype)
out[i] = r
return out
def exponbkgcdf(x, params):
scale = params['tau']
const = params['const']
if hasattr(scale, '__len__'):
assert len(scale) == 2, len(scale)
w = params['p1']
return w * (1 - np.exp(-x / scale[0])) + (1 - w) * (1 - np.exp(-x / scale[1])) + const * x
else:
return 1 - np.exp(-x / scale) + const * x
def fcn(x, p):
continuous = x['continuous']
bins = x['bins']
if continuous:
cdf = x['pmf_or_cdf']
prob = cdf(bins, p)
dist = np.diff(prob)
integral = prob[-1] - prob[0]
else:
pmf = x['pmf_or_cdf']
dist = []
for left, right in zip(bins, bins[1:]):
ints = np.arange(np.ceil(left), right)
dist.append(np.sum(pmf(ints, p)))
if bins[-1] == int(bins[-1]):
dist[-1] += pmf(bins[-1], p)
dist = np.array(dist)
integral = np.sum(dist)
norm = x['norm']
if x['hasoverflow']:
return dict(
bins = norm * dist,
overflow = norm * (1 - integral),
)
else:
return dict(
bins = norm * dist / integral,
)
@afterpulse.figmethod
def fithistogram(
sim, expr, condexpr, prior, pmf_or_cdf,
bins='auto',
bins_overflow=None,
continuous=False,
fig=None,
errorfactor=None,
mincount=3,
selection=True,
boxloc='center right',
fitlabel=None,
**kw,
):
"""
Fit an histogram.
Parameters
----------
sim : AfterPulse
expr : str
condexpr : str
The sample is sim.getexpr(expr, condexpr).
prior : (list of) array/dictionary of GVar
Prior for the fit. If `prior` and `pmf_or_cdf` are lists, a fit is
done for each pair in order.
pmf_or_cdf : (list of) function
The signature must be `pmf_or_cdf(x, params)` where `params` has the
same format of `prior`.
bins : int, sequence, str
Passed to np.histogram. Default 'auto'.
bins_overflow : sequence of two elements
If None, do not fit the overflow. It is assumed that all the
probability mass outside of the bins is contained in the overflow bin.
The overflow bin must be to the right of the other bins.
continuous : bool
If False (default), pmf_or_cdf must be the probability distribution of
an integer variable. If True, pmf_or_cdf must compute the cumulative
density up to the given point.
fig : matplotlib figure or axis, optional
If provided, the plot is drawn here.
errorfactor : 1D array, optional
If provided, the errors on the bin counts are multiplied by these
factors. If the array has different length than the number of bins,
the factors are applied starting from the first element.
mincount : int
Bins are grouped starting from the last bin until there at least
`mincount` elements in the last bin. (Applies to the overflow if
present.)
selection : bool
If True (default), write `condexpr` on the plot.
boxloc : str
The location of the text box with the fit information. Default
'center right'.
fitlabel : (list of) str, optional
Fit names used in the legend and text box.
**kw :
Additional keyword arguments are passed to lsqfit.nonlinear_fit.
Return
------
fit : (list of) lsqfit.nonlinear_fit
fig : matplotlib figure
"""
onefit = not hasattr(pmf_or_cdf, '__len__')
if onefit:
prior = [prior]
pmf_or_cdf = [pmf_or_cdf]
if fitlabel is not None:
fitlabel = [fitlabel]
# histogram
sample = sim.getexpr(expr, condexpr)
counts, bins = np.histogram(sample, bins)
hasoverflow = bins_overflow is not None
if hasoverflow:
(overflow,), _ = np.histogram(sample, bins_overflow)
else:
overflow = 0
if hasoverflow:
# add bins to the overflow bin until it has at least `mincount` counts
lencounts = len(counts)
for i in range(len(counts) - 1, -1, -1):
if overflow < mincount:
overflow += counts[i]
lencounts -= 1
else:
break
counts = counts[:lencounts]
bins = bins[:lencounts + 1]
else:
# group last bins until there are at least `mincount` counts
while len(counts) > 1:
if counts[-1] < mincount:
counts[-2] += counts[-1]
counts = counts[:-1]
bins[-2] = bins[-1]
bins = bins[:-1]
else:
break
# check total count
norm = np.sum(counts) + overflow
assert norm == sim.getexpr(f'count_nonzero({condexpr})')
# prepare data for fit
ucounts = upoisson(counts)
if errorfactor is not None:
errorfactor = np.asarray(errorfactor)
assert errorfactor.ndim == 1, errorfactor.ndim
end = min(len(errorfactor), len(ucounts))
ucounts[:end] = scalesdev(ucounts[:end], errorfactor[:end])
y = dict(bins=ucounts)
if hasoverflow:
y.update(overflow=upoisson(overflow))
# fit
x = []
fit = []
for ifit in range(len(prior)):
x.append(dict(
pmf_or_cdf = pmf_or_cdf[ifit],
continuous = continuous,
bins = bins,
norm = norm,
hasoverflow = hasoverflow,
))
fit.append(lsqfit.nonlinear_fit((x[ifit], y), fcn, prior[ifit], **kw))
# get figure
if hasattr(fig, 'get_axes'):
ax = fig.subplots()
else:
ax = fig
fig = ax.get_figure()
# plot data
center = (bins[1:] + bins[:-1]) / 2
wbar = np.diff(bins) / 2
kw = dict(linestyle='', capsize=4, marker='.', color='k')
uerrorbar(ax, center, y['bins'], xerr=wbar, label='histogram', **kw)
if hasoverflow:
oc = center[-1] + 2 * wbar[-1]
ys = y['overflow']
uerrorbar(ax, oc, ys, label='overflow', **kw)
# plot fit
info = [
f'N = {norm}'
]
styles = [
dict(color='#0004'),
dict(color='#f004'),
]
for ifit, style in zip(range(len(prior)), itertools.cycle(styles)):
thisfit = fit[ifit]
yfit = fcn(x[ifit], thisfit.palt)
ys = yfit['bins']
ym = np.repeat(gvar.mean(ys), 2)
ysdev = np.repeat(gvar.sdev(ys), 2)
xs = np.concatenate([bins[:1], np.repeat(bins[1:-1], 2), bins[-1:]])
label = fitlabel[ifit] if fitlabel is not None else 'fit' if ifit == 0 else f'fit {ifit + 1}'
style.update(zorder=1.9)
ax.fill_between(xs, ym - ysdev, ym + ysdev, label=label, **style)
if hasoverflow:
ys = yfit['overflow']
ym = np.full(2, gvar.mean(ys))
ysdev = np.full(2, gvar.sdev(ys))
xs = oc + 0.8 * (bins[-2:] - center[-1])
ax.fill_between(xs, ym - ysdev, ym + ysdev, **style)
# write fit results on the plot
if fitlabel is not None or ifit > 0:
space = 9 * ' '
label = fitlabel[ifit] if fitlabel is not None else f'Fit {ifit + 1}:'
info.append(space + label + space)
info.append(f'chi2/dof (pv) = {thisfit.chi2/thisfit.dof:.2g} ({thisfit.Q:.2g})')
p = thisfit.palt
for k, v in p.items():
m = p.extension_pattern.match(k)
if m:
f = p.extension_fcn.get(m.group(1), None)
if f:
k = m.group(2)
v = f(v)
if hasattr(v, '__len__'):
for i, vv in enumerate(v):
info.append(f'{k}{i+1} = {vv}')
else:
info.append(f'{k} = {v}')
textbox.textbox(ax, '\n'.join(info), loc=boxloc, fontsize='small')
# decorations
ax.legend(loc='upper right')
ax.minorticks_on()
ax.grid(which='major', linestyle='--')
ax.grid(which='minor', linestyle=':')
ax.set_xlabel(expr)
ax.set_ylabel('Count per bin')
if selection:
cond = breaklines.breaklines(f'Selection: {condexpr}', 40, ')', '&|')
textbox.textbox(ax, cond, loc='upper left', fontsize='small')
fig.tight_layout()
_, upper = ax.get_ylim()
ax.set_ylim(0, upper)
if onefit:
fit, = fit
return fit, fig
def intbins(min, max):
return -0.5 + np.arange(min, max + 2)
def pebins(boundaries, start):
return intbins(start, len(boundaries) - 1), intbins(1000, 1000)
gvar.BufferDict.uniform('U', 0, 1)
def _fitpe(sim, expr, condexpr, boundaries, pmf, prior, binstart, overflow, *, fig1, fig2, **kw):
bins, bins_overflow = pebins(boundaries, binstart)
value = sim.getexpr(expr)
of = value >= 1000
sim.setvar('overflow', of, overwrite=True)
if overflow:
top = 1 + np.max(value[~of])
histexpr = f'where(overflow,{top},{expr})'
else:
bins_overflow = None
condexpr = f'{condexpr}&~overflow'
histexpr = expr
fit, _ = fithistogram(sim, expr, condexpr, prior, pmf, bins, bins_overflow, fig=fig2, **kw)
sim.hist(histexpr, condexpr, fig=fig1)
return fit, fig1, fig2
@afterpulse.figmethod(figparams=['fig1', 'fig2'])
def fitpe(sim, expr, condexpr, boundaries, overflow=True, **kw):
pmf = [
borelpmf,
geompmf,
]
prior = [{
'U(mu_borel)': gvar.BufferDict.uniform('U', 0, 1),
}, {
'U(p_geom)': gvar.BufferDict.uniform('U', 0, 1),
}]
return _fitpe(sim, expr, condexpr, boundaries, pmf, prior, 1, overflow, **kw)
@afterpulse.figmethod(figparams=['fig1', 'fig2'])
def fitpepoisson(sim, expr, condexpr, boundaries, overflow=True, **kw):
pmf = [
genpoissonpmf,
geompoissonpmf,
]
prior = [{
'U(mu_borel)': gvar.BufferDict.uniform('U', 0, 1),
'log(mu_poisson)': gvar.gvar(0, 1),
}, {
'U(p_geom)': gvar.BufferDict.uniform('U', 0, 1),
'log(mu_poisson)': gvar.gvar(0, 1),
}]
return _fitpe(sim, expr, condexpr, boundaries, pmf, prior, 0, overflow, **kw)
@afterpulse.figmethod(figparams=['fig1', 'fig2'])
def fitapdecay(sim, expr, condexpr, const, *, fig1, fig2, **kw):
pmf = [
exponbkgcdf,
exponbkgcdf,
]
prior = [{
'const': const,
'log(tau)': gvar.gvar(np.log(1000), 1),
}, {
'const': const,
'log(tau)': gvar.gvar(np.log([400, 800]), np.ones(2)),
'p1': gvar.BufferDict.uniform('U', 0, 1)
}]
fit, _ = fithistogram(sim, expr, condexpr, prior, pmf, continuous=True, fig=fig2, **kw)
sim.hist(expr, condexpr, fig=fig1)
return fit, fig1, fig2
def scalesdev(x, f):
return x + (f - 1) * (x - gvar.mean(x))
def figmethod(*args, figparams=['fig']):
"""
Decorator for plotting methods of AfterPulseTile21.
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(self, *args, **kw):
# TODO this should return the list of figures even when passed axes
# maybe
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
vovloc = kw.pop('vovloc', 'lower center')
rt = meth(self, *args, **kw)
for fig in figs:
if hasattr(fig, 'get_axes'):
ax, = fig.get_axes()
else:
ax = fig
fig = ax.get_figure()
if 'event' not in fig.canvas.get_window_title() and kw.get('selection', True):
b, t = ax.get_ylim()
yscale = ax.get_yscale()
if yscale == 'log':
b = np.log(b)
t = np.log(t)
t += (t - b) / 9
if yscale == 'log':
b = np.exp(b)
t = np.exp(t)
ax.set_ylim(b, t)
fig.tight_layout()
textbox.textbox(ax, f'{self.vov} VoV', fontsize='medium', loc=vovloc)
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 AfterPulseTile21:
savedir = 'afterpulse_tile21'
wavfiles = [
'darksidehd/LF_TILE21_77K_54V_65VoV_1.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_2.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_3.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_4.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_5.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_6.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_7.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_8.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_9.wav',
'darksidehd/LF_TILE21_77K_54V_65VoV_10.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_1.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_2.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_3.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_4.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_5.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_6.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_7.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_8.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_9.wav',
'darksidehd/LF_TILE21_77K_54V_69VoV_10.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_1.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_2.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_3.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_4.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_5.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_6.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_7.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_8.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_9.wav',
'darksidehd/LF_TILE21_77K_54V_73VoV_10.wav',
]
# parameters:
# ptlength = length used for pre-trigger region
# aplength = filter length for afterpulse (default same as ptlength)
# dcut, dcutr = left/right cut on minorpos - mainpos
# npe = pe of main peak to search afterpulses
# lmargin = left cut on ptpos
# rmargin = right cut (from right margin) on ptpos
_defaults = dict(dcut=300, dcutr=5500, npe=1, lmargin=100, rmargin=500)
defaultparams = {
5.5: dict(ptlength=128, **_defaults),
7.5: dict(ptlength= 64, **_defaults),
9.5: dict(ptlength= 64, **_defaults),
}
defaultparams[5.5].update(dcut=250)
defaultparams[7.5].update(dcut=250)
defaultparams[9.5].update(dcut=150)
def __init__(self, vov, params={}):
self.vov = vov
self.params = dict(self.defaultparams.get(vov, {}))
self.params.update(params)
self.params.setdefault('aplength', self.params['ptlength'])
self.results = {}
self.maketemplates()
self.processdata()
@functools.cached_property
def filelist(self):
"""
A list of dictionaries with these keys:
'wavfile' the source wav
'simfile' the saved AfterPulse object file
'templfile' the saved template file
"""
filelist = []
for wavfile in self.wavfiles:
_, name = os.path.split(wavfile)
prefix, _ = os.path.splitext(name)
vbreak, vbias = re.search(r'(\d+)V_(\d+)VoV', prefix).groups()
vov = (int(vbias) - int(vbreak)) / 2
if vov == self.vov:
filelist.append(dict(
wavfile = wavfile,
simfile = f'{self.savedir}/{prefix}.npz',
templfile = savetemplate.templatepath(wavfile),
))
if len(filelist) == 0:
raise ValueError(f'no files for vov {vov}')
return filelist
def maketemplates(self):
for files in self.filelist:
wavfile = files['wavfile']
templfile = files['templfile']
if not os.path.exists(templfile):
savetemplate.savetemplate(wavfile, plot='save')
def processdata(self):
for files in self.filelist:
wavfile = files['wavfile']
simfile = files['simfile']
templfile = files['templfile']
if not os.path.exists(simfile):
directory, _ = os.path.split(simfile)
os.makedirs(directory, exist_ok=True)
data = readwav.readwav(wavfile)
template = _template.Template.load(templfile)
kw = dict(
batch = 100,
pbar = True,
trigger = np.full(len(data), savetemplate.defaulttrigger(wavfile)),
filtlengths = [32, 64, 128, 256, 512, 1024, 2048],
)
sim = afterpulse.AfterPulse(data, template, **kw)
print(f'save {simfile}...')
sim.save(simfile)
@functools.cached_property
def sim(self):
"""
The AfterPulse object.
"""
print('load analysis files...')
simlist = [
afterpulse.AfterPulse.load(files['simfile'])
for files in self.filelist
]
return afterpulse.AfterPulse.concatenate(simlist)
@functools.cached_property
def datalist(self):
"""
List of memory mapped source files.
"""
return [
readwav.readwav(files['wavfile'])
for files in self.filelist
]
@functools.cached_property
def ptilength(self):
"""get index of the filter length to use for pre-trigger pulses"""
ptlength = self.params['ptlength']
ilength = np.searchsorted(self.sim.filtlengths, ptlength)
assert self.sim.filtlengths[ilength] == ptlength
return ilength
@functools.cached_property
def ptsel(self):
lmargin = self.params['lmargin']
rmargin = self.params['rmargin']
ptlength = self.params['ptlength']
return f'(length=={ptlength})&(ptApos>={lmargin})&(ptApos<trigger-{rmargin})'
@functools.cached_property
def ptcut(self):
"""compute dark count height cut"""
ptlength = self.params['ptlength']
mainsel = f'good&(mainpos>=0)&(length=={ptlength})'
p01 = [
self.sim.getexpr('median(mainheight)', f'{mainsel}&(mainnpe=={npe})')
for npe in [0, 1]
]
cut, = afterpulse.maxdiff_boundaries(self.sim.getexpr('ptAamplh', self.ptsel), p01)
self.results.update(ptcut=cut)
return cut
@functools.cached_property
def ptboundaries(self):
return self.sim.computenpeboundaries(self.ptilength)
@functools.cached_property
def ptmainsel(self):
ptlength = self.params['ptlength']
return f'where(mainampl>=0,~saturated,good)&(mainpos>=0)&(length=={ptlength})'
@figmethod
def ptfingerplot(self, fig):
"""plot a fingerplot"""
self.sim.hist('mainamplh', self.ptmainsel, 'log', 1000, fig=fig)
ax, = fig.get_axes()
vspan(ax, self.ptcut)
vlines(ax, self.ptboundaries, linestyle=':')
@figmethod
def ptscatter(self, fig, **kw):
"""plot pre-trigger amplitude vs. position"""
ptlength = self.params['ptlength']
self.sim.scatter('ptApos', 'where(ptAamplh<1000,ptAamplh,-10)', f'length=={ptlength}', fig=fig, **kw)
ax, = fig.get_axes()
trigger = self.sim.getexpr('median(trigger)')
lmargin = self.params['lmargin']
rmargin = self.params['rmargin']
vspan(ax, lmargin, trigger - rmargin)
hspan(ax, self.ptcut)
hlines(ax, self.ptboundaries, linestyle=':')
@figmethod
def pthist(self, fig, **kw):
"""plot a histogram of pre-trigger peak height"""
self.sim.hist('ptAamplh', self.ptsel, 'log', fig=fig, **kw)
ax, = fig.get_axes()
vspan(ax, self.ptcut)
vlines(ax, self.ptboundaries, linestyle=':')
@functools.cached_property
def ptfactor(self):
"""correction factor for the rate to keep into account truncation of 1
pe distribution"""
l1pe, r1pe = self.ptboundaries[:2]
lowercount = self.sim.getexpr(f'count_nonzero({self.ptmainsel}&(mainamplh<={self.ptcut})&(mainamplh>{l1pe}))')
uppercount = self.sim.getexpr(f'count_nonzero({self.ptmainsel}&(mainamplh>{self.ptcut})&(mainamplh<{r1pe}))')
l = upoisson(lowercount)
u = upoisson(uppercount)
f = (l + u) / u
self.results.update(ptl1pe=l1pe, ptr1pe=r1pe, ptfactor=f)
return f
@functools.cached_property
def ptnevents(self):
n = len(self.sim.output)
self.results.update(ptnevents=n)
return n
@functools.cached_property
def pttime(self):
"""total time where pre-trigger pulses are searched"""
lmargin = self.params['lmargin']
rmargin = self.params['rmargin']
time = self.sim.getexpr(f'mean(trigger-{lmargin}-{rmargin})')
t = time * 1e-9 * self.ptnevents
self.results.update(pttime=t)
return t
@functools.cached_property
def ptcount(self):
sigcount = self.sim.getexpr(f'count_nonzero({self.ptsel}&(ptAamplh>{self.ptcut}))')
s = upoisson(sigcount)
self.results.update(ptcount=s)
return s
@functools.cached_property
def ptrate(self):
"""rate of pre-trigger pulses"""
r = self.ptfactor * self.ptcount / self.pttime
self.results.update(ptrate=r)
return r
@figmethod(figparams=['fig1', 'fig2'])
def ptdict(self, *, fig1, fig2, **kw):
"""fit pre-trigger pe histogram"""
fit, _, _ = fitpe(self.sim, 'ptAnpe', f'{self.ptsel}&(ptAamplh>{self.ptcut})', self.ptboundaries, fig1=fig1, fig2=fig2, **kw)
label = 'ptfit'
self.results.update(ptfit=fit[0], ptfitgeom=fit[1])
return fit, fig1, fig2
@figmethod(figparams=['fig1', 'fig2'])
def maindict(self, overflow=False, fixzero=False, *, fig1, fig2, **kw):
"""fit main peak pe histogram"""
ptlength = self.params['ptlength']
mainsel = f'(mainposbackup>=0)&(length=={ptlength})'
kwargs = dict(overflow=overflow, fig1=fig1, fig2=fig2)
if fixzero:
of = 'of' if overflow else ''
fitnormal = self.results['mainfit' + of]
factor = np.sqrt(fitnormal.chi2 / fitnormal.dof)
kwargs.update(errorfactor=[1 / factor])
kwargs.update(kw)
fit, _, _ = fitpepoisson(self.sim, 'mainnpebackup', mainsel, self.ptboundaries, **kwargs)
for i, kind in enumerate(['', 'geom']):
label = 'mainfit'
if overflow:
label += 'of'
label += kind
if fixzero:
label += 'fz'
self.results[label] = fit[i]
return fit, fig1, fig2
@figmethod
def ptevent(self, index=0, *, fig):
"""plot an event with an high pre-trigger peak"""
evts = self.sim.eventswhere(f'{self.ptsel}&(ptAamplh>{self.ptcut})')
ievt = evts[index]
self.sim.plotevent(self.datalist, ievt, self.ptilength, zoom='all', fig=fig)
@functools.cached_property
def apilength(self):
"""get index of the filter length to use for afterpulses"""
aplength = self.params['aplength']
ilength = np.searchsorted(self.sim.filtlengths, aplength)
assert self.sim.filtlengths[ilength] == aplength
return ilength
@functools.cached_property
def appresel(self):
"""afterpulse preselection (laser pe = 1 and other details)"""
npe = self.params['npe']
aplength = self.params['aplength']
return f'(length=={aplength})&(apApos>=0)&(mainnpebackup=={npe})'
@functools.cached_property
def apsel(self):
"""afterpulse event selection (time cut, but random still included)"""
dcut = self.params['dcut']
dcutr = self.params['dcutr']
return f'{self.appresel}&(apApos-mainposbackup>{dcut})&(apApos-mainposbackup<{dcutr})'
@functools.cached_property
def apcut(self):
"""compute afterpulses height cut"""
aplength = self.params['aplength']
mainsel = f'good&(mainpos>=0)&(length=={aplength})'
p01 = [
self.sim.getexpr('median(mainheight)', f'{mainsel}&(mainnpe=={npe})')
for npe in [0, 1]
]
cut, = afterpulse.maxdiff_boundaries(self.sim.getexpr('apAapamplh', self.apsel), p01)
cut = np.round(cut, 1)
self.results.update(apcut=cut)
return cut
@functools.cached_property
def apboundaries(self):
"""pe boundaries for afterpulse analysis"""
return self.sim.computenpeboundaries(self.apilength)
@figmethod
def apfingerplot(self, *, fig):
"""plot a fingerplot"""
aplength = self.params['aplength']
mainsel = f'where(mainampl>=0,~saturated,good)&(mainpos>=0)&(length=={aplength})'
self.sim.hist('mainamplh', mainsel, 'log', 1000, fig=fig)
ax, = fig.get_axes()
vspan(ax, self.apcut)
vlines(ax, self.apboundaries, linestyle=':')
@figmethod
def apscatter(self, *, fig, **kw):
"""plot afterpulses height vs. distance from main pulse"""
self.sim.scatter('apApos-mainposbackup', 'apAapamplh', self.appresel, fig=fig, **kw)
ax, = fig.get_axes()
hspan(ax, self.apcut)
dcut = self.params['dcut']
dcutr = self.params['dcutr']
vspan(ax, dcut, dcutr)
hlines(ax, self.apboundaries, linestyle=':')
@figmethod
def aphist(self, *, fig, **kw):
"""plot selected afterpulses height histogram"""
self.sim.hist('apAapamplh', self.apsel, 'log', fig=fig, **kw)
ax, = fig.get_axes()
vspan(ax, self.apcut)
vlines(ax, self.apboundaries, linestyle=':')
@functools.cached_property
def apcond(self):
"""afterpulse selection"""
return f'{self.apsel}&(apAapamplh>{self.apcut})'
@figmethod(figparams=['fig1', 'fig2'])
def apdict(self, overflow=False, *, fig1, fig2, **kw):
"""fit afterpulses pe histogram"""
kwargs = dict(overflow=overflow, fig1=fig1, fig2=fig2, mincount=5)
kwargs.update(**kw)
fit, _, _ = fitpe(self.sim, 'apAnpe', self.apcond, self.apboundaries, **kwargs)
for i, kind in enumerate(['', 'geom']):
label = 'apfit'
if overflow:
label += 'of'
label += kind
self.results[label] = fit[i]
return fit, fig1, fig2
@functools.cached_property
def apnevents(self):
nevents = self.sim.getexpr(f'count_nonzero({self.appresel})')
self.results.update(apnevents=nevents)
return nevents
@functools.cached_property
def apcount(self):
"""count for computing the afterpulse probability"""
apcount = self.sim.getexpr(f'count_nonzero({self.apcond})')
apcount = ubinom(apcount, self.apnevents)
self.results.update(apcount=apcount)
return apcount
@functools.cached_property
def aptime(self):
"""total time in afterpulse selection"""
dcut = self.params['dcut']
dcutr = self.params['dcutr']
time = (dcutr - dcut) * 1e-9 * self.apnevents
self.results.update(aptime=time)
return time
@functools.cached_property
def apbkg(self):
"""expected background from random pulses"""
bkg = self.ptrate * self.aptime
self.results.update(apbkg=bkg)
return bkg
@figmethod(figparams=['fig1', 'fig2'])
def apfittau(self, *, fig1, fig2, **kw):
"""fit decay constant of afterpulses"""
dcut = self.params['dcut']
dcutr = self.params['dcutr']
f = self.apbkg / gvar.mean(self.apcount)
const = 1 / (dcutr - dcut) * f / (1 - f)
nbins = int(15/20 * np.sqrt(gvar.mean(self.apcount)))
tau0 = 1500
bins = -tau0 * np.log1p(-np.linspace(0, 1 - np.exp(-(dcutr - dcut) / tau0), nbins + 1))
fit, _, _ = fitapdecay(self.sim, f'apApos-mainposbackup-{dcut}', self.apcond, const, bins=bins, fig1=fig1, fig2=fig2, **kw)
self.results.update(apfittau=fit[0], apfittau2=fit[1])
return fit, fig1, fig2
def _apbkgfit(self, fit):
x = fit.data[0]
bins = x['bins']
t = bins[-1] - bins[0]
c = fit.palt['const']
ct = c * t
count = x['norm']
bkg = count * ct / (1 + ct)
return bkg
@functools.cached_property
def apbkgfit(self):
fit = self.results['apfittau']
b = self._apbkgfit(fit)
self.results.update(apbkgfit=b)
return b
@functools.cached_property
def aptau(self):
"""decay parameter of afterpulses"""
fit = self.results['apfittau']
tau = fit.palt['tau']
if fit.Q < 0.01:
tau = scalesdev(tau, np.sqrt(fit.chi2 / fit.dof))
self.results.update(aptau=tau)
return tau
@functools.cached_property
def apfactor(self):
"""factor to keep into account temporal cuts"""
dcut = self.params['dcut']
dcutr = self.params['dcutr']
factor = 1 / exponinteg(dcut, dcutr, self.aptau)
self.results.update(apfactor=factor)
return factor
@functools.cached_property
def apccount(self):
"""afterpulse count corrected for temporal cuts and background"""
ccount = (self.apcount - self.apbkgfit) * self.apfactor
self.results.update(apccount=ccount)
return ccount
@functools.cached_property
def approb(self):
"""afterpulse probability"""
p = self.apccount / self.apnevents
self.results.update(approb=p)
return p
@functools.cached_property
def apbkgfit2(self):
fit = self.results['apfittau2']
b = self._apbkgfit(fit)