CMS 3D CMS Logo

Classes | Functions | Variables
plotting Namespace Reference

Classes

class  AggregateBins
 
class  AggregateHistos
 
class  CutEfficiency
 
class  DQMSubFolder
 
class  FakeDuplicate
 
class  Frame
 
class  FrameRatio
 
class  FrameTGraph2D
 
class  GetDirectoryCode
 
class  Plot
 
class  PlotFolder
 
class  PlotGroup
 
class  Plotter
 
class  PlotterFolder
 
class  PlotterInstance
 
class  PlotterItem
 
class  PlotterTableItem
 
class  PlotText
 
class  PlotTextBox
 
class  ROC
 
class  Subtract
 
class  Transform
 

Functions

def _calculateRatios (histos, ratioUncertainty=False)
 
def _copyStyle (src, dst)
 
def _createCanvas (name, width, height)
 
def _drawFrame (pad, bounds, xbinlabels=None, xbinlabelsize=None, xbinlabeloption=None, suffix="")
 
def _findBounds (th1s, ylog, xmin=None, xmax=None, ymin=None, ymax=None)
 
def _findBoundsY (th1s, ylog, ymin=None, ymax=None, coverage=None, coverageRange=None)
 
def _getDirectory (args, kwargs)
 
def _getDirectoryDetailed (tfile, possibleDirs, subDir=None)
 
def _getObject (tdirectory, name)
 
def _getOrCreateObject (tdirectory, nameOrCreator)
 
def _getXmax (obj, limitToNonZeroContent=False)
 
def _getXmin (obj, limitToNonZeroContent=False)
 
def _getYmax (obj, limitToNonZeroContent=False)
 
def _getYmaxWithError (th1)
 
def _getYmin (obj, limitToNonZeroContent=False)
 
def _getYminIgnoreOutlier (th1)
 
def _getYminMaxAroundMedian (obj, coverage, coverageRange=None)
 
def _modifyPadForRatio (pad, ratioFactor)
 
def _setStyle ()
 
def _th1ToOrderedDict (th1, renameBin=None)
 

Variables

 _gr
 
 _plotStylesColor
 
 _plotStylesMarker
 
 _ratio
 
 _ratioYTitle
 
 _th1
 
 _uncertainty
 
 _xerrshigh
 
 _xerrslow
 
 _xvalues
 
 _yerrshigh
 
 _yerrslow
 
 _yvalues
 
 IgnoreCommandLineOptions
 
 verbose
 

Function Documentation

def plotting._calculateRatios (   histos,
  ratioUncertainty = False 
)
private
Calculate the ratios for a list of histograms

Definition at line 144 of file plotting.py.

References funct.abs(), cond::serialization.equal(), and hpstanc_transforms.max.

Referenced by ntuplePlotting.draw().

