9 import os,os.path,sys,datetime,time,csv,re
10 from RecoLuminosity.LumiDB
import argparse,lumiTime,matplotRender,sessionManager,lumiParameters,RegexValidator,revisionDML,lumiCalcAPI,normDML
12 from matplotlib.figure
import Figure
16 output ({run:[cmsls,cmsls,...]},[[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)
36 if __name__==
'__main__':
37 referenceLabel=
'Delivered' 38 labels=[
'Delivered',
'Recorded']
39 allowedActions = [
'run',
'time',
'fill',
'perday',
'instpeakperday']
40 beamChoices=[
'PROTPHYS',
'IONPHYS',
'PAPHYS']
41 allowedscales=[
'linear',
'log',
'both']
42 beamModeChoices = [
"stable",
"quiet",
"either"]
43 amodetagChoices = [
"PROTPHYS",
"IONPHYS",
'PAPHYS' ]
44 actiontofilebasemap={
'time':
'lumivstime',
'run':
'lumivsrun',
'fill':
'lumivsfill',
'perday':
'lumiperday',
'instpeakperday':
'lumipeak'}
48 currentdir=os.getcwd()
49 rcparamfile=
'.lumiplotrc' 50 mplrcdir=matplotlib.get_configdir()
51 mpllumiconfig=os.path.join(mplrcdir,rcparamfile)
52 locallumiconfig=os.path.join(currentdir,rcparamfile)
53 figureparams={
'sizex':7.5,
'sizey':5.7,
'dpi':135}
54 if os.path.exists(locallumiconfig):
57 config=ConfigParser.RawConfigParser()
58 config.read(locallumiconfig)
59 figureparams[
'sizex']=config.getfloat(
'sizex')
60 figureparams[
'sizey']=config.getfloat(
'sizey')
61 figureparams[
'dpi']=config.getint(
'dpi')
62 except ConfigParser.NoOptionError:
64 elif os.path.exists(mpllumiconfig):
67 config=ConfigParser.RawConfigParser()
68 config.read(mpllumiconfig)
69 figureparams[
'sizex']=config.getfloat(
'sizex')
70 figureparams[
'sizey']=config.getfloat(
'sizey')
71 figureparams[
'dpi']=config.getint(
'dpi')
72 except ConfigParser.NoOptionError:
80 parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
81 description=
"Plot luminosity as function of the time variable of choice",
82 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
83 parser.add_argument(
'-c',
86 help=
'connect string to lumiDB',
87 default=
'frontier://LumiCalc/CMS_LUMI_PROD')
88 parser.add_argument(
'-P',
91 help=
'path to authentication file')
92 parser.add_argument(
'--datatag',
97 parser.add_argument(
'--normtag',
105 parser.add_argument(
'-i',
108 help=
'run/ls selection file')
112 parser.add_argument(
'--hltpath',
117 help=
'specific hltpath or hltpath pattern to calculate the effectived luminosity (optional)')
121 parser.add_argument(
'-b',
124 help=
'selection criteria beam status')
128 parser.add_argument(
'-f',
'--fill',
132 help=
'specific fill',
134 parser.add_argument(
'--amodetag',
137 help=
'accelerator mode')
138 parser.add_argument(
'--beamenergy',
143 help=
'beamenergy (in GeV) selection criteria')
144 parser.add_argument(
'--beamfluctuation',
145 dest=
'beamfluctuation',
149 help=
'allowed fraction of beamenergy to fluctuate')
150 parser.add_argument(
'--begin',
153 default=
'03/01/10 00:00:00',
155 help=
'min run start time,mm/dd/yy hh:mm:ss')
156 parser.add_argument(
'--end',
160 help=
'max run start time,mm/dd/yy hh:mm:ss')
164 parser.add_argument(
'--siteconfpath',
167 help=
'specific path to site-local-config.xml file, default to $CMS_PATH/SITECONF/local/JobConfig, if path undefined, fallback to cern proxy&server')
172 parser.add_argument(
'--inplotdata',
175 help=
'existing base plot(s) in text format')
176 parser.add_argument(
'--outplotdata',
179 help=
'output plot. By default, a text dump of the plot is produced.')
181 parser.add_argument(
'--with-annotation',
182 dest=
'withannotation',
184 help=
'annotate boundary run numbers')
185 parser.add_argument(
'--interactive',
188 help=
'graphical mode to draw plot in a QT pannel.')
189 parser.add_argument(
'--without-textoutput',
190 dest=
'withoutTextoutput',
192 help=
'not to write out text output file')
193 parser.add_argument(
'--without-png',
196 help=
'do not produce')
197 parser.add_argument(
'--yscale',
201 help=
'y_scale[linear,log,both]')
202 parser.add_argument(
'--lastpointfromdb',
203 dest=
'lastpointfromdb',
205 help=
'the last point in the plot is always recaculated from current values in LumiDB')
208 parser.add_argument(
'--without-correction',
211 help=
'without any correction/calibration')
214 parser.add_argument(
'--verbose',
217 help=
'verbose mode, print result also to screen')
218 parser.add_argument(
'--debug',
222 parser.add_argument(
'action',
223 choices=allowedActions,
224 help=
'type of plots')
225 options=parser.parse_args()
226 if options.yscale==
'both' and options.interactive:
227 print '--interactive mode can draw either yscale log or linear at a time' 229 outplotfilename = options.outplot
230 if not outplotfilename:
231 outplotfilename=actiontofilebasemap[options.action]
232 outtextfilename = outplotfilename+
'.csv' 233 if options.withoutTextoutput:
237 authpath=options.authpath,
238 siteconfpath=options.siteconfpath,
239 debugON=options.debug)
240 session=svc.openSession(isReadOnly=
True,cpp2sqltype=[(
'unsigned int',
'NUMBER(10)'),(
'unsigned long long',
'NUMBER(20)')])
241 lslength=lumip.lslengthsec()
242 begtime=options.begintime
243 endtime=options.endtime
246 endtime=lut.DatetimeToStr(datetime.datetime.utcnow(),customfm=
'%m/%d/%y %H:%M:%S')
248 if options.beamstatus==
'stable':
249 pbeammode=
'STABLE BEAMS' 255 inplot=options.inplot
257 inplots=inplot.split(
'+')
260 reader=csv.reader(f,delimiter=',')
262 if '#' in row[0]:
continue 263 resultlines.append(row)
280 session.transaction().
start(
True)
281 if options.action==
'perday' or options.action==
'instpeakperday':
282 maxDrawnDay=
int(lut.StrToDatetime(begtime,customfm=
'%m/%d/%y %H:%M:%S').
date().toordinal())
284 for drawnDay
in [
int(t[0])
for t
in resultlines]:
285 if drawnDay>maxDrawnDay:
287 newFirstDay=maxDrawnDay
288 midnight=datetime.time()
289 begT=datetime.datetime.combine(datetime.date.fromordinal(newFirstDay),midnight)
290 begTStr=lut.DatetimeToStr(begT,customfm=
'%m/%d/%y %H:%M:%S')
292 runlist=
lumiCalcAPI.runList(session.nominalSchema(),options.fillnum,runmin=
None,runmax=
None,startT=begTStr,stopT=endtime,l1keyPattern=
None,hltkeyPattern=
None,amodetag=options.amodetag,nominalEnergy=options.beamenergy,energyFlut=options.beamfluctuation,requiretrg=reqTrg,requirehlt=reqHlt)
293 if options.action==
'run' or options.action==
'time':
296 lastDrawnRun=
max([
int(t[0])
for t
in resultlines])
297 newFirstRun=lastDrawnRun+1
298 if options.lastpointfromdb:
299 newFirstRun=lastDrawnRun
300 runlist=
lumiCalcAPI.runList(session.nominalSchema(),options.fillnum,runmin=newFirstRun,runmax=
None,startT=begtime,stopT=endtime,l1keyPattern=
None,hltkeyPattern=
None,amodetag=options.amodetag,nominalEnergy=options.beamenergy,energyFlut=options.beamfluctuation,requiretrg=reqTrg,requirehlt=reqHlt)
301 if options.action==
'fill':
305 lastDrawnFill=
max([
int(t[0])
for t
in resultlines])
306 lastDrawnRun=
min([
int(t[1])
for t
in resultlines
if int(t[0])==lastDrawnFill])
307 newFirstRun=lastDrawnRun+1
308 if options.lastpointfromdb:
309 newFirstRun=lastDrawnRun
310 runlist=
lumiCalcAPI.runList(session.nominalSchema(),runmin=newFirstRun,runmax=
None,startT=begtime,stopT=endtime,l1keyPattern=
None,hltkeyPattern=
None,amodetag=options.amodetag,nominalEnergy=options.beamenergy,energyFlut=options.beamfluctuation,requiretrg=reqTrg,requirehlt=reqHlt)
311 fillrunMap=
lumiCalcAPI.fillrunMap(session.nominalSchema(),runmin=newFirstRun,runmax=
None,startT=begtime,stopT=endtime)
313 if options.inputfile:
316 if options.fillnum
or options.begin
or options.end
or options.amodetag
or options.beamenergy:
317 rruns=[val
for val
in runlist
if val
in irunlsdict.keys()]
318 for selectedrun
in irunlsdict.keys():
319 if selectedrun
not in rruns:
320 del irunlsdict[selectedrun]
322 rruns=irunlsdict.keys()
326 rruns=irunlsdict.keys()
329 print '[INFO] runs from db: ',irunlsdict
331 print '[INFO] last run in old plot: ',lastDrawnRun
332 print '[INFO] first run from DB in fresh plot: ',newFirstRun
334 print '[INFO] last day in old plot: ',maxDrawnDay
335 print '[INFO] first day from DB in fresh plot: ',newFirstDay
338 if len(resultlines)!=0:
339 print '[INFO] drawing all from old plot data' 341 print '[INFO] found no old nor new data, do nothing' 348 datatagname=options.datatag
361 if not options.withoutNorm:
362 normname=options.normtag
366 normname=normmap.keys()[0]
367 normid=normmap[normname]
371 raise RuntimeError(
'[ERROR] cannot resolve norm/correction')
375 fig=Figure(figsize=(figureparams[
'sizex'],figureparams[
'sizey']),dpi=figureparams[
'dpi'])
377 logfig=Figure(figsize=(figureparams[
'sizex'],figureparams[
'sizey']),dpi=figureparams[
'dpi'])
380 if not options.hltpath:
381 lumibyls=
lumiCalcAPI.lumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,normmap=normvalueDict,lumitype=
'HF')
383 referenceLabel=
'Recorded' 384 hltname=options.hltpath
386 if hltname==
'*' or hltname==
'all':
388 elif 1
in [c
in hltname
for c
in '*?[]']:
391 lumibyls=
lumiCalcAPI.effectiveLumiForIds(session.nominalSchema(),irunlsdict,dataidmap,runsummaryMap=GrunsummaryData,beamstatusfilter=pbeammode,normmap=normvalueDict,hltpathname=hltname,hltpathpattern=hltpat)
392 session.transaction().commit()
397 if options.action==
'run':
398 for run
in sorted(lumibyls):
399 rundata=lumibyls[run]
400 if not options.hltpath:
402 rawdata.setdefault(
'Delivered',[]).
append((run,sum([t[5]
for t
in rundata
if t[5]])))
403 rawdata.setdefault(
'Recorded',[]).
append((run,sum([t[6]
for t
in rundata
if t[6]])))
408 rawdata.setdefault(
'Recorded',[]).
append((run,sum([t[6]
for t
in rundata
if t[6]])))
409 for perlsdata
in rundata:
411 pathnames=effdict.keys()
412 for thispath
in pathnames:
413 pathdict.setdefault(thispath,[]).
append(effdict[thispath][3])
414 for thispath
in pathdict.keys():
415 labels.append(thispath)
416 rawdata.setdefault(thispath,[]).
append((run,sum([t
for t
in pathdict[thispath]
if t])))
417 if options.yscale==
'linear':
418 m.plotSumX_Run(rawdata,resultlines,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel,labels=labels)
419 elif options.yscale==
'log':
420 m.plotSumX_Run(rawdata,resultlines,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel,labels=labels)
422 m.plotSumX_Run(rawdata,resultlines,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel,labels=labels)
423 m.plotSumX_Run(rawdata,resultlines,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel,labels=labels)
424 if options.action==
'fill':
425 for fill
in sorted(fillrunMap):
426 for run
in fillrunMap[fill]:
427 if run
not in lumibyls:
continue 428 rundata=lumibyls[run]
429 if not options.hltpath:
431 rawdata.setdefault(
'Delivered',[]).
append((fill,run,sum([t[5]
for t
in rundata
if t[5]])))
432 rawdata.setdefault(
'Recorded',[]).
append((fill,run,sum([t[6]
for t
in rundata
if t[6]])))
437 rawdata.setdefault(
'Recorded',[]).
append((fill,run,sum([t[6]
for t
in rundata
if t[6]])))
438 for perlsdata
in rundata:
440 pathnames=effdict.keys()
441 for thispath
in pathnames:
442 pathdict.setdefault(thispath,[]).
append(effdict[thispath][3])
443 for thispath
in pathdict.keys():
444 labels.append(thispath)
445 rawdata.setdefault(thispath,[]).
append((fill,run,sum([t
for t
in pathdict[thispath]
if t])))
446 if options.yscale==
'linear':
447 m.plotSumX_Fill(rawdata,resultlines,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
448 elif options.yscale==
'log':
449 m.plotSumX_Fill(rawdata,resultlines,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
451 m.plotSumX_Fill(rawdata,resultlines,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
452 m.plotSumX_Fill(rawdata,resultlines,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
453 if options.action==
'time':
454 for run
in sorted(lumibyls):
455 rundata=lumibyls[run]
456 if not options.hltpath:
458 rawdata.setdefault(
'Delivered',[]).
append((run,rundata[0][2],rundata[-1][2],sum([t[5]
for t
in rundata
if t[5]])))
459 rawdata.setdefault(
'Recorded',[]).
append((run,rundata[0][2],rundata[-1][2],sum([t[6]
for t
in rundata
if t[6]])))
464 rawdata.setdefault(
'Recorded',[]).
append((run,rundata[0][2],rundata[-1][2],sum([t[6]
for t
in rundata
if t[6]])))
465 for perlsdata
in rundata:
467 pathnames=effdict.keys()
468 for thispath
in pathnames:
469 pathdict.setdefault(thispath,[]).
append(effdict[thispath][3])
470 for thispath
in pathdict.keys():
471 labels.append(thispath)
472 rawdata.setdefault(thispath,[]).
append((run,rundata[0][2],rundata[-1][2],sum([t
for t
in pathdict[thispath]
if t])))
473 if options.yscale==
'linear':
474 m.plotSumX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
475 elif options.yscale==
'log':
476 mlog.plotSumX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
478 m.plotSumX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
479 mlog.plotSumX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
480 if options.action==
'perday':
482 for run
in sorted(lumibyls):
483 rundata=lumibyls[run]
484 for lsdata
in rundata:
489 daynumber=lsTS.date().toordinal()
490 daydict.setdefault(daynumber,[]).
append((run,lumilsnum,dellum,reclum))
491 for day
in sorted(daydict):
493 daybeg=
str(daydata[0][0])+
':'+
str(daydata[0][1])
494 dayend=
str(daydata[-1][0])+
':'+
str(daydata[-1][1])
495 daydel=sum([t[2]
for t
in daydata
if t[2]])
496 dayrec=sum([t[3]
for t
in daydata
if t[3]])
497 rawdata.setdefault(
'Delivered',[]).
append((day,daybeg,dayend,daydel))
498 rawdata.setdefault(
'Recorded',[]).
append((day,daybeg,dayend,dayrec))
500 if options.yscale==
'linear':
501 m.plotPerdayX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
502 elif options.yscale==
'log':
503 mlog.plotPerdayX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
505 m.plotPerdayX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
506 mlog.plotPerdayX_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
507 if options.action==
'instpeakperday':
509 for run
in sorted(lumibyls):
510 rundata=lumibyls[run]
511 for lsdata
in rundata:
514 instlum=lsdata[5]/lslength
515 daynumber=lsTS.date().toordinal()
516 daydict.setdefault(daynumber,[]).
append((run,lumilsnum,instlum))
517 for day
in sorted(daydict):
522 for datatp
in daydata:
523 if datatp[2]>daymax_val:
527 rawdata.setdefault(
'Delivered',[]).
append((day,daymax_run,daymax_ls,daymax_val))
528 if options.yscale==
'linear':
529 m.plotPeakPerday_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
530 elif options.yscale==
'log':
531 mlog.plotPeakPerday_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
533 m.plotPeakPerday_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'linear',referenceLabel=referenceLabel)
534 mlog.plotPeakPerday_Time(rawdata,resultlines,minTime=begtime,maxTime=endtime,textoutput=outtextfilename,yscale=
'log',referenceLabel=referenceLabel)
535 if options.action==
'inst':
536 thisfillnumber=fillrunMap.keys()[0]
541 for run,rundata
in lumibyls.items():
545 starttime=rundata[0][2]
546 stoptime=rundata[-1][2]
547 for lsdata
in rundata:
556 rawydata.setdefault(
'Delivered',[]).
append(dellumi)
557 rawydata.setdefault(
'Recorded',[]).
append(reclumi)
558 rawxdata=[run,thisfillnumber,starttime,stoptime,totlumils,totcmsls]
559 m.plotInst_RunLS(rawxdata,rawydata,textoutput=
None)
561 if options.yscale==
'linear':
562 if options.interactive:
566 if not options.withoutpng:
567 m.drawPNG(outplotfilename+
'.png')
569 elif options.yscale==
'log':
570 if options.interactive:
571 mlog.drawInteractive()
574 if not options.withoutpng:
575 mlog.drawPNG(outplotfilename+
'_log.png')
578 if options.interactive:
579 print 'cannot draw both log and linear from interactive' 581 if not options.withoutpng:
582 m.drawPNG(outplotfilename+
'.png')
583 mlog.drawPNG(outplotfilename+
'_log.png')
def effectiveLumiForIds(schema, irunlsdict, dataidmap, runsummaryMap=None, beamstatusfilter=None, timeFilter=None, normmap=None, hltpathname=None, hltpathpattern=None, withBXInfo=False, bxAlgo=None, xingMinLum=None, withBeamIntensity=False, lumitype='HF', minbiasXsec=None)
def normIdByName(schema, normname)
def dataIdsByTagName(schema, tagname, runlist=None, withcomment=False, lumitype='HF')
def currentDataTag(schema, lumitype='HF')
def normIdByType(schema, lumitype='HF', defaultonly=True)
def runsummaryMap(schema, irunlsdict, dataidmap, lumitype='HF')
def parseInputFiles(inputfilename)
def lumiForIds(schema, irunlsdict, dataidmap, runsummaryMap, beamstatusfilter=None, timeFilter=None, normmap=None, withBXInfo=False, bxAlgo=None, xingMinLum=None, withBeamIntensity=False, lumitype='HF', minbiasXsec=None)
def fillrunMap(schema, fillnum=None, runmin=None, runmax=None, startT=None, stopT=None, l1keyPattern=None, hltkeyPattern=None, amodetag=None)
def normValueById(schema, normid)
def dataIdsByTagId(schema, tagid, runlist=None, withcomment=False, lumitype='HF')
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')