CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
lumiContext.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 ###############################################################################
4 # Command to display runsummary, L1,HLT and beam data used in lumi caculation #
5 # #
6 # Author: Zhen Xie #
7 ###############################################################################
8 
9 import os,sys,time
10 from RecoLuminosity.LumiDB import sessionManager,lumiTime,inputFilesetParser,csvSelectionParser,csvReporter,argparse,CommonUtil,lumiCalcAPI,lumiReport,RegexValidator,lumiTime,revisionDML
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 = "Additional information needed in the lumi calculation",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
37  allowedActions = ['hltbyls','hltmenu','trgbyls', 'beambyls','runsummary']
38  amodetagChoices = [ "PROTPHYS","IONPHYS","PAPHYS" ]
39  beamModeChoices = ["stable"]
40  #
41  # parse arguments
42  #
43  #
44  ################################################
45  # basic arguments
46  ################################################
47  #
48  parser.add_argument('action',choices=allowedActions,
49  help='command actions')
50  parser.add_argument('-c',dest='connect',action='store',
51  required=False,
52  help='connect string to lumiDB,optional',
53  default='frontier://LumiCalc/CMS_LUMI_PROD')
54  parser.add_argument('-P',dest='authpath',action='store',
55  required=False,
56  help='path to authentication file (optional)')
57  parser.add_argument('-r',dest='runnumber',action='store',
58  type=int,
59  required=False,
60  help='run number (optional)')
61  parser.add_argument('-o',dest='outputfile',action='store',
62  required=False,
63  help='output to csv file (optional)')
64  #################################################
65  #arg to select exact run and ls
66  #################################################
67  parser.add_argument('-i',dest='inputfile',action='store',
68  required=False,
69  help='run/ls selection file (optional)')
70  parser.add_argument('--name',dest='name',action='store',
71  help='hltpath/l1bit name/pattern'
72  )
73  #
74  #optional args to filter *runs*, they do not select on LS level.
75  #
76  parser.add_argument('-b',dest='beammode',action='store',
77  choices=beamModeChoices,
78  required=False,
79  help='beam mode choices [stable] (optional)')
80  parser.add_argument('-f','--fill',dest='fillnum',action='store',
81  default=None,required=False,
82  help='fill number (optional) ')
83  parser.add_argument('--amodetag',dest='amodetag',action='store',
84  choices=amodetagChoices,
85  required=False,
86  help='specific accelerator mode choices [PROTOPHYS,IONPHYS] (optional)')
87  parser.add_argument('--beamenergy',dest='beamenergy',action='store',
88  type=float,
89  default=None,
90  help='nominal beam energy in GeV')
91  parser.add_argument('--beamfluctuation',dest='beamfluctuation',
92  type=float,action='store',
93  default=0.2,
94  required=False,
95  help='fluctuation in fraction allowed to nominal beam energy, default 0.2, to be used together with -beamenergy (optional)')
96  parser.add_argument('--minintensity',dest='minintensity',
97  type=float,action='store',
98  default=0.1,
99  required=False,
100  help='filter on beam intensity , effective with --with-beamintensity (optional)')
101  parser.add_argument('--begin',dest='begin',action='store',
102  default=None,
103  required=False,
104  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$","must be form mm/dd/yy hh:mm:ss"),
105  help='min run start time, mm/dd/yy hh:mm:ss)'
106  )
107  parser.add_argument('--end',dest='end',action='store',
108  default=None,
109  required=False,
110  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$","must be form mm/dd/yy hh:mm:ss"),
111  help='max run start time, mm/dd/yy hh:mm:ss'
112  )
113  #################################################
114  #versions control
115  #################################################
116  parser.add_argument('--datatag',dest='datatag',action='store',
117  required=False,
118  help='version of lumi/trg/hlt data'
119  )
120  #
121  #command configuration
122  #
123  parser.add_argument('--siteconfpath',dest='siteconfpath',action='store',
124  default=None,
125  required=False,
126  help='specific path to site-local-config.xml file, optional. If path undefined, fallback to cern proxy&server')
127  #################################################
128  #switches
129  #################################################
130  parser.add_argument('--with-beamintensity',
131  dest='withbeamintensity',
132  action='store_true',
133  help='dump beam intensity'
134  )
135  parser.add_argument('--without-mask',
136  dest='withoutmask',
137  action='store_true',
138  help='not considering trigger mask'
139  )
140  parser.add_argument('--verbose',
141  dest='verbose',
142  action='store_true',
143  help='verbose mode for printing' )
144  parser.add_argument('--nowarning',
145  dest='nowarning',
146  action='store_true',
147  help='suppress bad for lumi warnings'
148  )
149  parser.add_argument('--debug',
150  dest='debug',
151  action='store_true',
152  help='debug')
153 
154  options=parser.parse_args()
155  if not options.runnumber and not options.inputfile and not options.fillnum and not options.begin:
156  raise RuntimeError('at least one run selection argument in [-r,-f,-i,--begin] is required')
157  reqrunmin=None
158  reqfillmin=None
159  reqtimemin=None
160  reqrunmax=None
161  reqfillmax=None
162  reqtimemax=None
163  timeFilter=[None,None]
164  pbeammode = None
165  iresults=[]
166  reqTrg=False
167  reqHlt=False
168  if options.beammode=='stable':
169  pbeammode = 'STABLE BEAMS'
170  if options.action=='trgbyls':
171  reqTrg=True
172  if options.action=='hltbyls':
173  reqHlt=True
174  if options.runnumber:
175  reqrunmax=options.runnumber
176  reqrunmin=options.runnumber
177  if options.fillnum:
178  reqfillmin=options.fillnum
179  reqfillmax=options.fillnum
180  if options.begin:
181  (reqrunmin,reqfillmin,reqtimemin)=CommonUtil.parseTime(options.begin)
182  if reqtimemin:
184  reqtimeminT=lute.StrToDatetime(reqtimemin,customfm='%m/%d/%y %H:%M:%S')
185  timeFilter[0]=reqtimeminT
186  if options.end:
187  (reqrunmax,reqfillmax,reqtimemax)=CommonUtil.parseTime(options.end)
188  if reqtimemax:
189  lute=lumiTime.lumiTime()
190  reqtimemaxT=lute.StrToDatetime(reqtimemax,customfm='%m/%d/%y %H:%M:%S')
191  timeFilter[1]=reqtimemaxT
192  sname=options.name
193  isdetail=False
194  spattern=None
195  if sname is not None:
196  isdetail=True
197  if sname=='*' or sname=='all':
198  sname=None
199  elif 1 in [c in sname for c in '*?[]']: #is a fnmatch pattern
200  spattern=sname
201  sname=None
202  if options.action == 'beambyls' and options.withbeamintensity and not options.outputfile:
203  print '[warning] --with-beamintensity must write data to a file, none specified using default "beamintensity.csv"'
204  options.outputfile='beamintensity.csv'
205 
206  ##############################################################
207  # check working environment
208  ##############################################################
209  #
210  # check DB environment
211  #
212  if options.authpath:
213  os.environ['CORAL_AUTH_PATH'] = options.authpath
214 
215  svc=sessionManager.sessionManager(options.connect,
216  authpath=options.authpath,
217  siteconfpath=options.siteconfpath,
218  debugON=options.debug)
219  session=svc.openSession(isReadOnly=True,cpp2sqltype=[('unsigned int','NUMBER(10)'),('unsigned long long','NUMBER(20)')])
220 
221  ##############################################################
222  # check run/ls list
223  ##############################################################
224 
225  irunlsdict={}
226  rruns=[]
227  session.transaction().start(True)
228  filerunlist=None
229  if options.inputfile:
230  (irunlsdict,iresults)=parseInputFiles(options.inputfile)
231  filerunlist=irunlsdict.keys()
232 
233  datatagname=options.datatag
234  if not datatagname:
235  (datatagid,datatagname)=revisionDML.currentDataTag(session.nominalSchema())
236  else:
237  datatagid=revisionDML.getDataTagId(session.nominalSchema(),datatagname)
238 
239  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)
240  if not dataidmap:
241  print '[INFO] No qualified run found, do nothing'
242  sys.exit(14)
243  rruns=[]
244  #crosscheck dataid value
245  for irun,(lid,tid,hid) in dataidmap.items():
246  if not lid:
247  print '[INFO] No qualified lumi data found for run, ',irun
248  if reqTrg and not tid:
249  print '[INFO] No qualified trg data found for run ',irun
250  continue
251  if reqHlt and not hid:
252  print '[INFO] No qualified hlt data found for run ',irun
253  continue
254  rruns.append(irun)
255  if not irunlsdict: #no file
256  irunlsdict=dict(zip(rruns,[None]*len(rruns)))
257  else:
258  for selectedrun in irunlsdict.keys():#if there's further filter on the runlist,clean input dict
259  if selectedrun not in rruns:
260  del irunlsdict[selectedrun]
261  if not irunlsdict:
262  print '[INFO] No qualified run found, do nothing'
263  sys.exit(13)
264 
265  session.transaction().commit()
266  thiscmmd=sys.argv[0]
267  lumiReport.toScreenHeader(thiscmmd,datatagname,'n/a','n/a','n/a','n/a')
268 
269  if options.action == 'trgbyls':
270  session.transaction().start(True)
271  result=lumiCalcAPI.trgForIds(session.nominalSchema(),irunlsdict,dataidmap,trgbitname=sname,trgbitnamepattern=spattern,withL1Count=True,withPrescale=True)
272  session.transaction().commit()
273  if not options.outputfile:
274  lumiReport.toScreenLSTrg(result,iresults=iresults,irunlsdict=irunlsdict,noWarning=options.nowarning,withoutmask=options.withoutmask)
275  else:
276  lumiReport.toScreenLSTrg(result,iresults=iresults,irunlsdict=irunlsdict,noWarning=options.nowarning,toFile=options.outputfile,withoutmask=options.withoutmask)
277  #print result
278  sys.exit(0)
279  if options.action == 'hltbyls':
280  if not options.name:
281  print '[ERROR] --name option is required by hltbyls, do nothing'
282  sys.exit(0)
283  withL1Pass=True
284  withHLTAccept=True
285  session.transaction().start(True)
286  result=lumiCalcAPI.hltForIds(session.nominalSchema(),irunlsdict,dataidmap,hltpathname=sname,hltpathpattern=spattern,withL1Pass=withL1Pass,withHLTAccept=withHLTAccept)
287  session.transaction().commit()
288  if not options.outputfile:
289  lumiReport.toScreenLSHlt(result,iresults=iresults)
290  else:
291  lumiReport.toScreenLSHlt(result,iresults=iresults,toFile=options.outputfile)
292  if options.action == 'hltmenu':
293  session.transaction().start(True)
294  result=lumiCalcAPI.hltpathsForRange(session.nominalSchema(),irunlsdict,hltpathname=sname,hltpathpattern=spattern)
295  session.transaction().commit()
296  #print result
297  if not options.outputfile:
298  lumiReport.toScreenConfHlt(result,iresults)
299  else:
300  lumiReport.toScreenConfHlt(result,iresults,toFile=options.outputfile)
301  if options.action == 'beambyls':
302  session.transaction().start(True)
303  dumpbeamintensity=False
304  if options.outputfile and options.verbose:
305  dumpbeamintensity=True
306  result=lumiCalcAPI.beamForIds(session.nominalSchema(),irunlsdict,dataidmap,withBeamIntensity=options.withbeamintensity,minIntensity=options.minintensity)
307  session.transaction().commit()
308  if not options.outputfile:
309  lumiReport.toScreenLSBeam(result,iresults=iresults,dumpIntensity=False)
310  else:
311  lumiReport.toScreenLSBeam(result,iresults=iresults,dumpIntensity=options.withbeamintensity,toFile=options.outputfile)
312  if options.action == 'runsummary':
313  session.transaction().start(True)
314  result=lumiCalcAPI.runsummary(session.nominalSchema(),irunlsdict)
315  session.transaction().commit()
317  for r in result:
318  run=r[0]
319  fill='n/a'
320  if r[5]:
321  fill=str(r[5])
322  starttime=c.StrToDatetime(r[7])
323  starttime=starttime.strftime('%m/%d/%y %H:%M:%S')
324  stoptime=c.StrToDatetime(r[8])
325  stoptime=stoptime.strftime('%m/%d/%y %H:%M:%S')
326  l1key=r[1]
327  hltkey=r[4]
328  amodetag=r[2]
329  egev='n/a'
330  if r[3]:
331  egev=str(r[3])
332  sequence=r[6]
333  print '==='
334  print 'Run ',str(run),' Fill ',fill,' Amodetag ',amodetag,' egev ',egev
335  print '\tStart '+starttime,' ',' Stop ',stoptime
336  print '\tL1key ',l1key,' HLTkey ',hltkey
337  del session
338  del svc
Definition: start.py:1
def parseInputFiles
Definition: lumiContext.py:12
def toScreenHeader
Definition: lumiReport.py:27
def toScreenLSHlt
Definition: lumiReport.py:1007
def toScreenConfHlt
Definition: lumiReport.py:1060
def toScreenLSBeam
Definition: lumiReport.py:1100
def toScreenLSTrg
Definition: lumiReport.py:942
def runsummary
Lumi data management and calculation API # # Author: Zhen Xie #.
Definition: lumiCalcAPI.py:10
def getDataTagId
Definition: revisionDML.py:658
def currentDataTag
Definition: revisionDML.py:513
def hltpathsForRange
Definition: lumiCalcAPI.py:53
def parseTime
Definition: CommonUtil.py:14