144 def _calculateRatios(histos, ratioUncertainty=False):
145  """Calculate the ratios for a list of histograms"""
146 
147  def _divideOrZero(numerator, denominator):
148  if denominator == 0:
149  return 0
150  return numerator/denominator
151 
152  def equal(a, b):
153  if a == 0. and b == 0.:
154  return True
155  return abs(a-b)/max(abs(a),abs(b)) < 1e-3
156 
157  def findBins(wrap, bins_xvalues):
158  ret = []
159  currBin = wrap.begin()
160  i = 0
161  while i < len(bins_xvalues) and currBin < wrap.end():
162  (xcenter, xlow, xhigh) = bins_xvalues[i]
163  xlowEdge = xcenter-xlow
164  xupEdge = xcenter+xhigh
165 
166  (curr_center, curr_low, curr_high) = wrap.xvalues(currBin)
167  curr_lowEdge = curr_center-curr_low
168  curr_upEdge = curr_center+curr_high
169 
170  if equal(xlowEdge, curr_lowEdge) and equal(xupEdge, curr_upEdge):
171  ret.append(currBin)
172  currBin += 1
173  i += 1
174  elif curr_upEdge <= xlowEdge:
175  currBin += 1
176  elif curr_lowEdge >= xupEdge:
177  ret.append(None)
178  i += 1
179  else:
180  ret.append(None)
181  currBin += 1
182  i += 1
183  if len(ret) != len(bins_xvalues):
184  ret.extend([None]*( len(bins_xvalues) - len(ret) ))
185  return ret
186 
187  # Define wrappers for TH1/TGraph/TGraph2D to have uniform interface
188  # TODO: having more global wrappers would make some things simpler also elsewhere in the code
189  class WrapTH1:
190  def __init__(self, th1, uncertainty):
191  self._th1 = th1
192  self._uncertainty = uncertainty
193 
194  xaxis = th1.GetXaxis()
195  xaxis_arr = xaxis.GetXbins()
196  if xaxis_arr.GetSize() > 0: # unequal binning
197  lst = [xaxis_arr[i] for i in xrange(0, xaxis_arr.GetSize())]
198  arr = array.array("d", lst)
199  self._ratio = ROOT.TH1F("foo", "foo", xaxis.GetNbins(), arr)
200  else:
201  self._ratio = ROOT.TH1F("foo", "foo", xaxis.GetNbins(), xaxis.GetXmin(), xaxis.GetXmax())
202  _copyStyle(th1, self._ratio)
203  self._ratio.SetStats(0)
204  self._ratio.SetLineColor(ROOT.kBlack)
205  self._ratio.SetLineWidth(1)
206  def draw(self, style=None):
207  st = style
208  if st is None:
209  if self._uncertainty:
210  st = "EP"
211  else:
212  st = "HIST P"
213  self._ratio.Draw("same "+st)
214  def begin(self):
215  return 1
216  def end(self):
217  return self._th1.GetNbinsX()+1
218  def xvalues(self, bin):
219  xval = self._th1.GetBinCenter(bin)
220  xlow = xval-self._th1.GetXaxis().GetBinLowEdge(bin)
221  xhigh = self._th1.GetXaxis().GetBinUpEdge(bin)-xval
222  return (xval, xlow, xhigh)
223  def yvalues(self, bin):
224  yval = self._th1.GetBinContent(bin)
225  yerr = self._th1.GetBinError(bin)
226  return (yval, yerr, yerr)
227  def y(self, bin):
228  return self._th1.GetBinContent(bin)
229  def divide(self, bin, scale):
230  self._ratio.SetBinContent(bin, _divideOrZero(self._th1.GetBinContent(bin), scale))
231  self._ratio.SetBinError(bin, _divideOrZero(self._th1.GetBinError(bin), scale))
232  def makeRatio(self):
233  pass
234  def getRatio(self):
235  return self._ratio
236 
237  class WrapTGraph:
238  def __init__(self, gr, uncertainty):
239  self._gr = gr
240  self._uncertainty = uncertainty
241  self._xvalues = []
242  self._xerrslow = []
243  self._xerrshigh = []
244  self._yvalues = []
245  self._yerrshigh = []
246  self._yerrslow = []
247  def draw(self, style=None):
248  if self._ratio is None:
249  return
250  st = style
251  if st is None:
252  if self._uncertainty:
253  st = "PZ"
254  else:
255  st = "PX"
256  self._ratio.Draw("same "+st)
257  def begin(self):
258  return 0
259  def end(self):
260  return self._gr.GetN()
261  def xvalues(self, bin):
262  return (self._gr.GetX()[bin], self._gr.GetErrorXlow(bin), self._gr.GetErrorXhigh(bin))
263  def yvalues(self, bin):
264  return (self._gr.GetY()[bin], self._gr.GetErrorYlow(bin), self._gr.GetErrorYhigh(bin))
265  def y(self, bin):
266  return self._gr.GetY()[bin]
267  def divide(self, bin, scale):
268  # Ignore bin if denominator is zero
269  if scale == 0:
270  return
271  # No more items in the numerator
272  if bin >= self._gr.GetN():
273  return
274  # denominator is missing an item
275  xvals = self.xvalues(bin)
276  xval = xvals[0]
277 
278  self._xvalues.append(xval)
279  self._xerrslow.append(xvals[1])
280  self._xerrshigh.append(xvals[2])
281  yvals = self.yvalues(bin)
282  self._yvalues.append(yvals[0] / scale)
283  if self._uncertainty:
284  self._yerrslow.append(yvals[1] / scale)
285  self._yerrshigh.append(yvals[2] / scale)
286  else:
287  self._yerrslow.append(0)
288  self._yerrshigh.append(0)
289  def makeRatio(self):
290  if len(self._xvalues) == 0:
291  self._ratio = None
292  return
293  self._ratio = ROOT.TGraphAsymmErrors(len(self._xvalues), array.array("d", self._xvalues), array.array("d", self._yvalues),
294  array.array("d", self._xerrslow), array.array("d", self._xerrshigh),
295  array.array("d", self._yerrslow), array.array("d", self._yerrshigh))
296  _copyStyle(self._gr, self._ratio)
297  def getRatio(self):
298  return self._ratio
299  class WrapTGraph2D(WrapTGraph):
300  def __init__(self, gr, uncertainty):
301  WrapTGraph.__init__(self, gr, uncertainty)
302  def xvalues(self, bin):
303  return (self._gr.GetX()[bin], self._gr.GetErrorX(bin), self._gr.GetErrorX(bin))
304  def yvalues(self, bin):
305  return (self._gr.GetY()[bin], self._gr.GetErrorY(bin), self._gr.GetErrorY(bin))
306 
307  def wrap(o):
308  if isinstance(o, ROOT.TH1):
309  return WrapTH1(o, ratioUncertainty)
310  elif isinstance(o, ROOT.TGraph):
311  return WrapTGraph(o, ratioUncertainty)
312  elif isinstance(o, ROOT.TGraph2D):
313  return WrapTGraph2D(o, ratioUncertainty)
314 
315  wrappers = [wrap(h) for h in histos]
316  ref = wrappers[0]
317 
318  wrappers_bins = []
319  ref_bins = [ref.xvalues(b) for b in xrange(ref.begin(), ref.end())]
320  for w in wrappers:
321  wrappers_bins.append(findBins(w, ref_bins))
322 
323  for i, bin in enumerate(xrange(ref.begin(), ref.end())):
324  (scale, ylow, yhigh) = ref.yvalues(bin)
325  for w, bins in zip(wrappers, wrappers_bins):
326  if bins[i] is None:
327  continue
328  w.divide(bins[i], scale)
329 
330  for w in wrappers:
331  w.makeRatio()
332 
333  return wrappers
334 
335 
def _copyStyle(src, dst)
Definition: plotting.py:1482
def divide(outfile, dest, numer, denom)
Definition: rootmath.py:291
bool equal(const T &first, const T &second)
Definition: Equal.h:34
def _calculateRatios(histos, ratioUncertainty=False)
Definition: plotting.py:144
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
#define end
Definition: vmac.h:37
def draw(name, histos, styles, legendLabels=[], xtitle=None, ytitle=None, drawOpt="HIST", legendDx=0, legendDy=0, legendDw=0, legendDh=0, xmin=None, ymin=0, xmax=None, ymax=None, xlog=False, ylog=False, xgrid=True, ygrid=True, ratio=False, ratioYmin=0.5, ratioYmax=1.5, ratioYTitle=plotting._ratioYTitle)
#define begin
Definition: vmac.h:30
auto wrap(F iFunc) -> decltype(iFunc())
def plotting._copyStyle (   src,
  dst 
)
private

