Belle II Software  release-06-02-00
background.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 
11 
12 from basf2 import create_path, B2ERROR, B2INFO
13 from basf2.utils import pretty_print_table
14 import os
15 import glob
16 
17 
18 def get_background_files(folder=None, output_file_info=True):
19  """ Loads the location of the background files from the environmant variable
20  BELLE2_BACKGROUND_DIR which is set on the validation server and ensures that background
21  files exist and returns the list of background files which
22  can be directly used with add_simulation() :
23 
24  >>> add_simulation(main, bkgfiles=background.get_background_files())
25 
26  Will fail with an assert if no background folder set or if no background file was
27  found in the set folder.
28 
29  Parameters:
30  folder (str): A specific folder to search for background files can be given as an optional parameter
31  output_file_info (str): If true, a list of the found background files and there size will be printed
32  This is useful to understand later which background campaign has been used
33  to simulate events.
34  """
35 
36  env_name = 'BELLE2_BACKGROUND_DIR'
37  bg = None
38 
39  if folder is None:
40  if env_name not in os.environ:
41  raise RuntimeError("Environment variable {} for backgound files not set. Terminanting this script.".format(env_name))
42  folder = os.environ[env_name]
43 
44  bg = glob.glob(folder + '/*.root')
45 
46  if len(bg) == 0:
47  raise RuntimeError("No background files found in folder {} . Terminating this script.".format(folder))
48 
49  B2INFO("Background files loaded from folder {}".format(folder))
50 
51  # sort for easier comparison
52  bg = sorted(bg)
53 
54  if output_file_info:
55  bg_sizes = [os.path.getsize(f) for f in bg]
56  # reformat to work with pretty_print_table
57  table_rows = [list(entry) for entry in zip(bg, bg_sizes)]
58  table_rows.insert(0, ["- Background file name -", "- file size -"])
59 
60  pretty_print_table(table_rows, [0, 0])
61 
62  return bg
63 
64 
65 def add_output(path, bgType, realTime, sampleType, phase=3, fileName='output.root', excludeBranches=None):
66  '''
67  A function to be used for output of BG simulation.
68  @param path path name
69  @param bgType background type, to get available types: basf2 -m BeamBkgTagSetter
70  @param realTime equivalent time of superKEKB running in [ns]
71  @param sampleType 'study' (for BG studies) or 'usual', 'PXD', 'ECL' (for BG mixer)
72  @param specify the Phase, 1 for Phase 1, 2 for Phase 2, and 3 for Physics Run or Phase 3
73  @param fileName optional file name, can be overridden by basf2 -o
74  '''
75  if excludeBranches is None:
76  excludeBranches = []
77 
78  if sampleType == 'study':
79  madeFor = ''
80  branches = []
81  elif sampleType == 'usual' and phase == 3:
82  madeFor = ''
83  branches = [
84  'PXDSimHits',
85  'SVDSimHits',
86  'CDCSimHits',
87  'TOPSimHits',
88  'ARICHSimHits',
89  'ECLHits',
90  'BKLMSimHits',
91  'EKLMSimHits',
92  ]
93  elif sampleType == 'usual' and phase == 2:
94  madeFor = ''
95  branches = [
96  'PXDSimHits',
97  'SVDSimHits',
98  'CDCSimHits',
99  'TOPSimHits',
100  'ARICHSimHits',
101  'ECLHits',
102  'BKLMSimHits',
103  'EKLMSimHits',
104  'CLAWSSimHits',
105  'FANGSSimHits',
106  'PlumeSimHits',
107  'BeamabortSimHits',
108  'PindiodeSimHits',
109  'QcsmonitorSimHits',
110  'He3tubeSimHits',
111  'MicrotpcSimHits',
112  ]
113  elif sampleType == 'usual' and phase == 1:
114  madeFor = ''
115  branches = [
116  'ClawSimHits',
117  'BeamabortSimHits',
118  'PindiodeSimHits',
119  'QcsmonitorSimHits',
120  'He3tubeSimHits',
121  'MicrotpcSimHits',
122  'BgoSimHits',
123  'CsiSimHits',
124  ]
125  elif sampleType == 'ECL':
126  madeFor = 'ECL'
127  branches = ['ECLHits']
128  elif sampleType == 'PXD':
129  madeFor = 'PXD'
130  branches = ['PXDSimHits']
131  else:
132  madeFor = ''
133  branches = []
134  B2ERROR('add_output - invalid value of argument sampleType: %s'
135  % sampleType)
136 
137  # Set background tag in SimHits and add BackgroundMetaData into persistent tree
138  tagSetter = path.add_module('BeamBkgTagSetter', backgroundType=bgType, realTime=realTime,
139  specialFor=madeFor, Phase=phase)
140 
141  # Write out only non-empty events when producing samples for BG mixer
142  if sampleType != 'study':
143  emptyPath = create_path()
144  tagSetter.if_false(emptyPath)
145 
146  # Output to file. We don't need a TTreeIndex for background files and memory
147  # consumption can be improved by setting a lower autoFlushSize so that
148  # fewer and or smaller amounts of data have to be read for each GetEntry()
149  path.add_module('RootOutput', outputFileName=fileName, branchNames=branches, excludeBranchNames=excludeBranches,
150  buildIndex=False, autoFlushSize=-500000)