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
16from rawdata import add_unpackers
17from gdltrigger import filter_trigger_abort_gaps
18
19
20BGO_OBJECTS = (
21 'EventLevelTriggerTimeInfo',
22 'PXDDigits',
23 'SVDShaperDigits',
24 'CDCHits',
25 'TOPDigits',
26 'TOPInjectionVeto'
27 'ARICHDigits',
28 'ECLWaveforms',
29 'KLMDigits',
30 'TRGECLBGTCHits',
31 'TRGSummary'
32)
33
34
35class SelectTRGTypes(Module):
36 '''Select events according to given trigger types.'''
37
38 def __init__(self, trg_types=None):
39 '''Constructor.'''
40 super().__init__()
41
42 self.trg_types = trg_types
43
44 def initialize(self, trg_types=None):
45 '''Initialize the module.'''
46 from ROOT import Belle2
47
48 self.trg_summary = Belle2.PyStoreObj('TRGSummary')
49 self.trg_summary.isRequired()
50
51 def event(self):
52 '''Event processing.'''
53 self.return_value(0)
54
55 if not self.trg_summary.isValid():
56 # This should never happen: let's report without crashing the processing
57 B2ERROR('TRGSummary is not available: the event is discarded.')
58 return
59
60 for trg_type in self.trg_types:
61 if self.trg_summary.getTimType() == trg_type:
62 self.return_value(1)
63 return
64
65
66def get_trigger_types_for_bgo():
67 '''Get the default trigger types to be used for the Beam Background Overlay (BGO) production.'''
68 from ROOT import Belle2
69
70 trg_types = [
71 Belle2.TRGSummary.TTYP_DPHY, # 5 -> delayed physics for background
72 Belle2.TRGSummary.TTYP_RAND, # 7 -> random trigger events
73 ]
74 return trg_types
75
76
77def get_background_files(folder=None, output_file_info=True):
78 """ Loads the location of the background files from the environmant variable
79 BELLE2_BACKGROUND_DIR which is set on the validation server and ensures that background
80 files exist and returns the list of background files which
81 can be directly used with add_simulation() :
82
83 >>> add_simulation(main, bkgfiles=background.get_background_files())
84
85 Will fail with an assert if no background folder set or if no background file was
86 found in the set folder.
87
88 Parameters:
89 folder (str): A specific folder to search for background files can be given as an optional parameter
90 output_file_info (str): If true, a list of the found background files and there size will be printed
91 This is useful to understand later which background campaign has been used
92 to simulate events.
93 """
94
95 env_name = 'BELLE2_BACKGROUND_DIR'
96 bg = None
97
98 if folder is None:
99 if env_name not in os.environ:
100 raise RuntimeError("Environment variable {} for background files not set. Terminanting this script.".format(env_name))
101 folder = os.environ[env_name]
102
103 bg = glob.glob(folder + '/*.root')
104
105 if len(bg) == 0:
106 raise RuntimeError("No background files found in folder {} . Terminating this script.".format(folder))
107
108 B2INFO("Background files loaded from folder {}".format(folder))
109
110 # sort for easier comparison
111 bg = sorted(bg)
112
113 if output_file_info:
114 bg_sizes = [os.path.getsize(f) for f in bg]
115 # reformat to work with pretty_print_table
116 table_rows = [list(entry) for entry in zip(bg, bg_sizes)]
117 table_rows.insert(0, ["- Background file name -", "- file size -"])
118
119 pretty_print_table(table_rows, [0, 0])
120
121 return bg
122
123
124def add_output(path, bgType, realTime, sampleType, phase=3, fileName='output.root', excludeBranches=None):
125 '''
126 A function to be used for output of BG simulation.
127 @param path path name
128 @param bgType background type, to get available types: basf2 -m BeamBkgTagSetter
129 @param realTime equivalent time of superKEKB running in [ns]
130 @param sampleType 'study' (for BG studies) or 'usual', 'PXD', 'ECL' (for BG mixer)
131 @param specify the Phase, 1 for Phase 1, 2 for Phase 2, and 3 for Physics Run or Phase 3
132 @param fileName optional file name, can be overridden by basf2 -o
133 '''
134 if excludeBranches is None:
135 excludeBranches = []
136
137 if sampleType == 'study':
138 madeFor = ''
139 branches = []
140 elif sampleType == 'usual' and phase == 3:
141 madeFor = ''
142 branches = [
143 'PXDSimHits',
144 'SVDSimHits',
145 'CDCSimHits',
146 'TOPSimHits',
147 'ARICHSimHits',
148 'ECLHits',
149 'KLMSimHits',
150 ]
151 elif sampleType == 'usual' and phase == 2:
152 madeFor = ''
153 branches = [
154 'PXDSimHits',
155 'SVDSimHits',
156 'CDCSimHits',
157 'TOPSimHits',
158 'ARICHSimHits',
159 'ECLHits',
160 'KLMSimHits',
161 'CLAWSSimHits',
162 'FANGSSimHits',
163 'PlumeSimHits',
164 'BeamabortSimHits',
165 'PindiodeSimHits',
166 'QcsmonitorSimHits',
167 'He3tubeSimHits',
168 'MicrotpcSimHits',
169 ]
170 elif sampleType == 'usual' and phase == 1:
171 madeFor = ''
172 branches = [
173 'ClawSimHits',
174 'BeamabortSimHits',
175 'PindiodeSimHits',
176 'QcsmonitorSimHits',
177 'He3tubeSimHits',
178 'MicrotpcSimHits',
179 'BgoSimHits',
180 'CsiSimHits',
181 ]
182 elif sampleType == 'ECL':
183 madeFor = 'ECL'
184 branches = ['ECLHits']
185 elif sampleType == 'PXD':
186 madeFor = 'PXD'
187 branches = ['PXDSimHits']
188 else:
189 madeFor = ''
190 branches = []
191 B2ERROR('add_output - invalid value of argument sampleType: %s'
192 % sampleType)
193
194 # Set background tag in SimHits and add BackgroundMetaData into persistent tree
195 tagSetter = path.add_module('BeamBkgTagSetter', backgroundType=bgType, realTime=realTime,
196 specialFor=madeFor, Phase=phase)
197
198 # Write out only non-empty events when producing samples for BG mixer
199 if sampleType != 'study':
200 emptyPath = Path()
201 tagSetter.if_false(emptyPath)
202
203 # Output to file. We don't need a TTreeIndex for background files and memory
204 # consumption can be improved by setting a lower autoFlushSize so that
205 # fewer and or smaller amounts of data have to be read for each GetEntry()
206 path.add_module('RootOutput', outputFileName=fileName, branchNames=branches, excludeBranchNames=excludeBranches,
207 buildIndex=False, autoFlushSize=-500000)
208
209
210def add_bgo_modules(path, additionalBranches=None):
211 """
212 This function adds to the path all the necessary modules to produce Beam Background Overlay (BGO) files
213 starting from raw data.
214 This function already adds the ``RootOutput`` module with all the branch names correctly set.
215
216 Arguments:
217 path (Path): Path to add module to
218 additionalBranches (list): Additional objects/arrays of event durability to save
219 """
220
221 empty = Path()
222
223 # Gearbox
224 path.add_module('Gearbox')
225
226 # Geometry
227 path.add_module('Geometry')
228
229 # Unpack TRGSummary
230 path.add_module('TRGGDLUnpacker')
231 path.add_module('TRGGDLSummary')
232
233 # Show progress of processing
234 path.add_module('Progress')
235
236 # Select specific triggered events
237 selector = path.add_module(SelectTRGTypes(trg_types=get_trigger_types_for_bgo()))
238 selector.if_false(empty)
239
240 # Filter away the events falling in the trigger abort gaps
241 filter_trigger_abort_gaps(path)
242
243 # Unpack detector data
244 add_unpackers(path, components=['PXD', 'SVD', 'CDC', 'ECL', 'TOP', 'ARICH', 'KLM'])
245
246 # Convert ECLDsps to ECLWaveforms
247 compress = path.add_module('ECLCompressBGOverlay', CompressionAlgorithm=3)
248 compress.if_false(empty)
249
250 # Shift the time of KLMDigits
251 path.add_module('KLMDigitTimeShifter')
252
253 # ECL trigger unpacker and BGOverlay dataobject
254 path.add_module('TRGECLUnpacker')
255 path.add_module('TRGECLBGTCHit')
256
257 # Output
258 branches = list(BGO_OBJECTS)
259 if additionalBranches:
260 branches += additionalBranches
261 path.add_module('RootOutput', branchNames=branches)
a (simplified) python wrapper for StoreObjPtr.
Definition PyStoreObj.h:67
trg_summary
The trigger summary object.
Definition background.py:48
trg_types
The trigger types.
Definition background.py:42
__init__(self, trg_types=None)
Definition background.py:38
initialize(self, trg_types=None)
Definition background.py:44