Definition at line 1482 of file plotting.py.

1482 def _copyStyle(src, dst):
1483  properties = []
1484  if hasattr(src, "GetLineColor") and hasattr(dst, "SetLineColor"):
1485  properties.extend(["LineColor", "LineStyle", "LineWidth"])
1486  if hasattr(src, "GetFillColor") and hasattr(dst, "SetFillColor"):
1487  properties.extend(["FillColor", "FillStyle"])
1488  if hasattr(src, "GetMarkerColor") and hasattr(dst, "SetMarkerColor"):
1489  properties.extend(["MarkerColor", "MarkerSize", "MarkerStyle"])
1490 
1491  for prop in properties:
1492  getattr(dst, "Set"+prop)(getattr(src, "Get"+prop)())
1493 
def _copyStyle(src, dst)
Definition: plotting.py:1482
def plotting._createCanvas (   name,
  width,
  height 
)
private

Definition at line 105 of file plotting.py.

Referenced by plotting.PlotGroup._drawSeparate(), ntuplePlotting.draw(), and plotting.PlotGroup.draw().

105 def _createCanvas(name, width, height):
106  # silence warning of deleting canvas with the same name
107  if not verbose:
108  backup = ROOT.gErrorIgnoreLevel
109  ROOT.gErrorIgnoreLevel = ROOT.kError
110  canvas = ROOT.TCanvas(name, name, width, height)
111  if not verbose:
112  ROOT.gErrorIgnoreLevel = backup
113  return canvas
114 
def _createCanvas(name, width, height)
Definition: plotting.py:105
def plotting._drawFrame (   pad,
  bounds,
  xbinlabels = None,
  xbinlabelsize = None,
  xbinlabeloption = None,
  suffix = "" 
)
private
Function to draw a frame

Arguments:
pad    -- TPad to where the frame is drawn
bounds -- List or 4-tuple for (xmin, ymin, xmax, ymax)

Keyword arguments:
xbinlabels      -- Optional list of strings for x axis bin labels
xbinlabelsize   -- Optional number for the x axis bin label size
xbinlabeloption -- Optional string for the x axis bin options (passed to ROOT.TH1.LabelsOption())
suffix          -- Optional string for a postfix of the frame name

Definition at line 1018 of file plotting.py.

1018 def _drawFrame(pad, bounds, xbinlabels=None, xbinlabelsize=None, xbinlabeloption=None, suffix=""):
1019  """Function to draw a frame
1020 
1021  Arguments:
1022  pad -- TPad to where the frame is drawn
1023  bounds -- List or 4-tuple for (xmin, ymin, xmax, ymax)
1024 
1025  Keyword arguments:
1026  xbinlabels -- Optional list of strings for x axis bin labels
1027  xbinlabelsize -- Optional number for the x axis bin label size
1028  xbinlabeloption -- Optional string for the x axis bin options (passed to ROOT.TH1.LabelsOption())
1029  suffix -- Optional string for a postfix of the frame name
1030  """
1031  if xbinlabels is None:
1032  frame = pad.DrawFrame(*bounds)
1033  else:
1034  # Special form needed if want to set x axis bin labels
1035  nbins = len(xbinlabels)
1036  frame = ROOT.TH1F("hframe"+suffix, "", nbins, bounds[0], bounds[2])
1037  frame.SetBit(ROOT.TH1.kNoStats)
1038  frame.SetBit(ROOT.kCanDelete)
1039  frame.SetMinimum(bounds[1])
1040  frame.SetMaximum(bounds[3])
1041  frame.GetYaxis().SetLimits(bounds[1], bounds[3])
1042  frame.Draw("")
1043 
1044  xaxis = frame.GetXaxis()
1045  for i in xrange(nbins):
1046  xaxis.SetBinLabel(i+1, xbinlabels[i])
1047  if xbinlabelsize is not None:
1048  xaxis.SetLabelSize(xbinlabelsize)
1049  if xbinlabeloption is not None:
1050  frame.LabelsOption(xbinlabeloption)
1051 
1052  return frame
1053 
def _drawFrame(pad, bounds, xbinlabels=None, xbinlabelsize=None, xbinlabeloption=None, suffix="")
Definition: plotting.py:1018
def plotting._findBounds (   th1s,
  ylog,
  xmin = None,
  xmax = None,
  ymin = None,
  ymax = None 
)
private
Find x-y axis boundaries encompassing a list of TH1s if the bounds are not given in arguments.

