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