ATLAS Offline Software
www/beamspotnt.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
3 
4 from __future__ import print_function
5 
6 """
7 beamspotnt is a command line utility for beam spot ntuples.
8 """
9 __author__ = 'Juerg Beringer'
10 __version__ = 'beamspotnt.py atlas/athena'
11 __usage__ = '''%prog [options] command [args ...]
12 
13 Commands are:
14 
15 dump Dump contents of a beam spot ntuple
16 maketable Make LaTeX table of selected entries
17 inspect Inspect ntuple and provide summary of contents
18 merge SRCNT Merge source beam spot ntuple into master ntuple
19  (use --srcnt to specify type if not BeamSpotFinderNt)
20 ave Calculate average of beam spot parameters
21 hist var Histogram of var
22 histvspileup var Profile histogram of var vs pileup
23 pull var:value Pull of var with respect to true value
24 plot var History of var
25 summary Summary history plots
26 ascii filename Write ASCII file with data in Massi\'s format
27 
28 Examples:
29 
30 beamspotnt -t BeamSpotCOOL -f IndetBeampos-ES1-UPD2 --ru 165815 --rl 165815 dump
31 '''
32 
33 #periodDef = '/afs/cern.ch/atlas/www/GROUPS/DATAPREPARATION/DataPeriods'
34 periodDef = '/afs/cern.ch/user/a/atlidbs/nt/DataPeriods'
35 
36 import sys, os, time, glob, re, copy, math
37 
38 # Create a properly quoted string of the command line to save
39 qargv = [ ]
40 for s in sys.argv:
41  if re.search('\s|\*|\?',s): # any white space or special characters in word so we need quoting?
42  if "'" in s:
43  qargv.append('"%s"' % re.sub('"',"'",s))
44  else:
45  qargv.append("'%s'" % re.sub("'",'"',s))
46  else:
47  qargv.append(s)
48 qcmd = ' '.join(qargv)
49 
50 from optparse import OptionParser
51 parser = OptionParser(usage=__usage__, version=__version__)
52 parser.add_option('-f', '--nt', dest='ntname', default='beamspotnt.root', help='master ntuple file name or COOL tag (default: beamspotnt.root)')
53 parser.add_option('-t', '--type', dest='type', default='BeamSpotNt', help='master ntuple type (default: BeamSpotNt)')
54 parser.add_option('-s', '--srctype', dest='srctype', default='BeamSpotNt', help='source ntuple type for merging (default: BeamSpotNt)')
55 parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='verbose output')
56 parser.add_option('-d', '--debug', dest='debug', action='store_true', default=False, help='debug output')
57 parser.add_option('-q', '--quiet', dest='quiet', action='store_true', default=False, help='reduce output')
58 parser.add_option('-r', '--run', dest='run', type='int', default=None, help='run number (single run)')
59 parser.add_option('', '--rl', dest='runMin', type='int', default=None, help='minimum run number (inclusive)')
60 parser.add_option('', '--ru', dest='runMax', type='int', default=None, help='maximum run number (inclusive)')
61 parser.add_option('', '--re', dest='runExclude', default=None, help='comma seperated list of runs to exclude')
62 parser.add_option('', '--fill', dest='fill', type='int', default=None, help='fill number (single fill)')
63 parser.add_option('', '--fl', dest='fillMin', type='int', default=None, help='minimum fill number (inclusive)')
64 parser.add_option('', '--fu', dest='fillMax', type='int', default=None, help='maximum fill number (inclusive)')
65 parser.add_option('', '--bcid', dest='bcid', type='int', default=None, help='BCID number (single BCID)')
66 parser.add_option('', '--bcl', dest='bcidMin', type='int', default=None, help='minimum BCID number (inclusive)')
67 parser.add_option('', '--bcu', dest='bcidMax', type='int', default=None, help='maximum BCID number (inclusive)')
68 parser.add_option('', '--lbl', dest='lbMin', type='int', default=None, help='minimum LB number (inclusive)')
69 parser.add_option('', '--lbu', dest='lbMax', type='int', default=None, help='maximum LB number (inclusive)')
70 parser.add_option('', '--tl', dest='timeMin', default=None, help='minimum start time')
71 parser.add_option('', '--tu', dest='timeMax', default=None, help='maximum end time')
72 parser.add_option('', '--status', dest='status', default='59', help='comma-separated list of accepted fit status values (default: 59)')
73 parser.add_option('', '--energy', dest='energy', default='13', help='center-of-mass energy')
74 parser.add_option('-p', '--period', dest='period', default=None, help='comma-separated list of accepted run periods (e.g. data10_7TeV.G)')
75 parser.add_option('', '--perioddef', dest='periodDef', default=periodDef, help='location of run period definition files (default: %s)' % periodDef)
76 parser.add_option('-g', '--grl', dest='grl', default=None, help='GRL to select runs/Lbs')
77 parser.add_option('', '--mc', dest='mc', action='store_true', default=False, help='flag to indicate beam spot results are from MC')
78 parser.add_option('', '--fillCOOL', dest='fillcooldata', action='store_true', default=False, help='fill data from COOL (time, fill#)')
79 parser.add_option('', '--fillDQ', dest='filldqdata', action='store_true', default=False, help='fill data from DataQualtiy')
80 parser.add_option('', '--pLbFile', dest='pseudoLbFile', default=None, help='File for pseudo LB info from scan')
81 parser.add_option('', '--pLbTimeUnit', dest='pseudoLbTimeUnit', default=1., help='Time unit for pseudo LB relative to seconds, e.g. 1e-9 for ns')
82 parser.add_option('', '--tz', dest='timezone', default='CET', help='time zone to use for time represenation (default: CERN local time)')
83 parser.add_option('', '--simpleaverage', dest='simpleaverage', action='store_true', default=False, help='use simple instead of weighted average (for checks only)')
84 parser.add_option('', '--lumicalcnt', dest='lumicalcnt', default=None, help='ave: use luminosity ntuple (from iLumiCalc.exe) for weighted average')
85 parser.add_option('', '--latex', dest='latex', action='store_true', default=False, help='output results in LaTeX')
86 parser.add_option('', '--splittable', dest='splittable', type='int', default=None, help='latex: split table, put first n cols into first table')
87 parser.add_option('', '--hist', dest='hist', action='store_true', default=False, help='ave: produce validation histograms')
88 parser.add_option('', '--summary', dest='summary', action='store_true', default=False, help='ave: produce validation summary plots')
89 parser.add_option('', '--rms', dest='rms', action='store_true', default=False, help='Use RMS instead of error on mean')
90 parser.add_option('', '--varlist', dest='varlist', default=None, help='list of beam spot variables used by ave')
91 parser.add_option('-n', '--nbins', dest='nbins', type='int', default=None, help='number of bins')
92 parser.add_option('', '--xmin', dest='xmin', default=None, help='x axis minimum')
93 parser.add_option('', '--xmax', dest='xmax', default=None, help='x axis maximum')
94 parser.add_option('', '--timeaxis', dest='timeaxis', action='store_true', default=False, help='use time on x axis instead of run or LB numbers')
95 parser.add_option('', '--talabel', dest='talabel', default=None, help='time axis label (default: Time (timezone))')
96 parser.add_option('', '--perbcid', dest='perbcid', action='store_true', default=False, help='plot per BCID instead of vs time/LB')
97 parser.add_option('', '--separation', dest='separation', action='store_true', default=False, help='plot versus beam separation for scans')
98 parser.add_option('', '--vsbunchpos', dest='vsbunchpos', action='store_true', default=False, help='plot versus bunch position in train')
99 parser.add_option('', '--ndivs', dest='ndivs', type='int', default=None, help='Number of x axis divisions (ROOT format)')
100 parser.add_option('', '--ymin', dest='ymin', type='float', default=None, help='y axis minimum')
101 parser.add_option('', '--ymax', dest='ymax', type='float', default=None, help='y axis maximum')
102 parser.add_option('-y', '--yscale', dest='yscale', type='float', default=1.0, help='y axis scale factor')
103 parser.add_option('-m', '--msize', dest='msize', type='float', default=None, help='set marker size')
104 parser.add_option('', '--lsize', dest='lsize', type='float', default=None, help='set axis label size')
105 parser.add_option('', '--ydef', dest='ydef', action='store_true', default=False, help='use default y range for given quantity')
106 parser.add_option('', '--defaults', dest='defaults', default='Gen', help='choose varDef defauls (default: Gen')
107 parser.add_option('', '--logy', dest='logy', action='store_true', default=False, help='log scale')
108 parser.add_option('', '--fit', dest='fit', default='', help='fit function (e.g. pol1)')
109 parser.add_option('', '--optfit', dest='optfit', default='', help="fit options (default: '')")
110 parser.add_option('-c', '--canvas', dest='canvas', default='', help='canvas size: default, page, wide, extrawide or square')
111 parser.add_option('', '--xdivs', dest='xdivs', type='int', default=1, help='number of pads on canvas in x (needs -c, default: 1)')
112 parser.add_option('', '--ydivs', dest='ydivs', type='int', default=1, help='number of pads on canvas in y (needs -c, default: 1)')
113 parser.add_option('', '--optstat', dest='optstat', default='emruo', help='default OptStat value (Default: emruo)')
114 parser.add_option('', '--ave', dest='ave', action='store_true', default=False, help='show average on plot')
115 parser.add_option('', '--newave', dest='newave', action='store_true', default=False, help='replicate the functionality of the old aveBeamSpot.py script.')
116 parser.add_option('', '--title', dest='title', default='', help='title text on plots')
117 parser.add_option('', '--comment', dest='comment', default='', help='additional text (use semicolon to indicate line breaks)')
118 parser.add_option('', '--datefmt', dest='datefmt', default='', help='date format')
119 parser.add_option('', '--adatefmt', dest='adatefmt', default='', help='axis date format')
120 parser.add_option('', '--plegend', dest='plegend', default='fit to groups of LBs', help='legend text for points')
121 parser.add_option('', '--alegend', dest='alegend', default='average of data shown:', help='legend text for average')
122 parser.add_option('', '--maxlegends', dest='maxlegends', type='int', default=10, help='maximum number of legend entries')
123 parser.add_option('', '--omitfill', dest='omitfill', action='store_true', default=False, help='remove any fill info from legend')
124 parser.add_option('', '--omitrun', dest='omitrun', action='store_true', default=False, help='remove any run info from legend')
125 parser.add_option('', '--omittime', dest='omittime', action='store_true', default=False, help='remove any time info from legend')
126 parser.add_option('', '--public', dest='public', action='store_true', default=False, help='use labelling for public plots')
127 parser.add_option('', '--prelim', dest='prelim', action='store_true', default=False, help='add ATLAS Preliminary to figure')
128 parser.add_option('', '--approval', dest='approval', action='store_true', default=False, help='Label figure ATLAS for approval')
129 parser.add_option('', '--published', dest='published', action='store_true', default=False, help='add ATLAS to figure')
130 parser.add_option('', '--customlabel', dest='customlabel', default='', help='add custom label after ATLAS to figure')
131 parser.add_option('', '--xtitoffset', dest='xtitoffset', type='float', default=None, help='x axis title offset')
132 parser.add_option('', '--ytitoffset', dest='ytitoffset', type='float', default=None, help='y axis title offset')
133 parser.add_option('', '--atlasx', dest='atlasx', type='float', default=None, help='x position for drawing ATLAS (Preliminary) label')
134 parser.add_option('', '--atlasy', dest='atlasy', type='float', default=None, help='y position for drawing ATLAS (Preliminary) label')
135 parser.add_option('', '--atlasdx', dest='atlasdx', type='float', default=None, help='x position offset for drawing Preliminary label')
136 parser.add_option('-o', '--output', dest='output', default='.gif', help='comma-separated list of output files or formats (default: .gif)')
137 parser.add_option('', '--name', dest='name', default='BeamSpotNtPlots', help='base name for plots (default: BeamSpotNtPlots)')
138 parser.add_option('', '--tgraphfile', dest='tgraphfile', default='', help='optional root file to save TGraph into')
139 parser.add_option('', '--tag', dest='cooltag', default='', help='COOL tag for writing average into beam spot SQLite file (also determines file name)')
140 parser.add_option('-i', '--interactive', dest='interactive', action='store_true', default=False, help='interactive')
141 parser.add_option('-b', '--batch', dest='batch', action='store_true', default=False, help='run in batch mode')
142 parser.add_option('', '--fullCorrelations', dest='fullCorrelations', action='store_true', default=False, help='Get all correlations')
143 parser.add_option('', '--scans', dest='scans', default='', help='comma-separated list of hypenated lb ranges for lumi scans')
144 parser.add_option('', '--acqFlag', dest='acqFlag', default = False, action='store_true', help='Cut on AcquistionFlag=1.0 for stationary points of VdM scan')
145 parser.add_option('', '--overlayScans', dest='overlayScans', default = False, action='store_true', help='overlay VdM scans on same plot')
146 parser.add_option('', '--useAve', dest='useAve', action='store_true', default=False, help='Average over poor fits in the beamspot -- performed during merging step')
147 (options,args) = parser.parse_args()
148 if len(args) < 1:
149  parser.error('wrong number of command line arguments')
150 cmd = args[0]
151 
152 if options.fillcooldata and options.pseudoLbFile:
153  sys.exit('Options fillColl and pseudoLbFile are mutually exclusive')
154 
155 # Reset DISPLAY if in batch
156 if options.batch:
157  os.unsetenv('DISPLAY')
158 
159 # Place after OptionParse to avoid conflict with ROOT option parsing
160 import ROOT
161 import InDetBeamSpotExample
162 
163 # Get BeamSpotData class and choose beam spot variable defaults
164 from InDetBeamSpotExample import BeamSpotData
165 if options.defaults:
166  BeamSpotData.varDefs = getattr(BeamSpotData,'varDefs'+options.defaults)
168 
169 #from InDetBeamSpotExample.COOLUtils import *
170 from InDetBeamSpotExample.Utils import getUserName, getHostName
171 from InDetBeamSpotExample import ROOTUtils
173 from math import *
174 
175 cmdOk = False
176 if options.interactive:
177  os.environ['PYTHONINSPECT'] = '1'
178 
179 if options.timezone:
180  os.environ['TZ'] = options.timezone
181  time.tzset()
182  timeLabel = 'Time (%s)' % options.timezone
183 else:
184  timeLabel = 'Local time'
185 if options.talabel:
186  timeLabel = options.talabel
187 
188 if not options.datefmt:
189  if options.public:
190  options.datefmt = '%b %Y'
191  else:
192  options.datefmt = '%a %b %d'
193 
194 # Graphics defaults
195 if options.atlasx==None:
196  if options.published:
197  options.atlasx = 0.83 if 'wide' in options.canvas else 0.8
198  else:
199  options.atlasx = 0.72 if 'wide' in options.canvas else 0.645
200 if options.atlasy==None:
201  if options.public:
202  options.atlasy = 0.86
203 if options.atlasdx==None:
204  options.atlasdx = 0.08 if 'wide' in options.canvas else 0.115
205 
206 ntClass = locals()[options.type]
207 
208 def setCuts(nt):
209  if options.run!=None:
210  nt.runMin = options.run
211  nt.runMax = options.run
212  if options.runMin!=None:
213  nt.runMin = options.runMin
214  if options.runMax!=None:
215  nt.runMax = options.runMax
216  if options.runExclude!=None:
217  nt.runListExclude = [int(r) for r in options.runExclude.split(',')]
218  if options.fill!=None:
219  nt.fillMin = options.fill
220  nt.fillMax = options.fill
221  if options.fillMin!=None:
222  nt.fillMin = options.fillMin
223  if options.fillMax!=None:
224  nt.fillMax = options.fillMax
225  if options.bcid!=None:
226  nt.bcidMin = options.bcid
227  nt.bcidMax = options.bcid
228  if options.bcidMin!=None:
229  nt.bcidMin = options.bcidMin
230  if options.bcidMax!=None:
231  nt.bcidMax = options.bcidMax
232  if options.lbMin!=None:
233  nt.lbMin = options.lbMin
234  if options.lbMax!=None:
235  nt.lbMax = options.lbMax
236  if options.timeMin!=None:
237  nt.timeMin = time.mktime(time.strptime(options.timeMin,'%b %d %H:%M:%S %Y'))
238  if options.timeMax!=None:
239  nt.timeMax = time.mktime(time.strptime(options.timeMax,'%b %d %H:%M:%S %Y'))
240  if options.status:
241  nt.statusList = [int(x) for x in options.status.split(',')]
242  if options.period:
243  for p in options.period.split(','):
244  project,period = p.split('.')
245  location = os.path.normpath(options.periodDef + '/' + project)
246  try:
247  fileName = glob.glob('%s/%s.runs.list' % (location,period))[0]
248  nt.runList.extend([int(r) for r in open(fileName).read().split()])
249  except:
250  sys.exit('ERROR: Definition file for period %s not found in directory %s' % (options.period, location))
251 
252  if not nt.runList:
253  sys.exit('ERROR: no runs found for requested periods')
254 
255  if options.grl:
256  nt.grl = options.grl
257 
258  if options.acqFlag:
259  nt.acqFlag = 1.0
260 
261 def getNt():
262  try:
263  if options.fullCorrelations:
264  nt = ntClass(options.ntname,fullCorrelations=True)
265  else:
266  nt = ntClass(options.ntname)
267  except Exception as e:
268  sys.exit('ERROR: '+str(e))
269 
270  setCuts(nt)
271  print (nt.summary())
272  print (nt.cutSummary())
273  return nt
274 
275 def cleanUpLowStat( allBSResultsInNt, averagenVtx, lbSize ):
276  i=0
277  while i < len( allBSResultsInNt ):
278  b = allBSResultsInNt[i]
279  if b.status < 70 and b.sigmaZErr == 0:
280  print ("Will change Z error for lb's " + str(b.lbStart) +" to " + str(b.lbEnd) + " which has " + str(b.nValid) + " verticies")
281  b.sigmaZErr = b.sigmaZ * 0.5
282  i += 1
283 
284  i=0
285  while i < len( allBSResultsInNt ):
286  b = allBSResultsInNt[i]
287 
288  if b.status < 70 and b.nValid < 2000 and b.nValid < averagenVtx:
289  print ("Will take an average for lb's " + str(b.lbStart) +" to " + str(b.lbEnd) + " which has " + str(b.nValid) + " verticies" )
290  lastGoodEntry = b
291  nextGoodEntry = b
292  iNeg = i-1;
293  # Find previous good entry
294  while iNeg >= 0:
295  if allBSResultsInNt[iNeg].status == 59 and allBSResultsInNt[iNeg].nValid > 2000 :
296  lastGoodEntry = allBSResultsInNt[iNeg]
297  print (" --- Starting with lb : " + str(lastGoodEntry.lbStart) +" to " + str(lastGoodEntry.lbEnd))
298  break
299  iNeg -= 1
300 
301  # Find the next good entry
302  iPos = i+1;
303  while iPos < len(allBSResultsInNt):
304  if allBSResultsInNt[iPos].status == 59 and allBSResultsInNt[iPos].nValid > 2000:
305  nextGoodEntry = allBSResultsInNt[iPos]
306  print (" --- Ending with lb : " + str(nextGoodEntry.lbStart) +" to " + str(nextGoodEntry.lbEnd))
307  break
308  iPos += 1
309 
310  #if all entries are useless then we are in trouble dont do anything
311  if lastGoodEntry == b and nextGoodEntry == b :
312  print ("Failed to do average - no good entries were found")
313  i+=1
314  continue
315 
316  #check the entries are reasonablly close to each other
317  if( ( nextGoodEntry == b or abs(nextGoodEntry.lbStart - b.lbEnd) > abs(lbSize) ) and (lastGoodEntry == b or abs(b.lbStart - lastGoodEntry.lbEnd) > abs(lbSize) ) ):
318  print ("Failed to do average - entries were too far away")
319  i+=1
320  continue
321 
322  #Calculate the average beamspot position for the following parameters
323  varList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY','sigmaXY']
324  calc = BeamSpotAverage(varList ,weightedAverage=True)
325  #Add current entry if it is reliable
326  if( b.status == 59 and b.posXErr != 0 and not math.isnan(b.posX) and not math.isnan(b.posZ) and not math.isnan(b.sigmaZ) ):
327  calc.add(b)
328  #Add previous entry if it is not too far away in time
329  if lastGoodEntry != b and abs(b.lbStart - lastGoodEntry.lbEnd) <= abs(lbSize) :
330  calc.add(lastGoodEntry)
331  #Add next entry if it is not too far away in time
332  if nextGoodEntry != b and abs(nextGoodEntry.lbStart - b.lbEnd) <= abs(lbSize) :
333  calc.add(nextGoodEntry)
334  calc.average()
335 
336  ave = calc.ave
337  err = calc.err
338  b.status = 666 #b.status << 4
339  bcopy = copy.deepcopy(b)
340 
341  for var in varList:
342  #print ("Var,index: {:>10} , {:>3}".format( var, calc.varList.index(var)))
343  setattr(bcopy, var, ave[calc.varList.index(var)])
344  setattr(bcopy, var+"Err", err[calc.varList.index(var)])
345 
346  bcopy.status = 59
347  i += 1
348  allBSResultsInNt.insert(i, bcopy)
349  i += 1
350 
351 
352 
353 
354 def fillInMissingLbs(allBSResultsInNt, lbSize):
355  i=0
356  lastValidEntry = -1
357  nextValidEntry = -1
358  while i < len( allBSResultsInNt ):
359  if allBSResultsInNt[i].status != 59:
360  i += 1
361  continue
362 
363  nextValidEntry = i
364 
365  if(lastValidEntry >= 0):
366  if allBSResultsInNt[nextValidEntry].lbStart != allBSResultsInNt[lastValidEntry].lbEnd + 1:
367  print ("Missing Lumi block from {:>5d} to {:>5d}".format( allBSResultsInNt[lastValidEntry].lbEnd + 1 , allBSResultsInNt[nextValidEntry].lbStart))
368 
369 
370  if allBSResultsInNt[nextValidEntry].lbStart - allBSResultsInNt[lastValidEntry].lbEnd + 1 > lbSize:
371  print ("--Lumi block gap too large wont fill in the gap" )
372  elif (allBSResultsInNt[nextValidEntry].lbStart-1) - (allBSResultsInNt[lastValidEntry].lbEnd+1) < 0 :
373  print ("Missing Lumi block is invalid from {:>5d} to {:>5d}".format( allBSResultsInNt[lastValidEntry].lbEnd+1, allBSResultsInNt[nextValidEntry].lbStart -1))
374  else:
375  varList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY','sigmaXY']
376  calc = BeamSpotAverage(varList ,weightedAverage=True)
377  calc.add(allBSResultsInNt[nextValidEntry])
378  calc.add(allBSResultsInNt[lastValidEntry])
379  calc.average()
380 
381  ave = calc.ave
382  err = calc.err
383 
384  bcopy = copy.deepcopy(b)
385 
386  for var in varList:
387  #print ("Var,index: {:>10} , {:>3}".format( var, calc.varList.index(var)))
388  setattr(bcopy, var, ave[calc.varList.index(var)])
389  setattr(bcopy, var+"Err", err[calc.varList.index(var)])
390 
391  bcopy.status = 59
392  bcopy.timeStart = 0
393  bcopy.timeEnd = 0
394  bcopy.nEvents = 1
395  bcopy.nValid = 1
396  bcopy.nVtxAll = 1
397  bcopy.nVtxPrim = 1
398  bcopy.lbStart = allBSResultsInNt[lastValidEntry].lbEnd + 1
399  bcopy.lbEnd = allBSResultsInNt[nextValidEntry].lbStart-1
400  allBSResultsInNt.insert(lastValidEntry+1, bcopy)
401  i += 1
402  nextValidEntry += 1
403 
404  lastValidEntry = nextValidEntry
405  i += 1
406 
407 
408 
410 
411  def __init__(self,nt):
412  ROOTUtils.PlotLibrary.__init__(self,options.name)
413  self.nt = nt
414  self.whatList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY','k']
415 
416  def writeText(self, var, legendList=[],
417  showRuns=True, showFills=True, showTime=True, otherTitle=None, otherComment=None,
418  legendX=0.6):
419  # Title and comment lines with optional run, fill and time/date info
420  if otherTitle!=None:
421  self.protect( ROOTUtils.drawText(0.2,0.86,0.06,otherTitle) )
422  else:
423  title = options.title or varDef(var,'title',var)
424  self.protect( ROOTUtils.drawText(0.2,0.86,0.06,title) )
425  comments = []
426  if otherComment:
427  comments.append(otherComment)
428  if options.comment:
429  comments.append(options.comment)
430  if showRuns and not options.omitrun:
431  if self.nt.selRunMin==self.nt.selRunMax:
432  comments.append('Run %i' % self.nt.selRunMin)
433  else:
434  comments.append('Runs %i - %i' % (self.nt.selRunMin,self.nt.selRunMax))
435  if showFills and not options.omitfill:
436  if self.nt.selFillMin==self.nt.selFillMax:
437  comments.append('Fill %i' % self.nt.selFillMin)
438  else:
439  comments.append('Fills %i - %i' % (self.nt.selFillMin,self.nt.selFillMax))
440  if showTime and not options.omittime:
441  if options.public:
442  t1 = time.strftime(options.datefmt,time.localtime(self.nt.selTimeMin))
443  t2 = time.strftime(options.datefmt,time.localtime(self.nt.selTimeMax))
444  else:
445  t1 = time.strftime(options.datefmt,time.localtime(self.nt.selTimeMin))
446  t2 = time.strftime(options.datefmt,time.localtime(self.nt.selTimeMax))
447  if t1==t2:
448  comments.append(t1)
449  else:
450  comments.append('%s - %s' % (t1,t2))
451 
452  self.protect( ROOTUtils.drawText(0.2,0.79,0.06,';'.join(comments),font=42) )
453  # ATLAS (preliminary) label
454  logoSize = options.lsize if options.lsize else 0.5
455  if options.prelim:
456  ROOTUtils.atlasLabel(options.atlasx,options.atlasy,True,offset=options.atlasdx,energy=options.energy,size=logoSize)
457  if options.approval:
458  ROOTUtils.atlasLabel(options.atlasx,options.atlasy,False,offset=options.atlasdx,isForApproval=True,energy=options.energy,size=logoSize)
459  if options.published:
460  ROOTUtils.atlasLabel(options.atlasx,options.atlasy,False,offset=options.atlasdx,energy=options.energy,size=logoSize)
461  if options.customlabel!="":
462  ROOTUtils.atlasLabel(options.atlasx,options.atlasy,False,offset=options.atlasdx,isForApproval=False,customstring=options.customlabel,energy=options.energy,size=logoSize)
463  # Legend
464  if legendList:
465  legendMinY = max(0.91-0.07*len(legendList),0.2)
466  self.protect( ROOTUtils.drawLegend(legendX,legendMinY,0.92,0.91,legendList) )
467 
468  def hist(self,what):
469  """Histogram of variable what.
470 
471  If what is of the form NAME:VALUE, VALUE will be subtracted
472  from each entry in order to produce plots of measured minus
473  true value."""
474  shift = 0.
475  try:
476  (what,shift) = what.split(':')
477  shift = float(shift)
478  except:
479  pass
480  ROOT.gStyle.SetOptStat(options.optstat) # emruo to add underflow, overflow
481  title = varDef(what,'title',what)+';'+varDef(what,'atit',what)
482  nBins = options.nbins if options.nbins else varDef(what,'nBins',100)
483  xmin = float(options.xmin) if options.xmin!=None else varDef(what,'min',-100)
484  xmax = float(options.xmax) if options.xmax!=None else varDef(what,'max',+100)
485  h = self.protect( ROOT.TH1F(what,title,nBins,xmin,xmax) )
486  if options.fit:
487  h.Sumw2()
488  h.GetYaxis().SetTitle('Number of fit results')
489  arescale = varDef(what,'arescale',1.0)
490  try:
491  for b in nt:
492  h.Fill(arescale*(getattr(b,what)-shift))
493  except Exception as e:
494  print ('ERROR filling histogram:',str(e))
495  h.Draw()
496  if options.fit:
497  ROOT.gStyle.SetOptFit(1111)
498  h.Fit(options.fit,options.optfit)
499  if options.logy:
500  ROOT.gPad.SetLogy(options.logy)
501  ndivs = varDef(what,'ndivs',override=options.ndivs)
502  if ndivs:
503  h.GetXaxis().SetNdivisions(ndivs,0)
504  if options.mc:
505  self.writeText(what,[],False,False,False)
506  else:
507  self.writeText(what,[],not options.public,options.public)
508 
509  def histvspileup(self,what):
510  """Profile histogram of variable what vs pileup.
511 
512  If what is of the form NAME:VALUE, VALUE will be subtracted
513  from each entry in order to produce plots of measured minus
514  true value."""
515  shift = 0.
516  try:
517  (what,shift) = what.split(':')
518  shift = float(shift)
519  except:
520  pass
521  ROOT.gStyle.SetOptStat(options.optstat) # emruo to add underflow, overflow
522  title = varDef(what,'title',what)+';Number of pileup vertices;'+varDef(what,'atit',what)
523  nBins = options.nbins if options.nbins else varDef(what,'nBins',100)
524  xmin = float(options.xmin) if options.xmin!=None else varDef(what,'min',-100)
525  xmax = float(options.xmax) if options.xmax!=None else varDef(what,'max',+100)
526  h = self.protect( ROOT.TProfile(what,title,nBins,0,nBins) )
527  if options.fit:
528  h.Sumw2()
529  h.GetYaxis().SetRangeUser(xmin,xmax)
530  arescale = varDef(what,'arescale',1.0)
531  try:
532  for b in nt:
533  h.Fill(getattr(b,'pileup'),arescale*(getattr(b,what)-shift))
534  except Exception as e:
535  print ('ERROR filling histogram:',str(e))
536  h.Draw()
537  if options.fit:
538  ROOT.gStyle.SetOptFit(1111)
539  h.Fit(options.fit,options.optfit)
540  if options.logy:
541  ROOT.gPad.SetLogy(options.logy)
542  ndivs = varDef(what,'ndivs',override=options.ndivs)
543  if ndivs:
544  h.GetYaxis().SetNdivisions(ndivs,0)
545  if options.mc:
546  self.writeText(what,[],False,False,False)
547  else:
548  self.writeText(what,[],not options.public,options.public)
549 
550  def pull(self,what):
551  """Pull histogram of variable what.
552 
553  what must be of the form name:value, where value is the
554  correct value of variable name."""
555  try:
556  (what,value) = what.split(':')
557  value = float(value)
558  except:
559  print(('ERROR: Illegal input %s for pull variable - must be of the form NAME:VALUE' % what))
560  return
561  ROOT.gStyle.SetOptStat(options.optstat)
562  title = ';Pull'
563  nBins = options.nbins if options.nbins else varDef(what,'nBins',100)
564  xmin = float(options.xmin) if options.xmin!=None else -4.
565  xmax = float(options.xmax) if options.xmax!=None else +4.
566  h = self.protect( ROOT.TH1F(what,title,nBins,xmin,xmax) )
567  if options.fit:
568  h.Sumw2()
569  h.GetYaxis().SetTitle('Number of fit results')
570  whatErr = what+'Err'
571  try:
572  for b in nt:
573  h.Fill((getattr(b,what)-value)/getattr(b,whatErr))
574  except Exception as e:
575  print ('ERROR filling histogram:',str(e))
576  h.Draw()
577  if options.fit:
578  ROOT.gStyle.SetOptFit(1111)
579  h.Fit(options.fit,options.optfit)
580  if options.logy:
581  ROOT.gPad.SetLogy(options.logy)
582  if options.ndivs:
583  h.GetXaxis().SetNdivisions(options.ndivs,0)
584  if options.mc:
585  self.writeText(what,[],False,False,False)
586  else:
587  self.writeText(what,[],not options.public,options.public)
588 
589  def plot(self,what):
590  """History of variable what vs LB or time."""
591  ROOT.gStyle.SetOptStat(0)
592  if options.ave:
593  calc = BeamSpotAverage([what],weightedAverage=not options.simpleaverage)
594  grDict = {}
595 
596  arescale = varDef(what,'arescale',1.0)
597  for b in nt:
598  if b.sigmaX < 0.01 or b.sigmaY < 0.01:
599  print ("OUTLIER ", b.run, b.lbStart, b.lbEnd, b.sigmaX, b.sigmaY)
600  if not b.bcid in grDict:
601  grDict[b.bcid] = BeamSpotGraph(timeAxis=options.timeaxis, separationAxis=options.separation)
602  # What was this for? Why ignore if no time info available?
603  #if b.timeStart>0 and b.timeEnd>0:
604  grDict[b.bcid].add(b,what,arescale)
605  if options.ave:
606  calc.add(b)
607 
608  print ('Plotting data from %i BCID ...\n' % len(grDict))
609 
610  # Determine axis range
611  xmin = 1E10
612  xmax = -1E10
613  ymin = 1E10
614  ymax = -1E10
615  for gr in [grDict.get(bcid) for bcid in grDict]:
616  xmin = min(xmin,gr.xmin)
617  xmax = max(xmax,gr.xmax)
618  ymin = min(ymin,gr.ymin)
619  ymax = max(ymax,gr.ymax)
620 
621  # Prevent xmin>xmax or ymin>ymax if no succesful fits (but still allow user to override)
622  if xmin>xmax:
623  xmin,xmax=0,1
624  if ymin>ymax:
625  ymin,ymax=0,1
626 
627  h = (xmax-xmin)
628  xmax += .05*h if len(grDict)==1 else 0.3*h
629  xmin -= .05*h
630  h = (ymax-ymin)/2*options.yscale
631  ymax += 1.3*h
632  ymin -= 0.5*h
633  if options.xmin!=None:
634  xmin = time.mktime(time.strptime(options.xmin,'%b %d %H:%M:%S %Y')) if options.timeaxis else float(options.xmin)
635  if options.xmax!=None:
636  xmax = time.mktime(time.strptime(options.xmax,'%b %d %H:%M:%S %Y')) if options.timeaxis else float(options.xmax)
637  if options.ydef:
638  ymin = varDef(what,'min',-100)
639  ymax = varDef(what,'max',+100)
640  if options.ymin!=None:
641  ymin = options.ymin
642  if options.ymax!=None:
643  ymax = options.ymax
644 
645  # Axis settings
646  if options.timeaxis:
647  atit = ';%s;%s' % (timeLabel,varDef(what,'atit',what))
648  elif options.separation:
649  atit = ';%s;%s' % ('Nominal Separation [mm]',varDef(what,'atit',what))
650  else:
651  atit = ';%s;%s' % ('Luminosity block number',varDef(what,'atit',what))
652  frame = ROOTUtils.drawAxisFrame(xmin,xmax,ymin,ymax,atit)
653  if options.logy:
654  ROOT.gPad.SetLogy(options.logy)
655  if options.timeaxis:
656  xAxis = frame.GetXaxis()
657  yAxis = frame.GetYaxis()
658  xAxis.SetTimeDisplay(1)
659 
660  # this may or may not be needed depending on the ROOT version... not sure whether to specify it or not.
661  # Setting this option in 5.34 seems to work, in 5.30 it offsets things by an hour, but then not setting it
662  # appears to result in bogus x-axis values.
663  xAxis.SetTimeOffset(0) # FIXME: this ignores options.timezone!
664 
665  if (xmax-xmin)/86400 < 1:
666  xAxis.SetTimeFormat('%H:%M')
667  else:
668  #d0 = ceil(xmin/86400) # day w/first tick mark
669  #d1 = floor(xmax/86400) # day w/last tick mark
670  #nTicks = d1-d0+1
671  #nDays = floor((xmax-xmin)/86400)
672  if options.public:
673  xAxis.SetTimeFormat('%b %d')
674  else:
675  xAxis.SetTimeFormat('#splitline{%b %d}{%H:%M}')
676  xAxis.SetLabelOffset(0.02)
677  xAxis.SetTitleOffset(1.6)
678  if options.lsize:
679  xAxis.SetLabelSize(options.lsize)
680  xAxis.SetTitleSize(options.lsize)
681  yAxis.SetLabelSize(options.lsize)
682  yAxis.SetTitleSize(options.lsize)
683  else:
684  xAxis.SetLabelSize(0.044)
685  if options.adatefmt:
686  xAxis.SetTimeFormat(options.adatefmt)
687  if options.ndivs:
688  xAxis.SetNdivisions(options.ndivs,0)
689  frame.LabelsOption('d','X') # Doesn't seem to work
690 
691  if options.xtitoffset:
692  xAxis.SetTitleOffset(options.xtitoffset)
693  if options.ytitoffset:
694  yAxis.SetTitleOffset(options.ytitoffset)
695 
696  legendList = []
697 
698  # Show average
699  if options.ave:
700  calc.average()
701  dx = (xmax-xmin)/30
702  mean = calc.ave[0]
703  if options.rms:
704  error = calc.rms[0]
705  else:
706  error = calc.err[0]
707  b = ROOTUtils.drawHorizontalBand(xmin+dx,xmax-dx,mean,error,centralLine=True)
708  legendList.append([b,options.alegend,'FL'])
709  legendList.append([None,'%s %s #pm %s %s' % (fmtVal(what,mean,True),varDef(what,'units'),
710  fmtVal(what,error,True),varDef(what,'units')),''])
711 
712  # Loop over graphs for all BCIDs
713  styleFactory = ROOTUtils.StyleFactory()
714  for bcid in sorted(grDict.keys()):
715  gr = grDict[bcid]
716 
717  # Get and save TGraphErrors, if desired
718  name = what if bcid==0 else '%s-bcid%04i' % (what,bcid)
719  tgraph = self.protect( gr.getTGraph(name) )
720  if not tgraph:
721  continue
722  if options.tgraphfile:
723  print ('Saving TGraphErrors',tgraph.GetName(),'to file',options.tgraphfile)
724  tgraphfile = ROOT.TFile(options.tgraphfile,'UPDATE')
725  tgraph.Write()
726  tgraphfile.Close()
727 
728  # Draw data points
729  if len(grDict)==1:
730  tgraph.SetMarkerSize(options.msize if options.msize else 0.8)
731  if options.plegend:
732  legendList.append([tgraph,options.plegend,'PLE'])
733  else:
734  tgraph.SetMarkerColor(styleFactory.nextColorStyle())
735  tgraph.SetMarkerStyle(styleFactory.nextMarkerStyle())
736  tgraph.SetMarkerSize(options.msize if options.msize else 1.2)
737  if len(legendList)<options.maxlegends:
738  text = 'All' if bcid==0 else 'BCID %i' % bcid
739  legendList.append([tgraph,text,'PLE'])
740  tgraph.Draw('P')
741 
742  # Indicate if legend incomplete
743  if len(grDict)>options.maxlegends:
744  legendList.append([None,'...',''])
745 
746  # Fit data, if desired
747  if options.fit and len(grDict)==1:
748  ROOT.gStyle.SetOptFit(1111)
749  legendList = [] # No legend to avoid crowding plot
750  tgraph.Fit(options.fit,'','SAME', gr.xmin,gr.xmax) #-0.05, 0.05) #ZEBRA
751 
752  # Draw title and legend
753  legendX = 0.6 if len(grDict)==1 else 0.8
754  self.writeText(what,legendList if not options.public else [],not options.public,legendX=legendX)
755 
756  def perbcid(self,what):
757  """Variable what vs BCID."""
758  ROOT.gStyle.SetOptStat(0)
759  if options.ave:
760  calc = BeamSpotAverage([what],weightedAverage=not options.simpleaverage)
761  gr = BeamSpotGraph(bcidAxis=True)
762  for b in nt:
763  gr.add(b,what)
764  if options.ave:
765  calc.add(b)
766  atit = ';%s;%s' % ('BCID',varDef(what,'atit',what))
767 
768  # Axis range and labels
769  xmin = max(-100,gr.xmin-100)
770  xmax = min(3600,gr.xmax+100) # 3564 is the max number of BCIDS + a little space
771  ymin = gr.ymin
772  ymax = gr.ymax
773 
774  # Prevent xmin>xmax or ymin>ymax if no succesful fits (but still allow user to override)
775  if xmin>xmax:
776  xmin,xmax=0,1
777  if ymin>ymax:
778  ymin,ymax=0,1
779 
780  h = (ymax-ymin)/2*options.yscale
781  ymax += 1.3*h
782  ymin -= 0.5*h
783  if options.ydef:
784  ymin = varDef(what,'min',-100)
785  ymax = varDef(what,'max',+100)
786  if options.ymin!=None:
787  ymin = options.ymin
788  if options.ymax!=None:
789  ymax = options.ymax
790  frame = ROOTUtils.drawAxisFrame(xmin,xmax,ymin,ymax,atit)
791  if options.logy:
792  ROOT.gPad.SetLogy(options.logy)
793 
794  legendList = []
795 
796  # Show average
797  if options.ave:
798  calc.average()
799  dx = (xmax-xmin)/30
800  mean = calc.ave[0]
801  if options.rms:
802  error = calc.rms[0]
803  else:
804  error = calc.err[0]
805  b = ROOTUtils.drawHorizontalBand(xmin+dx,xmax-dx,mean,error,centralLine=True)
806  legendList.append([b,options.alegend,'FL'])
807  legendList.append([None,'%s %s #pm %s %s' % (fmtVal(what,mean,True),varDef(what,'units'),
808  fmtVal(what,error,True),varDef(what,'units')),''])
809 
810  # Save and draw graph
811  name = '%s-perBCID' % what
812  tgraph = self.protect( gr.getTGraph(name) )
813  if not tgraph:
814  return
815  if options.tgraphfile:
816  print ('Saving TGraphErrors',tgraph.GetName(),'to file',options.tgraphfile)
817  tgraphfile = ROOT.TFile(options.tgraphfile,'UPDATE')
818  tgraph.Write()
819  tgraphfile.Close()
820  tgraph.SetMarkerSize(options.msize if options.msize else 0.8)
821  if options.plegend:
822  legendList.append([tgraph,options.plegend,'PLE'])
823  tgraph.Draw('P')
824 
825  # Draw title and legend
826  self.writeText(what,legendList,not options.public)
827 
828  def vsBunchPos(self,what):
829  """Variable what vs bunch position in train."""
830  ROOT.gStyle.SetOptStat(0)
831 
832  lastb = -999
833  startb = -999
834  calcmap = {}
835  bunchnrs = []
836  trainGap = 36
837 
838  for b in nt:
839  if b.bcid - lastb > trainGap:
840  startb = b.bcid
841 
842  lastb = b.bcid
843  bunchnumber = b.bcid - startb
844 
845  if bunchnumber in calcmap:
846  calcmap[bunchnumber].add(b)
847  else:
848  calcmap[bunchnumber] = BeamSpotAverage([what], weightedAverage = not options.simpleaverage)
849  bunchnrs.append(bunchnumber)
850 
851  gr = self.protect( ROOT.TGraphErrors(len(bunchnrs)))
852  counter = 0
853  xmin = -10
854  xmax = 1
855  ymin = 1e9
856  ymax = -1e9
857 
858  for bunchnr in bunchnrs:
859  calcmap[bunchnr].average()
860  gr.SetPoint(counter, bunchnr, calcmap[bunchnr].ave[0])
861  gr.SetPointError(counter, 0.5, calcmap[bunchnr].err[0])
862  xmax = max(xmax, bunchnr)
863  ymin = min(ymin, calcmap[bunchnr].ave[0])
864  ymax = max(ymax, calcmap[bunchnr].ave[0])
865  counter += 1
866 
867  if xmin>xmax:
868  xmin,xmax=0,1
869  if ymin>ymax:
870  ymin,ymax=0,1
871 
872  xmax = xmax + 10
873  h = (ymax - ymin)/2*options.yscale
874  ymax += 2.0*h
875  ymin -= 1.0*h
876 
877  if options.xmin != None:
878  xmin = options.xmin
879  if options.xmax != None:
880  xmax = options.xmax
881  if options.ymin != None:
882  ymin = options.ymin
883  if options.ymax != None:
884  ymax = options.ymax
885 
886  gr.SetMarkerSize(options.msize if options.msize else 0.8)
887 
888  atit = ';%s;%s' % ('Bunch position in train',varDef(what,'atit',what))
889  frame = ROOTUtils.drawAxisFrame(xmin,xmax,ymin,ymax,atit)
890  if gr.GetN() == 0:
891  return
892 
893  legendList = []
894  if options.plegend:
895  legendList.append([gr,options.plegend,'PLE'])
896  gr.Draw('P')
897  self.writeText(what,legendList,not options.public)
898 
899  def plotscan(self,what):
900  """History of variable what vs LB, time or separation. Additionally overlap the results of more than one scan
901  """
902 
903  ROOT.gStyle.SetOptStat(0)
904  if options.ave:
905  calc = BeamSpotAverage([what],weightedAverage=not options.simpleaverage)
906  grDict = {}
907 
908  scans = [(int(s.split('-')[0]), int(s.split('-')[1])) for s in options.scans.split(',')]
909 
910  for b in nt:
911 
912  if options.separation and options.overlayScans:
913  try:
914  scanGroup = [s for s in scans if s[0] <= b.lbStart <= s[1]][0]
915  except IndexError:
916  # plB outside of scan ranges
917  continue
918  else:
919  scanGroup = 0
920 
921  if not scanGroup in grDict:
922  grDict[scanGroup] = BeamSpotGraph(timeAxis=options.timeaxis, separationAxis=options.separation)
923  grDict[scanGroup].add(b,what)
924  if options.ave:
925  calc.add(b)
926 
927  print ('Plotting data from %i scans ...\n' % len(grDict))
928 
929  # Determine axis range
930  xmin = 1E10
931  xmax = -1E10
932  ymin = 1E10
933  ymax = -1E10
934  for gr in [grDict.get(scan) for scan in grDict]:
935  xmin = min(xmin,gr.xmin)
936  xmax = max(xmax,gr.xmax)
937  ymin = min(ymin,gr.ymin)
938  ymax = max(ymax,gr.ymax)
939 
940  # Prevent xmin>xmax or ymin>ymax if no succesful fits (but still allow user to override)
941  if xmin>xmax:
942  xmin,xmax=0,1
943  if ymin>ymax:
944  ymin,ymax=0,1
945 
946  h = (xmax-xmin)
947  xmax += .05*h if len(grDict)==1 else 0.3*h
948  xmin -= .05*h
949  h = (ymax-ymin)/2*options.yscale
950  ymax += 1.3*h
951  ymin -= 0.5*h
952  if options.xmin!=None:
953  xmin = time.mktime(time.strptime(options.xmin,'%b %d %H:%M:%S %Y')) if options.timeaxis else float(options.xmin)
954  if options.xmax!=None:
955  xmax = time.mktime(time.strptime(options.xmax,'%b %d %H:%M:%S %Y')) if options.timeaxis else float(options.xmax)
956  if options.ydef:
957  ymin = varDef(what,'min',-100)
958  ymax = varDef(what,'max',+100)
959  if options.ymin!=None:
960  ymin = options.ymin
961  if options.ymax!=None:
962  ymax = options.ymax
963 
964  # Axis settings
965  if options.timeaxis:
966  atit = ';%s;%s' % (timeLabel,varDef(what,'atit',what))
967  elif options.separation:
968  atit = ';%s;%s' % ('Nominal Separation [mm]',varDef(what,'atit',what))
969  else:
970  atit = ';%s;%s' % ('Luminosity block number',varDef(what,'atit',what))
971  frame = ROOTUtils.drawAxisFrame(xmin,xmax,ymin,ymax,atit)
972  if options.logy:
973  ROOT.gPad.SetLogy(options.logy)
974  if options.timeaxis:
975  xAxis = frame.GetXaxis()
976  xAxis.SetTimeDisplay(1)
977  if (xmax-xmin)/86400 < 1:
978  xAxis.SetTimeFormat('%H:%M')
979  else:
980  #d0 = ceil(xmin/86400) # day w/first tick mark
981  #d1 = floor(xmax/86400) # day w/last tick mark
982  #nTicks = d1-d0+1
983  #nDays = floor((xmax-xmin)/86400)
984  xAxis.SetTimeFormat('#splitline{%b %d}{%H:%M}')
985  xAxis.SetLabelOffset(0.025)
986  xAxis.SetTitleOffset(1.6)
987  if options.adatefmt:
988  xAxis.SetTimeFormat(options.adatefmt)
989  if options.ndivs:
990  xAxis.SetNdivisions(options.ndivs,0)
991  frame.LabelsOption('d','X') # Doesn't seem to work
992 
993  legendList = []
994 
995  # Show average
996  if options.ave:
997  calc.average()
998  dx = (xmax-xmin)/30
999  mean = calc.ave[0]
1000  if options.rms:
1001  error = calc.rms[0]
1002  else:
1003  error = calc.err[0]
1004  b = ROOTUtils.drawHorizontalBand(xmin+dx,xmax-dx,mean,error,centralLine=True)
1005  legendList.append([b,options.alegend,'FL'])
1006  legendList.append([None,'%s %s #pm %s %s' % (fmtVal(what,mean,True),varDef(what,'units'),
1007  fmtVal(what,error,True),varDef(what,'units')),''])
1008 
1009  # Loop over graphs for all scans
1010  styleFactory = ROOTUtils.StyleFactory()
1011  for scan in sorted(grDict.keys()):
1012  gr = grDict[scan]
1013 
1014  # Get and save TGraphErrors, if desired
1015  name = what if scan==0 else '%s-scanoverlay' % (what)
1016  tgraph = self.protect( gr.getTGraph(name) )
1017  if not tgraph:
1018  continue
1019  if options.tgraphfile:
1020  print ('Saving TGraphErrors',tgraph.GetName(),'to file',options.tgraphfile)
1021  tgraphfile = ROOT.TFile(options.tgraphfile,'UPDATE')
1022  tgraph.Write()
1023  tgraphfile.Close()
1024 
1025  # Draw data points
1026  if len(grDict)==1:
1027  tgraph.SetMarkerSize(options.msize if options.msize else 0.8)
1028  if options.plegend:
1029  legendList.append([tgraph,options.plegend,'PLE'])
1030  else:
1031  tgraph.SetMarkerColor(styleFactory.nextColorStyle())
1032  tgraph.SetMarkerStyle(styleFactory.nextMarkerStyle())
1033  tgraph.SetMarkerSize(options.msize if options.msize else 1.2)
1034  if len(legendList)<options.maxlegends:
1035  text = 'All' if scan==0 else 'scan %i - %i' % scan
1036  legendList.append([tgraph,text,'PLE'])
1037  tgraph.Draw('P')
1038 
1039  # Indicate if legend incomplete
1040  if len(grDict)>options.maxlegends:
1041  legendList.append([None,'...',''])
1042 
1043  # Fit data, if desired
1044  if options.fit and len(grDict)==1:
1045  ROOT.gStyle.SetOptFit(1111)
1046  legendList = [] # No legend to avoid crowding plot
1047  tgraph.Fit(options.fit,'','SAME',gr.xmin,gr.xmax)
1048 
1049  # Draw title and legend
1050  legendX = 0.6 if len(grDict)==1 else 0.8
1051  self.writeText(what,legendList,not options.public,legendX=legendX)
1052 
1053 
1054 
1055 #
1056 # Dump beam spot ntuple
1057 #
1058 if cmd=='dump' and len(args)==1:
1059  print()
1060  nt = getNt()
1061  for b in nt:
1062  b.dump(options.verbose)
1063  cmdOk = True
1064 
1065 
1066 #
1067 # Make LaTeX table of results
1068 #
1069 
1070 tableTemplate = r"""
1071 \documentclass[12pt,twoside]{article}
1072 \usepackage[landscape]{geometry}
1073 \RequirePackage{xspace}
1074 \def\lumposx {\ensuremath{\overline{x}_{\mathcal{L}}}\xspace}
1075 \def\lumposy {\ensuremath{\overline{y}_{\mathcal{L}}}\xspace}
1076 \def\lumposz {\ensuremath{\overline{z}_{\mathcal{L}}}\xspace}
1077 \def\lumsigx {\ensuremath{\sigma_{x{\mathcal L}}}\xspace}
1078 \def\lumsigy {\ensuremath{\sigma_{y{\mathcal L}}}\xspace}
1079 \def\lumsigz {\ensuremath{\sigma_{z{\mathcal L}}}\xspace}
1080 \def\lumtiltx {\ensuremath{\overline{x}_{\mathcal{L}}'}\xspace}
1081 \def\lumtilty {\ensuremath{\overline{y}_{\mathcal{L}}'}\xspace}
1082 \def\lumrhoxy {\ensuremath{\rho_{xy}}\xspace}
1083 \begin{document}
1084 
1085 \begin{table}[htbp]
1086 \begin{center}
1087 \begin{tabular}{%s}
1088 \hline \hline
1089 %s \\
1090 \hline \hline
1091 
1092 %s
1093 
1094 \hline \hline
1095 \end{tabular}
1096 \end{center}
1097 \end{table}
1098 
1099 \end{document}
1100 """
1101 
1102 if cmd=='maketable' and len(args)==1:
1103  if options.varlist is None:
1104  #varList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY','k']
1105  varList = ['status','posX','posY','posZ','sigmaX','sigmaY','sigmaZ','k']
1106  else:
1107  varList = options.varlist.split(',')
1108  nt = getNt()
1109  rows = []
1110  for b in nt:
1111  cols = []
1112  for v in varList:
1113  try:
1114  cols.append('%s $\pm$ %s' % (fmtVal(v,getattr(b,v),True,useAlternate=True),
1115  fmtVal(v,getattr(b,v+'Err'),True,useAlternate=True)))
1116  except:
1117  cols.append('%10s' % (fmtVal(v,getattr(b,v),True,useAlternate=True)))
1118  rows.append('%s \\\\' % ' & '.join(cols))
1119  print()
1120  print (tableTemplate % (len(varList)*'c',
1121  ' & '.join(['%s' % varDef(n,'latexheader',useAlternate=True) for n in varList]),
1122  '\n'.join(rows)))
1123  print()
1124  cmdOk = True
1125 
1126 
1127 #
1128 # Dump beam spot ntuple
1129 #
1130 if cmd=='inspect' and len(args)==1:
1131  print()
1132  nt = getNt()
1133  runInfo = {}
1134  for b in nt:
1135  r = b.run
1136  if not b.run in runInfo:
1137  runInfo[r] = {
1138  'lbStart': None,
1139  'lbEnd': None,
1140  'status': set(),
1141  'hasErrors': False,
1142  'hasCOOL' : False
1143  }
1144  if runInfo[r]['lbStart'] is None or b.lbStart<runInfo[r]['lbStart']: runInfo[r]['lbStart'] = b.lbStart
1145  if runInfo[r]['lbEnd'] is None or b.lbEnd>runInfo[r]['lbEnd']: runInfo[r]['lbEnd'] = b.lbEnd
1146  runInfo[r]['status'].add(b.status)
1147  if b.timeStart and b.timeEnd and b.fill: runInfo[r]['hasCOOL'] = True
1148  if b.posXErr: runInfo[r]['hasErrors'] = True
1149  for r in sorted(runInfo.keys()):
1150  print ('%6s [ %10i, %10i ] %7s %9s fit status = %s' % (r,
1151  runInfo[r]['lbStart'],
1152  runInfo[r]['lbEnd'],
1153  'hasCOOL' if runInfo[r]['hasCOOL'] else '',
1154  'hasErrors' if runInfo[r]['hasErrors'] else '',
1155  sorted(list(runInfo[r]['status']))))
1156  print()
1157  print ('%i runs found\n' % len(runInfo.keys()))
1158  cmdOk = True
1159 
1160 
1161 
1162 #
1163 # Merge beam spot finder ntuple into master beam spot ntuple
1164 #
1165 if cmd=='merge' and len(args)==2:
1166  srcNtClass = locals()[options.srctype]
1167  srcNt = srcNtClass(args[1],fullCorrelations=options.fullCorrelations)
1168  setCuts(srcNt)
1169  print ('\nImporting from '+srcNt.summary())
1170  print (srcNt.cutSummary())
1171  dstNt = ntClass(options.ntname,True,fullCorrelations=options.fullCorrelations)
1172  print ('\nMerging into '+dstNt.summary())
1173 
1174  totalEntries = 0
1175  totalVtxs = 0
1176  lbSize = 0
1177  allBSResultsInNt = []
1178  for b in srcNt:
1179  allBSResultsInNt.append( b )
1180  if b.status == 59:
1181  totalEntries += 1
1182  totalVtxs += b.nValid
1183  lbSize += b.lbEnd - b.lbStart
1184 
1185  if totalEntries == 0:
1186  totalEntries = 1
1187  averagenVtx = totalVtxs/totalEntries
1188  print ('Average Entries: '+ str(averagenVtx))
1189  averagenVtx *= 0.33
1190 
1191  lbSize = lbSize/totalEntries + 1
1192  print ('Average number of lb used for fit: '+ str( lbSize ))
1193 
1194  #Sort entries in order of lb number
1195  #allBSResultsInNt.sort(key=lambda x: x.lbStart, reverse=False)
1196  allBSResultsInNt.sort()
1197  if options.useAve:
1198  cleanUpLowStat( allBSResultsInNt, averagenVtx, lbSize * 10)
1199  allBSResultsInNt.sort()
1200  fillInMissingLbs(allBSResultsInNt, lbSize * 10)
1201 
1202  for b in allBSResultsInNt:
1203  if options.fillcooldata:
1204  b.fillDataFromCOOL()
1205  if options.pseudoLbFile:
1206  b.fillDataFromPseudoLb(options.pseudoLbFile, float(options.pseudoLbTimeUnit))
1207  if options.filldqdata:
1208  b.fillDataFromDQ()
1209  if not options.quiet:
1210  b.dump(options.verbose)
1211  dstNt.fill(b)
1212  cmdOk = True
1213 
1214 
1215 
1216 #
1217 # Calculate average of beam spot parameters
1218 #
1219 if cmd=='ave' and len(args)==1:
1220  nt = getNt()
1221  if options.varlist is None:
1222  #varList = 'posX,posY,posZ,sigmaX,sigmaY,sigmaZ,tiltX,tiltY,rhoXY,sigmaXY,k'
1223  varList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY']
1224  if options.cooltag:
1225  varList.append('sigmaXY')
1226  else:
1227  varList = options.varlist.split(',')
1228 
1229  # Summary plot for checks
1230  plots = Plots(nt)
1231  plots.whatList = varList
1232  plots.saveAsList = options.output.split(',')
1233  plots.allCanvasSize = 'landscape'
1234  plots.allCanvasDivs = (3,3)
1235  if options.hist:
1236  plots.genPlot('all','hist')
1237  if options.summary:
1238  plots.genPlot('all','plot')
1239  print()
1240 
1241  # Averages
1242  calc = BeamSpotAverage(varList,weightedAverage=not options.simpleaverage)
1243  if options.lumicalcnt is not None:
1244  calc.readLumiData(options.lumicalcnt)
1245  minrun=1e10
1246  maxrun=0
1247  for b in nt:
1248  if options.verbose or options.debug:
1249  b.dump(options.debug)
1250  calc.add(b)
1251  minrun = min(b.run,minrun)
1252  maxrun = max(b.run,maxrun)
1253  calc.average()
1254  ave = calc.ave
1255  err = calc.err
1256  rms = calc.rms
1257  if calc.nWarnings:
1258  print ('... %i warnings detected' % calc.nWarnings)
1259  if options.lumicalcnt is not None:
1260  print ('... integrated luminosity of selected runs = %6.1f / pb' % (calc.sumw[0]/1.E6))
1261  print()
1262  if options.splittable:
1263  varRanges = [ range(options.splittable),
1264  range(options.splittable,len(calc.varList)) ]
1265  else:
1266  varRanges = [ range(len(calc.varList)) ]
1267  if options.latex:
1268  for r in varRanges:
1269  try:
1270  iTable += 1
1271  except:
1272  iTable = 1
1273  latexheader = 'Period '
1274  latexrow = '%s' % options.period.replace('_','\_')
1275  print ('\nAverage beam spot parameters (part %i):\n' % iTable)
1276  for i in r:
1277  parName = calc.varList[i]
1278  print ('%7s: %s +- %s %-3s (RMS = %s)' % (parName,
1279  fmtVal(parName,ave[i]),
1280  fmtVal(parName,err[i]),
1281  varDef(parName,'units'),
1282  fmtVal(parName,rms[i])))
1283  latexheader += '& %s ' % varDef(parName,'latexheader',parName,useAlternate=True)
1284  if options.rms:
1285  latexrow += ' & %s $\pm$ %s' % (fmtVal(parName,ave[i],useAlternate=True),fmtVal(parName,rms[i],useAlternate=True))
1286  else:
1287  latexrow += ' & %s $\pm$ %s' % (fmtVal(parName,ave[i],useAlternate=True),fmtVal(parName,err[i],useAlternate=True))
1288  print()
1289  print ('\nLaTeX code for table %i:\n' % iTable)
1290  print ('\\begin{table}[htbp]\n\\begin{center}\n\\begin{tabular}{l%s}' % (len(r)*'c'))
1291  print ('\hline \hline')
1292  print (latexheader,'\\\\ \hline')
1293  print()
1294  print (latexrow,' \\\\')
1295  print()
1296  print ('\hline \hline')
1297  print ('\\end{tabular}\n\\end{center}\n\\caption{\\label{tab:}}\n\\end{table}')
1298  print()
1299  if options.cooltag and minrun<1e10:
1300  from InDetBeamSpotExample.COOLUtils import *
1301  sqliteFile= options.cooltag+'.db'
1302  folderHandle = openBeamSpotDbFile(sqliteFile,True)
1303 
1304  if not options.newave:
1305  print ('\nWriting average to COOL SQLite file %s (folder tag = %s) ...' % (sqliteFile,options.cooltag))
1306  writeBeamSpotEntry(folderHandle,tag=options.cooltag,
1307  status=0,
1308  posX=ave[calc.varList.index('posX')],
1309  posY=ave[calc.varList.index('posY')],
1310  posZ=ave[calc.varList.index('posZ')],
1311  sigmaX=ave[calc.varList.index('sigmaX')],
1312  sigmaY=ave[calc.varList.index('sigmaY')],
1313  sigmaZ=ave[calc.varList.index('sigmaZ')],
1314  tiltX=ave[calc.varList.index('tiltX')],
1315  tiltY=ave[calc.varList.index('tiltY')],
1316  sigmaXY=ave[calc.varList.index('sigmaXY')],
1317  posXErr=err[calc.varList.index('posX')],
1318  posYErr=err[calc.varList.index('posY')],
1319  posZErr=err[calc.varList.index('posZ')],
1320  sigmaXErr=err[calc.varList.index('sigmaX')],
1321  sigmaYErr=err[calc.varList.index('sigmaY')],
1322  sigmaZErr=err[calc.varList.index('sigmaZ')],
1323  tiltXErr=err[calc.varList.index('tiltX')],
1324  tiltYErr=err[calc.varList.index('tiltY')],
1325  sigmaXYErr=err[calc.varList.index('sigmaXY')])
1326 
1327  else:
1328  print ('\nWriting average and LB info to COOL SQLite file %s (folder tag = %s) ...' % (sqliteFile,"nominal"))
1329  writeBeamSpotEntry(folderHandle,tag="nominal",
1330  runMin=int(minrun),runMax=int(maxrun),
1331  status=0,
1332  posX=ave[calc.varList.index('posX')],
1333  posY=ave[calc.varList.index('posY')],
1334  posZ=ave[calc.varList.index('posZ')],
1335  sigmaX=ave[calc.varList.index('sigmaX')],
1336  sigmaY=ave[calc.varList.index('sigmaY')],
1337  sigmaZ=ave[calc.varList.index('sigmaZ')],
1338  tiltX=ave[calc.varList.index('tiltX')],
1339  tiltY=ave[calc.varList.index('tiltY')],
1340  sigmaXY=ave[calc.varList.index('sigmaXY')],
1341  posXErr=err[calc.varList.index('posX')],
1342  posYErr=err[calc.varList.index('posY')],
1343  posZErr=err[calc.varList.index('posZ')],
1344  sigmaXErr=err[calc.varList.index('sigmaX')],
1345  sigmaYErr=err[calc.varList.index('sigmaY')],
1346  sigmaZErr=err[calc.varList.index('sigmaZ')],
1347  tiltXErr=err[calc.varList.index('tiltX')],
1348  tiltYErr=err[calc.varList.index('tiltY')],
1349  sigmaXYErr=err[calc.varList.index('sigmaXY')])
1350 
1351  print ('Copying beam spot data from',options.ntname)
1352  for b in nt:
1353  if options.lbMin and options.lbMin>b.lbStart:
1354  continue
1355  if options.lbMax and options.lbMax<b.lbEnd+1:
1356  continue
1357  try:
1358  runEndInt = b.runEnd
1359  except AttributeError:
1360  runEndInt = b.run
1361 
1362  if b.status in nt.statusList:
1363  writeBeamSpotEntry(folderHandle,tag='nominal',
1364  runMin=b.run,
1365  runMax=runEndInt,
1366  lbMin=b.lbStart,
1367  lbMax=b.lbEnd, # Beware - lbMax is inclusive
1368  status=b.status,
1369  posX=b.posX, posY=b.posY, posZ=b.posZ,
1370  sigmaX=b.sigmaX, sigmaY=b.sigmaY, sigmaZ=b.sigmaZ,
1371  tiltX=b.tiltX, tiltY=b.tiltY,
1372  sigmaXY=b.rhoXY*b.sigmaX*b.sigmaY,
1373  posXErr=b.posXErr, posYErr=b.posYErr, posZErr=b.posZErr,
1374  sigmaXErr=b.sigmaXErr, sigmaYErr=b.sigmaYErr, sigmaZErr=b.sigmaZErr,
1375  tiltXErr=b.tiltXErr, tiltYErr=b.tiltYErr,
1376  sigmaXYErr=sqrt( (b.sigmaX*b.sigmaX) * (b.sigmaY*b.sigmaY) * (b.rhoXYErr*b.rhoXYErr) +(b.sigmaX*b.sigmaX) * (b.sigmaYErr*b.sigmaYErr) * (b.rhoXY*b.rhoXY) + (b.sigmaXErr*b.sigmaXErr) * (b.sigmaY*b.sigmaY) * (b.rhoXY*b.rhoXY) ) )
1377 
1378  cmdOk = True
1379 
1380 #
1381 # Different histograms of beam spot variables
1382 #
1383 if (cmd=='hist' or cmd=='histvspileup' or cmd=='pull') and len(args)==2:
1384  var = args[1]
1385  nt = getNt()
1386  plots = Plots(nt)
1387  plots.saveAsList = options.output.split(',')
1388  if options.canvas:
1389  plots.singleCanvasSize = options.canvas
1390  plots.allCanvasSize = options.canvas
1391  plots.allCanvasDivs = (options.xdivs,options.ydivs)
1392  if ',' in var:
1393  plots.whatList = var.split(',')
1394  plots.genPlot('all',cmd)
1395  else:
1396  plots.genPlot(var,cmd)
1397  cmdOk = True
1398 
1399 
1400 #
1401 # Plot of beam spot variables vs LB or time
1402 #
1403 if cmd=='plot' and len(args)==2:
1404  var = args[1]
1405  nt = getNt()
1406  plots = Plots(nt)
1407  plots.saveAsList = options.output.split(',')
1408  if options.canvas:
1409  plots.singleCanvasSize = options.canvas
1410  plots.allCanvasSize = options.canvas
1411  plots.allCanvasDivs = (options.xdivs,options.ydivs)
1412  if options.perbcid:
1413  plotType = 'perbcid'
1414  elif options.vsbunchpos:
1415  plotType = 'vsBunchPos'
1416  else:
1417  plotType = 'plot'
1418  if ',' in var:
1419  plots.whatList = var.split(',')
1420  plots.genPlot('all',plotType)
1421  else:
1422  plots.genPlot(var,plotType)
1423  cmdOk = True
1424 
1425 
1426 #
1427 # Summary history of beam spot variables
1428 #
1429 if cmd=='summary' and len(args)==1:
1430  nt = getNt()
1431  if not options.msize:
1432  options.msize = 0.5
1433  plots = Plots(nt)
1434  plots.saveAsList = options.output.split(',')
1435  plots.allCanvasSize = 'landscape'
1436 
1437  labels=[]
1438  if "COOL-Current" not in options.ntname:
1439  plots.allCanvasDivs = (4,3)
1440  plots.whatList = ['posX','posY','posZ','k','sigmaX','sigmaY','sigmaZ','nValid','tiltX','tiltY','rhoXY']
1441  datasetinfo=options.ntname.replace("-DB_BEAMSPOT","").split('.')
1442  labels=["%s.%s.%s.%s" % (datasetinfo[0],datasetinfo[1],datasetinfo[2],datasetinfo[3])]
1443  labels+=["Generated on %s, at %s (%s)" % (time.strftime("%x"), time.strftime("%X"), time.strftime("%Z"))]
1444  else:
1445  plots.allCanvasDivs = (3,3)
1446  plots.whatList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY']
1447 
1448  # add some labels to the empty pad
1449 
1450  if options.perbcid:
1451  plots.genPlot('all','perbcid',labels=labels)
1452  elif options.vsbunchpos:
1453  plots.whatList.remove('nValid')
1454  plots.genPlot('all','vsBunchPos',labels=labels)
1455  else:
1456  plots.genPlot('all','plot',labels=labels)
1457 
1458  cmdOk = True
1459 
1460 
1461 #
1462 # Plot of beam spot variables vs LB or time
1463 #
1464 if cmd=='ascii' and len(args)==2:
1465  time0 = 1262304000 # unix time for Jan 1, 2010, 00:00:00 CET
1466  ascii = open(args[1],'w')
1467  ascii.write('# Beam spot data file\n')
1468  ascii.write('# Generated %s by %s on host %s using command:\n' % (time.asctime(),getUserName(),getHostName()))
1469  ascii.write('# %s\n' % qcmd)
1470  nt = getNt()
1471  for b in nt:
1472  ascii.write('1 ') # IP number
1473  ascii.write('%s ' % str(b.fill))
1474  ascii.write('%s ' % str(b.timeStart - time0 + int((b.timeEnd-b.timeStart)/2))) # Time in sec since Jan 1, 2010
1475  ascii.write('%s ' % str(b.posX))
1476  ascii.write('%s ' % str(b.posXErr))
1477  ascii.write('%s ' % str(b.posY))
1478  ascii.write('%s ' % str(b.posYErr))
1479  ascii.write('%s ' % str(b.posZ))
1480  ascii.write('%s ' % str(b.posZErr))
1481  ascii.write('0 0 0 0 0 0 ') # No data from raw Gauss fit w/o subtracting vtx-resolution
1482  ascii.write('%s ' % str(b.sigmaX))
1483  ascii.write('%s ' % str(b.sigmaXErr))
1484  ascii.write('%s ' % str(b.sigmaY))
1485  ascii.write('%s ' % str(b.sigmaYErr))
1486  ascii.write('%s ' % str(b.sigmaZ))
1487  ascii.write('%s ' % str(b.sigmaZErr))
1488  ascii.write('0 0 0\n') # No RMS info
1489  ascii.close()
1490  cmdOk = True
1491 
1492 
1493 if cmd=='scan' and len(args)==1:
1494 
1495  if not options.msize:
1496  options.msize = 0.5
1497 
1498  if options.timeaxis:
1499  xtype = 'time'
1500  elif options.separation:
1501  xtype = 'sep'
1502  else:
1503  xtype = 'lb'
1504 
1505  # Plot summary plots for full scan
1506  nt = getNt()
1507 
1508  plots = Plots(nt)
1509  plots.allCanvasSize = 'landscape'
1510  plots.allCanvasDivs = (3,3)
1511  plots.whatList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY']
1512  plots.saveAsList = ['%s-scanfull-%s-all.gif' %(options.name,xtype),
1513  '%s-scanfull-%s-all.eps' %(options.name,xtype),]
1514 
1515  if options.separation and options.overlayScans:
1516  plots.genPlot('all','plotscan')
1517  else:
1518  plots.genPlot('all','plot')
1519 
1520  plots.whatList.append('k')
1521 
1522  # Individual plot for full scan
1523  plots.singleCanvasSize = 'wide'
1524  for var in plots.whatList:
1525  plots.saveAsList = ['%s-scanfull-%s-%s.gif' %(options.name,xtype,var),
1526  '%s-scanfull-%s-%s.eps' %(options.name,xtype,var) ]
1527  if options.separation and options.overlayScans:
1528  graphs = plots.genPlot(var,'plotscan')
1529  else:
1530  graphs = plots.genPlot(var,'plot')
1531 
1532 
1533  # Plots for each scan range
1534  if options.scans:
1535  scans = [(int(s.split('-')[0]), int(s.split('-')[1])) for s in options.scans.split(',')]
1536  else:
1537  scans = []
1538 
1539  options.overlayScans = False
1540  for (lbMin, lbMax) in scans:
1541 
1542  nt = getNt()
1543  nt.lbMin = lbMin
1544  nt.lbMax = lbMax
1545 
1546  # Summary plot for each scan range
1547  plots = Plots(nt)
1548  plots.allCanvasSize = 'landscape'
1549  plots.allCanvasDivs = (3,3)
1550  plots.whatList = ['posX','posY','posZ','sigmaX','sigmaY','sigmaZ','tiltX','tiltY','rhoXY']
1551  plots.saveAsList = ['%s-scan%s-%s-%s-all.gif' %(options.name,lbMin,lbMax,xtype),
1552  '%s-scan%s-%s-%s-all.eps' %(options.name,lbMin,lbMax,xtype) ]
1553  plots.genPlot('all','plot')
1554 
1555  plots.whatList.append('k')
1556 
1557  # Individual plot for each scan range
1558  plots.singleCanvasSize = 'default'
1559  for var in plots.whatList:
1560  plots.saveAsList = ['%s-scan%s-%s-%s-%s.gif' %(options.name,lbMin,lbMax,xtype,var),
1561  '%s-scan%s-%s-%s-%s.eps' %(options.name,lbMin,lbMax,xtype,var) ]
1562  graphs = plots.genPlot(var,'plot')
1563 
1564  cmdOk = True
1565 
1566 
1567 if not cmdOk:
1568  print ('ERROR: Illegal command or number of arguments')
1569  sys.exit(1)
read
IovVectorMap_t read(const Folder &theFolder, const SelectionCriterion &choice, const unsigned int limit=10)
Definition: openCoraCool.cxx:569
python.Utils.getHostName
def getHostName()
Definition: InnerDetector/InDetExample/InDetBeamSpotExample/python/Utils.py:60
ROOTUtils.drawText
def drawText(x=0.74, y=0.87, dy=0.06, text='', font=62, color=1, align=11, linesep=';')
Definition: roofit/ROOTUtils.py:243
BeamSpotData
max
#define max(a, b)
Definition: cfImp.cxx:41
beamspotnt.ntClass
ntClass
Definition: bin/beamspotnt.py:211
vtune_athena.format
format
Definition: vtune_athena.py:14
drawFromPickle.average
def average(lst)
Definition: drawFromPickle.py:38
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
plotBeamSpotCompare.varDef
dictionary varDef
Definition: plotBeamSpotCompare.py:25
ROOTUtils.drawAxisFrame
def drawAxisFrame(xmin, xmax, ymin, ymax, title='', xTitleOffset=None, yTitleOffset=None, doPlot=True, protectFrame=True)
Definition: roofit/ROOTUtils.py:213
ROOTUtils.setStyle
def setStyle(style=None)
Definition: roofit/ROOTUtils.py:413
beamspotnt.Plots.writeText
def writeText(self, var, legendList=[], showRuns=True, showFills=True, showTime=True, otherTitle=None, otherComment=None, legendX=0.6)
Definition: bin/beamspotnt.py:423
beamspotnt.Plots.perbcid
def perbcid(self, what)
Definition: bin/beamspotnt.py:759
ROOTUtils.atlasLabel
def atlasLabel(x, y, isPreliminary=False, color=1, offset=0.115, isForApproval=False, energy=8, customstring="", size=0.05)
Definition: roofit/ROOTUtils.py:303
ROOTUtils.PlotLibrary.protect
def protect(self, obj)
Definition: roofit/ROOTUtils.py:101
beamspotnt.Plots.nt
nt
Definition: bin/beamspotnt.py:420
python.COOLUtils.writeBeamSpotEntry
def writeBeamSpotEntry(folderHandle, tag='nominal', runMin=0, runMax=(1<< 31) -1, lbMin=0, lbMax=(1<< 32) -2, status=0, posX=0., posY=0., posZ=0., sigmaX=30., sigmaY=30., sigmaZ=500., tiltX=0., tiltY=0., sigmaXY=0., posXErr=0., posYErr=0., posZErr=0., sigmaXErr=0., sigmaYErr=0., sigmaZErr=0., tiltXErr=0., tiltYErr=0., sigmaXYErr=0.)
Definition: COOLUtils.py:63
Plots
set of generic plots
Definition: computils.h:913
python.BeamSpotData.fmtVal
def fmtVal(var, value, strip=False, useAlternate=False)
Definition: BeamSpotData.py:248
beamspotnt.Plots.__init__
def __init__(self, nt)
Definition: bin/beamspotnt.py:418
ROOTUtils.drawHorizontalBand
def drawHorizontalBand(xmin, xmax, y, ywidth, color=33, protectBand=True, centralLine=False)
Definition: roofit/ROOTUtils.py:227
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
beamspotnt.fillInMissingLbs
def fillInMissingLbs(allBSResultsInNt, lbSize)
Definition: bin/beamspotnt.py:360
beamspotnt.Plots.whatList
whatList
Definition: bin/beamspotnt.py:421
add
bool add(const std::string &hname, TKey *tobj)
Definition: fastadd.cxx:55
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
beamspotnt.cleanUpLowStat
def cleanUpLowStat(allBSResultsInNt, averagenVtx, lbSize)
Definition: bin/beamspotnt.py:280
beamspotnt.Plots.vsBunchPos
def vsBunchPos(self, what)
Definition: bin/beamspotnt.py:831
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename T::value_type > sorted(T begin, T end)
Helper function to create a sorted vector from an unsorted one.
CxxUtils::set
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
Definition: bitmask.h:232
min
#define min(a, b)
Definition: cfImp.cxx:40
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
beamspotnt.getNt
def getNt()
Definition: bin/beamspotnt.py:266
ROOTUtils.PlotLibrary.__init__
def __init__(self, name='MyPlots', otherMethods=[])
Definition: roofit/ROOTUtils.py:85
beamspotnt.srcNtClass
srcNtClass
Definition: bin/beamspotnt.py:1169
COOLUtils
ROOTUtils.PlotLibrary
Definition: roofit/ROOTUtils.py:77
beamspotnt.Plots.hist
def hist(self, what)
Definition: bin/beamspotnt.py:475
Trk::open
@ open
Definition: BinningType.h:40
beamspotnt.Plots.plotscan
def plotscan(self, what)
Definition: bin/beamspotnt.py:902
beamspotnt.Plots
Definition: bin/beamspotnt.py:416
beamspotnt.Plots.plot
def plot(self, what)
Definition: bin/beamspotnt.py:596
if
if(febId1==febId2)
Definition: LArRodBlockPhysicsV0.cxx:567
str
Definition: BTagTrackIpAccessor.cxx:11
python.COOLUtils.openBeamSpotDbFile
def openBeamSpotDbFile(fileName, forceNew=False, folderName='/Indet/Beampos', dbName='BEAMSPOT')
Definition: COOLUtils.py:22
beamspotnt.Plots.pull
def pull(self, what)
Definition: bin/beamspotnt.py:557
dbg::print
void print(std::FILE *stream, std::format_string< Args... > fmt, Args &&... args)
Definition: SGImplSvc.cxx:70
beamspotnt.setCuts
def setCuts(nt)
Definition: bin/beamspotnt.py:213
ROOTUtils.drawLegend
def drawLegend(x1, y1, x2, y2, legendList=[], fillColor=0, lineColor=0, textSize=None, protectLegend=True)
Definition: roofit/ROOTUtils.py:259
readCCLHist.float
float
Definition: readCCLHist.py:83
beamspotnt.Plots.histvspileup
def histvspileup(self, what)
Definition: bin/beamspotnt.py:516
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
ROOTUtils.StyleFactory
Definition: roofit/ROOTUtils.py:171
python.Utils.getUserName
def getUserName(default='UNKNOWN')
Definition: InnerDetector/InDetExample/InDetBeamSpotExample/python/Utils.py:48