Arguments:
th1s -- List of TH1s
ylog -- Boolean indicating if y axis is in log scale or not (affects the automatic ymax)

Keyword arguments:
xmin -- Minimum x value; if None, take the minimum of TH1s
xmax -- Maximum x value; if None, take the maximum of TH1s
ymin -- Minimum y value; if None, take the minimum of TH1s
ymax -- Maximum y value; if None, take the maximum of TH1s

Definition at line 454 of file plotting.py.

References _findBoundsY(), _getXmax(), _getXmin(), ALCARECOTkAlBeamHalo_cff.filter, hpstanc_transforms.max, min(), and harvestTrackValidationPlots.str.

Referenced by ntuplePlotting.draw().

454 def _findBounds(th1s, ylog, xmin=None, xmax=None, ymin=None, ymax=None):
455  """Find x-y axis boundaries encompassing a list of TH1s if the bounds are not given in arguments.
456 
457  Arguments:
458  th1s -- List of TH1s
459  ylog -- Boolean indicating if y axis is in log scale or not (affects the automatic ymax)
460 
461  Keyword arguments:
462  xmin -- Minimum x value; if None, take the minimum of TH1s
463  xmax -- Maximum x value; if None, take the maximum of TH1s
464  ymin -- Minimum y value; if None, take the minimum of TH1s
465  ymax -- Maximum y value; if None, take the maximum of TH1s
466  """
467 
468  (ymin, ymax) = _findBoundsY(th1s, ylog, ymin, ymax)
469 
470  if xmin is None or xmax is None or isinstance(xmin, list) or isinstance(max, list):
471  xmins = []
472  xmaxs = []
473  for th1 in th1s:
474  xmins.append(_getXmin(th1, limitToNonZeroContent=isinstance(xmin, list)))
475  xmaxs.append(_getXmax(th1, limitToNonZeroContent=isinstance(xmax, list)))
476 
477  # Filter out cases where histograms have zero content
478  xmins = filter(lambda h: h is not None, xmins)
479  xmaxs = filter(lambda h: h is not None, xmaxs)
480 
481  if xmin is None:
482  xmin = min(xmins)
483  elif isinstance(xmin, list):
484  if len(xmins) == 0: # all histograms zero
485  xmin = min(xmin)
486  if verbose:
487  print "Histogram is zero, using the smallest given value for xmin from", str(xmin)
488  else:
489  xm = min(xmins)
490  xmins_below = filter(lambda x: x<=xm, xmin)
491  if len(xmins_below) == 0:
492  xmin = min(xmin)
493  if xm < xmin:
494  if verbose:
495  print "Histogram minimum x %f is below all given xmin values %s, using the smallest one" % (xm, str(xmin))
496  else:
497  xmin = max(xmins_below)
498 
499  if xmax is None:
500  xmax = max(xmaxs)
501  elif isinstance(xmax, list):
502  if len(xmaxs) == 0: # all histograms zero
503  xmax = max(xmax)
504  if verbose:
505  print "Histogram is zero, using the smallest given value for xmax from", str(xmin)
506  else:
507  xm = max(xmaxs)
508  xmaxs_above = filter(lambda x: x>xm, xmax)
509  if len(xmaxs_above) == 0:
510  xmax = max(xmax)
511  if xm > xmax:
512  if verbose:
513  print "Histogram maximum x %f is above all given xmax values %s, using the maximum one" % (xm, str(xmax))
514  else:
515  xmax = min(xmaxs_above)
516 
517  for th1 in th1s:
518  th1.GetXaxis().SetRangeUser(xmin, xmax)
519 
520  return (xmin, ymin, xmax, ymax)
521 
def _findBoundsY(th1s, ylog, ymin=None, ymax=None, coverage=None, coverageRange=None)
Definition: plotting.py:522
def _findBounds(th1s, ylog, xmin=None, xmax=None, ymin=None, ymax=None)
Definition: plotting.py:454
def _getXmax(obj, limitToNonZeroContent=False)
Definition: plotting.py:352
T min(T a, T b)
Definition: MathUtil.h:58
def _getXmin(obj, limitToNonZeroContent=False)
Definition: plotting.py:336
def plotting._findBoundsY (   th1s,
  ylog,
  ymin = None,
  ymax = None,
  coverage = None,
  coverageRange = None 
)
private
Find y axis boundaries encompassing a list of TH1s if the bounds are not given in arguments.

