CMS 3D CMS Logo

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