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