ATLAS Offline Software
dqBeamSpot.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
4 
5 
6 
7 """
8 Calculate beamspot DQ defects automatically from result of beamspot fit and
9 produce locally sqlite file that can later be merged into HEAD. Also dump
10 results to txt file for linking to web page
11 
12 """
13 __author__ = 'Carl Gwilliam'
14 __version__ = '$Id $'
15 __usage__ = '%prog [options] nt.root [nt.root ...]'
16 
17 import sys,os
18 from math import *
20 
21 # Argument parsing
22 from optparse import OptionParser
23 parser = OptionParser(usage=__usage__, version=__version__)
24 parser.add_option('-b', '--batch', dest='batch', action='store_true', default=False, help='run in batch mode')
25 parser.add_option('-i', '--interactive', dest='interactive', action='store_true', default=False, help='interactive')
26 parser.add_option('-e', '--extend', dest='extend', action='store_true', default=False, help='extend existing SQLite file (default: delete any existing file)')
27 parser.add_option('', '--noaverage', dest='noaverage', action='store_true', default=False, help='do not write per-run average beam spot with large width')
28 parser.add_option('', '--statlist', dest='statlist', default='59', help='comma separated list of status word values to accept (must have known fitId)')
29 parser.add_option('', '--lbmin', dest='lbmin', type='int', default=None, help='Minimum LB to consider')
30 parser.add_option('', '--lbmax', dest='lbmax', type='int', default=None, help='Maximum LB to consider')
31 parser.add_option('-o', '--output', dest='output', default='dqflags.db', help='name of output COOL SQLite file for DQ (default: dqflags.db')
32 parser.add_option('-t', '--tag', dest='tag', default='nominal', help='COOL tag (default: nominal)')
33 parser.add_option('-a', '--absent', dest='absent', action='store_true', default=False, help='Write absent (as well as present) defects to the DB (default: False)')
34 
35 (options,args) = parser.parse_args()
36 if len(args) < 1:
37  parser.error('wrong number of command line arguments')
38 
39 
40 # Setup ROOT
41 if options.batch:
42  os.unsetenv('DISPLAY')
43 import ROOT
44 from InDetBeamSpotExample import ROOTUtils
45 #ROOTUtils.setStyle()
46 
47 from InDetBeamSpotExample.Utils import getRunFromName
48 
49 # Prepare list of algorithms to consider
50 statList = []
51 fitIdList = []
52 for a in options.statlist.split(','):
53  statList.append(int(a))
54  try:
55  fitIDInt = int( format( int(a), '08b')[:4], 2)
56  fitIdList.append( fitIDInt )
57  except:
58  print ('ERROR: Status word value of %i has no known fitId entry' % int(a))
59  sys.exit(1)
60 
61 # First loop over all input files to determine if an everage is available
62 # (i.e. nEntires with correct fit status > 0)
63 
64 # Set initial min and max run numbers from file names
65 #try:
66 runs = [int(getRunFromName(f)) for f in args]
67 minRun = min(runs)
68 maxRun = max(runs)
69 #except:
70 # minRun = 1E10
71 # maxRun = -1
72 nEntries = 0
73 
74 print ('\nDetermining if average beamspot parameters available')
75 for filename in args:
76  print ('\nExtracting from file ',filename,':')
77 
78  f = ROOT.TFile(filename)
79  if f.Get('BeamSpotNt'):
80  bsNt = BeamSpotNt(filename)
81  elif f.Get('Beamspot/Beamspots'):
82  bsNt = BeamSpotFinderNt(filename)
83 
84  for bs in bsNt.allData():
85 
86  # Skip fits outside of desired LB range
87  if options.lbmin and options.lbmin>bs.lbStart:
88  continue
89  if options.lbmax and options.lbmax<bs.lbEnd+1:
90  continue
91  if not bs.status in statList:
92  continue
93  #Convert status word to ints for fitStatus and fitID
94  fitStatusInt = int( format( bs.status, '08b')[-2:], 2)
95  fitIDInt = int( format( bs.status, '08b')[:4], 2)
96 
97  print ('[%i, %3i - %3i]: %5i vertices, fitStatus = %i, fitID = %i' % (bs.run,bs.lbStart,bs.lbEnd+1,bs.nEvents,fitStatusInt,fitIDInt))
98 
99  minRun = min(bs.run,minRun)
100  maxRun = max(bs.run,maxRun)
101 
102  # Skip undesired fits
103  if fitStatusInt!=3:
104  print ('*** Skipping unsuccessful fit ...\n')
105  continue
106  if not fitIDInt in fitIdList:
107  print ('*** Skipping fit with ID =',fitIDInt,'\n')
108  continue
109 
110  nEntries += 1
111  print()
112 
113  f.Close()
114 
115 # Set DQ defect to 'ID_BS_NOBEAMSPOT' if there is no average beamspot or 'ID_BS_RUNAVERAGE' if
116 # there is (i.e. at least one succesfull fit and not options.noaverage)
117 
118 from InDetBeamSpotExample.DQUtilities import IDBSDefectWriter
119 idbsDefects = IDBSDefectWriter(options.output, not options.extend)
120 
121 if nEntries>0 and not options.noaverage:
122  print ('\nInitially Setting DQ defect to ID_BS_RUNAVERAGE for runs %s ... %s with average beamspot available' %(minRun, maxRun))
123  idbsDefects.defectType('ID_BS_RUNAVERAGE')
124 else:
125  print ('\nInitially setting DQ defect to ID_BS_NOBEAMSPOT for runs %s ... %s without average beamspot available' % (minRun, maxRun))
126  idbsDefects.defectType('ID_BS_NOBEAMSPOT')
127 
128 # for protection against multiple rows with same LB range
129 good_lbs={}
130 if minRun==maxRun:
131  good_lbs[minRun]={}
132 else:
133  for i in range(minRun,maxRun):
134  good_lbs[i]={}
135 # Loop over ntuple and set LBs for which beamspot is correctly determined (i.e. no defects)
136 for filename in args:
137  print ('Copying beam spot data from',filename)
138  f = ROOT.TFile(filename)
139  if f.Get('BeamSpotNt'):
140  bsNt = BeamSpotNt(filename)
141  elif f.Get('Beamspot/Beamspots'):
142  bsNt = BeamSpotFinderNt(filename)
143 
144  for bs in bsNt.allData():
145  # Skip entries outside of desired LB range
146  if options.lbmin and options.lbmin>bs.lbStart:
147  continue
148  if options.lbmax and options.lbmax<bs.lbEnd+1:
149  continue
150 
151  if bs.status in statList and bs.lbStart not in good_lbs[bs.run]:
152  # Fill GOOD Lbs where defect is NOT present (lbEnd for DQ is exclusive)
153  idbsDefects.add(minRun, maxRun, bs.lbStart, bs.lbEnd+1)
154  good_lbs[bs.run][bs.lbStart]=1
155 
156  else:
157  print ('WARNING: Skipping entry with status word %3s, lbStart=%4d, lbEnd=%4d' % (bs.status, bs.lbStart, bs.lbEnd))
158 
159  f.Close()
160 
161 # Set defects for those LBs where beamspot is not correctly determined by inverting good LB list
162 idbsDefects.complete(minRun, maxRun)
163 idbsDefects.dump()
164 
165 # Write to sqlite db and text file
166 if options.output:
167  idbsDefects.writeDefects(nonpresent = options.absent)
168  idbsDefects.dump(options.output)
169 
170 if options.lbmin or options.lbmax:
171  print ('\n**** WARNING: ONLY CONSIDERED ENTRIES IN RANGE [%s,%s] ****\n' % (options.lbmin,options.lbmax))
172 
173 # Enter interactive mode if desired
174 if options.interactive:
175  os.environ['PYTHONINSPECT'] = '1'
BeamSpotData
vtune_athena.format
format
Definition: vtune_athena.py:14
max
constexpr double max()
Definition: ap_fixedTest.cxx:33
min
constexpr double min()
Definition: ap_fixedTest.cxx:26
python.Utils.getRunFromName
def getRunFromName(name, default='', asInt=False)
Definition: InnerDetector/InDetExample/InDetBeamSpotExample/python/Utils.py:13
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:194
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
python.CaloAddPedShiftConfig.int
int
Definition: CaloAddPedShiftConfig.py:45