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