CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
lumiCalc2.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 ########################################################################
4 # Command to calculate luminosity from HF measurement stored in lumiDB #
5 # #
6 # Author: Zhen Xie #
7 ########################################################################
8 
9 import os,sys,time
10 from RecoLuminosity.LumiDB import sessionManager,lumiTime,inputFilesetParser,csvSelectionParser,selectionParser,csvReporter,argparse,CommonUtil,revisionDML,lumiCalcAPI,lumiReport,RegexValidator,normDML
11 
12 beamChoices=['PROTPHYS','IONPHYS','PAPHYS']
13 
14 def parseInputFiles(inputfilename):
15  '''
16  output ({run:[cmsls,cmsls,...]},[[resultlines]])
17  '''
18  selectedrunlsInDB={}
19  resultlines=[]
21  runlsbyfile=p.runsandls()
22  selectedProcessedRuns=p.selectedRunsWithresult()
23  selectedNonProcessedRuns=p.selectedRunsWithoutresult()
24  resultlines=p.resultlines()
25  for runinfile in selectedNonProcessedRuns:
26  selectedrunlsInDB[runinfile]=runlsbyfile[runinfile]
27  return (selectedrunlsInDB,resultlines)
28 
29 ##############################
30 ## ######################## ##
31 ## ## ################## ## ##
32 ## ## ## Main Program ## ## ##
33 ## ## ################## ## ##
34 ## ######################## ##
35 ##############################
36 
37 if __name__ == '__main__':
38  parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),description = "Lumi Calculation",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
39  allowedActions = ['overview', 'delivered', 'recorded', 'lumibyls','lumibylsXing']
40  beamModeChoices = [ "stable"]
41  amodetagChoices = [ "PROTPHYS","IONPHYS",'PAPHYS' ]
42  xingAlgoChoices =[ "OCC1","OCC2","ET"]
43 
44  #
45  # parse arguments
46  #
47  ################################################
48  # basic arguments
49  ################################################
50  parser.add_argument('action',choices=allowedActions,
51  help='command actions')
52  parser.add_argument('-c',dest='connect',action='store',
53  required=False,
54  help='connect string to lumiDB,optional',
55  default='frontier://LumiCalc/CMS_LUMI_PROD')
56  parser.add_argument('-P',dest='authpath',action='store',
57  required=False,
58  help='path to authentication file')
59  parser.add_argument('-r',dest='runnumber',action='store',
60  type=int,
61  required=False,
62  help='run number')
63  parser.add_argument('-o',dest='outputfile',action='store',
64  required=False,
65  help='output to csv file' )
66 
67  #################################################
68  #arg to select exact run and ls
69  #################################################
70  parser.add_argument('-i',dest='inputfile',action='store',
71  required=False,
72  help='lumi range selection file')
73  #################################################
74  #arg to select exact hltpath or pattern
75  #################################################
76  parser.add_argument('--hltpath',dest='hltpath',action='store',
77  default=None,required=False,
78  help='specific hltpath or hltpath pattern to calculate the effectived luminosity')
79  #################################################
80  #versions control
81  #################################################
82  parser.add_argument('--normtag',dest='normtag',action='store',
83  required=False,
84  help='version of lumi norm/correction')
85  parser.add_argument('--datatag',dest='datatag',action='store',
86  required=False,
87  help='version of lumi/trg/hlt data')
88 
89  ###############################################
90  # run filters
91  ###############################################
92  parser.add_argument('-f','--fill',dest='fillnum',action='store',
93  default=None,required=False,
94  help='fill number (optional) ')
95  parser.add_argument('--amodetag',dest='amodetag',action='store',
96  choices=amodetagChoices,
97  required=False,
98  help='specific accelerator mode choices [PROTOPHYS,IONPHYS,PAPHYS] (optional)')
99  parser.add_argument('--beamenergy',dest='beamenergy',action='store',
100  type=float,
101  default=None,
102  help='nominal beam energy in GeV')
103  parser.add_argument('--beamfluctuation',dest='beamfluctuation',
104  type=float,action='store',
105  default=0.2,
106  required=False,
107  help='fluctuation in fraction allowed to nominal beam energy, default 0.2, to be used together with -beamenergy (optional)')
108 
109  parser.add_argument('--begin',dest='begin',action='store',
110  default=None,
111  required=False,
112  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$|^\d{6}$|^\d{4}$","wrong format"),
113  help='min run start time (mm/dd/yy hh:mm:ss),min fill or min run'
114  )
115  parser.add_argument('--end',dest='end',action='store',
116  default=None,
117  required=False,
118  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$|^\d{6}$|^\d{4}$","wrong format"),
119  help='max run start time (mm/dd/yy hh:mm:ss),max fill or max run'
120  )
121  parser.add_argument('--minBiasXsec',dest='minbiasxsec',action='store',
122  default=69300.0,
123  type=float,
124  required=False,
125  help='minbias cross-section in ub'
126  )
127  #############################################
128  #ls filter
129  #############################################
130  parser.add_argument('-b',dest='beammode',action='store',
131  choices=beamModeChoices,
132  required=False,
133  help='beam mode choices [stable]')
134 
135  parser.add_argument('--xingMinLum', dest = 'xingMinLum',
136  type=float,
137  default=1e-03,
138  required=False,
139  help='Minimum perbunch luminosity to print, default=1e-03/ub')
140 
141  parser.add_argument('--xingAlgo', dest = 'xingAlgo',
142  default='OCC1',
143  required=False,
144  help='algorithm name for per-bunch lumi ')
145 
146  #############################################
147  #global scale factor
148  #############################################
149  parser.add_argument('-n',dest='scalefactor',action='store',
150  type=float,
151  default=1.0,
152  required=False,
153  help='user defined global scaling factor on displayed lumi values,optional')
154 
155  #################################################
156  #command configuration
157  #################################################
158  parser.add_argument('--siteconfpath',dest='siteconfpath',action='store',
159  default=None,
160  required=False,
161  help='specific path to site-local-config.xml file, optional. If path undefined, fallback to cern proxy&server')
162 
163  parser.add_argument('--headerfile',dest='headerfile',action='store',
164  default=None,
165  required=False,
166  help='write command header output to specified file'
167  )
168  #################################################
169  #switches
170  #################################################
171  parser.add_argument('--without-correction',
172  dest='withoutNorm',
173  action='store_true',
174  help='without any correction/calibration'
175  )
176  parser.add_argument('--without-checkforupdate',
177  dest='withoutCheckforupdate',
178  action='store_true',
179  help='without check for update'
180  )
181  #parser.add_argument('--verbose',
182  # dest='verbose',
183  # action='store_true',
184  # help='verbose mode for printing'
185  # )
186  parser.add_argument('--nowarning',
187  dest='nowarning',
188  action='store_true',
189  help='suppress bad for lumi warnings'
190  )
191  parser.add_argument('--debug',
192  dest='debug',
193  action='store_true',
194  help='debug'
195  )
196  options=parser.parse_args()
197  if not options.runnumber and not options.inputfile and not options.fillnum and not options.begin:
198  raise RuntimeError('at least one run selection argument in [-r,-f,-i,--begin] is required')
199  reqrunmin=None
200  reqfillmin=None
201  reqtimemin=None
202  reqrunmax=None
203  reqfillmax=None
204  reqtimemax=None
205  timeFilter=[None,None]
206  noWarning=options.nowarning
207  pbeammode = None
208  if options.beammode=='stable':
209  pbeammode = 'STABLE BEAMS'
210  iresults=[]
211  reqTrg=False
212  reqHlt=False
213  if options.action=='overview' or options.action=='lumibyls' or options.action=='lumibylsXing':
214  reqTrg=True
215  if options.action=='recorded':
216  reqTrg=True
217  reqHlt=True
218  if options.runnumber:
219  reqrunmax=options.runnumber
220  reqrunmin=options.runnumber
221  if options.fillnum:
222  reqfillmin=options.fillnum
223  reqfillmax=options.fillnum
224 
225 
226  if options.begin:
227  (runbeg,fillbeg,timebeg)=CommonUtil.parseTime(options.begin)
228  if runbeg: #there's --begin runnum #priority run,fill,time
229  if not reqrunmin:# there's no -r, then take this
230  reqrunmin=runbeg
231  elif fillbeg:
232  if not reqfillmin:
233  reqfillmin=fillbeg
234  elif timebeg:
235  reqtimemin=timebeg
236  if reqtimemin:
238  reqtimeminT=lute.StrToDatetime(reqtimemin,customfm='%m/%d/%y %H:%M:%S')
239  timeFilter[0]=reqtimeminT
240  if options.end:
241  (runend,fillend,timeend)=CommonUtil.parseTime(options.end)
242  if runend:
243  if not reqrunmax:#priority run,fill,time
244  reqrunmax=runend
245  elif fillend:
246  if not reqfillmax:
247  reqfillmax=fillend
248  elif timeend:
249  reqtimemax=timeend
250  if reqtimemax:
251  lute=lumiTime.lumiTime()
252  reqtimemaxT=lute.StrToDatetime(reqtimemax,customfm='%m/%d/%y %H:%M:%S')
253  timeFilter[1]=reqtimemaxT
254  if options.inputfile and (reqtimemax or reqtimemin):
255  #if use time and file filter together, there's no point of warning about missing LS,switch off
256  noWarning=True
257 
258  ##############################################################
259  # check working environment
260  ##############################################################
261  workingversion='UNKNOWN'
262  updateversion='NONE'
263  thiscmmd=sys.argv[0]
264  if not options.withoutCheckforupdate:
265  from RecoLuminosity.LumiDB import checkforupdate
266  cmsswWorkingBase=os.environ['CMSSW_BASE']
267  if not cmsswWorkingBase:
268  print 'Please check out RecoLuminosity/LumiDB from CVS,scram b,cmsenv'
269  sys.exit(11)
271  workingversion=c.runningVersion(cmsswWorkingBase,'lumiCalc2.py',isverbose=False)
272  if workingversion:
273  updateversionList=c.checkforupdate(workingversion,isverbose=False)
274  if updateversionList:
275  updateversion=updateversionList[-1][0]
276  #
277  # check DB environment
278  #
279  if options.authpath:
280  os.environ['CORAL_AUTH_PATH'] = options.authpath
281 
282  #############################################################
283  #pre-check option compatibility
284  #############################################################
285 
286  if options.action=='recorded':
287  if not options.hltpath:
288  raise RuntimeError('argument --hltpath pathname is required for recorded action')
289 
290  svc=sessionManager.sessionManager(options.connect,
291  authpath=options.authpath,
292  siteconfpath=options.siteconfpath,
293  debugON=options.debug)
294  session=svc.openSession(isReadOnly=True,cpp2sqltype=[('unsigned int','NUMBER(10)'),('unsigned long long','NUMBER(20)')])
295 
296  ##############################################################
297  # check run/ls list
298  ##############################################################
299  irunlsdict={}
300  rruns=[]
301  session.transaction().start(True)
302  filerunlist=None
303  if options.inputfile:
304  (irunlsdict,iresults)=parseInputFiles(options.inputfile)
305  filerunlist=irunlsdict.keys()
306 
307 
308  #if not irunlsdict: #no file
309  # irunlsdict=dict(zip(rruns,[None]*len(rruns)))
310  #else:
311  # for selectedrun in irunlsdict.keys():#if there's further filter on the runlist,clean input dict
312  # if selectedrun not in rruns:
313  # del irunlsdict[selectedrun]
314 
315  ##############################################################
316  # check datatag
317  # #############################################################
318  datatagname=options.datatag
319  if not datatagname:
320  (datatagid,datatagname)=revisionDML.currentDataTag(session.nominalSchema())
321  else:
322  datatagid=revisionDML.getDataTagId(session.nominalSchema(),datatagname)
323 
324  dataidmap=lumiCalcAPI.runList(session.nominalSchema(),datatagid,runmin=reqrunmin,runmax=reqrunmax,fillmin=reqfillmin,fillmax=reqfillmax,startT=reqtimemin,stopT=reqtimemax,l1keyPattern=None,hltkeyPattern=None,amodetag=options.amodetag,nominalEnergy=options.beamenergy,energyFlut=options.beamfluctuation,requiretrg=reqTrg,requirehlt=reqHlt,preselectedruns=filerunlist)
325  if not dataidmap:
326  print '[INFO] No qualified run found, do nothing'
327  sys.exit(14)
328  rruns=[]
329  #crosscheck dataid value
330  for irun,(lid,tid,hid) in dataidmap.items():
331  if not lid:
332  print '[INFO] No qualified lumi data found for run, ',irun
333  if reqTrg and not tid:
334  print '[INFO] No qualified trg data found for run ',irun
335  continue
336  if reqHlt and not hid:
337  print '[INFO] No qualified hlt data found for run ',irun
338  continue
339  rruns.append(irun)
340  if not irunlsdict: #no file
341  irunlsdict=dict(zip(rruns,[None]*len(rruns)))
342  else:
343  for selectedrun in irunlsdict.keys():#if there's further filter on the runlist,clean input dict
344  if selectedrun not in rruns:
345  del irunlsdict[selectedrun]
346  if not irunlsdict:
347  print '[INFO] No qualified run found, do nothing'
348  sys.exit(13)
349  ###############################################################
350  # check normtag and get norm values if required
351  ###############################################################
352  normname='NONE'
353  normid=0
354  normvalueDict={}
355  if not options.withoutNorm:
356  normname=options.normtag
357  if not normname:
358  normmap=normDML.normIdByType(session.nominalSchema(),lumitype='HF',defaultonly=True)
359  if len(normmap):
360  normname=normmap.keys()[0]
361  normid=normmap[normname]
362  else:
363  normid=normDML.normIdByName(session.nominalSchema(),normname)
364  if not normid:
365  raise RuntimeError('[ERROR] cannot resolve norm/correction')
366  sys.exit(12)
367  normvalueDict=normDML.normValueById(session.nominalSchema(),normid) #{since:[corrector(0),{paramname:paramvalue}(1),amodetag(2),egev(3),comment(4)]}
368  session.transaction().commit()
369  lumiReport.toScreenHeader(thiscmmd,datatagname,normname,workingversion,updateversion,'HF',toFile=options.headerfile)
370 
371 
372  ##################
373  # ls level #
374  ##################
375  session.transaction().start(True)
376 
377  GrunsummaryData=lumiCalcAPI.runsummaryMap(session.nominalSchema(),irunlsdict,dataidmap,lumitype='HF')
378  if options.action == 'delivered':
379  result=lumiCalcAPI.deliveredLumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,lumitype='HF')
380  lumiReport.toScreenTotDelivered(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
381  if options.action == 'overview':
382  result=lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,lumitype='HF')
383  lumiReport.toScreenOverview(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
384  if options.action == 'lumibyls':
385  if not options.hltpath:
386  result=lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,lumitype='HF',minbiasXsec=options.minbiasxsec)
387  lumiReport.toScreenLumiByLS(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
388  else:
389  hltname=options.hltpath
390  hltpat=None
391  if hltname=='*' or hltname=='all':
392  hltname=None
393  elif 1 in [c in hltname for c in '*?[]']: #is a fnmatch pattern
394  hltpat=hltname
395  hltname=None
396  result=lumiCalcAPI.effectiveLumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,hltpathname=hltname,hltpathpattern=hltpat,withBXInfo=False,bxAlgo=None,xingMinLum=options.xingMinLum,withBeamIntensity=False,lumitype='HF')
397  lumiReport.toScreenLSEffective(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
398  if options.action == 'recorded':#recorded actually means effective because it needs to show all the hltpaths...
399  hltname=options.hltpath
400  hltpat=None
401  if hltname is not None:
402  if hltname=='*' or hltname=='all':
403  hltname=None
404  elif 1 in [c in hltname for c in '*?[]']: #is a fnmatch pattern
405  hltpat=hltname
406  hltname=None
407  result=lumiCalcAPI.effectiveLumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,hltpathname=hltname,hltpathpattern=hltpat,withBXInfo=False,bxAlgo=None,xingMinLum=options.xingMinLum,withBeamIntensity=False,lumitype='HF')
408  lumiReport.toScreenTotEffective(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
409  if options.action == 'lumibylsXing':
410  result=lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,timeFilter=timeFilter,normmap=normvalueDict,withBXInfo=True,bxAlgo=options.xingAlgo,xingMinLum=options.xingMinLum,withBeamIntensity=False,lumitype='HF')
411  outfile=options.outputfile
412  if not outfile:
413  print '[WARNING] no output file given. lumibylsXing writes per-bunch lumi only to default file lumibylsXing.csv'
414  outfile='lumibylsXing.csv'
415  lumiReport.toCSVLumiByLSXing(result,options.scalefactor,outfile,irunlsdict=irunlsdict,noWarning=noWarning)
416  session.transaction().commit()
417  del session
418  del svc
Definition: start.py:1
def toScreenHeader
Definition: lumiReport.py:27
def toScreenOverview
Definition: lumiReport.py:260
def toScreenLumiByLS
Definition: lumiReport.py:392
def parseInputFiles
Definition: lumiCalc2.py:14
def toScreenTotDelivered
Definition: lumiReport.py:148
def normIdByType
Definition: normDML.py:92
def effectiveLumiForIds
Definition: lumiCalcAPI.py:532
def toScreenTotEffective
Definition: lumiReport.py:692
def toScreenLSEffective
Definition: lumiReport.py:538
def getDataTagId
Definition: revisionDML.py:658
def currentDataTag
Definition: revisionDML.py:513
def parseTime
Definition: CommonUtil.py:14
def normValueById
Definition: normDML.py:181
def deliveredLumiForIds
Definition: lumiCalcAPI.py:369
def runsummaryMap
Definition: lumiCalcAPI.py:21
def normIdByName
Definition: normDML.py:60
def toCSVLumiByLSXing
Definition: lumiReport.py:875