CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
lumiPatch.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 VERSION='1.00'
3 import os,sys,datetime
4 import coral
5 from RecoLuminosity.LumiDB import argparse,selectionParser,csvSelectionParser
6 
7 '''
8 --on wbm db
9 select LUMISEGMENTNR,DEADTIMEBEAMACTIVE from cms_wbm.LEVEL1_TRIGGER_CONDITIONS where RUNNUMBER=:runnumber order by LUMISEGMENTNR;
10 --on lumidb
11 update TRG set DEADTIME=:deadtimebeamactive where RUNNUM=:runnum and CMSLSNUM=:lsnum
12 --reapply calibration to inst lumi
13 update LUMISUMMARY set INSTLUMI=1.006319*INSTLUMI where RUNNUM in (1,3,57,90)
14 '''
15 
16 class constants(object):
17  def __init__(self):
18  self.debug=False
19  self.isdryrun=None
20  self.runinfoschema='CMS_RUNINFO'
21  self.wbmschema='CMS_WBM'
22  self.wbmdeadtable='LEVEL1_TRIGGER_CONDITIONS'
23  self.gtmonschema='CMS_GT_MON'
24  self.gtdeadview='GT_MON_TRIG_DEAD_VIEW'
25  self.lumitrgtable='TRG'
26  self.lumisummarytable='LUMISUMMARY'
27  self.runsummarytable='CMSRUNSUMMARY'
28 def missingTimeRuns(dbsession,c):
29  '''return all the runs with starttime or stoptime column NULL in lumi db
30  select runnum from CMSRUNSUMMARY where starttime is NULL or stoptime is NULL
31  '''
32  result=[]
33  try:
34  emptyBindVarList=coral.AttributeList()
35  dbsession.transaction().start(True)
36  schema=dbsession.nominalSchema()
37  if not schema:
38  raise 'cannot connect to schema '
39  if not schema.existsTable(c.runsummarytable):
40  raise 'non-existing table '+c.runsummarytable
41  query=schema.newQuery()
42  query.addToTableList(c.runsummarytable)
43  query.addToOutputList('RUNNUM','runnum')
44  query.setCondition('STARTTIME IS NULL AND STOPTIME IS NULL',emptyBindVarList)
45  query.addToOrderList('runnum')
46  queryOutput=coral.AttributeList()
47  queryOutput.extend('runnum','unsigned int')
48  query.defineOutput(queryOutput)
49  cursor=query.execute()
50  while next(cursor):
51  result.append(cursor.currentRow()['runnum'].data())
52  del query
53  dbsession.transaction().commit()
54  except Exception as e:
55  print str(e)
56  dbsession.transaction().rollback()
57  del dbsession
58  return result
59 def getTimeForRun(dbsession,c,runnums):
60  '''
61  get start stop time of run from runinfo database
62  select time from cms_runinfo.runsession_parameter where runnumber=:runnum and name='CMS.LVL0:START_TIME_T';
63  select time from cms_runinfo.runsession_parameter where runnumber=:runnum and name='CMS.LVL0:STOP_TIME_T';
64  '''
65  result={}#{runnum:(starttime,stoptime)}
66  tableName='RUNSESSION_PARAMETER'
67  try:
68  dbsession.transaction().start(True)
69  schema=dbsession.nominalSchema()
70  if not schema:
71  raise 'cannot connect to schema '
72  if not schema.existsTable(tableName):
73  raise 'non-existing table '+tableName
74 
75  startTime=''
76  stopTime=''
77  for runnum in runnums:
78  startTQuery=schema.newQuery()
79  startTQuery.addToTableList(tableName)
80  startTQuery.addToOutputList('TIME','starttime')
81  stopTQuery=schema.newQuery()
82  stopTQuery.addToTableList(tableName)
83  stopTQuery.addToOutputList('TIME','stoptime')
84  startTQueryCondition=coral.AttributeList()
85  stopTQueryCondition=coral.AttributeList()
86  startTQueryOutput=coral.AttributeList()
87  stopTQueryOutput=coral.AttributeList()
88  startTQueryCondition.extend('runnum','unsigned int')
89  startTQueryCondition.extend('name','string')
90  startTQueryOutput.extend('starttime','time stamp')
91  stopTQueryCondition.extend('runnum','unsigned int')
92  stopTQueryCondition.extend('name','string')
93  stopTQueryOutput.extend('stoptime','time stamp')
94  startTQueryCondition['runnum'].setData(int(runnum))
95  startTQueryCondition['name'].setData('CMS.LVL0:START_TIME_T')
96  startTQuery.setCondition('RUNNUMBER=:runnum AND NAME=:name',startTQueryCondition)
97  startTQuery.defineOutput(startTQueryOutput)
98  startTCursor=startTQuery.execute()
99  while next(startTCursor):
100  startTime=startTCursor.currentRow()['starttime'].data()
101  stopTQueryCondition['runnum'].setData(int(runnum))
102  stopTQueryCondition['name'].setData('CMS.LVL0:STOP_TIME_T')
103  stopTQuery.setCondition('RUNNUMBER=:runnum AND NAME=:name',stopTQueryCondition)
104  stopTQuery.defineOutput(stopTQueryOutput)
105  stopTCursor=stopTQuery.execute()
106  while next(stopTCursor):
107  stopTime=stopTCursor.currentRow()['stoptime'].data()
108  if not startTime or not stopTime:
109  print 'Warning: no startTime or stopTime found for run ',runnum
110  else:
111  result[runnum]=(startTime,stopTime)
112  del startTQuery
113  del stopTQuery
114  dbsession.transaction().commit()
115  except Exception as e:
116  print str(e)
117  dbsession.transaction().rollback()
118  del dbsession
119  return result
120 
121 def addTimeForRun(dbsession,c,runtimedict):
122  '''
123  Input runtimedict{runnumber:(startTimeT,stopTimeT)}
124  update CMSRUNSUMMARY set STARTTIME=:starttime,STOPTIME=:stoptime where RUNNUM=:runnum
125  #update CMSRUNSUMMARY set STOPTIME=:stoptime where RUNNUM=:runnum
126  '''
127  nchanged=0
128  totalchanged=0
129  try:
130  dbsession.transaction().start(False)
131  schema=dbsession.nominalSchema()
132  if not schema:
133  raise 'cannot connect to schema'
134  if not schema.existsTable(c.runsummarytable):
135  raise 'non-existing table '+c.runsummarytable
136  inputData=coral.AttributeList()
137  inputData.extend('starttime','time stamp')
138  inputData.extend('stoptime','time stamp')
139  inputData.extend('runnum','unsigned int')
140  runs=runtimedict.keys()
141  runs.sort()
142  for runnum in runs:
143  (startTimeT,stopTimeT)=runtimedict[runnum]
144  inputData['starttime'].setData(startTimeT)
145  inputData['stoptime'].setData(stopTimeT)
146  inputData['runnum'].setData(int(runnum))
147  nchanged=schema.tableHandle(c.runsummarytable).dataEditor().updateRows('STARTTIME=:starttime,STOPTIME=:stoptime','RUNNUM=:runnum',inputData)
148  print 'run '+str(runnum)+' update '+str(nchanged)+' row with starttime ,stoptime'
149  print startTimeT,stopTimeT
150  totalchanged=totalchanged+nchanged
151  if c.isdryrun:
152  dbsession.transaction().rollback()
153  else:
154  dbsession.transaction().commit()
155  except Exception as e:
156  print str(e)
157  dbsession.transaction().rollback()
158  del dbsession
159  print 'total number of rows changed: ',totalchanged
160 
161 def recalibrateLumiForRun(dbsession,c,delta,runnums):
162  '''
163  update LUMISUMMARY set INSTLUMI=:delta*INSTLUMI where RUNNUM in (1,3,57,90)
164  '''
165  updaterows=0
166  try:
167  dbsession.transaction().start(False)
168  schema=dbsession.nominalSchema()
169  if not schema:
170  raise 'cannot connect to schema'
171  if not schema.existsTable(c.lumisummarytable):
172  raise 'non-existing table '+c.lumisummarytable
173  runliststring=','.join([str(x) for x in runnums])
174  print 'applying delta '+delta+' on run list '+runliststring
175  nchanged=0
176  inputData=coral.AttributeList()
177  inputData.extend('delta','float')
178  inputData['delta'].setData(float(delta))
179  nchanged=schema.tableHandle(c.lumisummarytable).dataEditor().updateRows('INSTLUMI=INSTLUMI*:delta','RUNNUM in ('+runliststring+')',inputData)
180  print 'total number of row changed ',nchanged
181  if c.isdryrun:
182  dbsession.transaction().rollback()
183  else:
184  dbsession.transaction().commit()
185  return nchanged
186  except Exception as e:
187  print str(e)
188  dbsession.transaction().rollback()
189  del dbsession
190 
191 def GTdeadtimeBeamActiveForRun(dbsession,c,runnum):
192  '''
193  select lsnr,counts from cms_gt_mon.gt_mon_trig_dead_view where runnr=:runnumber and deadcounter='DeadtimeBeamActive' order by lsnr;
194  return result{lumisection:deadtimebeamactive}
195 
196  '''
197  result={}
198  try:
199  dbsession.transaction().start(True)
200  schema=dbsession.schema(c.gtmonschema)
201 
202  if not schema:
203  raise Exception('cannot connect to schema '+c.gtmonschema)
204  if not schema.existsView(c.gtdeadview):
205  raise Exception('non-existing view '+c.gtdeadview)
206 
207  deadOutput=coral.AttributeList()
208  deadOutput.extend("lsnr","unsigned int")
209  deadOutput.extend("deadcount","unsigned long long")
210 
211  deadBindVarList=coral.AttributeList()
212  deadBindVarList.extend("runnumber","unsigned int")
213  deadBindVarList.extend("countername","string")
214  deadBindVarList["runnumber"].setData(int(runnum))
215  deadBindVarList["countername"].setData('DeadtimeBeamActive')
216 
217  query=schema.newQuery()
218  query.addToTableList(c.gtdeadview)
219  query.addToOutputList('LSNR','lsnr')
220  query.addToOutputList('COUNTS','deadcount')
221  query.setCondition('RUNNR=:runnumber AND DEADCOUNTER=:countername',deadBindVarList)
222  query.addToOrderList('lsnr')
223  query.defineOutput(deadOutput)
224 
225  cursor=query.execute()
226  while next(cursor):
227  cmslsnum=cursor.currentRow()['lsnr'].data()
228  deadcount=cursor.currentRow()['deadcount'].data()
229  result[cmslsnum]=deadcount
230  #print 'deadcount',deadcount
231  del query
232  return result
233  except Exception as e:
234  print str(e)
235  dbsession.transaction().rollback()
236  del dbsession
237 
238 def WBMdeadtimeBeamActiveForRun(dbsession,c,runnum):
239  '''
240  select LUMISEGMENTNR,DEADTIMEBEAMACTIVE from cms_wbm.LEVEL1_TRIGGER_CONDITIONS where RUNNUMBER=:runnum order by LUMISEGMENTNR;
241  return result{lumisection:deadtimebeamactive}
242 
243  '''
244  result={}
245  try:
246  dbsession.transaction().start(True)
247  schema=dbsession.nominalSchema()
248  if not schema:
249  raise Exception('cannot connect to schema'+c.wbmschema)
250  if not schema.existsTable(c.wbmdeadtable):
251  raise Exception('non-existing table'+c.wbmdeadtable)
252 
253  deadOutput=coral.AttributeList()
254  deadOutput.extend("lsnr","unsigned int")
255  deadOutput.extend("deadcount","unsigned long long")
256 
257  deadBindVarList=coral.AttributeList()
258  deadBindVarList.extend("runnum","unsigned int")
259  deadBindVarList["runnum"].setData(int(runnum))
260 
261  query=schema.newQuery()
262  query.addToTableList(c.wbmdeadtable)
263  query.addToOutputList('LUMISEGMENTNR','lsnr')
264  query.addToOutputList('DEADTIMEBEAMACTIVE','deadcount')
265  query.setCondition('RUNNUMBER=:runnum',deadBindVarList)
266  query.addToOrderList('LUMISEGMENTNR')
267  query.defineOutput(deadOutput)
268 
269  cursor=query.execute()
270  while next(cursor):
271  cmslsnum=cursor.currentRow()['lsnr'].data()
272  deadcount=cursor.currentRow()['deadcount'].data()
273  result[cmslsnum]=deadcount
274  #print 'deadcount',deadcount
275  del query
276  return result
277  except Exception as e:
278  print str(e)
279  dbsession.transaction().rollback()
280  del dbsession
281 
282 def patchDeadtimeForRun(dbsession,c,runnum,deadtimeDict):
283  '''
284  input: deadtimeDict{ls:deadtimebeamactive}
285  loop over input
286  update TRG set DEADTIME=:deadtimebeamactive where RUNNUM=:runnum and CMSLSNUM=:lsnum
287  output: number of rows changed
288  '''
289  totalchanged=0
290  try:
291  dbsession.transaction().start(False)
292  schema=dbsession.nominalSchema()
293  if not schema:
294  raise Exception('cannot connect to schema ')
295  if not schema.existsTable(c.lumitrgtable):
296  raise Exception('non-existing table '+c.lumitrgtable)
297  for lsnum,deadtimebeamactive in deadtimeDict.items():
298  nchanged=0
299  inputData=coral.AttributeList()
300  inputData.extend('deadtimebeamactive','unsigned int')
301  inputData.extend('runnum','unsigned int')
302  inputData.extend('lsnum','unsigned int')
303  inputData['deadtimebeamactive'].setData(deadtimebeamactive)
304  inputData['runnum'].setData(runnum)
305  inputData['lsnum'].setData(lsnum)
306  nchanged=schema.tableHandle(c.lumitrgtable).dataEditor().updateRows('DEADTIME=:deadtimebeamactive','RUNNUM=:runnum AND CMSLSNUM=:lsnum',inputData)
307  print 'rows changed for ls ',str(lsnum),str(nchanged)
308  totalchanged+=nchanged
309  dbsession.transaction().commit()
310  return totalchanged
311  except Exception as e:
312  print str(e)
313  dbsession.transaction().rollback()
314  del dbsession
315 
316 def main():
317  c=constants()
318  parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),description="Patch LumiData")
319  parser.add_argument('-c',dest='destination',action='store',required=True,help='destination lumi db (required)')
320  parser.add_argument('-s',dest='source',action='store',required=False,help='source db (required except for lumicalib)')
321  parser.add_argument('-P',dest='authpath',action='store',required=True,help='path to authentication file (required)')
322  parser.add_argument('-r',dest='runnumber',action='store',required=False,help='run number (optional)')
323  parser.add_argument('-i',dest='inputfile',action='store',required=False,help='run selection file(optional)')
324  parser.add_argument('-delta',dest='delta',action='store',required=False,help='calibration factor wrt old data in lumiDB (required for lumicalib)')
325  parser.add_argument('action',choices=['deadtimeGT','deadtimeWBM','lumicalib','runtimestamp'],help='deadtimeGT: patch deadtime to deadtimebeamactive,\ndeadtimeWBM: patch deadtimeWBM to deadtimebeamactive,\nlumicalib: recalibrate inst lumi by delta where delta>1\n runtimestamp: add start,stop run timestamp where empty')
326  parser.add_argument('--dryrun',dest='dryrun',action='store_true',help='only print datasource query result, do not update destination')
327 
328  parser.add_argument('--debug',dest='debug',action='store_true',help='debug')
329  args=parser.parse_args()
330  runnumber=args.runnumber
331  destConnect=args.destination
332  sourceConnect=args.source
333  if args.authpath and len(args.authpath)!=0:
334  os.environ['CORAL_AUTH_PATH']=args.authpath
335  svc=coral.ConnectionService()
336  sourcesession=None
337  if sourceConnect:
338  sourcesession=svc.connect(sourceConnect,accessMode=coral.access_ReadOnly)
339  sourcesession.typeConverter().setCppTypeForSqlType("unsigned int","NUMBER(10)")
340  sourcesession.typeConverter().setCppTypeForSqlType("unsigned long long","NUMBER(20)")
341  destsession=svc.connect(destConnect,accessMode=coral.access_Update)
342  destsession.typeConverter().setCppTypeForSqlType("unsigned int","NUMBER(10)")
343  destsession.typeConverter().setCppTypeForSqlType("unsigned long long","NUMBER(20)")
344  if args.debug:
345  msg=coral.MessageStream('')
346  msg.setMsgVerbosity(coral.message_Level_Debug)
347  if args.dryrun:
348  c.isdryrun=True
349  else:
350  c.isdryrun=False
351 
352  deadresult={}
353 
354  if args.action == 'deadtimeGT':
355  if not sourceConnect:
356  raise Exception('deadtimeGT action requies -s option for source connection string')
357  deadresult=GTdeadtimeBeamActiveForRun(sourcesession,c,runnumber)
358  print 'reading from ',sourceConnect
359  print 'run : ',runnumber
360  print 'LS:deadtimebeamactive'
361  #print deadresult
362  if deadresult and len(deadresult)!=0:
363  for cmsls,deadtimebeamactive in deadresult.items():
364  print cmsls,deadtimebeamactive
365  else:
366  print 'no deadtime found for run ',runnumber
367  print 'exit'
368  return
369  print 'total LS: ',len(deadresult)
370 # if len(deadresult)!=max( [ (deadresult[x],x) for x in deadresult] )[1]:
371  if len(deadresult)!=max( [ x for x in deadresult.keys() ] ):
372  print 'total ls: ',len(deadresult)
373  #print 'max key: ',max( [ x for x in deadresult.keys()])
374  print 'alert: missing Lumi Sections in the middle'
375  for x in range(1,max( [ x for x in deadresult.keys()] ) ):
376  if x not in deadresult:
377  print 'filling up LS deadtime with 0: LS : ',x
378  deadresult[x]=0
379  #print deadresult
380  if not args.dryrun:
381  print 'updating ',destConnect
382  nupdated=patchDeadtimeForRun(destsession,c,int(runnumber),deadresult)
383  print 'number of updated rows ',nupdated
384  elif args.action == 'deadtimeWBM':
385  if not sourceConnect:
386  raise Exception('deadtimeWBM action requies -s option for source connection string')
387  deadresult=WBMdeadtimeBeamActiveForRun(sourcesession,c,runnumber)
388  print 'reading from ',sourceConnect
389  print 'run : ',runnumber
390  print 'LS:deadtimebeamactive'
391  #print deadresult
392  if deadresult and len(deadresult)!=0:
393  for cmsls,deadtimebeamactive in deadresult.items():
394  print cmsls,deadtimebeamactive
395  else:
396  print 'no deadtime found for run ',runnumber
397  print 'exit'
398  return
399  print 'total LS: ',len(deadresult)
400  if len(deadresult)!=max( [ (deadresult[x],x) for x in deadresult])[1]:
401  print 'alert: missing Lumi Sections in the middle'
402  for x in range(1,max( [ (deadresult[x],x) for x in deadresult])[1]):
403  if x not in deadresult:
404  print 'filling up LS deadtime with 0: LS : ',x
405  deadresult[x]=0
406  print deadresult
407  if not args.dryrun:
408  print 'updating ',destConnect
409  nupdated=patchDeadtimeForRun(destsession,c,int(runnumber),deadresult)
410  print 'number of updated rows ',nupdated
411  elif args.action == 'lumicalib':
412  if not args.delta or args.delta==0:
413  raise Exception('Must provide non-zero -delta argument')
414  runnums=[]
415  if args.runnumber:
416  runnums.append(args.runnumber)
417  elif args.inputfile:
418  basename,extension=os.path.splitext(args.inputfile)
419  if extension=='.csv':#if file ends with .csv,use csv parser,else parse as json file
420  fileparsingResult=csvSelectionParser.csvSelectionParser(args.inputfile)
421  else:
422  f=open(args.inputfile,'r')
423  inputfilecontent=f.read()
424  fileparsingResult=selectionParser.selectionParser(inputfilecontent)
425  if not fileparsingResult:
426  raise Exception('failed to parse the input file '+ifilename)
427  #print fileparsingResult.runsandls()
428  runnums=fileparsingResult.runs()
429  #print runnums
430  else:
431  raise Exception('Must provide -r or -i argument as input')
432  nupdated=recalibrateLumiForRun(destsession,c,args.delta,runnums)
433  elif args.action == 'runtimestamp':
434  if not sourceConnect:
435  raise Exception('runtimestamp action requies -s option for source connection string')
436  if not args.runnumber and not args.inputfile: #if no runnumber nor input file specified, check all
437  runnums=missingTimeRuns(destsession,c)
438  print 'these runs miss start/stop time: ',runnums
439  print 'total : ',len(runnums)
440  elif args.runnumber:
441  runnums=[int(args.runnumber)]
442  elif args.inputfile:
443  basename,extension=os.path.splitext(args.inputfile)
444  if extension=='.csv':#if file ends with .csv,use csv parser,else parse as json file
445  fileparsingResult=csvSelectionParser.csvSelectionParser(args.inputfile)
446  else:
447  f=open(args.inputfile,'r')
448  inputfilecontent=f.read()
449  fileparsingResult=selectionParser.selectionParser(inputfilecontent)
450  if not fileparsingResult:
451  raise Exception('failed to parse the input file '+ifilename)
452  runnums=fileparsingResult.runs()
453  result=getTimeForRun(sourcesession,c,runnums)
454  #for run,(startTimeT,stopTimeT) in result.items():
455  #print 'run: ',run
456  #if not startTimeT or not stopTimeT:
457  #print 'None'
458  #else:
459  #print 'start: ',startTimeT
460  #print 'stop: ',stopTimeT
461  addTimeForRun(destsession,c,result)
462  if sourcesession:
463  del sourcesession
464  del destsession
465  del svc
466 
467 if __name__=='__main__':
468  main()
469 
Definition: start.py:1
def getTimeForRun
Definition: lumiPatch.py:59
def missingTimeRuns
Definition: lumiPatch.py:28
def patchDeadtimeForRun
Definition: lumiPatch.py:282
def WBMdeadtimeBeamActiveForRun
Definition: lumiPatch.py:238
def GTdeadtimeBeamActiveForRun
Definition: lumiPatch.py:191
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def main
Definition: lumiPatch.py:316
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:82
Definition: main.py:1
def recalibrateLumiForRun
Definition: lumiPatch.py:161
def addTimeForRun
Definition: lumiPatch.py:121