Arguments:
th1s -- List of TH1s
ylog -- Boolean indicating if y axis is in log scale or not (affects the automatic ymax)

Keyword arguments:
ymin -- Minimum y value; if None, take the minimum of TH1s
ymax -- Maximum y value; if None, take the maximum of TH1s
coverage -- If set, use only values within the 'coverage' part around the median are used for min/max (useful for ratio)
coverageRange -- If coverage and this are set, use only the x axis specified by an (xmin,xmax) pair for the coverage 

Definition at line 522 of file plotting.py.

References _getYmax(), _getYmin(), _getYminIgnoreOutlier(), _getYminMaxAroundMedian(), ALCARECOTkAlBeamHalo_cff.filter, hpstanc_transforms.max, min(), and harvestTrackValidationPlots.str.

Referenced by _findBounds().

522 def _findBoundsY(th1s, ylog, ymin=None, ymax=None, coverage=None, coverageRange=None):
523  """Find y axis boundaries encompassing a list of TH1s if the bounds are not given in arguments.
524 
525  Arguments:
526  th1s -- List of TH1s
527  ylog -- Boolean indicating if y axis is in log scale or not (affects the automatic ymax)
528 
529  Keyword arguments:
530  ymin -- Minimum y value; if None, take the minimum of TH1s
531  ymax -- Maximum y value; if None, take the maximum of TH1s
532  coverage -- If set, use only values within the 'coverage' part around the median are used for min/max (useful for ratio)
533  coverageRange -- If coverage and this are set, use only the x axis specified by an (xmin,xmax) pair for the coverage
534  """
535  if coverage is not None:
536  # the only use case for coverage for now is ratio, for which
537  # the scalings are not needed (actually harmful), so let's
538  # just ignore them if 'coverage' is set
539  y_scale_max = lambda y: y
540  y_scale_min = lambda y: y
541  else:
542  if ylog:
543  y_scale_max = lambda y: y*1.5
544  else:
545  y_scale_max = lambda y: y*1.05
546  y_scale_min = lambda y: y*0.9 # assuming log
547 
548  if ymin is None or ymax is None or isinstance(ymin, list) or isinstance(ymax, list):
549  ymins = []
550  ymaxs = []
551  for th1 in th1s:
552  if coverage is not None:
553  (_ymin, _ymax) = _getYminMaxAroundMedian(th1, coverage, coverageRange)
554  else:
555  if ylog and isinstance(ymin, list):
556  _ymin = _getYminIgnoreOutlier(th1)
557  else:
558  _ymin = _getYmin(th1, limitToNonZeroContent=isinstance(ymin, list))
559  _ymax = _getYmax(th1, limitToNonZeroContent=isinstance(ymax, list))
560 # _ymax = _getYmaxWithError(th1)
561 
562  ymins.append(_ymin)
563  ymaxs.append(_ymax)
564 
565  if ymin is None:
566  ymin = min(ymins)
567  elif isinstance(ymin, list):
568  ym_unscaled = min(ymins)
569  ym = y_scale_min(ym_unscaled)
570  ymins_below = filter(lambda y: y<=ym, ymin)
571  if len(ymins_below) == 0:
572  ymin = min(ymin)
573  if ym_unscaled < ymin:
574  if verbose:
575  print "Histogram minimum y %f is below all given ymin values %s, using the smallest one" % (ym, str(ymin))
576  else:
577  ymin = max(ymins_below)
578 
579  if ymax is None:
580  # in case ymax is automatic, ymin is set by list, and the
581  # histograms are zero, ensure here that ymax > ymin
582  ymax = y_scale_max(max(ymaxs+[ymin]))
583  elif isinstance(ymax, list):
584  ym_unscaled = max(ymaxs)
585  ym = y_scale_max(ym_unscaled)
586  ymaxs_above = filter(lambda y: y>ym, ymax)
587  if len(ymaxs_above) == 0:
588  ymax = max(ymax)
589  if ym_unscaled > ymax:
590  if verbose:
591  print "Histogram maximum y %f is above all given ymax values %s, using the maximum one" % (ym_unscaled, str(ymax))
592  else:
593  ymax = min(ymaxs_above)
594 
595  for th1 in th1s:
596  th1.GetYaxis().SetRangeUser(ymin, ymax)
597 
598  return (ymin, ymax)
599 
def _getYmax(obj, limitToNonZeroContent=False)
Definition: plotting.py:383
def _findBoundsY(th1s, ylog, ymin=None, ymax=None, coverage=None, coverageRange=None)
Definition: plotting.py:522
def _getYmin(obj, limitToNonZeroContent=False)
Definition: plotting.py:368
def _getYminIgnoreOutlier(th1)
Definition: plotting.py:401
T min(T a, T b)
Definition: MathUtil.h:58
def _getYminMaxAroundMedian(obj, coverage, coverageRange=None)
Definition: plotting.py:418
def plotting._getDirectory (   args,
  kwargs 
)
private

Definition at line 93 of file plotting.py.

References _getDirectoryDetailed().

Referenced by plotting.PlotterTableItem.create().

