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