CMS 3D CMS Logo

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 from __future__ import print_function
10 import os,sys,time
11 from RecoLuminosity.LumiDB import sessionManager,lumiTime,inputFilesetParser,csvSelectionParser,csvReporter,argparse,CommonUtil,lumiCalcAPI,lumiReport,RegexValidator,lumiTime,revisionDML
12 
13 def parseInputFiles(inputfilename):
14  '''
15  output ({run:[cmsls,cmsls,...]},[[resultlines]])
16  '''
17  selectedrunlsInDB={}
18  resultlines=[]
20  runlsbyfile=p.runsandls()
21  selectedProcessedRuns=p.selectedRunsWithresult()
22  selectedNonProcessedRuns=p.selectedRunsWithoutresult()
23  resultlines=p.resultlines()
24  for runinfile in selectedNonProcessedRuns:
25  selectedrunlsInDB[runinfile]=runlsbyfile[runinfile]
26  return (selectedrunlsInDB,resultlines)
27 
28 ##############################
29 ## ######################## ##
30 ## ## ################## ## ##
31 ## ## ## Main Program ## ## ##
32 ## ## ################## ## ##
33 ## ######################## ##
34 ##############################
35 
36 if __name__ == '__main__':
37  parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),description = "Additional information needed in the lumi calculation",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
38  allowedActions = ['hltbyls','hltmenu','trgbyls', 'beambyls','runsummary']
39  amodetagChoices = [ "PROTPHYS","IONPHYS","PAPHYS" ]
40  beamModeChoices = ["stable"]
41  #
42  # parse arguments
43  #
44  #
45  ################################################
46  # basic arguments
47  ################################################
48  #
49  parser.add_argument('action',choices=allowedActions,
50  help='command actions')
51  parser.add_argument('-c',dest='connect',action='store',
52  required=False,
53  help='connect string to lumiDB,optional',
54  default='frontier://LumiCalc/CMS_LUMI_PROD')
55  parser.add_argument('-P',dest='authpath',action='store',
56  required=False,
57  help='path to authentication file (optional)')
58  parser.add_argument('-r',dest='runnumber',action='store',
59  type=int,
60  required=False,
61  help='run number (optional)')
62  parser.add_argument('-o',dest='outputfile',action='store',
63  required=False,
64  help='output to csv file (optional)')
65  #################################################
66  #arg to select exact run and ls
67  #################################################
68  parser.add_argument('-i',dest='inputfile',action='store',
69  required=False,
70  help='run/ls selection file (optional)')
71  parser.add_argument('--name',dest='name',action='store',
72  help='hltpath/l1bit name/pattern'
73  )
74  #
75  #optional args to filter *runs*, they do not select on LS level.
76  #
77  parser.add_argument('-b',dest='beammode',action='store',
78  choices=beamModeChoices,
79  required=False,
80  help='beam mode choices [stable] (optional)')
81  parser.add_argument('-f','--fill',dest='fillnum',action='store',
82  default=None,required=False,
83  help='fill number (optional) ')
84  parser.add_argument('--amodetag',dest='amodetag',action='store',
85  choices=amodetagChoices,
86  required=False,
87  help='specific accelerator mode choices [PROTOPHYS,IONPHYS] (optional)')
88  parser.add_argument('--beamenergy',dest='beamenergy',action='store',
89  type=float,
90  default=None,
91  help='nominal beam energy in GeV')
92  parser.add_argument('--beamfluctuation',dest='beamfluctuation',
93  type=float,action='store',
94  default=0.2,
95  required=False,
96  help='fluctuation in fraction allowed to nominal beam energy, default 0.2, to be used together with -beamenergy (optional)')
97  parser.add_argument('--minintensity',dest='minintensity',
98  type=float,action='store',
99  default=0.1,
100  required=False,
101  help='filter on beam intensity , effective with --with-beamintensity (optional)')
102  parser.add_argument('--begin',dest='begin',action='store',
103  default=None,
104  required=False,
105  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$","must be form mm/dd/yy hh:mm:ss"),
106  help='min run start time, mm/dd/yy hh:mm:ss)'
107  )
108  parser.add_argument('--end',dest='end',action='store',
109  default=None,
110  required=False,
111  type=RegexValidator.RegexValidator("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$","must be form mm/dd/yy hh:mm:ss"),
112  help='max run start time, mm/dd/yy hh:mm:ss'
113  )
114  #################################################
115  #versions control
116  #################################################
117  parser.add_argument('--datatag',dest='datatag',action='store',
118  required=False,
119  help='version of lumi/trg/hlt data'
120  )
121  #
122  #command configuration
123  #
124  parser.add_argument('--siteconfpath',dest='siteconfpath',action='store',
125  default=None,
126  required=False,
127  help='specific path to site-local-config.xml file, optional. If path undefined, fallback to cern proxy&server')
128  #################################################
129  #switches
130  #################################################
131  parser.add_argument('--with-beamintensity',
132  dest='withbeamintensity',
133  action='store_true',
134  help='dump beam intensity'
135  )
136  parser.add_argument('--without-mask',
137  dest='withoutmask',
138  action='store_true',
139  help='not considering trigger mask'
140  )
141  parser.add_argument('--verbose',
142  dest='verbose',
143  action='store_true',
144  help='verbose mode for printing' )
145  parser.add_argument('--nowarning',
146  dest='nowarning',
147  action='store_true',
148  help='suppress bad for lumi warnings'
149  )
150  parser.add_argument('--debug',
151  dest='debug',
152  action='store_true',
153  help='debug')
154 
155  options=parser.parse_args()
156  if not options.runnumber and not options.inputfile and not options.fillnum and not options.begin:
157  raise RuntimeError('at least one run selection argument in [-r,-f,-i,--begin] is required')
158  reqrunmin=None
159  reqfillmin=None
160  reqtimemin=None
161  reqrunmax=None
162  reqfillmax=None
163  reqtimemax=None
164  timeFilter=[None,None]
165  pbeammode = None
166  iresults=[]
167  reqTrg=False
168  reqHlt=False
169  if options.beammode=='stable':
170  pbeammode = 'STABLE BEAMS'
171  if options.action=='trgbyls':
172  reqTrg=True
173  if options.action=='hltbyls':
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  if options.begin:
182  (reqrunmin,reqfillmin,reqtimemin)=CommonUtil.parseTime(options.begin)
183  if reqtimemin:
185  reqtimeminT=lute.StrToDatetime(reqtimemin,customfm='%m/%d/%y %H:%M:%S')
186  timeFilter[0]=reqtimeminT
187  if options.end:
188  (reqrunmax,reqfillmax,reqtimemax)=CommonUtil.parseTime(options.end)
189  if reqtimemax:
190  lute=lumiTime.lumiTime()
191  reqtimemaxT=lute.StrToDatetime(reqtimemax,customfm='%m/%d/%y %H:%M:%S')
192  timeFilter[1]=reqtimemaxT
193  sname=options.name
194  isdetail=False
195  spattern=None
196  if sname is not None:
197  isdetail=True
198  if sname=='*' or sname=='all':
199  sname=None
200  elif 1 in [c in sname for c in '*?[]']: #is a fnmatch pattern
201  spattern=sname
202  sname=None
203  if options.action == 'beambyls' and options.withbeamintensity and not options.outputfile:
204  print('[warning] --with-beamintensity must write data to a file, none specified using default "beamintensity.csv"')
205  options.outputfile='beamintensity.csv'
206 
207  ##############################################################
208  # check working environment
209  ##############################################################
210  #
211  # check DB environment
212  #
213  if options.authpath:
214  os.environ['CORAL_AUTH_PATH'] = options.authpath
215 
216  svc=sessionManager.sessionManager(options.connect,
217  authpath=options.authpath,
218  siteconfpath=options.siteconfpath,
219  debugON=options.debug)
220  session=svc.openSession(isReadOnly=True,cpp2sqltype=[('unsigned int','NUMBER(10)'),('unsigned long long','NUMBER(20)')])
221 
222  ##############################################################
223  # check run/ls list
224  ##############################################################
225 
226  irunlsdict={}
227  rruns=[]
228  session.transaction().start(True)
229  filerunlist=None
230  if options.inputfile:
231  (irunlsdict,iresults)=parseInputFiles(options.inputfile)
232  filerunlist=irunlsdict.keys()
233 
234  datatagname=options.datatag
235  if not datatagname:
236  (datatagid,datatagname)=revisionDML.currentDataTag(session.nominalSchema())
237  else:
238  datatagid=revisionDML.getDataTagId(session.nominalSchema(),datatagname)
239 
240  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)
241  if not dataidmap:
242  print('[INFO] No qualified run found, do nothing')
243  sys.exit(14)
244  rruns=[]
245  #crosscheck dataid value
246  for irun,(lid,tid,hid) in dataidmap.items():
247  if not lid:
248  print('[INFO] No qualified lumi data found for run, ',irun)
249  if reqTrg and not tid:
250  print('[INFO] No qualified trg data found for run ',irun)
251  continue
252  if reqHlt and not hid:
253  print('[INFO] No qualified hlt data found for run ',irun)
254  continue
255  rruns.append(irun)
256  if not irunlsdict: #no file
257  irunlsdict=dict(list(zip(rruns,[None]*len(rruns))))
258  else:
259  for selectedrun in irunlsdict.keys():#if there's further filter on the runlist,clean input dict
260  if selectedrun not in rruns:
261  del irunlsdict[selectedrun]
262  if not irunlsdict:
263  print('[INFO] No qualified run found, do nothing')
264  sys.exit(13)
265 
266  session.transaction().commit()
267  thiscmmd=sys.argv[0]
268  lumiReport.toScreenHeader(thiscmmd,datatagname,'n/a','n/a','n/a','n/a')
269 
270  if options.action == 'trgbyls':
271  session.transaction().start(True)
272  result=lumiCalcAPI.trgForIds(session.nominalSchema(),irunlsdict,dataidmap,trgbitname=sname,trgbitnamepattern=spattern,withL1Count=True,withPrescale=True)
273  session.transaction().commit()
274  if not options.outputfile:
275  lumiReport.toScreenLSTrg(result,iresults=iresults,irunlsdict=irunlsdict,noWarning=options.nowarning,withoutmask=options.withoutmask)
276  else:
277  lumiReport.toScreenLSTrg(result,iresults=iresults,irunlsdict=irunlsdict,noWarning=options.nowarning,toFile=options.outputfile,withoutmask=options.withoutmask)
278  #print result
279  sys.exit(0)
280  if options.action == 'hltbyls':
281  if not options.name:
282  print('[ERROR] --name option is required by hltbyls, do nothing')
283  sys.exit(0)
284  withL1Pass=True
285  withHLTAccept=True
286  session.transaction().start(True)
287  result=lumiCalcAPI.hltForIds(session.nominalSchema(),irunlsdict,dataidmap,hltpathname=sname,hltpathpattern=spattern,withL1Pass=withL1Pass,withHLTAccept=withHLTAccept)
288  session.transaction().commit()
289  if not options.outputfile:
290  lumiReport.toScreenLSHlt(result,iresults=iresults)
291  else:
292  lumiReport.toScreenLSHlt(result,iresults=iresults,toFile=options.outputfile)
293  if options.action == 'hltmenu':
294  session.transaction().start(True)
295  result=lumiCalcAPI.hltpathsForRange(session.nominalSchema(),irunlsdict,hltpathname=sname,hltpathpattern=spattern)
296  session.transaction().commit()
297  #print result
298  if not options.outputfile:
299  lumiReport.toScreenConfHlt(result,iresults)
300  else:
301  lumiReport.toScreenConfHlt(result,iresults,toFile=options.outputfile)
302  if options.action == 'beambyls':
303  session.transaction().start(True)
304  dumpbeamintensity=False
305  if options.outputfile and options.verbose:
306  dumpbeamintensity=True
307  result=lumiCalcAPI.beamForIds(session.nominalSchema(),irunlsdict,dataidmap,withBeamIntensity=options.withbeamintensity,minIntensity=options.minintensity)
308  session.transaction().commit()
309  if not options.outputfile:
310  lumiReport.toScreenLSBeam(result,iresults=iresults,dumpIntensity=False)
311  else:
312  lumiReport.toScreenLSBeam(result,iresults=iresults,dumpIntensity=options.withbeamintensity,toFile=options.outputfile)
313  if options.action == 'runsummary':
314  session.transaction().start(True)
315  result=lumiCalcAPI.runsummary(session.nominalSchema(),irunlsdict)
316  session.transaction().commit()
318  for r in result:
319  run=r[0]
320  fill='n/a'
321  if r[5]:
322  fill=str(r[5])
323  starttime=c.StrToDatetime(r[7])
324  starttime=starttime.strftime('%m/%d/%y %H:%M:%S')
325  stoptime=c.StrToDatetime(r[8])
326  stoptime=stoptime.strftime('%m/%d/%y %H:%M:%S')
327  l1key=r[1]
328  hltkey=r[4]
329  amodetag=r[2]
330  egev='n/a'
331  if r[3]:
332  egev=str(r[3])
333  sequence=r[6]
334  print('===')
335  print('Run ',str(run),' Fill ',fill,' Amodetag ',amodetag,' egev ',egev)
336  print('\tStart '+starttime,' ',' Stop ',stoptime)
337  print('\tL1key ',l1key,' HLTkey ',hltkey)
338  del session
339  del svc
def parseInputFiles(inputfilename)
Definition: lumiContext.py:13
Definition: start.py:1
def toScreenLSHlt(hltdata, iresults=[], toFile=None)
Definition: lumiReport.py:1010
def hltpathsForRange(schema, runlist, hltpathname=None, hltpathpattern=None)
Definition: lumiCalcAPI.py:54
def currentDataTag(schema, lumitype='HF')
Definition: revisionDML.py:515
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def toScreenConfHlt(hltconfdata, iresults=[], toFile=None)
Definition: lumiReport.py:1063
def toScreenLSTrg(trgdata, iresults=[], irunlsdict=None, noWarning=True, toFile=None, withoutmask=False)
Definition: lumiReport.py:945
def hltForIds(schema, irunlsdict, dataidmap, hltpathname=None, hltpathpattern=None, withL1Pass=False, withHLTAccept=False)
Definition: lumiCalcAPI.py:153
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
def beamForIds(schema, irunlsdict, dataidmap, withBeamIntensity=False, minIntensity=0.1)
Definition: lumiCalcAPI.py:116
def parseTime(iTime)
Definition: CommonUtil.py:16
def toScreenHeader(commandname, datatagname, normtag, worktag, updatetag, lumitype, toFile=None)
Definition: lumiReport.py:30
def trgForIds(schema, irunlsdict, dataidmap, trgbitname=None, trgbitnamepattern=None, withL1Count=False, withPrescale=False)
Definition: lumiCalcAPI.py:198
#define str(s)
def toScreenLSBeam(beamdata, iresults=[], dumpIntensity=False, toFile=None)
Definition: lumiReport.py:1103
def runsummary(schema, irunlsdict)
Lumi data management and calculation API # # Author: Zhen Xie #.
Definition: lumiCalcAPI.py:11
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run
def getDataTagId(schema, tagname, lumitype='HF')
Definition: revisionDML.py:660
def runList(schema, datatagid, runmin=None, runmax=None, fillmin=None, fillmax=None, startT=None, stopT=None, l1keyPattern=None, hltkeyPattern=None, amodetag=None, nominalEnergy=None, energyFlut=0.2, requiretrg=True, requirehlt=True, preselectedruns=None, lumitype='HF')
Definition: lumiCalcAPI.py:48