93 def _getDirectory(*args, **kwargs):
94  return GetDirectoryCode.codesToNone(_getDirectoryDetailed(*args, **kwargs))
95 
def _getDirectory(args, kwargs)
Definition: plotting.py:93
def _getDirectoryDetailed(tfile, possibleDirs, subDir=None)
Definition: plotting.py:69
def plotting._getDirectoryDetailed (   tfile,
  possibleDirs,
  subDir = None 
)
private
Get TDirectory from TFile.

Definition at line 69 of file plotting.py.

References join().

Referenced by _getDirectory(), and plotting.PlotterFolder.create().

69 def _getDirectoryDetailed(tfile, possibleDirs, subDir=None):
70  """Get TDirectory from TFile."""
71  if tfile is None:
73  for pdf in possibleDirs:
74  d = tfile.Get(pdf)
75  if d:
76  if subDir is not None:
77  # Pick associator if given
78  d = d.Get(subDir)
79  if d:
80  return d
81  else:
82  if verbose:
83  print "Did not find subdirectory '%s' from directory '%s' in file %s" % (subDir, pdf, tfile.GetName())
84 # if "Step" in subDir:
85 # raise Exception("Foo")
87  else:
88  return d
89  if verbose:
90  print "Did not find any of directories '%s' from file %s" % (",".join(possibleDirs), tfile.GetName())
92 
def _getDirectoryDetailed(tfile, possibleDirs, subDir=None)
Definition: plotting.py:69
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def plotting._getObject (   tdirectory,
  name 
)
private

Definition at line 45 of file plotting.py.

Referenced by _getOrCreateObject(), plotting.Subtract.create(), plotting.FakeDuplicate.create(), plotting.AggregateHistos.create(), and plotting.PlotterFolder.create().

45 def _getObject(tdirectory, name):
46  obj = tdirectory.Get(name)
47  if not obj:
48  if verbose:
49  print "Did not find {obj} from {dir}".format(obj=name, dir=tdirectory.GetPath())
50  return None
51  return obj
52 
def _getObject(tdirectory, name)
Definition: plotting.py:45
def plotting._getOrCreateObject (   tdirectory,
  nameOrCreator 
)
private

Definition at line 53 of file plotting.py.

References _getObject().

Referenced by plotting.Plot._createOne(), plotting.Transform.create(), plotting.CutEfficiency.create(), plotting.AggregateBins.create(), plotting.ROC.create(), and trackingPlots.TimePerTrackPlot.create().

