CMS 3D CMS Logo

ntuplemaker.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  ntuplemaker
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  -o, --output = OUTPUT: filename of ROOT file with plots.
28  -x, --xcrossing = XCROSSING : Bunch crossing number.
29 
30  Francisco Yumiceva (yumiceva@fnal.gov)
31  Fermilab 2010
32 
33 """
34 from __future__ import print_function
35 
36 
37 import os, string, re, sys, math
38 import commands, time
39 from BeamSpotObj import BeamSpot
40 from IOVObj import IOV
41 from CommonMethods import *
42 
43 try:
44  import ROOT
45 except:
46  print("\nCannot load PYROOT, make sure you have setup ROOT in the path")
47  print("and pyroot library is also defined in the variable PYTHONPATH, try:\n")
48  if (os.getenv("PYTHONPATH")):
49  print(" setenv PYTHONPATH ${PYTHONPATH}:$ROOTSYS/lib\n")
50  else:
51  print(" setenv PYTHONPATH $ROOTSYS/lib\n")
52  sys.exit()
53 
54 from ROOT import *
55 from array import array
56 
57 def getFill( json, run ):
58 
59  thefill = 0
60  run = int(run)
61  keys = json.keys()
62 
63  for i in keys:
64 
65  run0 = int(json[i][0])
66  run1 = int(json[i][1])
67  if run>= run0 and run<=run1:
68  thefill = i
69 
70  return int(thefill)
71 
72 if __name__ == '__main__':
73 
74 
75 
76  # fill and runs
77  FillList = {}
78  runsfile = open("FillandRuns.txt")
79  for line in runsfile:
80  if line.find('fill:') != -1:
81  aline = line.split()
82  afill = aline[1]
83  run0 = aline[3]
84  run1 = aline[5]
85  FillList[int(afill)] = [int(run0),int(run1)]
86 
87  #print FillList
88 
89  # create ntuple
90  gROOT.ProcessLine(
91  "struct spot {\
92  Float_t position[3];\
93  Float_t posError[3];\
94  Float_t width[3];\
95  Float_t widthError[3];\
96  Float_t slope[2];\
97  Float_t slopeError[2];\
98  Float_t time[2];\
99  Int_t run;\
100  Int_t lumi[2];\
101  Int_t fill;\
102  };" );
103 
104  bntuple = spot()
105  fntuple = TFile( 'bntuple.root', 'RECREATE' )
106  tbylumi = TTree( 'bylumi', 'beam spot data lumi by lumi' )
107  tbylumi.Branch('fill', AddressOf( bntuple, 'fill'), 'fill/I' )
108  tbylumi.Branch('run', AddressOf( bntuple, 'run'), 'run/I' )
109  tbylumi.Branch('lumi', AddressOf( bntuple, 'lumi'), 'lumi[2]/I' )
110  tbylumi.Branch('position', AddressOf( bntuple, 'position'),'position[3]/F')
111  tbylumi.Branch('posErr', AddressOf( bntuple, 'posError'),'posError[3]/F')
112  tbylumi.Branch('width', AddressOf( bntuple, 'width'),'width[3]/F')
113  tbylumi.Branch('widthErr', AddressOf( bntuple, 'widthError'),'widthError[3]/F')
114  tbylumi.Branch('slope', AddressOf( bntuple, 'slope'),'slope[2]/F')
115  tbylumi.Branch('slopeErr', AddressOf( bntuple, 'slopeError'),'slopeError[2]/F')
116  tbylumi.Branch('time', AddressOf( bntuple, 'time'),'time[2]/F')
117 
118  tbyIOV = TTree( 'byIOV', 'beam spot data by IOV' )
119  tbyIOV.Branch('fill', AddressOf( bntuple, 'fill'), 'fill/I' )
120  tbyIOV.Branch('run', AddressOf( bntuple, 'run'), 'run/I' )
121  tbyIOV.Branch('lumi', AddressOf( bntuple, 'lumi'), 'lumi[2]/I' )
122  tbyIOV.Branch('position', AddressOf( bntuple, 'position'),'position[3]/F')
123  tbyIOV.Branch('posErr', AddressOf( bntuple, 'posError'),'posError[3]/F')
124  tbyIOV.Branch('width', AddressOf( bntuple, 'width'),'width[3]/F')
125  tbyIOV.Branch('widthErr', AddressOf( bntuple, 'widthError'),'widthError[3]/F')
126  tbyIOV.Branch('slope', AddressOf( bntuple, 'slope'),'slope[2]/F')
127  tbyIOV.Branch('slopeErr', AddressOf( bntuple, 'slopeError'),'slopeError[2]/F')
128  tbyIOV.Branch('time', AddressOf( bntuple, 'time'),'time[2]/F')
129 
130  tbyrun = TTree( 'byrun', 'beam spot data by run' )
131  tbyrun.Branch('fill', AddressOf( bntuple, 'fill'), 'fill/I' )
132  tbyrun.Branch('run', AddressOf( bntuple, 'run'), 'run/I' )
133  tbyrun.Branch('lumi', AddressOf( bntuple, 'lumi'), 'lumi[2]/I' )
134  tbyrun.Branch('position', AddressOf( bntuple, 'position'),'position[3]/F')
135  tbyrun.Branch('posErr', AddressOf( bntuple, 'posError'),'posError[3]/F')
136  tbyrun.Branch('width', AddressOf( bntuple, 'width'),'width[3]/F')
137  tbyrun.Branch('widthErr', AddressOf( bntuple, 'widthError'),'widthError[3]/F')
138  tbyrun.Branch('slope', AddressOf( bntuple, 'slope'),'slope[2]/F')
139  tbyrun.Branch('slopeErr', AddressOf( bntuple, 'slopeError'),'slopeError[2]/F')
140  tbyrun.Branch('time', AddressOf( bntuple, 'time'),'time[2]/F')
141 
142 
143  # COMMAND LINE OPTIONS
144  #################################
145  option,args = parse(__doc__)
146  if not args and not option: exit()
147 
148  if not option.data:
149  print(" need to provide beam spot data file")
150  exit()
151 
152  if option.batch:
153  ROOT.gROOT.SetBatch()
154 
155  datafilename = "tmp_beamspot.dat"
156  if option.create:
157  datafilename = option.create
158 
159  getDBdata = True
160  if option.data:
161  getDBdata = False
162 
163  IOVbase = 'lumibase'
164  firstRun = "0:0"
165  lastRun = "4999999999:4999999999"
166 
167  if option.initial:
168  firstRun = option.initial
169  if option.final:
170  lastRun = option.final
171 
172  # GET IOVs
173  ################################
174 
175  if getDBdata:
176 
177  print(" read DB to get list of IOVs for the given tag")
178  acommand = 'cmscond_list_iov -c frontier://PromptProd/CMS_COND_31X_BEAMSPOT -P /afs/cern.ch/cms/DB/conddb -t '+ tag
179  tmpstatus = commands.getstatusoutput( acommand )
180  tmplistiov = tmpstatus[1].split('\n')
181  #print tmplistiov
182 
183  iovlist = []
184  passline = False
185  iline = jline = 0
186  totlines = len(tmplistiov)
187  for line in tmplistiov:
188 
189  if line.find('since') != -1:
190  passline = True
191  jline = iline
192  if passline and iline > jline and iline < totlines-1:
193  linedata = line.split()
194  #print linedata
195  aIOV = IOV()
196  aIOV.since = int(linedata[0])
197  aIOV.till = int(linedata[1])
198  iovlist.append( aIOV )
199  iline += 1
200 
201  print(" total number of IOVs = " + str(len(iovlist)))
202 
203 
204  # GET DATA
205  ################################
206 
207  otherArgs = ''
208  if option.destDB:
209  otherArgs = " -d " + option.destDB
210  if option.auth:
211  otherArgs = otherArgs + " -a "+ option.auth
212 
213  print(" get beam spot data from DB for IOVs. This can take a few minutes ...")
214 
215  tmpfile = open(datafilename,'w')
216 
217  for iIOV in iovlist:
218  passiov = False
219  tmprunfirst = firstRun
220  tmprunlast = lastRun
221  tmplumifirst = 1
222  tmplumilast = 9999999
223  if IOVbase=="lumibase":
224  #tmprunfirst = int(firstRun.split(":")[0])
225  #tmprunlast = int(lastRun.split(":")[0])
226  #tmplumifirst = int(firstRun.split(":")[1])
227  #tmplumilast = int(lastRun.split(":")[1])
228  tmprunfirst = pack( int(firstRun.split(":")[0]) , int(firstRun.split(":")[1]) )
229  tmprunlast = pack( int(lastRun.split(":")[0]) , int(lasstRun.split(":")[1]) )
230  #print "since = " + str(iIOV.since) + " till = "+ str(iIOV.till)
231  if iIOV.since >= int(tmprunfirst) and int(tmprunlast) < 0 and iIOV.since <= int(tmprunfirst):
232  print(" IOV: " + str(iIOV.since))
233  passiov = True
234  if iIOV.since >= int(tmprunfirst) and int(tmprunlast) > 0 and iIOV.till <= int(tmprunlast):
235  print(" IOV: " + str(iIOV.since) + " to " + str(iIOV.till))
236  passiov = True
237  if iIOV.since >= int(tmprunlast) and iIOV.till >= 4294967295:
238  print(" IOV: " + str(iIOV.since) + " to " + str(iIOV.till))
239  passiov = True
240  if passiov:
241  acommand = 'getBeamSpotDB.py -t '+ tag + " -r " + str(iIOV.since) +otherArgs
242  if IOVbase=="lumibase":
243  tmprun = unpack(iIOV.since)[0]
244  tmplumi = unpack(iIOV.since)[1]
245  acommand = 'getBeamSpotDB.py -t '+ tag + " -r " + str(tmprun) +" -l "+tmplumi +otherArgs
246  status = commands.getstatusoutput( acommand )
247  tmpfile.write(status[1])
248 
249  print(" beam spot data collected and stored in file " + datafilename)
250 
251  tmpfile.close()
252 
253 
254  # PROCESS DATA
255  ###################################
256 
257  # check if input data exists if given
258  if option.data:
259  if os.path.isdir(option.data):
260  tmp = commands.getstatusoutput("ls "+option.data)
261  files = tmp[1].split()
262  datafilename = "combined_all.txt"
263  output = open(datafilename,"w")
264 
265  for f in files:
266  if os.path.isdir(option.data+"/"+f) is False:
267  input = open(option.data +"/"+f)
268  output.writelines(input.readlines())
269  output.close()
270  print(" data files have been collected in "+datafilename)
271 
272  elif os.path.exists(option.data):
273  datafilename = option.data
274  else:
275  print(" input beam spot data DOES NOT exist, file " + option.data)
276  exit()
277 
278  listbeam = []
279 
280  if option.xcrossing:
281  listmap = readBeamSpotFile(datafilename,listbeam,IOVbase,firstRun,lastRun)
282  # bx
283  print("List of bunch crossings in the file:")
284  print(listmap.keys())
285  listbeam = listmap[option.Xrossing]
286  else:
287  readBeamSpotFile(datafilename,listbeam,IOVbase,firstRun,lastRun)
288 
289  sortAndCleanBeamList(listbeam,IOVbase)
290 
291 
292  ###################################
293 
294  for ii in range(0,len(listbeam)):
295 
296  ibeam = listbeam[ii]
297 
298  bntuple.position = array('f', [float(ibeam.X), float(ibeam.Y), float(ibeam.Z)])
299  bntuple.posError = array('f', [float(ibeam.Xerr),float(ibeam.Yerr),float(ibeam.Zerr)])
300  bntuple.width = array('f', [float(ibeam.beamWidthX), float(ibeam.beamWidthY), float(ibeam.sigmaZ)])
301  bntuple.widthError = array('f',[float(ibeam.beamWidthXerr),float(ibeam.beamWidthYerr),float(ibeam.sigmaZerr)])
302  bntuple.run = int(ibeam.Run)
303  bntuple.fill = int( getFill( FillList, int(ibeam.Run) ) )
304  bntuple.lumi = array('i', [int(ibeam.IOVfirst),int(ibeam.IOVlast)])
305  line = ibeam.IOVBeginTime
306  begintime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
307  line = ibeam.IOVEndTime
308  endtime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
309  bntuple.time = array('f', [begintime, endtime])
310  tbylumi.Fill()
311 
312 
313  iovlist = listbeam
314  iovlist = createWeightedPayloads("tmp.txt",iovlist,False)
315 
316  for ii in range(0,len(iovlist)):
317 
318  ibeam = iovlist[ii]
319 
320  bntuple.position = array('f', [float(ibeam.X), float(ibeam.Y), float(ibeam.Z)])
321  bntuple.posError = array('f', [float(ibeam.Xerr),float(ibeam.Yerr),float(ibeam.Zerr)])
322  bntuple.width = array('f', [float(ibeam.beamWidthX), float(ibeam.beamWidthY), float(ibeam.sigmaZ)])
323  bntuple.widthError = array('f',[float(ibeam.beamWidthXerr),float(ibeam.beamWidthYerr),float(ibeam.sigmaZerr)])
324  bntuple.run = int(ibeam.Run)
325  bntuple.fill = int( getFill( FillList, int(ibeam.Run) ) )
326  bntuple.lumi = array('i', [int(ibeam.IOVfirst),int(ibeam.IOVlast)])
327  line = ibeam.IOVBeginTime
328  begintime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
329  line = ibeam.IOVEndTime
330  endtime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
331  bntuple.time = array('f', [begintime, endtime])
332 
333  tbyIOV.Fill()
334 
335  weightedlist = listbeam
336  weightedlist = createWeightedPayloads("tmp.txt",weightedlist,True)
337 
338  for ii in range(0,len(weightedlist)):
339 
340  ibeam = weightedlist[ii]
341 
342  bntuple.position = array('f', [float(ibeam.X), float(ibeam.Y), float(ibeam.Z)])
343  bntuple.posError = array('f', [float(ibeam.Xerr),float(ibeam.Yerr),float(ibeam.Zerr)])
344  bntuple.width = array('f', [float(ibeam.beamWidthX), float(ibeam.beamWidthY), float(ibeam.sigmaZ)])
345  bntuple.widthError = array('f',[float(ibeam.beamWidthXerr),float(ibeam.beamWidthYerr),float(ibeam.sigmaZerr)])
346  bntuple.run = int(ibeam.Run)
347  bntuple.fill = int( getFill( FillList, int(ibeam.Run) ) )
348  bntuple.lumi = array('i', [int(ibeam.IOVfirst),int(ibeam.IOVlast)])
349  line = ibeam.IOVBeginTime
350  begintime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
351  line = ibeam.IOVEndTime
352  endtime = time.mktime( time.strptime(line.split()[0] + " " + line.split()[1] + " " + line.split()[2],"%Y.%m.%d %H:%M:%S %Z") )
353  bntuple.time = array('f', [begintime, endtime])
354 
355  tbyrun.Fill()
356 
357 
358  os.system('rm tmp.txt')
359  fntuple.cd()
360  tbylumi.Write()
361  tbyIOV.Write()
362  tbyrun.Write()
363  fntuple.Close()
364 
365  # CLEAN temporal files
366  ###################################
367  #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
def getFill(json, run)
Definition: ntuplemaker.py:57
#define str(s)
double split
Definition: MVATrainer.cc:139