-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathrun_analysis.py
More file actions
802 lines (686 loc) · 30.1 KB
/
Copy pathrun_analysis.py
File metadata and controls
802 lines (686 loc) · 30.1 KB
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
'''
Run analysis in one of the different styles.
'''
import os
import sys
import time
import logging
import importlib.util
import string
from inspect import signature
import ROOT # type: ignore
import cppyy
from anascript import get_element, get_element_dict, get_attribute
from sample import get_process_info, get_process_dict
from sample import get_subfile_list, get_chunk_list
from utils import generate_graph, save_benchmark
from run_fccanalysis import run_fccanalysis
ROOT.gROOT.SetBatch(True)
LOGGER = logging.getLogger('FCCAnalyses.run')
# _____________________________________________________________________________
def initialize(args, rdf_module, anapath: str):
'''
Common initialization steps.
'''
# Put runBatch deprecation warning
if hasattr(rdf_module, 'runBatch'):
if rdf_module.runBatch:
LOGGER.error('runBatch script attribute is no longer supported, '
'use "fccanalysis submit" instead!\nAborting...')
sys.exit(3)
# for convenience and compatibility with user code
if args.use_data_source:
ROOT.gInterpreter.Declare("using namespace FCCAnalyses::PodioSource;")
else:
ROOT.gInterpreter.Declare("using namespace FCCAnalyses;")
geometry_file = get_element(rdf_module, "geometryFile")
readout_name = get_element(rdf_module, "readoutName")
if geometry_file != "" and readout_name != "":
ROOT.CaloNtupleizer.loadGeometry(geometry_file, readout_name)
# set multithreading (no MT if number of events is specified)
ncpus = 1
if args.nevents is None:
if isinstance(args.ncpus, int) and args.ncpus >= 1:
ncpus = args.ncpus
else:
ncpus = get_element(rdf_module, "nCPUS")
if ncpus < 0: # use all available threads
ROOT.EnableImplicitMT()
ncpus = ROOT.GetThreadPoolSize()
ROOT.ROOT.EnableImplicitMT(ncpus)
ROOT.EnableThreadSafety()
if ROOT.IsImplicitMTEnabled():
LOGGER.info('Multithreading enabled. Running over %i threads',
ROOT.GetThreadPoolSize())
else:
LOGGER.info('No multithreading enabled. Running in single thread...')
# custom header files
include_paths = get_attribute(rdf_module, "includePaths", [])
if include_paths:
basepath = os.path.dirname(os.path.abspath(anapath)) + "/"
# Check if the include paths exist
for path in include_paths:
if not os.path.isfile(os.path.join(basepath, path)):
LOGGER.error('Include header file "%s" not found!'
'\nAborting...', path)
sys.exit(3)
ROOT.gInterpreter.ProcessLine(".O2")
for path in include_paths:
LOGGER.info('Loading %s...', path)
success = ROOT.gInterpreter.Declare(
f'#include "{os.path.join(basepath, path)}"'
)
if not success:
LOGGER.error('Error occurred when JIT compiling "%s" include '
'header file!\nAborting...', path)
sys.exit(3)
# check if analyses plugins need to be loaded before anything
# still in use?
analyses_list = get_element(rdf_module, "analysesList")
if analyses_list and len(analyses_list) > 0:
LOGGER.warning('[DEPRECATED] Ability to load additional pre-compiled '
'analysis libraries will disappear soon!')
_ana = []
for ana_lib in analyses_list:
LOGGER.info('Loading analysis library "%s"...', ana_lib)
if ana_lib.startswith('libFCCAnalysis_'):
ROOT.gSystem.Load(ana_lib)
else:
ROOT.gSystem.Load(f'libFCCAnalysis_{ana_lib}')
if not hasattr(ROOT, ana_lib):
ROOT.error('Analysis %s not properly loaded!\nAborting...',
ana_lib)
sys.exit(3)
_ana.append(getattr(ROOT, ana_lib).dictionary)
# _____________________________________________________________________________
def run_rdf(rdf_module,
input_list: list[str],
outfile_path: str,
args) -> tuple[int, int]:
'''
Create RDataFrame and snapshot it.
'''
dframe = ROOT.RDataFrame("events", input_list)
if args.progress_bar:
ROOT.RDF.Experimental.AddProgressBar(dframe)
# limit number of events processed
if args.nevents is not None:
dframe2 = dframe.Range(0, args.nevents)
else:
dframe2 = dframe
try:
evtcount_init = dframe2.Count()
dframe3 = get_element(rdf_module.RDFanalysis, "analysers")(dframe2)
branch_list = ROOT.vector('string')()
blist = get_element(rdf_module.RDFanalysis, "output")()
for bname in blist:
branch_list.push_back(bname)
# Registering Count before Snapshot to avoid additional event loops
evtcount_final = dframe3.Count()
# Generate computational graph of the analysis
if args.graph:
graph_path = args.graph_path
if graph_path is None:
graph_path = os.path.join(os.getcwd(), 'fccanalysis_graph.dot')
generate_graph(dframe, graph_path)
dframe3.Snapshot("events", outfile_path, branch_list)
except cppyy.gbl.std.runtime_error as err:
LOGGER.error('%s\nDuring the execution of the analysis script an '
'exception occurred!\nAborting...', err)
sys.exit(3)
return evtcount_init.GetValue(), evtcount_final.GetValue()
# _____________________________________________________________________________
def apply_filepath_rewrites(filepath: str) -> str:
'''
Apply path rewrites if applicable.
'''
# Stripping leading and trailing white spaces
filepath_stripped = filepath.strip()
# Stripping leading and trailing slashes
filepath_stripped = filepath_stripped.strip('/')
# Splitting the path along slashes
filepath_splitted = filepath_stripped.split('/')
if len(filepath_splitted) > 1 and filepath_splitted[0] == 'eos':
if filepath_splitted[1] == 'experiment':
filepath = 'root://eospublic.cern.ch//' + filepath_stripped
elif filepath_splitted[1] == 'user':
filepath = 'root://eosuser.cern.ch//' + filepath_stripped
elif 'home-' in filepath_splitted[1]:
filepath = 'root://eosuser.cern.ch//eos/user/' + \
filepath_stripped.replace('eos/home-', '')
else:
LOGGER.warning('Unknown EOS path type!\nPlease check with the '
'developers as this might impact performance of '
'the analysis.')
return filepath
# _____________________________________________________________________________
def run_local(rdf_module, infile_list, args):
'''
Run analysis locally.
'''
# Create list of files to be processed
info_msg = f'Creating dataframe from {len(infile_list)} files:\n'
file_list = ROOT.vector('string')()
# Amount of events processed in previous stage (= 0 if it is the first
# stage)
nevents_orig = 0
# The amount of events in the input file(s)
nevents_local = 0
for filepath in infile_list:
filepath = apply_filepath_rewrites(filepath)
file_list.push_back(filepath)
info_msg += f'\t- {filepath}\n'
try:
infile = ROOT.TFile.Open(filepath, 'READ')
except OSError as excp:
LOGGER.error('While opening input file:\n%s\nan error '
'occurred:\n%s\nAborting...', filepath, excp)
sys.exit(3)
try:
nevents_orig += infile.Get('eventsProcessed').GetVal()
except AttributeError:
pass
try:
nevents_local += infile.Get("events").GetEntries()
except AttributeError:
LOGGER.error('Input file:\n%s\nis missing events TTree!\n'
'Aborting...', filepath)
infile.Close()
sys.exit(3)
infile.Close()
LOGGER.info(info_msg)
# Adjust number of events in case --nevents was specified
if args.nevents is not None and args.nevents < nevents_local:
nevents_local = args.nevents
if nevents_orig > 0:
LOGGER.info('Number of events:\n\t- original: %s\n\t- local: %s',
f'{nevents_orig:,}', f'{nevents_local:,}')
else:
LOGGER.info('Number of local events: %s', f'{nevents_local:,}')
outfile_path = args.output
LOGGER.info('Output file path:\n%s', outfile_path)
# Run RDF
start_time = time.time()
inn, outn = run_rdf(rdf_module, file_list, outfile_path, args)
elapsed_time = time.time() - start_time
# replace nevents_local by inn = the amount of processed events
info_msg = f"{' SUMMARY ':=^80}\n"
info_msg += 'Elapsed time (H:M:S): '
info_msg += time.strftime('%H:%M:%S', time.gmtime(elapsed_time))
info_msg += '\nEvents processed/second: '
info_msg += f'{int(inn/elapsed_time):,}'
info_msg += f'\nTotal events processed: {int(inn):,}'
info_msg += f'\nNo. result events: {int(outn):,}'
if inn > 0:
info_msg += f'\nReduction factor local: {outn/inn}'
if nevents_orig > 0:
info_msg += f'\nReduction factor total: {outn/nevents_orig}'
info_msg += '\n'
info_msg += 80 * '='
info_msg += '\n'
LOGGER.info(info_msg)
# Update resulting root file with number of processed events
# and number of selected events
with ROOT.TFile(outfile_path, 'update') as outfile:
param = ROOT.TParameter(int)(
'eventsProcessed',
nevents_orig if nevents_orig != 0 else inn)
param.Write()
param = ROOT.TParameter(int)('eventsSelected', outn)
param.Write()
outfile.Write()
if args.bench:
analysis_name = get_element(rdf_module, 'analysisName')
if not analysis_name:
analysis_name = args.anascript_path
bench_time = {}
bench_time['name'] = 'Time spent running the analysis: '
bench_time['name'] += analysis_name
bench_time['unit'] = 'Seconds'
bench_time['value'] = elapsed_time
bench_time['range'] = 10
bench_time['extra'] = 'Analysis path: ' + args.anascript_path
save_benchmark('benchmarks_smaller_better.json', bench_time)
bench_evt_per_sec = {}
bench_evt_per_sec['name'] = 'Events processed per second: '
bench_evt_per_sec['name'] += analysis_name
bench_evt_per_sec['unit'] = 'Evt/s'
bench_evt_per_sec['value'] = nevents_local / elapsed_time
bench_time['range'] = 1000
bench_time['extra'] = 'Analysis path: ' + args.anascript_path
save_benchmark('benchmarks_bigger_better.json', bench_evt_per_sec)
# _____________________________________________________________________________
def run_stages(args, rdf_module, anapath):
'''
Run regular stage.
'''
# Set ncpus, load header files, custom dicts, ...
initialize(args, rdf_module, anapath)
# Check if outputDir exist and if not create it
output_dir = get_element(rdf_module, "outputDir")
if not os.path.exists(output_dir) and output_dir:
os.system(f'mkdir -p {output_dir}')
# Check if EOS outputDir exist and if not create it
output_dir_eos = get_element(rdf_module, "outputDirEos")
if not os.path.exists(output_dir_eos) and output_dir_eos:
os.system(f'mkdir -p {output_dir_eos}')
# Check if test mode is specified, and if so run the analysis on it (this
# will exit after)
if args.test:
LOGGER.info('Running over test file...')
testfile_path = get_element(rdf_module, "testFile")
directory, _ = os.path.split(args.output)
if directory:
os.system(f'mkdir -p {directory}')
run_local(rdf_module, [testfile_path], args)
sys.exit(0)
# Check if files are specified, and if so run the analysis on it/them (this
# will exit after)
if len(args.files_list) > 0:
LOGGER.info('Running over files provided in command line argument...')
directory, _ = os.path.split(args.output)
if directory:
os.system(f'mkdir -p {directory}')
run_local(rdf_module, args.files_list, args)
sys.exit(0)
# Check if the process list is specified
process_list = get_element(rdf_module, 'processList')
for process_name in process_list:
try:
process_input_dir = process_list[process_name]['inputDir']
except KeyError:
process_input_dir = None
file_list, event_list = get_process_info(
process_name,
get_element(rdf_module, "prodTag"),
get_element(rdf_module, "inputDir"),
process_input_dir)
if len(file_list) <= 0:
LOGGER.error('No files to process!\nAborting...')
sys.exit(3)
# Determine the fraction of the input to be processed
fraction = 1.
if get_element_dict(process_list[process_name], 'fraction'):
fraction = get_element_dict(process_list[process_name], 'fraction')
if fraction < 1:
file_list = get_subfile_list(file_list, event_list, fraction)
# Determine the number of chunks the output will be split into
chunks = 1
if get_element_dict(process_list[process_name], 'chunks'):
chunks = get_element_dict(process_list[process_name], 'chunks')
chunk_list = [file_list]
if chunks > 1:
chunk_list = get_chunk_list(file_list, chunks)
LOGGER.info('Number of the output files: %s', f'{len(chunk_list):,}')
# Put together output path
output_stem = process_name
if get_element_dict(process_list[process_name], 'output'):
output_stem = get_element_dict(process_list[process_name],
'output')
output_dir = get_attribute(rdf_module, 'outputDir', '')
if len(chunk_list) == 1:
output_filepath = os.path.join(output_dir, output_stem+'.root')
output_dir = None
else:
output_filepath = None
output_dir = os.path.join(output_dir, output_stem)
info_msg = f'Will run over process "{process_name}" with:'
if fraction < 1:
info_msg += f'\n - fraction: {fraction}'
info_msg += f'\n - number of input files: {len(file_list):,}'
if output_dir:
info_msg += f'\n - output directory: {output_dir}'
if output_filepath:
info_msg += f'\n - output file path: {output_filepath}'
if len(chunk_list) > 1:
info_msg += f'\n - number of output chunks: {chunks}'
LOGGER.info(info_msg)
# Running locally
LOGGER.info('Running locally...')
if len(chunk_list) == 1:
args.output = output_filepath
run_local(rdf_module, chunk_list[0], args)
else:
# Create directory if more than 1 chunk
if not os.path.exists(output_dir):
os.system(f'mkdir -p {output_dir}')
for index, chunk in enumerate(chunk_list):
args.output = os.path.join(output_dir, f'chunk{index}.root')
run_local(rdf_module, chunk, args)
def run_histmaker(args, rdf_module, anapath):
'''
Run the analysis using histmaker (all stages integrated into one).
'''
# Check whether to use PODIO ROOT DataSource to load the events
if get_element(rdf_module, "useDataSource", False):
args.use_data_source = True
# set ncpus, load header files, custom dicts, ...
initialize(args, rdf_module, anapath)
# Determining Key4hep stack and OS
if 'KEY4HEP_STACK' not in os.environ:
LOGGER.error('Key4hep stack not setup!\nAborting...')
sys.exit(3)
k4h_stack_env = os.environ['KEY4HEP_STACK']
if 'sw-nightlies.hsf.org' in k4h_stack_env:
key4hep_stack = 'nightlies'
elif 'sw.hsf.org' in k4h_stack_env:
key4hep_stack = 'release'
else:
LOGGER.error('Key4hep stack not recognized!\nAborting...')
sys.exit(3)
if 'almalinux9' in k4h_stack_env:
key4hep_os = 'alma9'
elif 'ubuntu22' in k4h_stack_env:
key4hep_os = 'ubuntu22'
elif 'ubuntu24' in k4h_stack_env:
key4hep_os = 'ubuntu24'
else:
LOGGER.error('Key4hep OS not recognized!\nAborting...')
sys.exit(3)
# load process dictionary
proc_dict_location = get_element(rdf_module, "procDict", True)
if not proc_dict_location:
LOGGER.error('Location of the procDict not provided.\nAborting...')
sys.exit(3)
proc_dict = get_process_dict(proc_dict_location)
# check if outputDir exist and if not create it
output_dir = get_element(rdf_module, "outputDir")
if not os.path.exists(output_dir) and output_dir != '':
os.system(f'mkdir -p {output_dir}')
do_scale = get_element(rdf_module, "doScale", True)
int_lumi = get_element(rdf_module, "intLumi", True)
# check if the process list is specified, and create graphs for them
process_list = get_element(rdf_module, "processList")
graph_function = getattr(rdf_module, "build_graph")
results = [] # all the histograms
hweights = [] # all the weights
evtcounts = [] # event count of the input file
# number of events processed per process, in a potential previous step
events_processed_dict = {}
for process_name, process_dict in process_list.items():
try:
process_input_dir = process_list[process_name]['inputDir']
except KeyError:
process_input_dir = None
if args.test:
try:
if get_element_dict(process_dict, 'testfile') is not None:
testfile_path = get_element_dict(process_dict, 'testfile')
if isinstance(testfile_path, string.Template):
testfile_path = testfile_path.substitute(
key4hep_os=key4hep_os,
key4hep_stack=key4hep_stack
)
file_list = [testfile_path]
except TypeError:
LOGGER.warning('No test file for process %s found!\n'
'Aborting...')
sys.exit(3)
fraction = 1
output = process_name
chunks = 1
else:
file_list, event_list = get_process_info(
process_name,
get_element(rdf_module, "prodTag"),
get_element(rdf_module, "inputDir"),
process_input_dir)
if len(file_list) == 0:
LOGGER.error('No files to process!\nAborting...')
sys.exit(3)
fraction = 1
output = process_name
chunks = 1
try:
if get_element_dict(process_dict, 'fraction') is not None:
fraction = get_element_dict(process_dict, 'fraction')
if get_element_dict(process_dict, 'output') is not None:
output = get_element_dict(process_dict, 'output')
if get_element_dict(process_dict, 'chunks') is not None:
chunks = get_element_dict(process_dict, 'chunks')
except TypeError:
LOGGER.warning('No values set for process %s will use default '
'values!', process_name)
if fraction < 1:
file_list = get_subfile_list(file_list, event_list, fraction)
# get the number of events processed, in a potential previous step
file_list_root = ROOT.vector('string')()
# amount of events processed in previous stage (= 0 if it is the first
# stage)
nevents_meta = 0
for file_name in file_list:
if not args.use_data_source:
file_name = apply_filepath_rewrites(file_name)
file_list_root.push_back(file_name)
# Skip check for processed events in case of first stage
if get_element(rdf_module, "prodTag") is None:
infile = ROOT.TFile.Open(str(file_name), 'READ')
# Fetch parameter directly to bypass PyROOT dynamic lookup
events_param = infile.Get("eventsProcessed")
if events_param:
nevents_meta += events_param.GetVal()
else:
LOGGER.debug('Missing "eventsProcessed" in %s! Cross-section scaling may fall back to filtered event count.', file_name)
infile.Close()
if args.test:
break
events_processed_dict[process_name] = nevents_meta
info_msg = f'Add process "{process_name}" with:'
info_msg += f'\n\tfraction = {fraction}'
info_msg += f'\n\tnFiles = {len(file_list_root):,}'
info_msg += f'\n\toutput = {output}\n\tchunks = {chunks}'
LOGGER.info(info_msg)
if args.use_data_source:
if ROOT.podio.DataSource:
LOGGER.debug('Found Podio ROOT DataSource.')
else:
LOGGER.error('Podio ROOT DataSource library not found!'
'\nAborting...')
sys.exit(3)
LOGGER.info('Loading events through podio::DataSource...')
try:
dframe = ROOT.podio.CreateDataFrame(file_list_root)
except TypeError as excp:
LOGGER.error('Unable to build dataframe using '
'podio::DataSource!\n%s', excp)
sys.exit(3)
else:
dframe = ROOT.ROOT.RDataFrame("events", file_list_root)
evtcount = dframe.Count()
if args.progress_bar:
ROOT.RDF.Experimental.AddProgressBar(dframe)
try:
n_params = len(signature(graph_function).parameters)
if n_params == 2:
res, hweight = graph_function(dframe, process_name)
else:
res, hweight = graph_function(dframe, process_name, args)
except cppyy.gbl.std.runtime_error as err:
LOGGER.error(err)
LOGGER.error('During loading of the analysis an error occurred!'
'\nAborting...')
sys.exit(3)
results.append(res)
hweights.append(hweight)
evtcounts.append(evtcount)
# Generate computational graph of the analysis
if args.graph:
graph_path = args.graph_path
if graph_path is None:
graph_path = os.path.join(os.getcwd(), 'fccanalysis_graph.dot')
generate_graph(dframe, graph_path)
LOGGER.info('Starting the event loop...')
start_time = time.time()
ROOT.ROOT.RDF.RunGraphs(evtcounts)
LOGGER.info('Event loop done!')
elapsed_time = time.time() - start_time
LOGGER.info('Writing out output files...')
nevents_tot = 0
for process, res, hweight, evtcount in zip(process_list,
results,
hweights,
evtcounts):
# get the cross-sections etc. First try locally, then the procDict
if 'crossSection' in process_list[process]:
cross_section = process_list[process]['crossSection']
elif process in proc_dict and 'crossSection' in proc_dict[process]:
cross_section = proc_dict[process]['crossSection']
else:
LOGGER.warning('Can\'t find cross-section for process %s in '
'processList or procDict!\nUsing default value '
'of 1', process)
cross_section = 1
if 'kfactor' in process_list[process]:
kfactor = process_list[process]['kfactor']
elif process in proc_dict and 'kfactor' in proc_dict[process]:
kfactor = proc_dict[process]['kfactor']
else:
kfactor = 1
if 'matchingEfficiency' in process_list[process]:
matching_efficiency = process_list[process]['matchingEfficiency']
elif process in proc_dict \
and 'matchingEfficiency' in proc_dict[process]:
matching_efficiency = proc_dict[process]['matchingEfficiency']
else:
matching_efficiency = 1
events_processed = events_processed_dict[process] \
if events_processed_dict[process] != 0 else evtcount.GetValue()
scale = cross_section*kfactor*matching_efficiency/events_processed
nevents_tot += evtcount.GetValue()
hists_to_write = {}
for r in res:
hist = r.GetValue()
hname = hist.GetName()
# merge histograms in case histogram exists
if hist.GetName() in hists_to_write:
hists_to_write[hname].Add(hist)
else:
hists_to_write[hname] = hist
LOGGER.info('Writing out process %s, nEvents processed %s',
process, f'{evtcount.GetValue():,}')
with ROOT.TFile(os.path.join(output_dir, f'{process}.root'),
'RECREATE'):
for hist in hists_to_write.values():
if do_scale:
hist.Scale(scale * int_lumi)
hist.Write()
# write all meta info to the output file
param = ROOT.TParameter(int)("eventsProcessed", events_processed)
param.Write()
param = ROOT.TParameter(float)("sumOfWeights", hweight.GetValue())
param.Write()
param = ROOT.TParameter(float)("intLumi", int_lumi)
param.Write()
param = ROOT.TParameter(float)("crossSection", cross_section)
param.Write()
param = ROOT.TParameter(float)("kfactor", kfactor)
param.Write()
param = ROOT.TParameter(float)("matchingEfficiency",
matching_efficiency)
param.Write()
info_msg = f"{' SUMMARY ':=^80}\n"
info_msg += 'Elapsed time (H:M:S): '
info_msg += time.strftime('%H:%M:%S', time.gmtime(elapsed_time))
info_msg += '\nEvents processed/second: '
info_msg += f'{int(nevents_tot/elapsed_time):,}'
info_msg += f'\nTotal events processed: {nevents_tot:,}'
info_msg += '\n'
info_msg += 80 * '='
info_msg += '\n'
LOGGER.info(info_msg)
def run(parser):
'''
Set things in motion.
'''
try:
dash_dash_index = sys.argv.index('--')
args = parser.parse_args(sys.argv[1:dash_dash_index])
args.remaining = sys.argv[dash_dash_index+1:]
except ValueError:
args = parser.parse_args()
args.remaining = []
if not hasattr(args, 'command'):
LOGGER.error('Error occurred during sub-command routing!\nAborting...')
sys.exit(3)
if args.command != 'run':
LOGGER.error('Unknown sub-command "%s"!\nAborting...')
sys.exit(3)
# Work with absolute path of the analysis script
anapath = os.path.abspath(args.anascript_path)
# Check that the analysis file exists
if not os.path.isfile(anapath):
LOGGER.error('Analysis script %s not found!\nAborting...',
anapath)
sys.exit(3)
# Set verbosity level of the RDataFrame
if args.verbose:
# ROOT.ROOT.ELogLevel.kInfo verbosity level is more
# equivalent to DEBUG in other log systems
verbosity = ROOT.RLogScopedVerbosity(
ROOT.Detail.RDF.RDFLogChannel(),
ROOT.ROOT.ELogLevel.kInfo)
if verbosity:
LOGGER.debug('Setting verbosity level "kInfo" for RDataFrame...')
if args.more_verbose:
verbosity = ROOT.RLogScopedVerbosity(
ROOT.Detail.RDF.RDFLogChannel(),
ROOT.ROOT.ELogLevel.kDebug)
if verbosity:
LOGGER.debug('Setting verbosity level "kDebug" for RDataFrame...')
if args.most_verbose:
verbosity = ROOT.RLogScopedVerbosity(
ROOT.Detail.RDF.RDFLogChannel(),
ROOT.ROOT.ELogLevel.kDebug+10)
if verbosity:
LOGGER.debug('Setting verbosity level "kDebug+10" for '
'RDataFrame...')
# Load the pre-compiled analyzers
LOGGER.info('Loading analyzers from libFCCAnalyses...')
ROOT.gSystem.Load("libFCCAnalyses")
# Is this still needed?? 01/04/2022 still to be the case
fcc_loaded = ROOT.dummyLoader()
if fcc_loaded:
LOGGER.debug('Succesfuly loaded main FCCanalyses analyzers.')
# Load the analysis script as a module
LOGGER.info('Loading analysis script:\n%s', anapath)
try:
rdf_spec = importlib.util.spec_from_file_location('rdfanalysis',
anapath)
rdf_module = importlib.util.module_from_spec(rdf_spec)
rdf_spec.loader.exec_module(rdf_module)
except SyntaxError as err:
LOGGER.error('Syntax error encountered in the analysis script:\n%s',
err)
sys.exit(3)
# Decide which style of analysis to run
n_ana_styles = 0
for analysis_style in ["build_graph", "RDFanalysis", "Analysis"]:
if hasattr(rdf_module, analysis_style):
LOGGER.debug("Analysis style found: %s", analysis_style)
n_ana_styles += 1
if n_ana_styles == 0:
LOGGER.error('Analysis file does not contain required objects!\n'
'Provide either RDFanalysis class, Analysis class, or '
'build_graph function.')
sys.exit(3)
if n_ana_styles > 1:
LOGGER.error('Analysis file ambiguous!\n'
'Multiple analysis styles used!\n'
'Provide only one out of "RDFanalysis", "Analysis", '
'or "build_graph".')
sys.exit(3)
if hasattr(rdf_module, "Analysis"):
run_fccanalysis(args, rdf_module)
# Adjustments for the old approaches
if args.progress_bar is None:
args.progress_bar = True
if args.files_list is None:
args.files_list = []
if get_element(rdf_module, 'graph', False):
args.graph = True
if get_element(rdf_module, 'graphPath') != '':
args.graph_path = get_element(rdf_module, 'graphPath')
if hasattr(rdf_module, "RDFanalysis"):
run_stages(args, rdf_module, anapath)
if hasattr(rdf_module, "build_graph"):
run_histmaker(args, rdf_module, anapath)