CMS 3D CMS Logo

plotBeamSpotDB.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #____________________________________________________________
3 #
4 #
5 # A very simple way to make plots with ROOT via an XML file
6 #
7 # Francisco Yumiceva
8 # yumiceva@fnal.gov
9 #
10 # Fermilab, 2010
11 #
12 #____________________________________________________________
13 
14 """
15  plotBeamSpotDB
16 
17  A very simple script to plot the beam spot data stored in condDB
18 
19  usage: %prog -t <tag name>
20  -a, --auth = AUTH: DB authorization path. online(/nfshome0/popcondev/conddb).
21  -b, --batch : Run ROOT in batch mode.
22  -c, --create = CREATE: name for beam spot data file.
23  -d, --data = DATA: input beam spot data file.
24  -D, --destDB = DESTDB: destination DB string. online(oracle://cms_orcon_prod/CMS_COND_31X_BEAMSPOT).
25  -i, --initial = INITIAL: First IOV. Options: run number, or run:lumi, eg. \"133200:21\"
26  -f, --final = FINAL: Last IOV. Options: run number, or run:lumi
27  -g, --graph : create a TGraphError instead of a TH1 object
28  -n, --noplot : Only extract beam spot data, plots are not created..
29  -o, --output = OUTPUT: filename of ROOT file with plots.
30  -p, --payload = PAYLOAD: filename of output text file. Combine and splits lumi IOVs.
31  -P, --Print : create PNG plots from canvas.
32  -s, --suffix = SUFFIX: Suffix will be added to plots filename.
33  -t, --tag = TAG: Database tag name.
34  -T, --Time : create plots with time axis.
35  -I, --IOVbase = IOVBASE: options: runbase(default), lumibase, timebase
36  -w, --wait : Pause script after plotting a new histograms.
37  -W, --weighted : Create a weighted result for a range of lumi IOVs, skip lumi IOV combination and splitting.
38  -x, --xcrossing = XCROSSING : Bunch crossing number.
39 
40  Francisco Yumiceva (yumiceva@fnal.gov)
41  Fermilab 2010
42 
43 """
44 from __future__ import print_function
45 
46 
47 import os, string, re, sys, math
48 import commands, time
49 from BeamSpotObj import BeamSpot
50 from IOVObj import IOV
51 from CommonMethods import *
52 
53 try:
54  import ROOT
55 except:
56  print("\nCannot load PYROOT, make sure you have setup ROOT in the path")
57  print("and pyroot library is also defined in the variable PYTHONPATH, try:\n")
58  if (os.getenv("PYTHONPATH")):
59  print(" setenv PYTHONPATH ${PYTHONPATH}:$ROOTSYS/lib\n")
60  else:
61  print(" setenv PYTHONPATH $ROOTSYS/lib\n")
62  sys.exit()
63 
64 from ROOT import TFile, TGraphErrors, TGaxis, TDatime
65 from ROOT import TCanvas, TH1F
66 
67 # ROOT STYLE
68 #############################
69 def SetStyle():
70 
71  # canvas
72  ROOT.gStyle.SetCanvasBorderMode(0)
73  ROOT.gStyle.SetCanvasColor(0)
74  ROOT.gStyle.SetCanvasDefH(600)
75  ROOT.gStyle.SetCanvasDefW(600)
76  ROOT.gStyle.SetCanvasDefX(0)
77  ROOT.gStyle.SetCanvasDefY(0)
78  # pad
79  ROOT.gStyle.SetPadBorderMode(0)
80  ROOT.gStyle.SetPadColor(0)
81  ROOT.gStyle.SetPadGridX(False)
82  ROOT.gStyle.SetPadGridY(False)
83  ROOT.gStyle.SetGridColor(0)
84  ROOT.gStyle.SetGridStyle(3)
85  ROOT.gStyle.SetGridWidth(1)
86 
87  ROOT.gStyle.SetFrameBorderMode(0)
88  ROOT.gStyle.SetFrameFillColor(0)
89  ROOT.gStyle.SetTitleColor(1)
90  ROOT.gStyle.SetStatColor(0)
91 
92  # set the paper & margin sizes
93  ROOT.gStyle.SetPaperSize(20,26)
94  ROOT.gStyle.SetPadTopMargin(0.04)
95  ROOT.gStyle.SetPadRightMargin(0.04)
96  ROOT.gStyle.SetPadBottomMargin(0.14)
97  ROOT.gStyle.SetPadLeftMargin(0.11)
98  ROOT.gStyle.SetPadTickX(1)
99  ROOT.gStyle.SetPadTickY(1)
100 
101  ROOT.gStyle.SetTextFont(42) #132
102  ROOT.gStyle.SetTextSize(0.09)
103  ROOT.gStyle.SetLabelFont(42,"xyz")
104  ROOT.gStyle.SetTitleFont(42,"xyz")
105  ROOT.gStyle.SetLabelSize(0.035,"xyz")
106  ROOT.gStyle.SetTitleSize(0.045,"xyz")
107  ROOT.gStyle.SetTitleOffset(1.1,"y")
108 
109  # use bold lines and markers
110  ROOT.gStyle.SetMarkerStyle(8)
111  ROOT.gStyle.SetHistLineWidth(2)
112  ROOT.gStyle.SetLineWidth(1)
113  #ROOT.gStyle.SetLineStyleString(2,"[12 12]") // postscript dashes
114 
115  ROOT.gStyle.SetMarkerSize(0.6)
116 
117  # do not display any of the standard histogram decorations
118  ROOT.gStyle.SetOptTitle(0)
119  ROOT.gStyle.SetOptStat(0) #("m")
120  ROOT.gStyle.SetOptFit(0)
121 
122  #ROOT.gStyle.SetPalette(1,0)
123  ROOT.gStyle.cd()
124  ROOT.gROOT.ForceStyle()
125 #########################################
126 
127 
128 if __name__ == '__main__':
129 
130  # style
131  SetStyle()
132 
133  printCanvas = False
134  printFormat = "png"
135  printBanner = False
136  Banner = "CMS Preliminary"
137 
138  # COMMAND LINE OPTIONS
139  #################################
140  option,args = parse(__doc__)
141  if not args and not option: exit()
142 
143  tag = ''
144  if not option.tag and not option.data:
145  print(" need to provide DB tag name or beam spot data file")
146  exit()
147  else:
148  tag = option.tag
149 
150  if option.batch:
151  ROOT.gROOT.SetBatch()
152 
153  datafilename = "tmp_beamspot.dat"
154  if option.create:
155  datafilename = option.create
156 
157  getDBdata = True
158  if option.data:
159  getDBdata = False
160 
161  IOVbase = 'runbase'
162  if option.IOVbase:
163  if option.IOVbase != "runbase" and option.IOVbase != "lumibase" and option.IOVbase != "timebase":
164  print("\n\n unknown iov base option: "+ option.IOVbase +" \n\n\n")
165  exit()
166  IOVbase = option.IOVbase
167 
168  firstRun = "0"
169  lastRun = "4999999999"
170  if IOVbase == "lumibase":
171  firstRun = "0:0"
172  lastRun = "4999999999:4999999999"
173 
174  if option.initial:
175  firstRun = option.initial
176  if option.final:
177  lastRun = option.final
178 
179  # GET IOVs
180  ################################
181 
182  if getDBdata:
183 
184  print(" read DB to get list of IOVs for the given tag")
185  mydestdb = 'frontier://PromptProd/CMS_COND_31X_BEAMSPOT'
186  if option.destDB:
187  mydestdb = option.destDB
188  acommand = 'cmscond_list_iov -c '+mydestdb+' -P /afs/cern.ch/cms/DB/conddb -t '+ tag
189  tmpstatus = commands.getstatusoutput( acommand )
190  tmplistiov = tmpstatus[1].split('\n')
191  #print tmplistiov
192 
193  iovlist = []
194  passline = False
195  iline = jline = 0
196  totlines = len(tmplistiov)
197  for line in tmplistiov:
198 
199  if line.find('since') != -1:
200  passline = True
201  jline = iline
202  if passline and iline > jline and iline < totlines-1:
203  linedata = line.split()
204  #print linedata
205  aIOV = IOV()
206  aIOV.since = int(linedata[0])
207  aIOV.till = int(linedata[1])
208  iovlist.append( aIOV )
209  iline += 1
210 
211  print(" total number of IOVs = " + str(len(iovlist)))
212 
213 
214  # GET DATA
215  ################################
216 
217  otherArgs = ''
218  if option.destDB:
219  otherArgs = " -d " + option.destDB
220  if option.auth:
221  otherArgs = otherArgs + " -a "+ option.auth
222 
223  print(" get beam spot data from DB for IOVs. This can take a few minutes ...")
224 
225  tmpfile = open(datafilename,'w')
226 
227  for iIOV in iovlist:
228  passiov = False
229  tmprunfirst = firstRun
230  tmprunlast = lastRun
231  tmplumifirst = 1
232  tmplumilast = 9999999
233  if IOVbase=="lumibase":
234  #tmprunfirst = int(firstRun.split(":")[0])
235  #tmprunlast = int(lastRun.split(":")[0])
236  #tmplumifirst = int(firstRun.split(":")[1])
237  #tmplumilast = int(lastRun.split(":")[1])
238  tmprunfirst = pack( int(firstRun.split(":")[0]) , int(firstRun.split(":")[1]) )
239  tmprunlast = pack( int(lastRun.split(":")[0]) , int(lastRun.split(":")[1]) )
240  #print "since = " + str(iIOV.since) + " till = "+ str(iIOV.till)
241  if iIOV.since >= int(tmprunfirst) and int(tmprunlast) < 0 and iIOV.since <= int(tmprunfirst):
242  print(" IOV: " + str(iIOV.since))
243  passiov = True
244  if iIOV.since >= int(tmprunfirst) and int(tmprunlast) > 0 and iIOV.till <= int(tmprunlast):
245  print(" a IOV: " + str(iIOV.since) + " to " + str(iIOV.till))
246  passiov = True
247  #if iIOV.since >= int(tmprunlast) and iIOV.till >= 4294967295:
248  # print " b IOV: " + str(iIOV.since) + " to " + str(iIOV.till)
249  # passiov = True
250  if passiov:
251  acommand = 'getBeamSpotDB.py -t '+ tag + " -r " + str(iIOV.since) +otherArgs
252  if IOVbase=="lumibase":
253  tmprun = unpack(iIOV.since)[0]
254  tmplumi = unpack(iIOV.since)[1]
255  acommand = 'getBeamSpotDB.py -t '+ tag + " -r " + str(tmprun) +" -l "+str(tmplumi) +otherArgs
256  print(acommand)
257  status = commands.getstatusoutput( acommand )
258  tmpfile.write(status[1])
259 
260  print(" beam spot data collected and stored in file " + datafilename)
261 
262  tmpfile.close()
263 
264 
265  # PROCESS DATA
266  ###################################
267 
268  # check if input data exists if given
269  if option.data:
270  if os.path.isdir(option.data):
271  tmp = commands.getstatusoutput("ls "+option.data)
272  files = tmp[1].split()
273  datafilename = "combined_all.txt"
274  output = open(datafilename,"w")
275 
276  for f in files:
277  input = open(option.data +"/"+f)
278  output.writelines(input.readlines())
279  output.close()
280  print(" data files have been collected in "+datafilename)
281 
282  elif os.path.exists(option.data):
283  datafilename = option.data
284  else:
285  print(" input beam spot data DOES NOT exist, file " + option.data)
286  exit()
287 
288  listbeam = []
289 
290  if option.xcrossing:
291  listmap = readBeamSpotFile(datafilename,listbeam,IOVbase,firstRun,lastRun)
292  # bx
293  print("List of bunch crossings in the file:")
294  print(listmap.keys())
295  listbeam = listmap[option.Xrossing]
296  else:
297  readBeamSpotFile(datafilename,listbeam,IOVbase,firstRun,lastRun)
298 
299  sortAndCleanBeamList(listbeam,IOVbase)
300 
301  if IOVbase == "lumibase" and option.payload:
302  weighted = True;
303  if not option.weighted:
304  weighted = False
305  createWeightedPayloads(option.payload,listbeam,weighted)
306  if option.noplot:
307  print(" no plots requested, exit now.")
308  sys.exit()
309  # MAKE PLOTS
310  ###################################
311  TGaxis.SetMaxDigits(8)
312 
313  graphlist = []
314  graphnamelist = ['X','Y','Z','SigmaZ','dxdz','dydz','beamWidthX', 'beamWidthY']
315  graphtitlelist = ['beam spot X','beam spot Y','beam spot Z','beam spot #sigma_Z','beam spot dX/dZ','beam spot dY/dZ','beam width X','beam width Y']
316  graphXaxis = 'Run number'
317  if IOVbase == 'runbase':
318  graphXaxis = "Run number"
319  if IOVbase == 'lumibase':
320  graphXaxis = 'Lumi section'
321  if IOVbase == 'timebase' or option.Time:
322  graphXaxis = "Time"
323  #dh = ROOT.TDatime(2010,06,01,00,00,00)
324  ROOT.gStyle.SetTimeOffset(0) #dh.Convert())
325 
326  graphYaxis = ['beam spot X [cm]','beam spot Y [cm]','beam spot Z [cm]', 'beam spot #sigma_{Z} [cm]', 'beam spot dX/dZ', 'beam spot dY/dZ','beam width X [cm]', 'beam width Y [cm]']
327 
328  cvlist = []
329 
330  for ig in range(0,8):
331  cvlist.append( TCanvas(graphnamelist[ig],graphtitlelist[ig], 1200, 600) )
332  if option.graph:
333  graphlist.append( TGraphErrors( len(listbeam) ) )
334  else:
335  graphlist.append( TH1F("name","title",len(listbeam),0,len(listbeam)) )
336 
337  graphlist[ig].SetName(graphnamelist[ig])
338  graphlist[ig].SetTitle(graphtitlelist[ig])
339  ipoint = 0
340  for ii in range(0,len(listbeam)):
341 
342  ibeam = listbeam[ii]
343  datax = dataxerr = 0.
344  datay = datayerr = 0.
345  if graphnamelist[ig] == 'X':
346  datay = ibeam.X
347  datayerr = ibeam.Xerr
348  if graphnamelist[ig] == 'Y':
349  datay = ibeam.Y
350  datayerr = ibeam.Yerr
351  if graphnamelist[ig] == 'Z':
352  datay = ibeam.Z
353  datayerr = ibeam.Zerr
354  if graphnamelist[ig] == 'SigmaZ':
355  datay = ibeam.sigmaZ
356  datayerr = ibeam.sigmaZerr
357  if graphnamelist[ig] == 'dxdz':
358  datay = ibeam.dxdz
359  datayerr = ibeam.dxdzerr
360  if graphnamelist[ig] == 'dydz':
361  datay = ibeam.dydz
362  datayerr = ibeam.dydzerr
363  if graphnamelist[ig] == 'beamWidthX':
364  datay = ibeam.beamWidthX
365  datayerr = ibeam.beamWidthXerr
366  if graphnamelist[ig] == 'beamWidthY':
367  datay = ibeam.beamWidthY
368  datayerr = ibeam.beamWidthYerr
369 
370  datax = ibeam.IOVfirst
371  if IOVbase=="lumibase":
372  datax = str(ibeam.Run) + ":" + str(ibeam.IOVfirst)
373  if ibeam.IOVfirst != ibeam.IOVlast:
374  datax = str(ibeam.Run) + ":" + str(ibeam.IOVfirst)+"-"+str(ibeam.IOVlast)
375  #print datax
376  if option.graph:
377  if IOVbase=="lumibase":
378  #first = int( pack( int(ibeam.Run) , int(ibeam.IOVfirst) ) )
379  #last = int( pack( int(ibeam.Run) , int(ibeam.IOVlast) ) )
380  first = ibeam.IOVfirst
381  last = ibeam.IOVlast
382  if option.Time:
383  atime = ibeam.IOVBeginTime
384  first = time.mktime( time.strptime(atime.split()[0] + " " + atime.split()[1] + " " + atime.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
385  atime = ibeam.IOVEndTime
386  last = time.mktime( time.strptime(atime.split()[0] + " " + atime.split()[1] + " " + atime.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
387  da_first = TDatime(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(first - time.timezone)))
388  da_last = TDatime(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(last - time.timezone)))
389  if ipoint == 0:
390  ## print local time
391  da_first.Print()
392  ## print gmt time
393  print("GMT = " + str(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(first - time.timezone))))
394  reftime = first
395  ptm = time.localtime(reftime)
396  da = TDatime(time.strftime('%Y-%m-%d %H:%M:%S',ptm))
397  if time.daylight and ptm.tm_isdst:
398  offset_daylight = time.timezone - time.altzone
399  ROOT.gStyle.SetTimeOffset(da.Convert(1) - 3600)
400 
401  datax = (float(last) - float(first))/2 + float(first) - da.Convert() + 3600
402  ## Comment out this block if running on Mac ##
403  if time.daylight and ptm.tm_isdst:
404  datax += offset_daylight
405  ##################################
406 
407  dataxerr = (float(last) - float(first))/2
408  graphlist[ig].SetPoint(ipoint, float(datax), float(datay) )
409  graphlist[ig].SetPointError(ipoint, float(dataxerr), float(datayerr) )
410  else:
411  graphlist[ig].GetXaxis().SetBinLabel(ipoint +1 , str(datax) )
412  graphlist[ig].SetBinContent(ipoint +1, float(datay) )
413  graphlist[ig].SetBinError(ipoint +1, float(datayerr) )
414 
415  ipoint += 1
416  if option.Time:
417  ## print local time
418  da_last.Print()
419  print("GMT = " + str(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(last - time.timezone))))
420  graphlist[ig].GetXaxis().SetTimeDisplay(1);
421  graphlist[ig].GetXaxis().SetTimeFormat("#splitline{%Y/%m/%d}{%H:%M}")
422  if option.graph:
423  graphlist[ig].Draw('AP')
424  else:
425  graphlist[ig].Draw('P E1 X0')
426  graphlist[ig].GetXaxis().SetTitle(graphXaxis)
427  graphlist[ig].GetYaxis().SetTitle(graphYaxis[ig])
428  #graphlist[ig].Fit('pol1')
429  cvlist[ig].Update()
430  cvlist[ig].SetGrid()
431  if option.Print:
432  suffix = ''
433  if option.suffix:
434  suffix = option.suffix
435  cvlist[ig].Print(graphnamelist[ig]+"_"+suffix+".png")
436  if option.wait:
437  raw_input( 'Press ENTER to continue\n ' )
438  #graphlist[0].Print('all')
439 
440  if option.output:
441  outroot = TFile(option.output,"RECREATE")
442  for ig in graphlist:
443  ig.Write()
444 
445  outroot.Close()
446  print(" plots have been written to "+option.output)
447 
448 
449 
450  # CLEAN temporal files
451  ###################################
452  #os.system('rm tmp_beamspotdata.log')
def pack(high, low)
def readBeamSpotFile(fileName, listbeam=[], IOVbase="runbase", firstRun='1', lastRun='4999999999')
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def createWeightedPayloads(fileName, listbeam=[], weighted=True)
CREATE FILE FOR PAYLOADS.
def sortAndCleanBeamList(listbeam=[], IOVbase="lumibase")
Sort and clean list of data for consecutive duplicates and bad fits.
def parse(path, config)
Definition: dumpparser.py:13
#define str(s)
double split
Definition: MVATrainer.cc:139