Belle II Software development
processing.py
1
8
9import os
10import argparse
11import multiprocessing
12import tempfile
13
14import basf2
15from softwaretrigger import constants, path_utils
16from geometry import check_components
17from pxd import add_pxd_percentframe
18from rawdata import add_unpackers
19from reconstruction import add_reconstruction, add_cosmics_reconstruction
20from tracking import add_roiFinder, add_roi_payload_assembler
21
22
23def setup_basf2_and_db(event_distribution_mode=constants.EventDistributionModes.ringbuffer):
24 """
25 Setup local database usage for HLT
26 """
27 parser = argparse.ArgumentParser(description='basf2 for online')
28
29 if event_distribution_mode == constants.EventDistributionModes.ringbuffer:
30 parser.add_argument('input_buffer_name', type=str,
31 help='Input Ring Buffer names')
32 parser.add_argument('output_buffer_name', type=str,
33 help='Output Ring Buffer name')
34 parser.add_argument('histo_port', type=int,
35 help='Port of the HistoManager to connect to')
36 parser.add_argument('--input-file', type=str,
37 help="Input sroot file, if set no RingBuffer input will be used",
38 default=None)
39 parser.add_argument('--output-file', type=str,
40 help="Filename for SeqRoot output, if set no RingBuffer output will be used",
41 default=None)
42 parser.add_argument('--histo-output-file', type=str,
43 help="Filename for histogram output",
44 default=None)
45 parser.add_argument('--no-output',
46 help="Don't write any output files",
47 action="store_true", default=False)
48 else:
49 parser.add_argument("--input", required=True, type=str, help="ZMQ Address of the distributor process")
50 parser.add_argument("--output", required=True, type=str, help="ZMQ Address of the collector process")
51 parser.add_argument("--dqm", required=True, type=str, help="ZMQ Address of the histoserver process")
52 parser.add_argument('--input-file', type=str,
53 help="Input (s)root file, ZMQ input address is ignored if this is set",
54 default=None)
55 parser.add_argument('--output-file', type=str,
56 help="Filename for (s)root output, ZMQ input address is ignored if this is set",
57 default=None)
58 parser.add_argument('--histo-output-file', type=str,
59 help="Filename for histogram output, ZMQ histoserver address is ignored if this is set",
60 default=None)
61
62 parser.add_argument('--number-processes', type=int, default=multiprocessing.cpu_count() - 5,
63 help='Number of parallel processes to use')
64 parser.add_argument('--local-db-path', type=str,
65 help="set path to the local payload locations to use for the ConditionDB",
66 default=constants.DEFAULT_DB_FILE_LOCATION)
67 parser.add_argument('--local-db-tag', type=str, nargs="*",
68 help="Use the local db with a specific tag (can be applied multiple times, order is relevant)")
69 parser.add_argument('--central-db-tag', type=str, nargs="*",
70 help="Use the central db with a specific tag (can be applied multiple times, order is relevant)")
71 parser.add_argument('--udp-hostname', type=str,
72 help="set hostname for UDP logging connection", default=None)
73 parser.add_argument('--udp-port', type=int,
74 help="set port number for UDP logging connection", default=None)
75
76 args = parser.parse_args()
77
78 # Local DB specification
79 basf2.conditions.override_globaltags()
80 if args.central_db_tag:
81 for central_tag in args.central_db_tag:
82 basf2.conditions.prepend_globaltag(central_tag)
83 else:
84 if args.local_db_tag:
85 for local_tag in args.local_db_tag:
86 basf2.conditions.prepend_globaltag(local_tag)
87 else:
88 basf2.conditions.globaltags = ["online"]
89 basf2.conditions.metadata_providers = ["file://" + basf2.find_file(args.local_db_path + "/metadata.sqlite")]
90 basf2.conditions.payload_locations = [basf2.find_file(args.local_db_path)]
91
92 # Number of processes
93 basf2.set_nprocesses(args.number_processes)
94
95 # basf2 logging setup
96 basf2.set_log_level(basf2.LogLevel.ERROR)
97 # And because reasons we want every log message to be only one line,
98 # otherwise the LogFilter in daq_slc throws away the other lines
99 basf2.logging.enable_escape_newlines = True
100
101 # UDP logging
102 if (args.udp_hostname is not None) and (args.udp_port is not None):
103 basf2.logging.add_udp(args.udp_hostname, args.udp_port)
104
105 # Online realm
106 basf2.set_realm("online")
107
108 return args
109
110
111def start_path(args, location):
112 """
113 Create and return a path used for HLT and ExpressReco running
114 """
115 path = basf2.create_path()
116
117 input_buffer_module_name = ""
118 if location == constants.Location.expressreco:
119 input_buffer_module_name = "Rbuf2Ds"
120 elif location == constants.Location.hlt:
121 input_buffer_module_name = "Raw2Ds"
122 else:
123 basf2.B2FATAL(f"Does not know location {location}")
124
125 # Input
126 if not args.input_file:
127 path.add_module(input_buffer_module_name, RingBufferName=args.input_buffer_name)
128 else:
129 if args.input_file.endswith(".sroot"):
130 path.add_module('SeqRootInput', inputFileName=args.input_file)
131 else:
132 path.add_module('RootInput', inputFileName=args.input_file)
133
134 # Histogram Handling
135 if not args.histo_output_file:
136 path.add_module('DqmHistoManager', Port=args.histo_port, DumpInterval=1000, workDirName=tempfile.gettempdir()+"/")
137 else:
138 workdir = os.path.dirname(args.histo_output_file)
139 filename = os.path.basename(args.histo_output_file)
140 path.add_module('HistoManager', histoFileName=filename, workDirName=workdir)
141
142 return path
143
144
145def start_zmq_path(args, location, event_distribution_mode):
146 path = basf2.Path()
147 reco_path = basf2.Path()
148
149 if event_distribution_mode == constants.EventDistributionModes.zmq:
150 if location == constants.Location.expressreco:
151 input_module = path.add_module("HLTZMQ2Ds", input=args.input, addExpressRecoObjects=True)
152 elif location == constants.Location.hlt:
153 input_module = path.add_module("HLTZMQ2Ds", input=args.input)
154 else:
155 basf2.B2FATAL(f"Does not know location {location}")
156 else:
157 if not args.input_file:
158 if location == constants.Location.expressreco:
159 input_module = path.add_module("HLTZMQ2Ds", input=args.input, addExpressRecoObjects=True)
160 elif location == constants.Location.hlt:
161 input_module = path.add_module("HLTZMQ2Ds", input=args.input)
162 else:
163 basf2.B2FATAL(f"Does not know location {location}")
164 else:
165 if args.input_file.endswith(".sroot"):
166 path.add_module('SeqRootInput', inputFileName=args.input_file)
167 else:
168 path.add_module('RootInput', inputFileName=args.input_file)
169
170 # zmq needs to discard the first event from HLTZMQ2Ds level
171 if not args.histo_output_file:
172 if event_distribution_mode == constants.EventDistributionModes.zmq:
173 input_module.if_value("==0", reco_path, basf2.AfterConditionPath.CONTINUE)
174 reco_path.add_module("HLTDQM2ZMQ", output=args.dqm, sendOutInterval=30)
175 # zmqbasf2 needs to pass the first event to the remaining path
176 elif event_distribution_mode == constants.EventDistributionModes.zmqbasf2:
177 path.add_module("HLTDQM2ZMQ", output=args.dqm, sendOutInterval=30)
178 else:
179 basf2.B2FATAL(f"Does not know event_distribution_mode {event_distribution_mode}")
180 else:
181 workdir = os.path.dirname(args.histo_output_file)
182 filename = os.path.basename(args.histo_output_file)
183 path.add_module('HistoManager', histoFileName=filename, workDirName=workdir)
184
185 return path, reco_path
186
187
188def add_hlt_processing(path,
189 run_type=constants.RunTypes.beam,
190 softwaretrigger_mode=constants.SoftwareTriggerModes.filter,
191 prune_input=True,
192 prune_output=True,
193 unpacker_components=None,
194 reco_components=None,
195 create_hlt_unit_histograms=True,
196 switch_off_slow_modules_for_online=True,
197 dqm_run_type=None,
198 **kwargs):
199 """
200 Add all modules for processing on HLT filter machines
201 """
202
203 # Check if the run is cosmic and set the Environment accordingly
204 if run_type == constants.RunTypes.cosmic:
205 basf2.declare_cosmics()
206
207 # Check if the run is beam and set the Environment accordingly
208 if run_type == constants.RunTypes.beam:
209 basf2.declare_beam()
210
211 if dqm_run_type is None:
212 dqm_run_type = run_type
213
214 # Always avoid the top-level 'import ROOT'.
215 import ROOT # noqa
216
217 path.add_module('StatisticsSummary').set_name('Sum_Wait')
218
219 if unpacker_components is None:
220 unpacker_components = constants.DEFAULT_HLT_COMPONENTS
221 if reco_components is None:
222 reco_components = constants.DEFAULT_HLT_COMPONENTS
223
224 check_components(unpacker_components)
225 check_components(reco_components)
226
227 # ensure that only DataStore content is present that we expect in
228 # in the HLT configuration. If ROIpayloads or tracks are present in the
229 # input file, this can be a problem and lead to crashes
230 if prune_input:
231 path.add_module("PruneDataStore", matchEntries=constants.HLT_INPUT_OBJECTS)
232
233 # Add the geometry (if not already present)
234 path_utils.add_geometry_if_not_present(path)
235 path.add_module('StatisticsSummary').set_name('Sum_Initialization')
236
237 # Unpack the event content
238 add_unpackers(path, components=unpacker_components, writeKLMDigitRaws=True)
239
240 # HLT prefilter
241 path_utils.add_prefilter_module(path)
242
243 # Build one path for all accepted events...
244 accept_path = basf2.Path()
245
246 # Do the reconstruction needed for the HLT decision
247 path_utils.add_pre_filter_reconstruction(
248 path,
249 run_type=run_type,
250 components=reco_components,
251 switch_off_slow_modules_for_online=switch_off_slow_modules_for_online,
252 **kwargs
253 )
254
255 # Perform HLT filter calculation
256 path_utils.add_filter_software_trigger(path, store_array_debug_prescale=1)
257
258 # Add the part of the dqm modules, which should run after every reconstruction
259 path_utils.add_hlt_dqm(path, run_type=dqm_run_type, components=reco_components, dqm_mode=constants.DQMModes.before_filter,
260 create_hlt_unit_histograms=create_hlt_unit_histograms)
261
262 # Only turn on the filtering (by branching the path) if filtering is turned on
263 if softwaretrigger_mode == constants.SoftwareTriggerModes.filter:
264 # Now split up the path according to the HLT decision
265 hlt_filter_module = path_utils.add_filter_module(path)
266 # There are two possibilities for the output of this module
267 # (1) the event is dismissed -> only store the metadata
268 path_utils.hlt_event_abort(hlt_filter_module, "==0", ROOT.Belle2.EventMetaData.c_HLTDiscard)
269 # (2) the event is accepted -> go on with the hlt reconstruction
270 hlt_filter_module.if_value("==1", accept_path, basf2.AfterConditionPath.CONTINUE)
271 elif softwaretrigger_mode == constants.SoftwareTriggerModes.monitor:
272 # Otherwise just always go with the accept path
273 path.add_path(accept_path)
274 else:
275 basf2.B2FATAL(f"The software trigger mode {softwaretrigger_mode} is not supported.")
276
277 # For accepted events we continue the reconstruction
278 path_utils.add_post_filter_reconstruction(
279 accept_path,
280 run_type=run_type,
281 components=reco_components,
282 switch_off_slow_modules_for_online=switch_off_slow_modules_for_online,
283 **kwargs
284 )
285
286 # Only create the ROIs for accepted events
287 add_roiFinder(accept_path)
288 accept_path.add_module('StatisticsSummary').set_name('Sum_ROI_Finder')
289
290 # Add the HLT DQM modules only in case the event is accepted
291 path_utils.add_hlt_dqm(
292 accept_path,
293 run_type=dqm_run_type,
294 components=reco_components,
295 dqm_mode=constants.DQMModes.filtered,
296 create_hlt_unit_histograms=create_hlt_unit_histograms)
297
298 # Make sure to create ROI payloads for sending them to ONSEN
299 # Do this for all events
300 # Normally, the payload assembler marks the event with the software trigger decision to inform the hardware to
301 # drop the data for the event in case the decision is "no"
302 # However, if we are running in monitoring mode, we ignore the decision
303 pxd_ignores_hlt_decision = (softwaretrigger_mode == constants.SoftwareTriggerModes.monitor)
304 add_roi_payload_assembler(path, ignore_hlt_decision=pxd_ignores_hlt_decision)
305 path.add_module('StatisticsSummary').set_name('Sum_ROI_Payload_Assembler')
306
307 # Add the part of the dqm modules, which should run on all events, not only on the accepted ones
308 path_utils.add_hlt_dqm(path, run_type=dqm_run_type, components=reco_components, dqm_mode=constants.DQMModes.all_events,
309 create_hlt_unit_histograms=create_hlt_unit_histograms)
310
311 if prune_output:
312 # And in the end remove everything which should not be stored
313 path_utils.add_store_only_rawdata_path(path)
314 path.add_module('StatisticsSummary').set_name('Sum_Close_Event')
315
316
317def add_hlt_passthrough(path):
318 """
319 Add all modules for operating HLT machines in passthrough mode.
320 """
321 add_pxd_percentframe(path, fraction=0.1, random_position=True)
322 add_roi_payload_assembler(path, ignore_hlt_decision=True)
323
324
325def add_expressreco_processing(path,
326 run_type=constants.RunTypes.beam,
327 select_only_accepted_events=False,
328 prune_input=True,
329 prune_output=True,
330 unpacker_components=None,
331 reco_components=None,
332 do_reconstruction=True,
333 switch_off_slow_modules_for_online=True,
334 dqm_run_type=None,
335 **kwargs):
336 """
337 Add all modules for processing on the ExpressReco machines
338 """
339
340 # Check if the run is cosmic and set the Environment accordingly
341 if run_type == constants.RunTypes.cosmic:
342 basf2.declare_cosmics()
343
344 # Check if the run is beam and set the Environment accordingly
345 if run_type == constants.RunTypes.beam:
346 basf2.declare_beam()
347
348 if dqm_run_type is None:
349 dqm_run_type = run_type
350
351 if unpacker_components is None:
352 unpacker_components = constants.DEFAULT_EXPRESSRECO_COMPONENTS
353 if reco_components is None:
354 reco_components = constants.DEFAULT_EXPRESSRECO_COMPONENTS
355
356 check_components(unpacker_components)
357 check_components(reco_components)
358
359 # If turned on, only events selected by the HLT will go to ereco.
360 # this is needed as by default also un-selected events will get passed to ereco,
361 # however they are empty.
362 if select_only_accepted_events:
363 skim_module = path.add_module("TriggerSkim", triggerLines=["software_trigger_cut&all&total_result"], resultOnMissing=0)
364 skim_module.if_value("==0", basf2.Path(), basf2.AfterConditionPath.END)
365
366 # ensure that only DataStore content is present that we expect in
367 # in the ExpressReco configuration. If tracks are present in the
368 # input file, this can be a problem and lead to crashes
369 if prune_input:
370 path.add_module("PruneDataStore", matchEntries=constants.EXPRESSRECO_INPUT_OBJECTS)
371
372 path_utils.add_geometry_if_not_present(path)
373 add_unpackers(path, components=unpacker_components, writeKLMDigitRaws=True)
374
375 # dont filter/prune pxd for partly broken events, as we loose diagnostics in DQM
376 basf2.set_module_parameters(path, "PXDPostErrorChecker", CriticalErrorMask=0)
377
378 if do_reconstruction:
379 if run_type == constants.RunTypes.beam:
380 add_reconstruction(path,
381 components=reco_components,
382 pruneTracks=False,
383 skipGeometryAdding=True,
384 add_trigger_calculation=False,
385 switch_off_slow_modules_for_online=switch_off_slow_modules_for_online,
386 **kwargs)
387 elif run_type == constants.RunTypes.cosmic:
388 add_cosmics_reconstruction(path, components=reco_components, pruneTracks=False,
389 skipGeometryAdding=True, **kwargs)
390 else:
391 basf2.B2FATAL(f"Run Type {run_type} not supported.")
392
393 basf2.set_module_parameters(path, "SVDTimeGrouping", forceGroupingFromDB=False,
394 isEnabledIn6Samples=True, isEnabledIn3Samples=True)
395
396 path_utils.add_expressreco_dqm(path, dqm_run_type, components=reco_components)
397
398 if prune_output:
399 path.add_module("PruneDataStore", matchEntries=constants.ALWAYS_SAVE_OBJECTS + constants.RAWDATA_OBJECTS +
400 constants.PROCESSED_OBJECTS)
401
402
403def finalize_path(path, args, location, show_progress_bar=True):
404 """
405 Add the required output modules for expressreco/HLT
406 """
407 save_objects = constants.ALWAYS_SAVE_OBJECTS + constants.RAWDATA_OBJECTS
408 if location == constants.Location.expressreco:
409 save_objects += constants.PROCESSED_OBJECTS
410
411 if show_progress_bar:
412 path.add_module("Progress")
413
414 # Limit streaming objects for parallel processing
415 basf2.set_streamobjs(save_objects)
416
417 if args.no_output:
418 return
419
420 output_buffer_module_name = ""
421 if location == constants.Location.expressreco:
422 output_buffer_module_name = "Ds2Sample"
423 elif location == constants.Location.hlt:
424 output_buffer_module_name = "Ds2Rbuf"
425 else:
426 basf2.B2FATAL(f"Does not know location {location}")
427
428 if not args.output_file:
429 path.add_module(output_buffer_module_name, RingBufferName=args.output_buffer_name,
430 saveObjs=save_objects)
431 else:
432 if args.output_file.endswith(".sroot"):
433 path.add_module("SeqRootOutput", saveObjs=save_objects, outputFileName=args.output_file)
434 else:
435 # We are storing everything on purpose!
436 path.add_module("RootOutput", outputFileName=args.output_file)
437
438
439def finalize_zmq_path(path, args, location):
440 """
441 Add the required output modules for expressreco/HLT
442 """
443 save_objects = constants.ALWAYS_SAVE_OBJECTS + constants.RAWDATA_OBJECTS
444 if location == constants.Location.expressreco:
445 save_objects += constants.PROCESSED_OBJECTS
446
447 # Limit streaming objects for parallel processing
448 basf2.set_streamobjs(save_objects)
449
450 if not args.output_file:
451 if location == constants.Location.expressreco:
452 path.add_module("HLTDs2ZMQ", output=args.output, raw=False, outputConfirmation=False)
453 elif location == constants.Location.hlt:
454 path.add_module("HLTDs2ZMQ", output=args.output, raw=True, outputConfirmation=True)
455 else:
456 basf2.B2FATAL(f"Does not know location {location}")
457 else:
458 if args.output_file.endswith(".sroot"):
459 path.add_module("SeqRootOutput", saveObjs=save_objects, outputFileName=args.output_file)
460 else:
461 # We are storing everything on purpose!
462 path.add_module("RootOutput", outputFileName=args.output_file)