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=='recorded':
171  reqTrg=True
172  reqHlt=True
173  if options.runnumber:
174  reqrunmax=options.runnumber
175  reqrunmin=options.runnumber
176  if options.fillnum:
177  reqfillmin=options.fillnum
178  reqfillmax=options.fillnum
179 
180  if options.begin:
181  (runbeg,fillbeg,timebeg)=CommonUtil.parseTime(options.begin)
182  if runbeg: #there's --begin runnum #priority run,fill,time
183  if not reqrunmin:# there's no -r, then take this
184  reqrunmin=runbeg
185  elif fillbeg:
186  if not reqfillmin:
187  reqfillmin=fillbeg
188  elif timebeg:
189  reqtimemin=timebeg
190  if reqtimemin:
192  reqtimeminT=lute.StrToDatetime(reqtimemin,customfm='%m/%d/%y %H:%M:%S')
193  timeFilter[0]=reqtimeminT
194  if options.end:
195  (runend,fillend,timeend)=CommonUtil.parseTime(options.end)
196  if runend:
197  if not reqrunmax:#priority run,fill,time
198  reqrunmax=runend
199  elif fillend:
200  if not reqfillmax:
201  reqfillmax=fillend
202  elif timeend:
203  reqtimemax=timeend
204  if reqtimemax:
205  lute=lumiTime.lumiTime()
206  reqtimemaxT=lute.StrToDatetime(reqtimemax,customfm='%m/%d/%y %H:%M:%S')
207  timeFilter[1]=reqtimemaxT
208  if options.inputfile and (reqtimemax or reqtimemin):
209  #if use time and file filter together, there's no point of warning about missing LS,switch off
210  noWarning=True
211 
212  ##############################################################
213  # check working environment
214  ##############################################################
215  workingversion='UNKNOWN'
216  updateversion='NONE'
217  thiscmmd=sys.argv[0]
218  if not options.withoutCheckforupdate:
219  from RecoLuminosity.LumiDB import checkforupdate
220  cmsswWorkingBase=os.environ['CMSSW_BASE']
221  if not cmsswWorkingBase:
222  print 'Please check out RecoLuminosity/LumiDB from CVS,scram b,cmsenv'
223  sys.exit(11)
224  c=checkforupdate.checkforupdate('pixeltagstatus.txt')
225  workingversion=c.runningVersion(cmsswWorkingBase,'pixelLumiCalc.py',isverbose=False)
226  if workingversion:
227  updateversionList=c.checkforupdate(workingversion,isverbose=False)
228  if updateversionList:
229  updateversion=updateversionList[-1][0]
230  #
231  # check DB environment
232  #
233  if options.authpath:
234  os.environ['CORAL_AUTH_PATH'] = options.authpath
235  #############################################################
236  #pre-check option compatibility
237  #############################################################
238  if options.action=='recorded':
239  if not options.hltpath:
240  raise RuntimeError('argument --hltpath pathname is required for recorded action')
241  svc=sessionManager.sessionManager(options.connect,
242  authpath=options.authpath,
243  siteconfpath=options.siteconfpath,
244  debugON=options.debug)
245 
246  session=svc.openSession(isReadOnly=True,cpp2sqltype=[('unsigned int','NUMBER(10)'),('unsigned long long','NUMBER(20)')])
247  ##############################################################
248  # check run/ls list
249  ##############################################################
250  irunlsdict={}
251  rruns=[]
252  session.transaction().start(True)
253  filerunlist=None
254  if options.inputfile:
255  (irunlsdict,iresults)=parseInputFiles(options.inputfile)
256  filerunlist=irunlsdict.keys()
257  ##############################################################
258  # check datatag
259  # #############################################################
260  datatagname=options.datatag
261  if not datatagname:
262  (datatagid,datatagname)=revisionDML.currentDataTag(session.nominalSchema())
263  else:
264  datatagid=revisionDML.getDataTagId(session.nominalSchema(),datatagname)
265 
266  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')
267  if not dataidmap:
268  print '[INFO] No qualified run found, do nothing'
269  sys.exit(14)
270  rruns=[]
271  for irun,(lid,tid,hid) in dataidmap.items():
272  if not lid:
273  print '[INFO] No qualified lumi data found for run, ',irun
274  if reqTrg and not tid:
275  print '[INFO] No qualified trg data found for run ',irun
276  continue
277  if reqHlt and not hid:
278  print '[INFO] No qualified hlt data found for run ',irun
279  continue
280  rruns.append(irun)
281  if not irunlsdict: #no file
282  irunlsdict=dict(zip(rruns,[None]*len(rruns)))
283  else:
284  for selectedrun in irunlsdict.keys():#if there's further filter on the runlist,clean input dict
285  if selectedrun not in rruns:
286  del irunlsdict[selectedrun]
287  if not irunlsdict:
288  print '[INFO] No qualified run found, do nothing'
289  sys.exit(13)
290  ###############################################################
291  # check normtag and get norm values if required
292  ###############################################################
293  normname='NONE'
294  normid=0
295  normvalueDict={}
296  if not options.withoutNorm:
297  normname=options.normtag
298  if not normname:
299  normmap=normDML.normIdByType(session.nominalSchema(),lumitype='PIXEL',defaultonly=True)
300  if len(normmap):
301  normname=normmap.keys()[0]
302  normid=normmap[normname]
303  else:
304  normid=normDML.normIdByName(session.nominalSchema(),normname)
305  if not normid:
306  raise RuntimeError('[ERROR] cannot resolve norm/correction')
307  sys.exit(12)
308  normvalueDict=normDML.normValueById(session.nominalSchema(),normid) #{since:[corrector(0),{paramname:paramvalue}(1),amodetag(2),egev(3),comment(4)]}
309  session.transaction().commit()
310  lumiReport.toScreenHeader(thiscmmd,datatagname,normname,workingversion,updateversion,'PIXEL',toFile=options.headerfile)
311 
312  ##################
313  # ls level #
314  ##################
315  session.transaction().start(True)
316  GrunsummaryData=lumiCalcAPI.runsummaryMap(session.nominalSchema(),irunlsdict,dataidmap,lumitype='PIXEL')
317  if options.action == 'overview':
318  result=lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=None,timeFilter=timeFilter,normmap=normvalueDict,lumitype='PIXEL')
319  lumiReport.toScreenOverview(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
320  if options.action == 'lumibyls':
321  if not options.hltpath:
322  result=lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=None,timeFilter=timeFilter,normmap=normvalueDict,lumitype='PIXEL',minbiasXsec=options.minbiasxsec)
323  lumiReport.toScreenLumiByLS(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
324  else:
325  hltname=options.hltpath
326  hltpat=None
327  if hltname=='*' or hltname=='all':
328  hltname=None
329  elif 1 in [c in hltname for c in '*?[]']: #is a fnmatch pattern
330  hltpat=hltname
331  hltname=None
332  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')
333  lumiReport.toScreenLSEffective(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile,)
334  if options.action == 'recorded':#recorded actually means effective because it needs to show all the hltpaths...
335  hltname=options.hltpath
336  hltpat=None
337  if hltname is not None:
338  if hltname=='*' or hltname=='all':
339  hltname=None
340  elif 1 in [c in hltname for c in '*?[]']: #is a fnmatch pattern
341  hltpat=hltname
342  hltname=None
343  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')
344  lumiReport.toScreenTotEffective(result,iresults,options.scalefactor,irunlsdict=irunlsdict,noWarning=noWarning,toFile=options.outputfile)
345  session.transaction().commit()
346  del session
347  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