CMS 3D CMS Logo

lumiPatch.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 from __future__ import print_function
3 VERSION='1.00'
4 import os,sys,datetime
5 import coral
6 from RecoLuminosity.LumiDB import argparse,selectionParser,csvSelectionParser
7 
8 '''
9 --on wbm db
10 select LUMISEGMENTNR,DEADTIMEBEAMACTIVE from cms_wbm.LEVEL1_TRIGGER_CONDITIONS where RUNNUMBER=:runnumber order by LUMISEGMENTNR;
11 --on lumidb
12 update TRG set DEADTIME=:deadtimebeamactive where RUNNUM=:runnum and CMSLSNUM=:lsnum
13 --reapply calibration to inst lumi
14 update LUMISUMMARY set INSTLUMI=1.006319*INSTLUMI where RUNNUM in (1,3,57,90)
15 '''
16 
18  def __init__(self):
19  self.debug=False
20  self.isdryrun=None
21  self.runinfoschema='CMS_RUNINFO'
22  self.wbmschema='CMS_WBM'
23  self.wbmdeadtable='LEVEL1_TRIGGER_CONDITIONS'
24  self.gtmonschema='CMS_GT_MON'
25  self.gtdeadview='GT_MON_TRIG_DEAD_VIEW'
26  self.lumitrgtable='TRG'
27  self.lumisummarytable='LUMISUMMARY'
28  self.runsummarytable='CMSRUNSUMMARY'
29 def missingTimeRuns(dbsession,c):
30  '''return all the runs with starttime or stoptime column NULL in lumi db
31  select runnum from CMSRUNSUMMARY where starttime is NULL or stoptime is NULL
32  '''
33  result=[]
34  try:
35  emptyBindVarList=coral.AttributeList()
36  dbsession.transaction().start(True)
37  schema=dbsession.nominalSchema()
38  if not schema:
39  raise 'cannot connect to schema '
40  if not schema.existsTable(c.runsummarytable):
41  raise 'non-existing table '+c.runsummarytable
42  query=schema.newQuery()
43  query.addToTableList(c.runsummarytable)
44  query.addToOutputList('RUNNUM','runnum')
45  query.setCondition('STARTTIME IS NULL AND STOPTIME IS NULL',emptyBindVarList)
46  query.addToOrderList('runnum')
47  queryOutput=coral.AttributeList()
48  queryOutput.extend('runnum','unsigned int')
49  query.defineOutput(queryOutput)
50  cursor=query.execute()
51  while next(cursor):
52  result.append(cursor.currentRow()['runnum'].data())
53  del query
54  dbsession.transaction().commit()
55  except Exception as e:
56  print(str(e))
57  dbsession.transaction().rollback()
58  del dbsession
59  return result
60 def getTimeForRun(dbsession,c,runnums):
61  '''
62  get start stop time of run from runinfo database
63  select time from cms_runinfo.runsession_parameter where runnumber=:runnum and name='CMS.LVL0:START_TIME_T';
64  select time from cms_runinfo.runsession_parameter where runnumber=:runnum and name='CMS.LVL0:STOP_TIME_T';
65  '''
66  result={}#{runnum:(starttime,stoptime)}
67  tableName='RUNSESSION_PARAMETER'
68  try:
69  dbsession.transaction().start(True)
70  schema=dbsession.nominalSchema()
71  if not schema:
72  raise 'cannot connect to schema '
73  if not schema.existsTable(tableName):
74  raise 'non-existing table '+tableName
75 
76  startTime=''
77  stopTime=''
78  for runnum in runnums:
79  startTQuery=schema.newQuery()
80  startTQuery.addToTableList(tableName)
81  startTQuery.addToOutputList('TIME','starttime')
82  stopTQuery=schema.newQuery()
83  stopTQuery.addToTableList(tableName)
84  stopTQuery.addToOutputList('TIME','stoptime')
85  startTQueryCondition=coral.AttributeList()
86  stopTQueryCondition=coral.AttributeList()
87  startTQueryOutput=coral.AttributeList()
88  stopTQueryOutput=coral.AttributeList()
89  startTQueryCondition.extend('runnum','unsigned int')
90  startTQueryCondition.extend('name','string')
91  startTQueryOutput.extend('starttime','time stamp')
92  stopTQueryCondition.extend('runnum','unsigned int')
93  stopTQueryCondition.extend('name','string')
94  stopTQueryOutput.extend('stoptime','time stamp')
95  startTQueryCondition['runnum'].setData(int(runnum))
96  startTQueryCondition['name'].setData('CMS.LVL0:START_TIME_T')
97  startTQuery.setCondition('RUNNUMBER=:runnum AND NAME=:name',startTQueryCondition)
98  startTQuery.defineOutput(startTQueryOutput)
99  startTCursor=startTQuery.execute()
100  while next(startTCursor):
101  startTime=startTCursor.currentRow()['starttime'].data()
102  stopTQueryCondition['runnum'].setData(int(runnum))
103  stopTQueryCondition['name'].setData('CMS.LVL0:STOP_TIME_T')
104  stopTQuery.setCondition('RUNNUMBER=:runnum AND NAME=:name',stopTQueryCondition)
105  stopTQuery.defineOutput(stopTQueryOutput)
106  stopTCursor=stopTQuery.execute()
107  while next(stopTCursor):
108  stopTime=stopTCursor.currentRow()['stoptime'].data()
109  if not startTime or not stopTime:
110  print('Warning: no startTime or stopTime found for run ',runnum)
111  else:
112  result[runnum]=(startTime,stopTime)
113  del startTQuery
114  del stopTQuery
115  dbsession.transaction().commit()
116  except Exception as e:
117  print(str(e))
118  dbsession.transaction().rollback()
119  del dbsession
120  return result
121 
122 def addTimeForRun(dbsession,c,runtimedict):
123  '''
124  Input runtimedict{runnumber:(startTimeT,stopTimeT)}
125  update CMSRUNSUMMARY set STARTTIME=:starttime,STOPTIME=:stoptime where RUNNUM=:runnum
126  #update CMSRUNSUMMARY set STOPTIME=:stoptime where RUNNUM=:runnum
127  '''
128  nchanged=0
129  totalchanged=0
130  try:
131  dbsession.transaction().start(False)
132  schema=dbsession.nominalSchema()
133  if not schema:
134  raise 'cannot connect to schema'
135  if not schema.existsTable(c.runsummarytable):
136  raise 'non-existing table '+c.runsummarytable
137  inputData=coral.AttributeList()
138  inputData.extend('starttime','time stamp')
139  inputData.extend('stoptime','time stamp')
140  inputData.extend('runnum','unsigned int')
141  runs=sorted(runtimedict.keys())
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(dbsession, c, runnums)
Definition: lumiPatch.py:60
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:65
def addTimeForRun(dbsession, c, runtimedict)
Definition: lumiPatch.py:122
def WBMdeadtimeBeamActiveForRun(dbsession, c, runnum)
Definition: lumiPatch.py:238
def missingTimeRuns(dbsession, c)
Definition: lumiPatch.py:29
def recalibrateLumiForRun(dbsession, c, delta, runnums)
Definition: lumiPatch.py:161
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:82
def main()
Definition: lumiPatch.py:316
def patchDeadtimeForRun(dbsession, c, runnum, deadtimeDict)
Definition: lumiPatch.py:282
Definition: main.py:1
#define str(s)
def GTdeadtimeBeamActiveForRun(dbsession, c, runnum)
Definition: lumiPatch.py:191
def __init__(self)
Definition: lumiPatch.py:18