53 def _getOrCreateObject(tdirectory, nameOrCreator):
54  if hasattr(nameOrCreator, "create"):
55  return nameOrCreator.create(tdirectory)
56  return _getObject(tdirectory, nameOrCreator)
57 
def _getOrCreateObject(tdirectory, nameOrCreator)
Definition: plotting.py:53
def _getObject(tdirectory, name)
Definition: plotting.py:45
def plotting._getXmax (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 352 of file plotting.py.

References hpstanc_transforms.max, and harvestTrackValidationPlots.str.

Referenced by _findBounds().

352 def _getXmax(obj, limitToNonZeroContent=False):
353  if isinstance(obj, ROOT.TH1):
354  xaxis = obj.GetXaxis()
355  if limitToNonZeroContent:
356  for i in xrange(obj.GetNbinsX(), 0, -1):
357  if obj.GetBinContent(i) != 0:
358  return xaxis.GetBinUpEdge(i)
359  # None for all bins being zero
360  return None
361  else:
362  return xaxis.GetBinUpEdge(xaxis.GetLast())
363  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
364  m = max([obj.GetX()[i] for i in xrange(0, obj.GetN())])
365  return m*1.1 if m > 0 else m*0.9
366  raise Exception("Unsupported type %s" % str(obj))
367 
def _getXmax(obj, limitToNonZeroContent=False)
Definition: plotting.py:352
def plotting._getXmin (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 336 of file plotting.py.

References min(), and harvestTrackValidationPlots.str.

Referenced by _findBounds().

336 def _getXmin(obj, limitToNonZeroContent=False):
337  if isinstance(obj, ROOT.TH1):
338  xaxis = obj.GetXaxis()
339  if limitToNonZeroContent:
340  for i in xrange(1, obj.GetNbinsX()+1):
341  if obj.GetBinContent(i) != 0:
342  return xaxis.GetBinLowEdge(i)
343  # None for all bins being zero
344  return None
345  else:
346  return xaxis.GetBinLowEdge(xaxis.GetFirst())
347  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
348  m = min([obj.GetX()[i] for i in xrange(0, obj.GetN())])
349  return m*0.9 if m > 0 else m*1.1
350  raise Exception("Unsupported type %s" % str(obj))
351 
T min(T a, T b)
Definition: MathUtil.h:58
def _getXmin(obj, limitToNonZeroContent=False)
Definition: plotting.py:336
def plotting._getYmax (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 383 of file plotting.py.

References hpstanc_transforms.max, and harvestTrackValidationPlots.str.

Referenced by _findBoundsY().

383 def _getYmax(obj, limitToNonZeroContent=False):
384  if isinstance(obj, ROOT.TH2):
385  yaxis = obj.GetYaxis()
386  return yaxis.GetBinUpEdge(yaxis.GetLast())
387  elif isinstance(obj, ROOT.TH1):
388  if limitToNonZeroContent:
389  lst = [obj.GetBinContent(i) for i in xrange(1, obj.GetNbinsX()+1) if obj.GetBinContent(i) != 0 ]
390  return max(lst) if len(lst) != 0 else 0
391  else:
392  return obj.GetMaximum()
393  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
394  m = max([obj.GetY()[i] for i in xrange(0, obj.GetN())])
395  return m*1.1 if m > 0 else m*0.9
396  raise Exception("Unsupported type %s" % str(obj))
397 
def _getYmax(obj, limitToNonZeroContent=False)
Definition: plotting.py:383
def plotting._getYmaxWithError (   th1)
private

Definition at line 398 of file plotting.py.

References hpstanc_transforms.max.

399  return max([th1.GetBinContent(i)+th1.GetBinError(i) for i in xrange(1, th1.GetNbinsX()+1)])
400 
def _getYmaxWithError(th1)
Definition: plotting.py:398
def plotting._getYmin (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 368 of file plotting.py.

References min(), and harvestTrackValidationPlots.str.

Referenced by _findBoundsY().

368 def _getYmin(obj, limitToNonZeroContent=False):
369  if isinstance(obj, ROOT.TH2):
370  yaxis = obj.GetYaxis()
371  return yaxis.GetBinLowEdge(yaxis.GetFirst())
372  elif isinstance(obj, ROOT.TH1):
373  if limitToNonZeroContent:
374  lst = [obj.GetBinContent(i) for i in xrange(1, obj.GetNbinsX()+1) if obj.GetBinContent(i) != 0 ]
375  return min(lst) if len(lst) != 0 else 0
376  else:
377  return obj.GetMinimum()
378  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
379  m = min([obj.GetY()[i] for i in xrange(0, obj.GetN())])
380  return m*0.9 if m > 0 else m*1.1
381  raise Exception("Unsupported type %s" % str(obj))
382 
def _getYmin(obj, limitToNonZeroContent=False)
Definition: plotting.py:368
T min(T a, T b)
Definition: MathUtil.h:58
def plotting._getYminIgnoreOutlier (   th1)
private

Definition at line 401 of file plotting.py.

References ALCARECOTkAlBeamHalo_cff.filter, and createfilelist.int.

Referenced by _findBoundsY().

402  yvals = filter(lambda n: n>0, [th1.GetBinContent(i) for i in xrange(1, th1.GetNbinsX()+1)])
403  yvals.sort()
404  if len(yvals) == 0:
405  return th1.GetMinimum()
406  if len(yvals) == 1:
407  return yvals[0]
408 
409  # Define outlier as being x10 less than minimum of the 95 % of the non-zero largest values
410  ind_min = len(yvals)-1 - int(len(yvals)*0.95)
411  min_val = yvals[ind_min]
412  for i in xrange(0, ind_min):
413  if yvals[i] > 0.1*min_val:
414  return yvals[i]
415 
416  return min_val
417 
def _getYminIgnoreOutlier(th1)
Definition: plotting.py:401
def plotting._getYminMaxAroundMedian (   obj,
  coverage,
  coverageRange = None 
)
private

Definition at line 418 of file plotting.py.

References ALCARECOTkAlBeamHalo_cff.filter, createfilelist.int, and harvestTrackValidationPlots.str.

Referenced by _findBoundsY().

418 def _getYminMaxAroundMedian(obj, coverage, coverageRange=None):
419  inRange = lambda x: True
420  inRange2 = lambda xmin,xmax: True
421  if coverageRange:
422  inRange = lambda x: coverageRange[0] <= x <= coverageRange[1]
423  inRange2 = lambda xmin,xmax: coverageRange[0] <= xmin and xmax <= coverageRange[1]
424 
425  if isinstance(obj, ROOT.TH1):
426  yvals = [obj.GetBinContent(i) for i in xrange(1, obj.GetNbinsX()+1) if inRange2(obj.GetXaxis().GetBinLowEdge(i), obj.GetXaxis().GetBinUpEdge(i))]
427  yvals = filter(lambda x: x != 0, yvals)
428  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
429  yvals = [obj.GetY()[i] for i in xrange(0, obj.GetN()) if inRange(obj.GetX()[i])]
430  else:
431  raise Exception("Unsupported type %s" % str(obj))
432  if len(yvals) == 0:
433  return (0, 0)
434  if len(yvals) == 1:
435  return (yvals[0], yvals[0])
436  if len(yvals) == 2:
437  return (yvals[0], yvals[1])
438 
439  yvals.sort()
440  nvals = int(len(yvals)*coverage)
441  if nvals < 2:
442  # Take median and +- 1 values
443  if len(yvals) % 2 == 0:
444  half = len(yvals)/2
445  return ( yvals[half-1], yvals[half] )
446  else:
447  middle = len(yvals)/2
448  return ( yvals[middle-1], yvals[middle+1] )
449  ind_min = (len(yvals)-nvals)/2
450  ind_max = len(yvals)-1 - ind_min
451 
452  return (yvals[ind_min], yvals[ind_max])
453 
def _getYminMaxAroundMedian(obj, coverage, coverageRange=None)
Definition: plotting.py:418
def plotting._modifyPadForRatio (   pad,
  ratioFactor 
)
private

Definition at line 115 of file plotting.py.

Referenced by ntuplePlotting.draw().

115 def _modifyPadForRatio(pad, ratioFactor):
116  pad.Divide(1, 2)
117 
118  divisionPoint = 1-1/ratioFactor
119 
120  topMargin = pad.GetTopMargin()
121  bottomMargin = pad.GetBottomMargin()
122  divisionPoint += (1-divisionPoint)*bottomMargin # correct for (almost-)zeroing bottom margin of pad1
123  divisionPointForPad1 = 1-( (1-divisionPoint) / (1-0.02) ) # then correct for the non-zero bottom margin, but for pad1 only
124 
125  # Set the lower point of the upper pad to divisionPoint
126  pad1 = pad.cd(1)
127  yup = 1.0
128  ylow = divisionPointForPad1
129  xup = 1.0
130  xlow = 0.0
131  pad1.SetPad(xlow, ylow, xup, yup)
132  pad1.SetFillStyle(4000) # transparent
133  pad1.SetBottomMargin(0.02) # need some bottom margin here for eps/pdf output (at least in ROOT 5.34)
134 
135  # Set the upper point of the lower pad to divisionPoint
136  pad2 = pad.cd(2)
137  yup = divisionPoint
138  ylow = 0.0
139  pad2.SetPad(xlow, ylow, xup, yup)
140  pad2.SetFillStyle(4000) # transparent
141  pad2.SetTopMargin(0.0)
142  pad2.SetBottomMargin(bottomMargin/(ratioFactor*divisionPoint))
143 
def _modifyPadForRatio(pad, ratioFactor)
Definition: plotting.py:115
def plotting._setStyle ( )
private

Definition at line 17 of file plotting.py.

17 def _setStyle():
18  _absoluteSize = True
19  if _absoluteSize:
20  font = 43
21  titleSize = 22
22  labelSize = 22
23  statSize = 14
24  else:
25  font = 42
26  titleSize = 0.05
27  labelSize = 0.05
28  statSize = 0.025
29 
30  ROOT.gROOT.SetStyle("Plain")
31  ROOT.gStyle.SetPadRightMargin(0.07)
32  ROOT.gStyle.SetPadLeftMargin(0.13)
33  ROOT.gStyle.SetTitleFont(font, "XYZ")
34  ROOT.gStyle.SetTitleSize(titleSize, "XYZ")
35  ROOT.gStyle.SetTitleOffset(1.2, "Y")
36  #ROOT.gStyle.SetTitleFontSize(0.05)
37  ROOT.gStyle.SetLabelFont(font, "XYZ")
38  ROOT.gStyle.SetLabelSize(labelSize, "XYZ")
39  ROOT.gStyle.SetTextSize(labelSize)
40  ROOT.gStyle.SetStatFont(font)
41  ROOT.gStyle.SetStatFontSize(statSize)
42 
43  ROOT.TGaxis.SetMaxDigits(4)
44 
def _setStyle()
Definition: plotting.py:17
def plotting._th1ToOrderedDict (   th1,
  renameBin = None 
)
private

Definition at line 96 of file plotting.py.

Referenced by plotting.AggregateBins.create(), and trackingPlots.TrackingSummaryTable.create().

96 def _th1ToOrderedDict(th1, renameBin=None):
97  values = collections.OrderedDict()
98  for i in xrange(1, th1.GetNbinsX()+1):
99  binLabel = th1.GetXaxis().GetBinLabel(i)
100  if renameBin is not None:
101  binLabel = renameBin(binLabel)
102  values[binLabel] = (th1.GetBinContent(i), th1.GetBinError(i))
103  return values
104 
def _th1ToOrderedDict(th1, renameBin=None)
Definition: plotting.py:96

Variable Documentation

plotting._gr
private

Definition at line 239 of file plotting.py.

plotting._plotStylesColor
private

Definition at line 1015 of file plotting.py.

plotting._plotStylesMarker
private

Definition at line 1016 of file plotting.py.

plotting._ratio
private

Definition at line 199 of file plotting.py.

plotting._ratioYTitle
private

Definition at line 15 of file plotting.py.

plotting._th1
private

Definition at line 191 of file plotting.py.

plotting._uncertainty
private

Definition at line 192 of file plotting.py.

plotting._xerrshigh
private

Definition at line 243 of file plotting.py.

plotting._xerrslow
private

Definition at line 242 of file plotting.py.

plotting._xvalues
private

Definition at line 241 of file plotting.py.

plotting._yerrshigh
private

Definition at line 245 of file plotting.py.

plotting._yerrslow
private

Definition at line 246 of file plotting.py.

plotting._yvalues
private

Definition at line 244 of file plotting.py.

plotting.IgnoreCommandLineOptions

Definition at line 10 of file plotting.py.

plotting.verbose

Definition at line 14 of file plotting.py.