PageRenderTime 37ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/RecoLuminosity/LumiDB/scripts/lumiPatch.py

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