CMS 3D CMS Logo

matplotRender.py
Go to the documentation of this file.
1 '''
2 Specs:
3 -- We use matplotlib OO class level api, we do not use its high-level helper modules. Favor endured stability over simplicity.
4 -- PNG as default batch file format
5 -- we support http mode by sending string buf via meme type image/png. Sending a premade static plot to webserver is considered a uploading process instead of http dynamic graphical mode.
6 '''
7 from __future__ import print_function
8 import sys,os
9 import numpy,datetime
10 import matplotlib
11 from RecoLuminosity.LumiDB import CommonUtil,lumiTime,csvReporter
12 
13 batchonly=False
14 if 'DISPLAY' not in os.environ or not os.environ['DISPLAY']:
15  batchonly=True
16  matplotlib.use('Agg',warn=False)
17 else:
18  try:
19  from RecoLuminosity.LumiDB import lumiQTWidget
20  except ImportError:
21  print('unable to import GUI backend, switch to batch only mode')
22  matplotlib.use('Agg',warn=False)
23  batchonly=True
24 from matplotlib.backends.backend_agg import FigureCanvasAgg as CanvasBackend
25 from matplotlib.figure import Figure
26 from matplotlib.font_manager import fontManager,FontProperties
27 matplotlib.rcParams['lines.linewidth']=1.5
28 matplotlib.rcParams['grid.linewidth']=0.2
29 matplotlib.rcParams['xtick.labelsize']=11
30 matplotlib.rcParams['ytick.labelsize']=11
31 matplotlib.rcParams['legend.fontsize']=10
32 matplotlib.rcParams['axes.labelsize']=11
33 matplotlib.rcParams['font.weight']=567
34 
36  '''
37  input : largest total lumivalue
38  output: (unitstring,denomitor)
39  '''
40  unitstring='$\mu$b$^{-1}$s$^{-1}$'
41  denomitor=1.0
42  if t>=1.0e3 and t<1.0e06:
43  denomitor=1.0e3
44  unitstring='nb$^{-1}$s$^{-1}$'
45  elif t>=1.0e6 and t<1.0e9:
46  denomitor=1.0e6
47  unitstring='pb$^{-1}$s$^{-1}$'
48  elif t>=1.0e9 and t<1.0e12:
49  denomitor=1.0e9
50  unitstring='fb$^{-1}$s$^{-1}$'
51  elif t>=1.0e12 and t<1.0e15:
52  denomitor=1.0e12
53  unitstring='ab$^{-1}$s$^{-1}$'
54  elif t<=1.0e-3 and t>1.0e-6: #left direction
55  denomitor=1.0e-3
56  unitstring='mb$^{-1}$s$^{-1}$'
57  elif t<=1.0e-6 and t>1.0e-9:
58  denomitor=1.0e-6
59  unitstring='b$^{-1}$s$^{-1}$'
60  elif t<=1.0e-9 and t>1.0e-12:
61  denomitor=1.0e-9
62  unitstring='kb$^{-1}$s$^{-1}$'
63  return (unitstring,denomitor)
64 
66  '''
67  input : largest total lumivalue
68  output: (unitstring,denomitor)
69  '''
70  unitstring='$\mu$b$^{-1}$'
71  denomitor=1.0
72  if t>=1.0e3 and t<1.0e06:
73  denomitor=1.0e3
74  unitstring='nb$^{-1}$'
75  elif t>=1.0e6 and t<1.0e9:
76  denomitor=1.0e6
77  unitstring='pb$^{-1}$'
78  elif t>=1.0e9 and t<1.0e12:
79  denomitor=1.0e9
80  unitstring='fb$^{-1}$'
81  elif t>=1.0e12 and t<1.0e15:
82  denomitor=1.0e12
83  unitstring='ab$^{-1}$'
84  elif t<=1.0e-3 and t>1.0e-6: #left direction
85  denomitor=1.0e-3
86  unitstring='mb$^{-1}$'
87  elif t<=1.0e-6 and t>1.0e-9:
88  denomitor=1.0e-6
89  unitstring='b$^{-1}$'
90  elif t<=1.0e-9 and t>1.0e-12:
91  denomitor=1.0e-9
92  unitstring='kb$^{-1}$'
93  return (unitstring,denomitor)
94 
95 class matplotRender():
96  def __init__(self,fig):
97  self.__fig=fig
98  self.__canvas=''
99  self.colormap={}
100  self.colormap['Delivered']='r'
101  self.colormap['Recorded']='b'
102  self.colormap['Effective']='g'
103  self.colormap['Max Inst']='r'
104 
105  def plotSumX_Run(self,rawdata={},resultlines=[],minRun=None,maxRun=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None):
106  '''
107  input:
108  rawdata = {'Delivered':[(runnumber,lumiperrun),..],'Recorded':[(runnumber,lumiperrun),..]}
109  resultlines = [[runnumber,dellumiperrun,reclumiperrun],[runnumber,dellumiperrun,reclumiperrun],]
110  minRun : minimal runnumber required
111  maxRun : max runnumber required
112  yscale: linear,log or both
113  withannotation: wheather the boundary points should be annotated
114  referenceLabel: the one variable that decides the total unit and the plot x-axis range
115  labels: labels of the variables to plot
116  textoutput: text output file name.
117  '''
118  ypoints={}
119  ytotal={}
120  for r in resultlines:#parse old text data
121  runnumber=int(r[0])
122  if rawdata and runnumber in [t[0] for t in rawdata[referenceLabel]]:continue#use text input only if not in selected data
123  if minRun and runnumber<minRun: continue
124  if maxRun and runnumber>maxRun: continue
125  for i,lab in enumerate(labels) :
126  v=float(r[-(len(labels)-i)-1])#the values to plot are always the last n fields
127  rawdata.setdefault(lab,[]).append((runnumber,v))
128  if not rawdata:
129  print('[WARNING]: no data to plot , exit')
130  return
131 
132  tot=sum([t[1] for t in rawdata[referenceLabel]])
133  (unitstring,denomitor)=guessLumiUnit(tot)
134  csvreport=None
135  rows=[]
136  flat=[]
137  for label,yvalues in rawdata.items():
138  yvalues.sort()
139  flat.append([t[1] for t in yvalues])
140  ypoints[label]=[]
141  ytotal[label]=0.0
142  lumivals=[t[1] for t in yvalues]
143  for i,val in enumerate(lumivals):
144  ypoints[label].append(sum(lumivals[0:i+1])/denomitor)#integrated lumi
145  ytotal[label]=sum(lumivals)/denomitor
146  xpoints=[t[0] for t in rawdata[referenceLabel]]
147  ax=self.__fig.add_subplot(111)
148  if yscale=='linear':
149  ax.set_yscale('linear')
150  elif yscale=='log':
151  ax.set_yscale('log')
152  else:
153  raise RuntimeError('unsupported yscale '+yscale)
154  ax.set_xlabel(r'Run',position=(0.95,0))
155  ax.set_ylabel(r'L '+unitstring,position=(0,0.9))
156  xticklabels=ax.get_xticklabels()
157  for tx in xticklabels:
158  tx.set_rotation(30)
159  majorLocator=matplotlib.ticker.LinearLocator( nticks )
160  majorFormatter=matplotlib.ticker.FormatStrFormatter('%d')
161  minorLocator=matplotlib.ticker.LinearLocator(numticks=4*nticks)
162  ax.xaxis.set_major_locator(majorLocator)
163  ax.xaxis.set_major_formatter(majorFormatter)
164  ax.xaxis.set_minor_locator(minorLocator)
165  ax.set_xbound(lower=xpoints[0],upper=xpoints[-1])
166  ax.grid(True)
167  keylist=sorted(ypoints.keys())
168  keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on
169  legendlist=[]
170  head=['#Run']
171  textsummaryhead=['#TotalRun']
172  textsummaryline=['#'+str(len(xpoints))]
173  for ylabel in keylist:
174  cl='k'
175  if ylabel in self.colormap:
176  cl=self.colormap[ylabel]
177  ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps')
178  legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring)
179  textsummaryhead.append('Total'+ylabel)
180  textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring)
181  head.append(ylabel)
182  if textoutput:
183  csvreport=csvReporter.csvReporter(textoutput)
184  csvreport.writeRow(head)
185  allruns=[int(t[0]) for t in rawdata[referenceLabel]]
186  flat.insert(0,allruns)
187  rows=list(zip(*flat))
188  csvreport.writeRows([list(t) for t in rows])
189  csvreport.writeRow(textsummaryhead)
190  csvreport.writeRow(textsummaryline)
191  #font=FontProperties(size='medium',weight='demibold')
192  #legend
193  ax.legend(tuple(legendlist),loc='upper left')
194  #adjust
195  self.__fig.subplots_adjust(bottom=0.18,left=0.1)
196  #annotations
197  if withannotation:
198  trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
199  ax.text(xpoints[0],1.025,str(xpoints[0]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
200  ax.text(xpoints[-1],1.025,str(xpoints[-1]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
201 
202 
203  def plotSumX_Fill(self,rawdata={},resultlines=[],minFill=None,maxFill=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None):
204  '''
205  input:
206  rawdata = {'Delivered':[(fill,runnumber,lumiperrun)],'Recorded':[(fill,runnumber,lumiperrun)]}
207  resultlines = [[fillnumber,runnumber,dellumiperrun,reclumiperrun],[fillnumber,runnumber,dellumiperrun,reclumiperrun],]
208  minFill : min fill to draw
209  maxFill : max fill to draw
210  yscale: linear,log or both
211  withannotation: wheather the boundary points should be annotated
212  textoutput: text output file name.
213  '''
214  ytotal={}
215  ypoints={}
216  for r in resultlines: #parse old text data
217  fillnum=int(r[0])
218  runnum=int(r[1])
219  if rawdata and (fillnum,runnum) in [(t[0],t[1]) for t in rawdata[referenceLabel]]:continue
220  if minFill and fillnum<minFill:continue
221  if maxFill and fillnum>maxFill:continue
222  for i,lab in enumerate(labels) :
223  v=float(r[-(len(labels)-i)])#the values to plot are always the last n fields
224  rawdata.setdefault(lab,[]).append((fillnum,runnum,v))
225  #print 'fillrunDict ',fillrunDict
226  if not rawdata:
227  print('[WARNING]: no data, do nothing')
228  return
229  tot=sum([t[2] for t in rawdata[referenceLabel]])
230  beginfo=''
231  endinfo=''
232  (unitstring,denomitor)=guessLumiUnit(tot)
233  csvreport=None
234  rows=[]
235  flat=[]
236  for label,yvalues in rawdata.items():
237  yvalues.sort()
238  flat.append([t[2] for t in yvalues])
239  ypoints[label]=[]
240  ytotal[label]=0.0
241  lumivals=[t[2] for t in yvalues]
242  for i,val in enumerate(lumivals):
243  ypoints[label].append(sum(lumivals[0:i+1])/denomitor)
244  ytotal[label]=sum(lumivals)/denomitor
245  xpoints=[t[0] for t in rawdata[referenceLabel]]#after sort
246  ax=self.__fig.add_subplot(111)
247  ax.set_xlabel(r'LHC Fill Number',position=(0.84,0))
248  ax.set_ylabel(r'L '+unitstring,position=(0,0.9))
249  ax.set_xbound(lower=xpoints[0],upper=xpoints[-1])
250  if yscale=='linear':
251  ax.set_yscale('linear')
252  elif yscale=='log':
253  ax.set_yscale('log')
254  else:
255  raise RuntimeError('unsupported yscale '+yscale)
256  xticklabels=ax.get_xticklabels()
257  majorLocator=matplotlib.ticker.LinearLocator( nticks )
258  majorFormatter=matplotlib.ticker.FormatStrFormatter('%d')
259  #minorLocator=matplotlib.ticker.MultipleLocator(sampleinterval)
260  ax.xaxis.set_major_locator(majorLocator)
261  ax.xaxis.set_major_formatter(majorFormatter)
262  #ax.xaxis.set_minor_locator(minorLocator)
263  ax.grid(True)
264  keylist=sorted(ypoints.keys())
265  keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on
266  legendlist=[]
267  head=['#fill','run']
268  textsummaryhead=['#TotalFill']
269  textsummaryline=['#'+str(len(xpoints))]
270  for ylabel in keylist:
271  cl='k'
272  if ylabel in self.colormap:
273  cl=self.colormap[ylabel]
274  ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps')
275  legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring)
276  textsummaryhead.append('Total'+ylabel)
277  textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring)
278  head.append(ylabel)
279  if textoutput:
280  csvreport=csvReporter.csvReporter(textoutput)
281  allfills=[int(t[0]) for t in rawdata[referenceLabel]]
282  allruns=[int(t[1]) for t in rawdata[referenceLabel]]
283  flat.insert(0,allfills)
284  flat.insert(1,allruns)
285  rows=list(zip(*flat))
286  csvreport.writeRow(head)
287  csvreport.writeRows([list(t) for t in rows])
288  csvreport.writeRow(textsummaryhead)
289  csvreport.writeRow(textsummaryline)
290  #font=FontProperties(size='medium',weight='demibold')
291  #annotations
292  if withannotation:
293  trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
294  ax.text(xpoints[0],1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
295  ax.text(xpoints[-1],1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
296  #legend
297  ax.legend(tuple(legendlist),loc='upper left')
298  #adjust
299  self.__fig.subplots_adjust(bottom=0.1,left=0.1)
300 
301  def plotSumX_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None):
302  '''
303  input:
304  rawdata = {'Delivered':[(runnumber,starttimestamp,stoptimestamp,lumiperrun)],'Recorded':[(runnumber,starttimestamp,stoptimestamp,lumiperrun)]}
305  resultlines = [[runnumber,starttimestampStr,stoptimestampStr,dellumiperrun,reclumiperrun],[runnumber,starttimestampStr,stoptimestampStr,dellumiperrun,reclumiperrun],]
306  minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S
307  maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S
308  yscale: linear,log or both
309  withannotation: wheather the boundary points should be annotated
310  referenceLabel: the one variable that decides the total unit and the plot x-axis range
311  labels: labels of the variables to plot
312  '''
313  xpoints=[]
314  ypoints={}
315  ytotal={}
316  lut=lumiTime.lumiTime()
317  if not minTime:
318  minTime='03/01/10 00:00:00'
319  minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S')
320  if not maxTime:
321  maxTime=datetime.datetime.utcnow()
322  else:
323  maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S')
324  for r in resultlines:
325  runnumber=int(r[0])
326  starttimeStr=r[1].split('.')[0]
327  starttime=lut.StrToDatetime(starttimeStr,customfm='%Y-%m-%d %H:%M:%S')
328  stoptimeStr=r[2].split('.')[0]
329  stoptime=lut.StrToDatetime(stoptimeStr,customfm='%Y-%m-%d %H:%M:%S')
330  if rawdata and runnumber in [t[0] for t in rawdata[referenceLabel]]:continue
331  if starttime<minTime:continue
332  if starttime>maxTime:continue
333 
334  for i,lab in enumerate(labels):
335  v=float(r[-(len(labels)-i)])
336  rawdata.setdefault(lab,[]).append((runnumber,starttime,stoptime,v))
337  if not rawdata:
338  print('[WARNING]: no data, do nothing')
339  return
340  tot=sum([t[3] for t in rawdata[referenceLabel]])
341  (unitstring,denomitor)=guessLumiUnit(tot)
342  csvreport=None
343  rows=[]
344  flat=[]
345  for label,yvalues in rawdata.items():
346  yvalues.sort()
347  flat.append([t[3] for t in yvalues])
348  if label==referenceLabel:
349  minTime=yvalues[0][1]
350  maxTime=yvalues[-1][1]
351  ypoints[label]=[]
352  lumivals=[t[3] for t in yvalues]
353  for i,val in enumerate(lumivals):
354  ypoints[label].append(sum(lumivals[0:i+1])/denomitor)
355  ytotal[label]=sum(lumivals)/denomitor
356  xpoints=[matplotlib.dates.date2num(t[1]) for t in rawdata[referenceLabel]]
357  ax=self.__fig.add_subplot(111)
358  ax.set_yscale(yscale)
359  yearStrMin=minTime.strftime('%Y')
360  yearStrMax=maxTime.strftime('%Y')
361  if yearStrMin==yearStrMax:
362  dateFmt=matplotlib.dates.DateFormatter('%d/%m')
363  else:
364  dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y')
365  majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks)
366  ax.xaxis.set_major_locator(majorLoc)
367  minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4)
368  ax.xaxis.set_major_formatter(dateFmt)
369  ax.set_xlabel(r'Date',position=(0.84,0))
370  ax.set_ylabel(r'L '+unitstring,position=(0,0.9))
371  ax.xaxis.set_minor_locator(minorLoc)
372  ax.set_xbound(lower=xpoints[0],upper=xpoints[-1])
373  xticklabels=ax.get_xticklabels()
374  for tx in xticklabels:
375  tx.set_horizontalalignment('left')
376  ax.grid(True)
377  keylist=sorted(ypoints.keys())
378  keylist.insert(0,keylist.pop(keylist.index(referenceLabel)))#move refereceLabel to front from now on
379  legendlist=[]
380  head=['#Run','StartTime','StopTime']
381  textsummaryhead=['#TotalRun']
382  textsummaryline=['#'+str(len(xpoints))]
383  for ylabel in keylist:
384  cl='k'
385  if ylabel in self.colormap:
386  cl=self.colormap[ylabel]
387  ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps')
388  legendlist.append(ylabel+' '+'%.3f'%(ytotal[ylabel])+' '+unitstring)
389  textsummaryhead.append('Total'+ylabel)
390  textsummaryline.append('%.3f'%(ytotal[ylabel])+' '+unitstring)
391  head.append(ylabel)
392  if textoutput:
393  csvreport=csvReporter.csvReporter(textoutput)
394  csvreport.writeRow(head)
395  allruns=[int(t[0]) for t in rawdata[referenceLabel]]
396  allstarts=[ lut.DatetimeToStr(t[1],customfm='%Y-%m-%d %H:%M:%S') for t in rawdata[referenceLabel] ]
397  allstops=[ lut.DatetimeToStr(t[2],customfm='%Y-%m-%d %H:%M:%S') for t in rawdata[referenceLabel] ]
398  flat.insert(0,allruns)
399  flat.insert(1,allstarts)
400  flat.insert(2,allstops)
401  rows=list(zip(*flat))
402  csvreport.writeRows([list(t) for t in rows])
403  csvreport.writeRow(textsummaryhead)
404  csvreport.writeRow(textsummaryline)
405  #annotations
406  trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
407  #print 'run boundary ',runs[0],runs[-1]
408  #print 'xpoints boundary ',xpoints[0],xpoints[-1]
409  #annotation
410  if withannotation:
411  runs=[t[0] for t in rawdata[referenceLabel]]
412  ax.text(xpoints[0],1.025,str(runs[0]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
413  ax.text(xpoints[-1],1.025,str(runs[-1]),transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
414 
415  if yearStrMin==yearStrMax:
416  firsttimeStr=rawdata[referenceLabel][1][1].strftime('%b %d %H:%M') #time range(start) in the title is the first run beg time
417  lasttimeStr=rawdata[referenceLabel][-1][2].strftime('%b %d %H:%M') #time range(stop) in the tile is the last run stop time
418  #firstimeStr=minTime.strftime('%b %d %H:%M')
419  #lasttimeStr=maxTime.strftime('%b %d %H:%M')
420  #ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+' ('+firstimeStr+' - '+lasttimeStr+' UTC)',size='small',family='fantasy')
421  ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+' ('+firsttimeStr+' - '+lasttimeStr+' UTC)',size='small')
422  else:
423  #ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+'-'+yearStrMax,size='small',family='fantasy')
424  ax.set_title('CMS Total Integrated Luminosity '+yearStrMin+'-'+yearStrMax,size='small')
425  ax.legend(tuple(legendlist),loc='upper left')
426  ax.autoscale_view(tight=True,scalex=True,scaley=False)
427  self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right')
428  self.__fig.subplots_adjust(bottom=0.2,left=0.15)
429 
430  def plotPerdayX_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,yscale='linear',withannotation=False,referenceLabel='Delivered',labels=['Delivered','Recorded'],textoutput=None):
431  '''
432  Input:
433  rawdata={'Delivered':[(day,begrun:ls,endrun:ls,lumi)],'Recorded':[(dayofyear,begrun:ls,endrun:ls,lumi)]}
434  resultlines=[[day,begrun:ls,endrun:ls,deliveredperday,recordedperday],[]]
435  minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S
436  maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S
437  withannotation: wheather the boundary points should be annotated
438  referenceLabel: the one variable that decides the total unit and the plot x-axis range
439  labels: labels of the variables to plot
440  '''
441  xpoints=[]
442  ypoints={}
443  ymax={}
444  lut=lumiTime.lumiTime()
445  if not minTime:
446  minTime='03/01/10 00:00:00'
447  minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S')
448  if not maxTime:
449  maxTime=datetime.datetime.utcnow()
450  else:
451  maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S')
452  for r in resultlines:
453  day=int(r[0])
454  begrunls=r[1]
455  endrunls=r[2]
456  #[begrun,begls]=[int(s) for s in r[1].split(':')]
457  if rawdata and day in [t[0] for t in rawdata[referenceLabel]]:continue
458  if day < minTime.date().toordinal():continue
459  if day > maxTime.date().toordinal():continue
460  for i,lab in enumerate(labels):
461  v=float(r[-(len(labels)-i)-1])
462  rawdata.setdefault(lab,[]).append((day,begrunls,endrunls,v))
463  if not rawdata:
464  print('[WARNING]: no data, do nothing')
465  return
466  maxlum=max([t[3] for t in rawdata[referenceLabel]])
467  minlum=min([t[3] for t in rawdata[referenceLabel] if t[3]>0]) #used only for log scale, fin the non-zero bottom
468  (unitstring,denomitor)=guessLumiUnit(maxlum)
469  csvreport=None
470  rows=[]
471  flat=[]
472  MinDay=minTime.date().toordinal()
473  MaxDay=maxTime.date().toordinal()
474  fulldays=range(MinDay,MaxDay+1)
475  allstarts=[]
476  allstops=[]
477  for label,yvalues in rawdata.items():
478  yvalues.sort()
479  flat.append([t[3] for t in yvalues])
480  alldays=[t[0] for t in yvalues]
481  alldates=[str(datetime.date.fromordinal(t)) for t in alldays]
482  ypoints[label]=[]
483  lumivals=[t[3] for t in yvalues]
484  for d in fulldays:
485  if not d in alldays:
486  ypoints[label].append(0.0)
487  else:
488  thisdaylumi=[t[3] for t in yvalues if t[0]==d][0]
489  if yscale=='log':
490  if thisdaylumi<minlum:
491  thisdaylumi=minlum/denomitor
492  else:
493  thisdaylumi=thisdaylumi/denomitor
494  else:
495  thisdaylumi=thisdaylumi/denomitor
496  ypoints[label].append(thisdaylumi)
497  ymax[label]=max(lumivals)/denomitor
498  xpoints=fulldays
499  if textoutput:
500  csvreport=csvReporter.csvReporter(textoutput)
501  head=['#day','begrunls','endrunls','delivered','recorded','date']
502  csvreport.writeRow(head)
503  flat.insert(0,alldays)
504  allstarts=[ t[1] for t in rawdata[referenceLabel]]
505  allstops=[ t[2] for t in rawdata[referenceLabel]]
506  #print 'allstarts ',allstarts
507  flat.insert(1,allstarts)
508  flat.insert(2,allstops)
509  flat.append(alldates)
510  rows=list(zip(*flat))
511  csvreport.writeRows([list(t) for t in rows])
512  yearStrMin=minTime.strftime('%Y')
513  yearStrMax=maxTime.strftime('%Y')
514  if yearStrMin==yearStrMax:
515  dateFmt=matplotlib.dates.DateFormatter('%d/%m')
516  else:
517  dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y')
518  ax=self.__fig.add_subplot(111)
519  if yscale=='linear':
520  ax.set_yscale('linear')
521  elif yscale=='log':
522  ax.set_yscale('log')
523  else:
524  raise RuntimeError('unsupported yscale '+yscale)
525  majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks)
526  minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4)
527  ax.xaxis.set_major_formatter(dateFmt)
528  ax.set_xlabel(r'Date',position=(0.84,0))
529  ax.xaxis.set_major_locator(majorLoc)
530  ax.xaxis.set_minor_locator(minorLoc)
531  xticklabels=ax.get_xticklabels()
532  for tx in xticklabels:
533  tx.set_horizontalalignment('right')
534  ax.grid(True)
535  legendlist=[]
536  ax.set_ylabel(r'L '+unitstring,position=(0,0.9))
537  textsummaryhead=['#TotalRunningDays']
538  textsummaryline=['#'+str(len(alldays))]
539  for ylabel in labels:
540  cl='k'
541  if ylabel in self.colormap:
542  cl=self.colormap[ylabel]
543  ax.plot(xpoints,ypoints[ylabel],label=ylabel,color=cl,drawstyle='steps')
544  legendlist.append(ylabel+' Max '+'%.3f'%(ymax[ylabel])+' '+unitstring)
545  textsummaryhead.append('Max'+ylabel)
546  textsummaryline.append('%.3f'%(ymax[ylabel])+' '+unitstring)
547  if textoutput:
548  csvreport.writeRow(textsummaryhead)
549  csvreport.writeRow(textsummaryline)
550  ax.legend(tuple(legendlist),loc='upper left')
551  ax.set_xbound(lower=matplotlib.dates.date2num(minTime),upper=matplotlib.dates.date2num(maxTime))
552  #if withannotation:
553  # begtime=boundaryInfo[0][0]
554  # beginfo=boundaryInfo[0][1]
555  # endtime=boundaryInfo[1][0]
556  # endinfo=boundaryInfo[1][1]
557  # #annotations
558  # trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
559  # ax.text(matplotlib.dates.date2num(begtime),1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
560  # ax.text(matplotlib.dates.date2num(endtime),1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
561 
562  firstday=datetime.date.fromordinal(rawdata[referenceLabel][0][0])
563  lastday=datetime.date.fromordinal(rawdata[referenceLabel][-1][0])
564  firstdayStr=firstday.strftime('%Y %b %d')
565  lastdayStr=lastday.strftime('%Y %b %d')
566  ax.set_title('CMS Integrated Luminosity/Day ('+firstdayStr+' - '+lastdayStr+')',size='small')
567  #ax.autoscale(tight=True)
568  ax.autoscale_view(tight=True,scalex=True,scaley=False)
569  #ax.set_xmargin(0.015)
570  self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right')
571  self.__fig.subplots_adjust(bottom=0.2,left=0.15)
572 
573  def plotPeakPerday_Time(self,rawdata={},resultlines=[],minTime=None,maxTime=None,nticks=6,withannotation=False,yscale='linear',referenceLabel='Delivered',labels=['Delivered'],textoutput=None):
574  '''
575  THIS PLOT IS DELIVERED ONLY
576  Input:
577  rawdata={'Delivered':[(day,run,ls,instlumi)]}
578  resultlines=[[day,run,ls,maxinstlum],[]]
579  minTime (python DateTime) : min *begin* time to draw: format %m/%d/%y %H:%M:%S
580  maxTime (python DateTime): max *begin* time to draw %m/%d/%y %H:%M:%S
581  withannotation: wheather the boundary points should be annotated
582  referenceLabel: the one variable that decides the total unit and the plot x-axis range
583  labels: labels of the variables to plot
584  '''
585  xpoints=[]
586  ypoints={}
587  legendlist=[]
588  maxinfo=''
589  ymax={}
590  lut=lumiTime.lumiTime()
591  if not minTime:
592  minTime='03/01/10 00:00:00'
593  minTime=lut.StrToDatetime(minTime,customfm='%m/%d/%y %H:%M:%S')
594  if not maxTime:
595  maxTime=datetime.datetime.utcnow()
596  else:
597  maxTime=lut.StrToDatetime(maxTime,customfm='%m/%d/%y %H:%M:%S')
598  for r in resultlines:
599  day=int(r[0])
600  runnumber=int(r[1])
601  lsnum=int(r[2].split('.')[0])
602  if rawdata and day in [int(t[0]) for t in rawdata[referenceLabel]]:continue
603  if day < minTime.date().toordinal():continue
604  if day > maxTime.date().toordinal():continue
605  for i,lab in enumerate(labels):
606  v=float(r[-(len(labels)-i)-1])
607  rawdata.setdefault(lab,[]).append((day,runnumber,lsnum,v))
608  if not rawdata:
609  print('[WARNING]: no data, do nothing')
610  return
611  maxlum=max([t[3] for t in rawdata[referenceLabel]])
612  minlum=min([t[3] for t in rawdata[referenceLabel] if t[3]>0]) #used only for log scale, fin the non-zero bottom
613  (unitstring,denomitor)=guessInstLumiUnit(maxlum)
614 
615  csvreport=None
616  rows=[]
617  flat=[]
618  MinDay=minTime.date().toordinal()
619  MaxDay=maxTime.date().toordinal()
620  fulldays=range(MinDay,MaxDay+1)
621  for label in rawdata.keys():
622  yvalues=sorted(rawdata[label])
623  alldays=[t[0] for t in yvalues]
624  alldates=[str(datetime.date.fromordinal(t)) for t in alldays]
625  ypoints[label]=[]
626  lumivals=[t[3] for t in yvalues]
627  flat.append(lumivals)
628  for d in fulldays:
629  if not d in alldays:
630  ypoints[label].append(0.0)
631  else:
632  thisdaylumi=[t[3] for t in yvalues if t[0]==d][0]
633  if yscale=='log':
634  if thisdaylumi<minlum:
635  thisdaylumi=minlum/denomitor
636  else:
637  thisdaylumi=thisdaylumi/denomitor
638  else:
639  thisdaylumi=thisdaylumi/denomitor
640  ypoints[label].append(thisdaylumi)
641  ymax[label]=max(lumivals)/denomitor
642  'ymax ',max(lumivals)
643  xpoints=fulldays
644  if textoutput:
645  csvreport=csvReporter.csvReporter(textoutput)
646  head=['#day','run','lsnum','maxinstlumi','date']
647  csvreport.writeRow(head)
648  flat.insert(0,alldays)
649  allruns=[ t[1] for t in rawdata[referenceLabel]]
650  allls=[ t[2] for t in rawdata[referenceLabel]]
651  flat.insert(1,allruns)
652  flat.insert(2,allls)
653  flat.append(alldates)
654  rows=list(zip(*flat))
655  csvreport.writeRows([list(t) for t in rows])
656 
657  yearStrMin=minTime.strftime('%Y')
658  yearStrMax=maxTime.strftime('%Y')
659  if yearStrMin==yearStrMax:
660  dateFmt=matplotlib.dates.DateFormatter('%d/%m')
661  else:
662  dateFmt=matplotlib.dates.DateFormatter('%d/%m/%y')
663  ax=self.__fig.add_subplot(111)
664  if yscale=='linear':
665  ax.set_yscale('linear')
666  elif yscale=='log':
667  ax.set_yscale('log')
668  else:
669  raise RuntimeError('unsupported yscale '+yscale)
670  majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks)
671  minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4)
672  ax.xaxis.set_major_formatter(dateFmt)
673  ax.set_xlabel(r'Date',position=(0.84,0))
674  ax.set_ylabel(r'L '+unitstring,position=(0,0.9))
675  ax.xaxis.set_major_locator(majorLoc)
676  ax.xaxis.set_minor_locator(minorLoc)
677  xticklabels=ax.get_xticklabels()
678  for tx in xticklabels:
679  tx.set_horizontalalignment('right')
680  ax.grid(True)
681  cl=self.colormap['Max Inst']
682  textsummaryhead=['#TotalRunningDays']
683  textsummaryline=['#'+str(len(alldays))]
684  for ylabel in labels:
685  cl='k'
686  if ylabel in self.colormap:
687  cl=self.colormap[ylabel]
688  ax.plot(xpoints,ypoints[ylabel],label='Max Inst',color=cl,drawstyle='steps')
689  legendlist.append('Max Inst %.3f'%(ymax[ylabel])+' '+unitstring)
690  textsummaryhead.append('Max Inst'+ylabel)
691  textsummaryline.append('%.3f'%(ymax[ylabel])+' '+unitstring)
692  if textoutput:
693  csvreport.writeRow(textsummaryhead)
694  csvreport.writeRow(textsummaryline)
695  ax.legend(tuple(legendlist),loc='upper left')
696  ax.set_xbound(lower=matplotlib.dates.date2num(minTime),upper=matplotlib.dates.date2num(maxTime))
697  if withannotation:
698  #annotations
699  trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
700  ax.text(xpoints[0],1.025,beginfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
701  ax.text(xpoints[-1],1.025,endinfo,transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
702  ax.annotate(maxinfo,xy=(xmax,ymax),xycoords='data',xytext=(0,13),textcoords='offset points',arrowprops=dict(facecolor='green',shrink=0.05),size='x-small',horizontalalignment='center',color='green',bbox=dict(facecolor='white'))
703 
704  firstday=datetime.date.fromordinal(rawdata[referenceLabel][0][0])
705  lastday=datetime.date.fromordinal(rawdata[referenceLabel][-1][0])
706  firstdayStr=firstday.strftime('%Y %b %d')
707  lastdayStr=lastday.strftime('%Y %b %d')
708  ax.set_title('CMS Peak Luminosity/Day ('+firstdayStr+' - '+lastdayStr+')',size='small')
709 
710  #ax.autoscale(tight=True)
711  ax.autoscale_view(tight=True,scalex=True,scaley=False)
712  #ax.set_xmargin(0.015)
713  self.__fig.autofmt_xdate(bottom=0.18,rotation=15,ha='right')
714  self.__fig.subplots_adjust(bottom=0.2,left=0.15)
715 
716  def plotInst_RunLS(self,rawxdata,rawydata,nticks=6,textoutput=None):
717  '''
718  Input: rawxdata [run,fill,starttime,stoptime,totalls,ncmsls]
719  rawydata {label:[lumi]}
720  '''
721  lslength=23.357
722  lut=lumiTime.lumiTime()
723  runnum=rawxdata[0]
724  fill=rawxdata[1]
725  starttime=lut.DatetimeToStr(rawxdata[2],customfm='%m/%d/%y %H:%M:%S')
726  stoptime=lut.DatetimeToStr(rawxdata[3],customfm='%m/%d/%y %H:%M:%S')
727  totalls=rawxdata[-2]
728  ncmsls=rawxdata[-1]
729  peakinst=max(rawydata['Delivered'])/lslength
730  totaldelivered=sum(rawydata['Delivered'])
731  totalrecorded=sum(rawydata['Recorded'])
732  xpoints=range(1,totalls+1)
733  #print len(xpoints)
734  ypoints={}
735  ymax={}
736  for ylabel,yvalue in rawydata.items():
737  ypoints[ylabel]=[y/lslength for y in yvalue]
738  ymax[ylabel]=max(yvalue)/lslength
739  left=0.15
740  width=0.7
741  bottom=0.1
742  height=0.65
743  bottom_h=bottom+height
744  rect_scatter=[left,bottom,width,height]
745  rect_table=[left,bottom_h,width,0.25]
746 
747  nullfmt=matplotlib.ticker.NullFormatter()
748  nullloc=matplotlib.ticker.NullLocator()
749  axtab=self.__fig.add_axes(rect_table,frameon=False)
750  axtab.set_axis_off()
751  axtab.xaxis.set_major_formatter(nullfmt)
752  axtab.yaxis.set_major_formatter(nullfmt)
753  axtab.xaxis.set_major_locator(nullloc)
754  axtab.yaxis.set_major_locator(nullloc)
755 
756  ax=self.__fig.add_axes(rect_scatter)
757 
758  majorLoc=matplotlib.ticker.LinearLocator(numticks=nticks)
759  minorLoc=matplotlib.ticker.LinearLocator(numticks=nticks*4)
760  ax.set_xlabel(r'LS',position=(0.96,0))
761  ax.set_ylabel(r'L $\mu$b$^{-1}$s$^{-1}$',position=(0,0.9))
762  ax.xaxis.set_major_locator(majorLoc)
763  ax.xaxis.set_minor_locator(minorLoc)
764  ax.set_xbound(lower=xpoints[0],upper=xpoints[-1])
765  xticklabels=ax.get_xticklabels()
766  for tx in xticklabels:
767  tx.set_horizontalalignment('right')
768  ax.grid(True)
769  keylist=sorted(ypoints.keys())
770  legendlist=[]
771 
772  for ylabel in keylist:
773  cl='k'
774  if ylabel in self.colormap:
775  cl=self.colormap[ylabel]
776  ax.plot(xpoints,ypoints[ylabel],'.',label=ylabel,color=cl)
777  legendlist.append(ylabel)
778  #ax.axhline(0,color='green',linewidth=0.2)
779  ax.axvline(xpoints[ncmsls-1],color='green',linewidth=0.2)
780  (unitstring,denomitor)=guessLumiUnit(totaldelivered)
781  colLabels=('run','fill','max inst(/$\mu$b/s)','delivered('+unitstring+')','recorded('+unitstring+')')
782  cellText=[[str(runnum),str(fill),'%.3f'%(peakinst),'%.3f'%(totaldelivered/denomitor),'%.3f'%(totalrecorded/denomitor)]]
783 
784  sumtable=axtab.table(cellText=cellText,colLabels=colLabels,colWidths=[0.12,0.1,0.27,0.27,0.27],cellLoc='center',loc='center')
785  trans=matplotlib.transforms.BlendedGenericTransform(ax.transData,ax.transAxes)
786  axtab.add_table(sumtable)
787 
788  ax.text(xpoints[0],1.02,starttime[0:17],transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
789  ax.text(xpoints[ncmsls-1],1.02,stoptime[0:17],transform=trans,horizontalalignment='left',size='x-small',color='green',bbox=dict(facecolor='white'))
790  ax.legend(tuple(legendlist),loc='upper right',numpoints=1)
791 
792  def drawHTTPstring(self):
793  self.__canvas=CanvasBackend(self.__fig)
794  cherrypy.response.headers['Content-Type']='image/png'
795  buf=StringIO()
796  self.__canvas.print_png(buf)
797  return buf.getvalue()
798 
799  def drawPNG(self,filename):
800  self.__canvas=CanvasBackend(self.__fig)
801  self.__canvas.print_figure(filename)
802 
803  def drawInteractive(self):
804  if batchonly:
805  print('interactive mode is not available for your setup, exit')
806  sys.exit()
808  aw.show()
809  aw.destroy()
810 
811 if __name__=='__main__':
812  import csv
813  print('=====testing plotSumX_Run======')
814  f=open('/afs/cern.ch/cms/lumi/www/plots/operation/totallumivsrun-2011.csv','r')
815  reader=csv.reader(f,delimiter=',')
816  resultlines=[]
817  for row in reader:
818  if not row[0].isdigit():continue
819  resultlines.append(row)
820  #print resultlines
821  fig=Figure(figsize=(7.2,5.4),dpi=120)
823  m.plotSumX_Run(rawdata={},resultlines=resultlines,minRun=None,maxRun=None,nticks=6,yscale='linear',withannotation=False)
824  #m.drawPNG('totallumivsrun-2011test.png')
825  m.drawInteractive()
826  print('DONE')
827 
828 '''
829  print '=====testing plotSumX_Fill======'
830  f=open('/afs/cern.ch/cms/lumi/www/plots/operation/totallumivsfill-2011.csv','r')
831  reader=csv.reader(f,delimiter=',')
832  resultlines=[]
833  for row in reader:
834  if not row[0].isdigit():continue
835  resultlines.append(row)
836  #print resultlines
837  fig=Figure(figsize=(7.2,5.4),dpi=120)
838  m=matplotRender(fig)
839  m.plotSumX_Fill(rawdata={},resultlines=resultlines,minFill=None,maxFill=None,nticks=6,yscale='linear',withannotation=True)
840  m.drawPNG('totallumivsfill-2011test.png')
841  print 'DONE'
842  print '=====testing plotSumX_Time======'
843  f=open('/afs/cern.ch/cms/lumi/www/publicplots/totallumivstime-2011.csv','r')
844  reader=csv.reader(f,delimiter=',')
845  resultlines=[]
846  for row in reader:
847  if not row[0].isdigit():continue
848  resultlines.append(row)
849  #print resultlines
850  fig=Figure(figsize=(7.25,5.4),dpi=120)
851  m=matplotRender(fig)
852  m.plotSumX_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False)
853  m.drawPNG('totallumivstime-2011test.png')
854  print 'DONE'
855 
856  print '=====testing plotPerdayX_Time======'
857  f=open('/afs/cern.ch/cms/lumi/www/publicplots/lumiperday-2011.csv','r')
858  reader=csv.reader(f,delimiter=',')
859  resultlines=[]
860  for row in reader:
861  if not row[0].isdigit():continue
862  resultlines.append(row)
863  #print resultlines
864  fig=Figure(figsize=(7.25,5.4),dpi=120)
865  m=matplotRender(fig)
866  m.plotPerdayX_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False)
867  m.drawPNG('lumiperday-2011test.png')
868  print 'DONE'
869 
870  print '=====testing plotPeakPerday_Time======'
871  f=open('/afs/cern.ch/cms/lumi/www/publicplots/lumipeak-2011.csv','r')
872  reader=csv.reader(f,delimiter=',')
873  resultlines=[]
874  for row in reader:
875  if not row[0].isdigit():continue
876  resultlines.append(row)
877  #print resultlines
878  fig=Figure(figsize=(7.25,5.4),dpi=120)
879  m=matplotRender(fig)
880  m.plotPeakPerday_Time(rawdata={},resultlines=resultlines,minTime="03/14/11 09:00:00",maxTime=None,nticks=6,yscale='linear',withannotation=False)
881  m.drawPNG('lumipeak-2011test.png')
882  print 'DONE'
883 
884 '''
def plotInst_RunLS(self, rawxdata, rawydata, nticks=6, textoutput=None)
def plotSumX_Time(self, rawdata={}, resultlines=[], minTime=None, maxTime=None, nticks=6, yscale='linear', withannotation=False, referenceLabel='Delivered', labels=['Delivered', Recorded, textoutput=None)
def guessLumiUnit(t)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def guessInstLumiUnit(t)
def plotPerdayX_Time(self, rawdata={}, resultlines=[], minTime=None, maxTime=None, nticks=6, yscale='linear', withannotation=False, referenceLabel='Delivered', labels=['Delivered', Recorded, textoutput=None)
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
T min(T a, T b)
Definition: MathUtil.h:58
def plotSumX_Fill(self, rawdata={}, resultlines=[], minFill=None, maxFill=None, nticks=6, yscale='linear', withannotation=False, referenceLabel='Delivered', labels=['Delivered', Recorded, textoutput=None)
def plotPeakPerday_Time(self, rawdata={}, resultlines=[], minTime=None, maxTime=None, nticks=6, withannotation=False, yscale='linear', referenceLabel='Delivered', labels=['Delivered'], textoutput=None)
def drawPNG(self, filename)
#define str(s)
def plotSumX_Run(self, rawdata={}, resultlines=[], minRun=None, maxRun=None, nticks=6, yscale='linear', withannotation=False, referenceLabel='Delivered', labels=['Delivered', Recorded, textoutput=None)
double split
Definition: MVATrainer.cc:139
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