Belle II Software development
background.py
1#!/usr/bin/env python3
2
3
10
11import glob
12import os
13
14from basf2 import Module, Path, B2ERROR, B2INFO
15from basf2.utils import pretty_print_table
16
17
18class SelectTRGTypes(Module):
19 '''Select events according to given trigger types.'''
20
21 def __init__(self, trg_types=None):
22 '''Constructor.'''
23 from ROOT import Belle2
24 super().__init__()
25
26 self.trg_summary = Belle2.PyStoreObj('TRGSummary')
27
28 self.trg_types = trg_types
29
30 def initialize(self, trg_types=None):
31 '''Initialize the module.'''
32 self.trg_summary.isRequired()
33
34 def event(self):
35 '''Event processing.'''
36 self.return_value(0)
37
38 if not self.trg_summary.isValid():
39 # This should never happen: let's report without crashing the processing
40 B2ERROR('TRGSummary is not available: the event is discarded.')
41 return
42
43 for trg_type in self.trg_types:
44 if self.trg_summary.getTimType() == trg_type:
45 self.return_value(1)
46 return
47
48
49def get_trigger_types_for_bgo():
50 '''Get the default trigger types to be used for the Beam Background Overlay (BGO) production.'''
51 from ROOT import Belle2
52
53 trg_types = [
54 Belle2.TRGSummary.TTYP_DPHY, # 5 -> delayed physics for background
55 Belle2.TRGSummary.TTYP_RAND, # 7 -> random trigger events
56 ]
57 return trg_types
58
59
60def get_background_files(folder=None, output_file_info=True):
61 """ Loads the location of the background files from the environmant variable
62 BELLE2_BACKGROUND_DIR which is set on the validation server and ensures that background
63 files exist and returns the list of background files which
64 can be directly used with add_simulation() :
65
66 >>> add_simulation(main, bkgfiles=background.get_background_files())
67
68 Will fail with an assert if no background folder set or if no background file was
69 found in the set folder.
70
71 Parameters:
72 folder (str): A specific folder to search for background files can be given as an optional parameter
73 output_file_info (str): If true, a list of the found background files and there size will be printed
74 This is useful to understand later which background campaign has been used
75 to simulate events.
76 """
77
78 env_name = 'BELLE2_BACKGROUND_DIR'
79 bg = None
80
81 if folder is None:
82 if env_name not in os.environ:
83 raise RuntimeError("Environment variable {} for background files not set. Terminanting this script.".format(env_name))
84 folder = os.environ[env_name]
85
86 bg = glob.glob(folder + '/*.root')
87
88 if len(bg) == 0:
89 raise RuntimeError("No background files found in folder {} . Terminating this script.".format(folder))
90
91 B2INFO("Background files loaded from folder {}".format(folder))
92
93 # sort for easier comparison
94 bg = sorted(bg)
95
96 if output_file_info:
97 bg_sizes = [os.path.getsize(f) for f in bg]
98 # reformat to work with pretty_print_table
99 table_rows = [list(entry) for entry in zip(bg, bg_sizes)]
100 table_rows.insert(0, ["- Background file name -", "- file size -"])
101
102 pretty_print_table(table_rows, [0, 0])
103
104 return bg
105
106
107def add_output(path, bgType, realTime, sampleType, phase=3, fileName='output.root', excludeBranches=None):
108 '''
109 A function to be used for output of BG simulation.
110 @param path path name
111 @param bgType background type, to get available types: basf2 -m BeamBkgTagSetter
112 @param realTime equivalent time of superKEKB running in [ns]
113 @param sampleType 'study' (for BG studies) or 'usual', 'PXD', 'ECL' (for BG mixer)
114 @param specify the Phase, 1 for Phase 1, 2 for Phase 2, and 3 for Physics Run or Phase 3
115 @param fileName optional file name, can be overridden by basf2 -o
116 '''
117 if excludeBranches is None:
118 excludeBranches = []
119
120 if sampleType == 'study':
121 madeFor = ''
122 branches = []
123 elif sampleType == 'usual' and phase == 3:
124 madeFor = ''
125 branches = [
126 'PXDSimHits',
127 'SVDSimHits',
128 'CDCSimHits',
129 'TOPSimHits',
130 'ARICHSimHits',
131 'ECLHits',
132 'KLMSimHits',
133 ]
134 elif sampleType == 'usual' and phase == 2:
135 madeFor = ''
136 branches = [
137 'PXDSimHits',
138 'SVDSimHits',
139 'CDCSimHits',
140 'TOPSimHits',
141 'ARICHSimHits',
142 'ECLHits',
143 'KLMSimHits',
144 'CLAWSSimHits',
145 'FANGSSimHits',
146 'PlumeSimHits',
147 'BeamabortSimHits',
148 'PindiodeSimHits',
149 'QcsmonitorSimHits',
150 'He3tubeSimHits',
151 'MicrotpcSimHits',
152 ]
153 elif sampleType == 'usual' and phase == 1:
154 madeFor = ''
155 branches = [
156 'ClawSimHits',
157 'BeamabortSimHits',
158 'PindiodeSimHits',
159 'QcsmonitorSimHits',
160 'He3tubeSimHits',
161 'MicrotpcSimHits',
162 'BgoSimHits',
163 'CsiSimHits',
164 ]
165 elif sampleType == 'ECL':
166 madeFor = 'ECL'
167 branches = ['ECLHits']
168 elif sampleType == 'PXD':
169 madeFor = 'PXD'
170 branches = ['PXDSimHits']
171 else:
172 madeFor = ''
173 branches = []
174 B2ERROR('add_output - invalid value of argument sampleType: %s'
175 % sampleType)
176
177 # Set background tag in SimHits and add BackgroundMetaData into persistent tree
178 tagSetter = path.add_module('BeamBkgTagSetter', backgroundType=bgType, realTime=realTime,
179 specialFor=madeFor, Phase=phase)
180
181 # Write out only non-empty events when producing samples for BG mixer
182 if sampleType != 'study':
183 emptyPath = Path()
184 tagSetter.if_false(emptyPath)
185
186 # Output to file. We don't need a TTreeIndex for background files and memory
187 # consumption can be improved by setting a lower autoFlushSize so that
188 # fewer and or smaller amounts of data have to be read for each GetEntry()
189 path.add_module('RootOutput', outputFileName=fileName, branchNames=branches, excludeBranchNames=excludeBranches,
190 buildIndex=False, autoFlushSize=-500000)
a (simplified) python wrapper for StoreObjPtr.
Definition PyStoreObj.h:67
trg_summary
The trigger summary object.
Definition background.py:26
trg_types
The trigger types.
Definition background.py:28
__init__(self, trg_types=None)
Definition background.py:21
initialize(self, trg_types=None)
Definition background.py:30