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