/
analysis_tools.py
1400 lines (1214 loc) · 56.2 KB
/
analysis_tools.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
"""Tools of general use for columnar analysis
These helper classes were previously part of ``coffea.processor``
but have been migrated and updated to be compatible with awkward-array 1.0
"""
import warnings
from collections import namedtuple
from functools import lru_cache
import awkward
import dask.array
import dask_awkward
import hist
import hist.dask
import numpy
from dask_awkward.lib.core import compatible_partitions
from dask_awkward.utils import IncompatiblePartitions
import coffea.processor
import coffea.util
class WeightStatistics:
def __init__(self, sumw=0.0, sumw2=0.0, minw=numpy.inf, maxw=-numpy.inf, n=0):
self.sumw = sumw
self.sumw2 = sumw2
self.minw = minw
self.maxw = maxw
self.n = n
def __repr__(self):
return f"WeightStatistics(sumw={self.sumw}, sumw2={self.sumw2}, minw={self.minw}, maxw={self.maxw}, n={self.n})"
def identity(self):
return WeightStatistics()
def add(self, other):
self.sumw += other.sumw
self.sumw2 += other.sumw2
self.minw = min(self.minw, other.minw)
self.maxw = max(self.maxw, other.maxw)
self.n += other.n
def __add__(self, other):
temp = WeightStatistics(self.sumw, self.sumw2, self.minw, self.maxw, self.n)
return temp.add(other)
def __iadd__(self, other):
return self.add(other)
class Weights:
"""Container for event weights and associated systematic shifts
This container keeps track of correction factors and systematic
effects that can be encoded as multiplicative modifiers to the event weight.
All weights are stored in vector form.
Parameters
----------
size : int | None
size of the weight arrays to be handled (i.e. the number of events / instances).
If None then we expect to operate in delayed mode.
storeIndividual : bool, optional
store not only the total weight + variations, but also each individual weight.
Default is false.
"""
def __init__(self, size, storeIndividual=False):
self._weight = None if size is None else numpy.ones(size)
self._weights = {}
self._modifiers = {}
self._weightStats = {}
self._storeIndividual = storeIndividual
@property
def weightStatistics(self):
return self._weightStats
def __add_eager(self, name, weight, weightUp, weightDown, shift):
"""Add a new weight with eager calculation"""
if isinstance(weight, numpy.ma.MaskedArray):
# TODO what to do with option-type? is it representative of unknown weight
# and we default to one or is it an invalid weight and we should never use this
# event in the first place (0) ?
weight = weight.filled(1.0)
self._weight = self._weight * weight
if self._storeIndividual:
self._weights[name] = weight
self.__add_variation(name, weight, weightUp, weightDown, shift)
self._weightStats[name] = WeightStatistics(
weight.sum(),
(weight**2).sum(),
weight.min(),
weight.max(),
weight.size,
)
def __add_delayed(self, name, weight, weightUp, weightDown, shift):
"""Add a new weight with delayed calculation"""
if isinstance(dask_awkward.type(weight), awkward.types.OptionType):
# TODO what to do with option-type? is it representative of unknown weight
# and we default to one or is it an invalid weight and we should never use this
# event in the first place (0) ?
weight = dask_awkward.fill_none(weight, 1.0)
if self._weight is None:
self._weight = weight
else:
self._weight = self._weight * weight
if self._storeIndividual:
self._weights[name] = weight
self.__add_variation(name, weight, weightUp, weightDown, shift)
self._weightStats[name] = {
"sumw": dask_awkward.sum(weight),
"sumw2": dask_awkward.sum(weight**2),
"minw": dask_awkward.min(weight),
"maxw": dask_awkward.max(weight),
}
def add(self, name, weight, weightUp=None, weightDown=None, shift=False):
"""Add a new weight
Adds a named correction to the event weight, and optionally also associated
systematic uncertainties.
Parameters
----------
name : str
name of correction
weight : numpy.ndarray
the nominal event weight associated with the correction
weightUp : numpy.ndarray, optional
weight with correction uncertainty shifted up (if available)
weightDown : numpy.ndarray, optional
weight with correction uncertainty shifted down. If ``weightUp`` is supplied, and
the correction uncertainty is symmetric, this can be set to None to auto-calculate
the down shift as ``1 / weightUp``.
shift : bool, optional
if True, interpret weightUp and weightDown as a relative difference (additive) to the
nominal value
.. note:: ``weightUp`` and ``weightDown`` are assumed to be rvalue-like and may be modified in-place by this function
"""
if name.endswith("Up") or name.endswith("Down"):
raise ValueError(
"Avoid using 'Up' and 'Down' in weight names, instead pass appropriate shifts to add() call"
)
weight = coffea.util._ensure_flat(weight, allow_missing=True)
if isinstance(weight, numpy.ndarray) and isinstance(
self._weight, numpy.ndarray
):
self.__add_eager(name, weight, weightUp, weightDown, shift)
elif isinstance(weight, dask_awkward.Array) and isinstance(
self._weight, (dask_awkward.Array, type(None))
):
self.__add_delayed(name, weight, weightUp, weightDown, shift)
else:
raise ValueError(
f"Incompatible weights: self._weight={type(self.weight)}, weight={type(weight)}"
)
def __add_multivariation_eager(
self, name, weight, modifierNames, weightsUp, weightsDown, shift=False
):
"""Add a new weight with multiple variations in eager mode"""
if isinstance(weight, numpy.ma.MaskedArray):
# TODO what to do with option-type? is it representative of unknown weight
# and we default to one or is it an invalid weight and we should never use this
# event in the first place (0) ?
weight = weight.filled(1.0)
self._weight = self._weight * weight
if self._storeIndividual:
self._weights[name] = weight
# Now loop on the variations
if len(modifierNames) > 0:
if len(modifierNames) != len(weightsUp) or len(modifierNames) != len(
weightsDown
):
raise ValueError(
"Provide the same number of modifier names related to the list of modified weights"
)
for modifier, weightUp, weightDown in zip(
modifierNames, weightsUp, weightsDown
):
systName = f"{name}_{modifier}"
self.__add_variation(systName, weight, weightUp, weightDown, shift)
self._weightStats[name] = WeightStatistics(
weight.sum(),
(weight**2).sum(),
weight.min(),
weight.max(),
weight.size,
)
def __add_multivariation_delayed(
self, name, weight, modifierNames, weightsUp, weightsDown, shift=False
):
"""Add a new weight with multiple variations in delayed mode"""
if isinstance(weight, awkward.types.OptionType):
# TODO what to do with option-type? is it representative of unknown weight
# and we default to one or is it an invalid weight and we should never use this
# event in the first place (0) ?
weight = dask_awkward.fill_none(weight, 1.0)
if self._weight is None:
self._weight = weight
else:
self._weight = self._weight * weight
if self._storeIndividual:
self._weights[name] = weight
# Now loop on the variations
if len(modifierNames) > 0:
if len(modifierNames) != len(weightsUp) or len(modifierNames) != len(
weightsDown
):
raise ValueError(
"Provide the same number of modifier names related to the list of modified weights"
)
for modifier, weightUp, weightDown in zip(
modifierNames, weightsUp, weightsDown
):
systName = f"{name}_{modifier}"
self.__add_variation(systName, weight, weightUp, weightDown, shift)
self._weightStats[name] = {
"sumw": dask_awkward.sum(weight),
"sumw2": dask_awkward.sum(weight**2),
"minw": dask_awkward.min(weight),
"maxw": dask_awkward.max(weight),
}
def add_multivariation(
self, name, weight, modifierNames, weightsUp, weightsDown, shift=False
):
"""Add a new weight with multiple variations
Each variation of a single weight is given a different modifier name.
This is particularly useful e.g. for btag SF variations.
Parameters
----------
name : str
name of correction
weight : numpy.ndarray
the nominal event weight associated with the correction
modifierNames: list of str
list of modifiers for each set of weights variation
weightsUp : list of numpy.ndarray
weight with correction uncertainty shifted up (if available)
weightsDown : list of numpy.ndarray
weight with correction uncertainty shifted down. If ``weightUp`` is supplied, and
the correction uncertainty is symmetric, this can be set to None to auto-calculate
the down shift as ``1 / weightUp``.
shift : bool, optional
if True, interpret weightUp and weightDown as a relative difference (additive) to the
nominal value
.. note:: ``weightUp`` and ``weightDown`` are assumed to be rvalue-like and may be modified in-place by this function
"""
if name.endswith("Up") or name.endswith("Down"):
raise ValueError(
"Avoid using 'Up' and 'Down' in weight names, instead pass appropriate shifts to add() call"
)
weight = coffea.util._ensure_flat(weight, allow_missing=True)
if isinstance(weight, numpy.ndarray) and isinstance(
self._weight, numpy.ndarray
):
self.__add_multivariation_eager(
name, weight, modifierNames, weightsUp, weightsDown, shift
)
elif isinstance(weight, dask_awkward.Array) and isinstance(
self._weight, (dask_awkward.Array, type(None))
):
self.__add_multivariation_delayed(
name, weight, modifierNames, weightsUp, weightsDown, shift
)
else:
raise ValueError(
f"Incompatible weights: self._weight={type(self.weight)}, weight={type(weight)}"
)
def __add_variation_eager(self, name, weight, weightUp, weightDown, shift):
"""Helper function to add an eagerly calculated weight variation."""
if weightUp is not None:
weightUp = coffea.util._ensure_flat(weightUp, allow_missing=True)
if isinstance(weightUp, numpy.ma.MaskedArray):
weightUp = weightUp.filled(1.0)
if shift:
weightUp += weight
weightUp[weight != 0.0] /= weight[weight != 0.0]
self._modifiers[name + "Up"] = weightUp
if weightDown is not None:
weightDown = coffea.util._ensure_flat(weightDown, allow_missing=True)
if isinstance(weightDown, numpy.ma.MaskedArray):
weightDown = weightDown.filled(1.0)
if shift:
weightDown = weight - weightDown
weightDown[weight != 0.0] /= weight[weight != 0.0]
self._modifiers[name + "Down"] = weightDown
def __add_variation_delayed(self, name, weight, weightUp, weightDown, shift):
"""Helper function to add a delayed-calculation weight variation."""
if weightUp is not None:
weightUp = coffea.util._ensure_flat(weightUp, allow_missing=True)
if isinstance(dask_awkward.type(weightUp), awkward.types.OptionType):
weightUp = dask_awkward.fill_none(weightUp, 1.0)
if shift:
weightUp = weightUp + weight
weightUp = dask_awkward.where(weight != 0.0, weightUp / weight, weightUp)
self._modifiers[name + "Up"] = weightUp
if weightDown is not None:
weightDown = coffea.util._ensure_flat(weightDown, allow_missing=True)
if isinstance(dask_awkward.type(weightDown), awkward.types.OptionType):
weightDown = dask_awkward.fill_none(weightDown, 1.0)
if shift:
weightDown = weight - weightDown
weightDown = dask_awkward.where(
weight != 0.0, weightDown / weight, weightDown
)
self._modifiers[name + "Down"] = weightDown
def __add_variation(
self, name, weight, weightUp=None, weightDown=None, shift=False
):
"""Helper function to add a weight variation.
Parameters
----------
name : str
name of systematic variation (just the name of the weight if only
one variation is added, or `name_syst` for multiple variations)
weight : numpy.ndarray
the nominal event weight associated with the correction
weightUp : numpy.ndarray, optional
weight with correction uncertainty shifted up (if available)
weightDown : numpy.ndarray, optional
weight with correction uncertainty shifted down. If ``weightUp`` is supplied, and
the correction uncertainty is symmetric, this can be set to None to auto-calculate
the down shift as ``1 / weightUp``.
shift : bool, optional
if True, interpret weightUp and weightDown as a relative difference (additive) to the
nominal value
.. note:: ``weightUp`` and ``weightDown`` are assumed to be rvalue-like and may be modified in-place by this function
"""
if isinstance(weight, numpy.ndarray):
self.__add_variation_eager(name, weight, weightUp, weightDown, shift)
elif isinstance(weight, dask_awkward.Array):
self.__add_variation_delayed(name, weight, weightUp, weightDown, shift)
@lru_cache
def weight(self, modifier=None):
"""Current event weight vector
Parameters
----------
modifier : str, optional
if supplied, provide event weight corresponding to a particular
systematic uncertainty shift, of form ``str(name + 'Up')`` or (Down)
Returns
-------
weight : numpy.ndarray
The weight vector, possibly modified by the effect of a given systematic variation.
"""
if modifier is None:
return self._weight
elif "Down" in modifier and modifier not in self._modifiers:
return self._weight / self._modifiers[modifier.replace("Down", "Up")]
return self._weight * self._modifiers[modifier]
def partial_weight(self, include=[], exclude=[], modifier=None):
"""Partial event weight vector
Return a partial weight by multiplying a subset of all weights.
Can be operated either by specifying weights to include or
weights to exclude, but not both at the same time. The method
can only be used if the individual weights are stored via the
``storeIndividual`` argument in the `Weights` initializer.
Parameters
----------
include : list
Weight names to include, defaults to []
exclude : list
Weight names to exclude, defaults to []
modifier : str, optional
if supplied, provide event weight corresponding to a particular
systematic uncertainty shift, of form ``str(name + 'Up')`` or (Down)
Returns
-------
weight : numpy.ndarray
The weight vector, corresponding to only the effect of the
corrections specified.
"""
return self._partial_weight(
include=tuple(include), exclude=tuple(exclude), modifier=modifier
)
@lru_cache
def _partial_weight(self, include, exclude, modifier=None):
if not self._storeIndividual:
raise ValueError(
"To be able to request weight exclusion, use storeIndividual=True when creating Weights object."
)
if (include and exclude) or not (include or exclude):
raise ValueError(
"Need to specify exactly one of the 'exclude' or 'include' arguments."
)
names = set(self._weights.keys())
if include:
names = names & set(include)
if exclude:
names = names - set(exclude)
w = None
if isinstance(self._weight, numpy.ndarray):
w = numpy.ones(self._weight.size)
elif isinstance(self._weight, dask_awkward.Array):
w = dask_awkward.ones_like(self._weight)
for name in names:
w = w * self._weights[name]
if modifier is None:
return w
elif modifier.replace("Down", "").replace("Up", "") not in names:
raise ValueError(
f"Modifier {modifier} is not in the list of included weights"
)
elif "Down" in modifier and modifier not in self._modifiers:
return w / self._modifiers[modifier.replace("Down", "Up")]
return w * self._modifiers[modifier]
@property
def variations(self):
"""List of available modifiers"""
keys = set(self._modifiers.keys())
# add any missing 'Down' variation
for k in self._modifiers.keys():
keys.add(k.replace("Up", "Down"))
return keys
class NminusOneToNpz:
"""Object to be returned by NminusOne.to_npz()"""
def __init__(self, file, labels, nev, masks, saver):
self._file = file
self._labels = labels
self._nev = nev
self._masks = masks
self._saver = saver
def __repr__(self):
return f"NminusOneToNpz(file={self._file}), labels={self._labels})"
@property
def file(self):
return self._file
@property
def labels(self):
return self._labels
@property
def nev(self):
return self._nev
@property
def masks(self):
return self._masks
def compute(self):
self._nev = list(dask.compute(*self._nev))
self._masks = list(dask.compute(*self._masks))
self._saver(self._file, labels=self._labels, nev=self._nev, masks=self._masks)
class CutflowToNpz:
"""Object to be returned by Cutflow.to_npz()"""
def __init__(
self, file, labels, nevonecut, nevcutflow, masksonecut, maskscutflow, saver
):
self._file = file
self._labels = labels
self._nevonecut = nevonecut
self._nevcutflow = nevcutflow
self._masksonecut = masksonecut
self._maskscutflow = maskscutflow
self._saver = saver
def __repr__(self):
return f"CutflowToNpz(file={self._file}), labels={self._labels})"
@property
def file(self):
return self._file
@property
def labels(self):
return self._labels
@property
def nevonecut(self):
return self._nevonecut
@property
def nevcutflow(self):
return self._nevcutflow
@property
def masksonecut(self):
return self._masksonecut
@property
def maskscutflow(self):
return self._maskscutflow
def compute(self):
self._nevonecut, self._nevcutflow = dask.compute(
self._nevonecut, self._nevcutflow
)
self._masksonecut, self._maskscutflow = dask.compute(
self._masksonecut, self._maskscutflow
)
self._nevonecut = list(self._nevonecut)
self._nevcutflow = list(self._nevcutflow)
self._masksonecut = list(self._masksonecut)
self._maskscutflow = list(self._maskscutflow)
self._saver(
self._file,
labels=self._labels,
nevonecut=self._nevonecut,
nevcutflow=self._nevcutflow,
masksonecut=self._masksonecut,
maskscutflow=self._maskscutflow,
)
class NminusOne:
"""Object to be returned by PackedSelection.nminusone()"""
def __init__(self, names, nev, masks, delayed_mode):
self._names = names
self._nev = nev
self._masks = masks
self._delayed_mode = delayed_mode
def __repr__(self):
return f"NminusOne(selections={self._names})"
def result(self):
"""Returns the results of the N-1 selection as a namedtuple
Returns
-------
result : NminusOneResult
A namedtuple with the following attributes:
nev : list of integers or dask_awkward.lib.core.Scalar objects
The number of events in each step of the N-1 selection as a list of integers or delayed integers
masks : list of boolean numpy.ndarray or dask_awkward.lib.core.Array objects
The boolean mask vectors of which events pass the N-1 selection each time as a list of materialized or delayed boolean arrays
"""
NminusOneResult = namedtuple("NminusOneResult", ["labels", "nev", "masks"])
labels = ["initial"] + [f"N - {i}" for i in self._names] + ["N"]
return NminusOneResult(labels, self._nev, self._masks)
def to_npz(self, file, compressed=False, compute=False):
"""Saves the results of the N-1 selection to a .npz file
Parameters
----------
file : str or file
Either the filename (string) or an open file (file-like object)
where the data will be saved. If file is a string or a Path, the
``.npz`` extension will be appended to the filename if it is not
already there.
compressed : bool, optional
If True, the data will be compressed in the ``.npz`` file.
Default is False.
compute : bool, optional
Whether to immediately start writing or to return an object
that the user can choose when to start writing by calling compute().
Default is False.
Returns
-------
out : NminusOneToNpz or None
If ``compute=True``, returns None. Otherwise, returns an object
that can be used to start writing the data by calling compute().
"""
labels, nev, masks = self.result()
if compressed:
saver = numpy.savez_compressed
else:
saver = numpy.savez
out = NminusOneToNpz(file, labels, nev, masks, saver)
if compute:
out.compute()
return None
else:
return out
def print(self):
"""Prints the statistics of the N-1 selection"""
if self._delayed_mode:
warnings.warn(
"Printing the N-1 selection statistics is going to compute dask_awkward objects."
)
self._nev = list(dask.compute(*self._nev))
nev = self._nev
print("N-1 selection stats:")
for i, name in enumerate(self._names):
stats = (
f"Ignoring {name:<20}"
f"pass = {nev[i+1]:<20}"
f"all = {nev[0]:<20}"
f"-- eff = {nev[i+1]*100/nev[0]:.1f} %"
)
print(stats)
stats_all = (
f"All cuts {'':<20}"
f"pass = {nev[-1]:<20}"
f"all = {nev[0]:<20}"
f"-- eff = {nev[-1]*100/nev[0]:.1f} %"
)
print(stats_all)
def yieldhist(self):
"""Returns the N-1 selection yields as a ``hist.Hist`` object
Returns
-------
h : hist.Hist or hist.dask.Hist
Histogram of the number of events surviving the N-1 selection
labels : list of strings
The bin labels of the histogram
"""
labels = ["initial"] + [f"N - {i}" for i in self._names] + ["N"]
if not self._delayed_mode:
h = hist.Hist(hist.axis.Integer(0, len(labels), name="N-1"))
h.fill(numpy.arange(len(labels), dtype=int), weight=self._nev)
else:
h = hist.dask.Hist(hist.axis.Integer(0, len(labels), name="N-1"))
for i, weight in enumerate(self._masks, 1):
h.fill(dask_awkward.full_like(weight, i, dtype=int), weight=weight)
h.fill(dask_awkward.zeros_like(weight, dtype=int))
return h, labels
def plot_vars(
self,
vars,
axes=None,
bins=None,
start=None,
stop=None,
edges=None,
transform=None,
):
"""Plot the histograms of variables for each step of the N-1 selection
Parameters
----------
vars : dict
A dictionary in the form ``{name: array}`` where ``name`` is the name of the variable,
and ``array`` is the corresponding array of values.
The arrays must be the same length as each mask of the N-1 selection.
axes : list of hist.axis objects, optional
The axes objects to histogram the variables on. This will override all the following arguments that define axes.
Must be the same length as ``vars``.
bins : iterable of integers or Nones, optional
The number of bins for each variable histogram. If not specified, it defaults to 20.
Must be the same length as ``vars``.
start : iterable of floats or integers or Nones, optional
The lower edge of the first bin for each variable histogram. If not specified, it defaults to the minimum value of the variable array.
Must be the same length as ``vars``.
stop : iterable of floats or integers or Nones, optional
The upper edge of the last bin for each variable histogram. If not specified, it defaults to the maximum value of the variable array.
Must be the same length as ``vars``.
edges : list of iterables of floats or integers, optional
The bin edges for each variable histogram. This overrides ``bins``, ``start``, and ``stop`` if specified.
Must be the same length as ``vars``.
transform : iterable of hist.axis.transform objects or Nones, optional
The transforms to apply to each variable histogram axis. If not specified, it defaults to None.
Must be the same length as ``vars``.
Returns
-------
hists : list of hist.Hist or hist.dask.Hist objects
A list of 2D histograms of the variables for each step of the N-1 selection.
The first axis is the variable, the second axis is the N-1 selection step.
labels : list of strings
The bin labels of y axis of the histogram.
"""
if self._delayed_mode:
for name, var in vars.items():
if not compatible_partitions(var, self._masks[0]):
raise IncompatiblePartitions("plot_vars", var, self._masks[0])
else:
for name, var in vars.items():
if len(var) != len(self._masks[0]):
raise ValueError(
f"The variable '{name}' has length '{len(var)}', but the masks have length '{len(self._masks[0])}'"
)
hists = []
labels = ["initial"] + [f"N - {i}" for i in self._names] + ["N"]
bins = [None] * len(vars) if bins is None else bins
start = [None] * len(vars) if start is None else start
stop = [None] * len(vars) if stop is None else stop
edges = [None] * len(vars) if edges is None else edges
transform = [None] * len(vars) if transform is None else transform
if axes is not None:
axes = axes
else:
axes = []
for (name, var), b, s1, s2, e, t in zip(
vars.items(), bins, start, stop, edges, transform
):
ax = coffea.util._gethistogramaxis(
name, var, b, s1, s2, e, t, self._delayed_mode
)
axes.append(ax)
checklengths = [
len(x) == len(vars) for x in (axes, bins, start, stop, edges, transform)
]
if not all(checklengths):
raise ValueError(
"vars, axes, bins, start, stop, edges, and transform must be the same length"
)
if not self._delayed_mode:
for (name, var), axis in zip(vars.items(), axes):
h = hist.Hist(
axis,
hist.axis.Integer(0, len(labels), name="N-1"),
)
arr = awkward.flatten(var)
h.fill(arr, awkward.zeros_like(arr, dtype=int))
for i, mask in enumerate(self.result().masks, 1):
arr = awkward.flatten(var[mask])
h.fill(arr, awkward.full_like(arr, i, dtype=int))
hists.append(h)
else:
for (name, var), axis in zip(vars.items(), axes):
h = hist.dask.Hist(
axis,
hist.axis.Integer(0, len(labels), name="N-1"),
)
arr = dask_awkward.flatten(var)
h.fill(arr, dask_awkward.zeros_like(arr, dtype=int))
for i, mask in enumerate(self.result().masks, 1):
arr = dask_awkward.flatten(var[mask])
h.fill(arr, dask_awkward.full_like(arr, i, dtype=int))
hists.append(h)
return hists, labels
class Cutflow:
"""Object to be returned by PackedSelection.cutflow()"""
def __init__(
self, names, nevonecut, nevcutflow, masksonecut, maskscutflow, delayed_mode
):
self._names = names
self._nevonecut = nevonecut
self._nevcutflow = nevcutflow
self._masksonecut = masksonecut
self._maskscutflow = maskscutflow
self._delayed_mode = delayed_mode
def __repr__(self):
return f"Cutflow(selections={self._names})"
def result(self):
"""Returns the results of the cutflow as a namedtuple
Returns
-------
result : CutflowResult
A namedtuple with the following attributes:
nevonecut : list of integers or dask_awkward.lib.core.Scalar objects
The number of events that survive each cut alone as a list of integers or delayed integers
nevcutflow : list of integers or dask_awkward.lib.core.Scalar objects
The number of events that survive the cumulative cutflow as a list of integers or delayed integers
masksonecut : list of boolean numpy.ndarray or dask_awkward.lib.core.Array objects
The boolean mask vectors of which events pass each cut alone as a list of materialized or delayed boolean arrays
maskscutflow : list of boolean numpy.ndarray or dask_awkward.lib.core.Array objects
The boolean mask vectors of which events pass the cumulative cutflow a list of materialized or delayed boolean arrays
"""
CutflowResult = namedtuple(
"CutflowResult",
["labels", "nevonecut", "nevcutflow", "masksonecut", "maskscutflow"],
)
labels = ["initial"] + list(self._names)
return CutflowResult(
labels,
self._nevonecut,
self._nevcutflow,
self._masksonecut,
self._maskscutflow,
)
def to_npz(self, file, compressed=False, compute=False):
"""Saves the results of the cutflow to a .npz file
Parameters
----------
file : str or file
Either the filename (string) or an open file (file-like object)
where the data will be saved. If file is a string or a Path, the
``.npz`` extension will be appended to the filename if it is not
already there.
compressed : bool, optional
If True, the data will be compressed in the ``.npz`` file.
Default is False.
compute : bool, optional
Whether to immediately start writing or to return an object
that the user can choose when to start writing by calling compute().
Default is False.
Returns
-------
out : CutflowToNpz or None
If ``compute=True``, returns None. Otherwise, returns an object
that can be used to start writing the data by calling compute().
"""
labels, nevonecut, nevcutflow, masksonecut, maskscutflow = self.result()
if compressed:
saver = numpy.savez_compressed
else:
saver = numpy.savez
out = CutflowToNpz(
file, labels, nevonecut, nevcutflow, masksonecut, maskscutflow, saver
)
if compute:
out.compute()
return None
else:
return out
def print(self):
"""Prints the statistics of the Cutflow"""
if self._delayed_mode:
warnings.warn(
"Printing the cutflow statistics is going to compute dask_awkward objects."
)
self._nevonecut, self._nevcutflow = dask.compute(
self._nevonecut, self._nevcutflow
)
nevonecut = self._nevonecut
nevcutflow = self._nevcutflow
print("Cutflow stats:")
for i, name in enumerate(self._names):
stats = (
f"Cut {name:<20}:"
f"pass = {nevonecut[i+1]:<20}"
f"cumulative pass = {nevcutflow[i+1]:<20}"
f"all = {nevonecut[0]:<20}"
f"-- eff = {nevonecut[i+1]*100/nevonecut[0]:.1f} %{'':<20}"
f"-- cumulative eff = {nevcutflow[i+1]*100/nevcutflow[0]:.1f} %"
)
print(stats)
def yieldhist(self):
"""Returns the cutflow yields as ``hist.Hist`` objects
Returns
-------
honecut : hist.Hist or hist.dask.Hist
Histogram of the number of events surviving each cut alone
hcutflow : hist.Hist or hist.dask.Hist
Histogram of the number of events surviving the cumulative cutflow
labels : list of strings
The bin labels of the histograms
"""
labels = ["initial"] + list(self._names)
if not self._delayed_mode:
honecut = hist.Hist(hist.axis.Integer(0, len(labels), name="onecut"))
hcutflow = honecut.copy()
hcutflow.axes.name = ("cutflow",)
honecut.fill(numpy.arange(len(labels), dtype=int), weight=self._nevonecut)
hcutflow.fill(numpy.arange(len(labels), dtype=int), weight=self._nevcutflow)
else:
honecut = hist.dask.Hist(hist.axis.Integer(0, len(labels), name="onecut"))
hcutflow = honecut.copy()
hcutflow.axes.name = ("cutflow",)
for i, weight in enumerate(self._masksonecut, 1):
honecut.fill(
dask_awkward.full_like(weight, i, dtype=int), weight=weight
)
honecut.fill(dask_awkward.zeros_like(weight, dtype=int))
for i, weight in enumerate(self._maskscutflow, 1):
hcutflow.fill(
dask_awkward.full_like(weight, i, dtype=int), weight=weight
)
hcutflow.fill(dask_awkward.zeros_like(weight, dtype=int))
return honecut, hcutflow, labels
def plot_vars(
self,
vars,
axes=None,
bins=None,
start=None,
stop=None,
edges=None,
transform=None,
):
"""Plot the histograms of variables for each step of the N-1 selection
Parameters
----------
vars : dict
A dictionary in the form ``{name: array}`` where ``name`` is the name of the variable,
and ``array`` is the corresponding array of values.
The arrays must be the same length as each mask of the cutflow.
axes : list of hist.axis objects, optional
The axes objects to histogram the variables on. This will override all the following arguments that define axes.
Must be the same length as ``vars``.
bins : iterable of integers or Nones, optional
The number of bins for each variable histogram. If not specified, it defaults to 20.
Must be the same length as ``vars``.
start : iterable of floats or integers or Nones, optional
The lower edge of the first bin for each variable histogram. If not specified, it defaults to the minimum value of the variable array.
Must be the same length as ``vars``.
stop : iterable of floats or integers or Nones, optional
The upper edge of the last bin for each variable histogram. If not specified, it defaults to the maximum value of the variable array.
Must be the same length as ``vars``.
edges : list of iterables of floats or integers, optional
The bin edges for each variable histogram. This overrides ``bins``, ``start``, and ``stop`` if specified.
Must be the same length as ``vars``.
transform : iterable of hist.axis.transform objects or Nones, optional
The transforms to apply to each variable histogram axis. If not specified, it defaults to None.
Must be the same length as ``vars``.
Returns
-------
histsonecut : list of hist.Hist or hist.dask.Hist objects
A list of 1D histograms of the variables of events surviving each cut alone.
The first axis is the variable, the second axis is the cuts.
histscutflow : list of hist.Hist or hist.dask.Hist objects
A list of 1D histograms of the variables of events surviving the cumulative cutflow.
The first axis is the variable, the second axis is the cuts.
labels : list of strings
The bin labels of the y axis of the histograms.
"""
if self._delayed_mode:
for name, var in vars.items():
if not compatible_partitions(var, self._masksonecut[0]):
raise IncompatiblePartitions("plot_vars", var, self._masksonecut[0])
else:
for name, var in vars.items():
if len(var) != len(self._masksonecut[0]):
raise ValueError(
f"The variable '{name}' has length '{len(var)}', but the masks have length '{len(self._masksonecut[0])}'"
)
histsonecut, histscutflow = [], []
labels = ["initial"] + list(self._names)
bins = [None] * len(vars) if bins is None else bins
start = [None] * len(vars) if start is None else start
stop = [None] * len(vars) if stop is None else stop
edges = [None] * len(vars) if edges is None else edges
transform = [None] * len(vars) if transform is None else transform
if axes is not None:
axes = axes
else:
axes = []
for (name, var), b, s1, s2, e, t in zip(
vars.items(), bins, start, stop, edges, transform