CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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  PlotEmpty
 
class  PlotFolder
 
class  PlotGroup
 
class  PlotOnSideGroup
 
class  Plotter
 
class  PlotterFolder
 
class  PlotterInstance
 
class  PlotterItem
 
class  PlotterTableItem
 
class  PlotText
 
class  PlotTextBox
 
class  ROC
 
class  Subtract
 
class  Transform
 

Functions

def _calculateRatios
 
def _copyStyle
 
def _createCanvas
 
def _drawFrame
 
def _findBounds
 
def _findBoundsY
 
def _getDirectory
 
def _getDirectoryDetailed
 
def _getObject
 
def _getOrCreateObject
 
def _getXmax
 
def _getXmin
 
def _getYmax
 
def _getYmaxWithError
 
def _getYmin
 
def _getYminIgnoreOutlier
 
def _getYminMaxAroundMedian
 
def _mergeBinLabels
 
def _mergeBinLabelsX
 
def _mergeBinLabelsY
 
def _modifyPadForRatio
 
def _setStyle
 
def _th1IncludeOnlyBins
 
def _th1RemoveEmptyBins
 
def _th1ToOrderedDict
 
def _th2RemoveEmptyBins
 

Variables

 _gr
 
list _plotStylesColor = [4, 2, ROOT.kBlack, ROOT.kOrange+7, ROOT.kMagenta-3, ROOT.kGreen+2]
 
list _plotStylesMarker = [21, 20, 22, 34, 33, 23]
 
 _ratio
 
string _ratioYTitle = "Ratio"
 
 _th1
 
 _uncertainty
 
 _xerrshigh
 
 _xerrslow
 
 _xvalues
 
 _yerrshigh
 
 _yerrslow
 
 _yvalues
 
 verbose = False
 

Function Documentation

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

Definition at line 148 of file plotting.py.

References submitPVValidationJobs.__init__(), funct.abs(), cond::serialization.equal(), and SiStripPI.max.

Referenced by ntuplePlotting.drawSingle().

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

Definition at line 1663 of file plotting.py.

1664 def _copyStyle(src, dst):
1665  properties = []
1666  if hasattr(src, "GetLineColor") and hasattr(dst, "SetLineColor"):
1667  properties.extend(["LineColor", "LineStyle", "LineWidth"])
1668  if hasattr(src, "GetFillColor") and hasattr(dst, "SetFillColor"):
1669  properties.extend(["FillColor", "FillStyle"])
1670  if hasattr(src, "GetMarkerColor") and hasattr(dst, "SetMarkerColor"):
1671  properties.extend(["MarkerColor", "MarkerSize", "MarkerStyle"])
1672 
1673  for prop in properties:
1674  getattr(dst, "Set"+prop)(getattr(src, "Get"+prop)())
def _copyStyle
Definition: plotting.py:1663
def plotting._createCanvas (   name,
  width,
  height 
)
private

Definition at line 109 of file plotting.py.

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

110 def _createCanvas(name, width, height):
111  # silence warning of deleting canvas with the same name
112  if not verbose:
113  backup = ROOT.gErrorIgnoreLevel
114  ROOT.gErrorIgnoreLevel = ROOT.kError
115  canvas = ROOT.TCanvas(name, name, width, height)
116  if not verbose:
117  ROOT.gErrorIgnoreLevel = backup
118  return canvas
def _createCanvas
Definition: plotting.py:109
def plotting._drawFrame (   pad,
  bounds,
  zmax = None,
  xbinlabels = None,
  xbinlabelsize = None,
  xbinlabeloption = None,
  ybinlabels = 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:
zmax            -- Maximum Z, needed for TH2 histograms
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 1187 of file plotting.py.

References sistrip::SpyUtilities.range().

1188 def _drawFrame(pad, bounds, zmax=None, xbinlabels=None, xbinlabelsize=None, xbinlabeloption=None, ybinlabels=None, suffix=""):
1189  """Function to draw a frame
1190 
1191  Arguments:
1192  pad -- TPad to where the frame is drawn
1193  bounds -- List or 4-tuple for (xmin, ymin, xmax, ymax)
1194 
1195  Keyword arguments:
1196  zmax -- Maximum Z, needed for TH2 histograms
1197  xbinlabels -- Optional list of strings for x axis bin labels
1198  xbinlabelsize -- Optional number for the x axis bin label size
1199  xbinlabeloption -- Optional string for the x axis bin options (passed to ROOT.TH1.LabelsOption())
1200  suffix -- Optional string for a postfix of the frame name
1201  """
1202  if xbinlabels is None and ybinlabels is None:
1203  frame = pad.DrawFrame(*bounds)
1204  else:
1205  # Special form needed if want to set x axis bin labels
1206  nbins = len(xbinlabels)
1207  if ybinlabels is None:
1208  frame = ROOT.TH1F("hframe"+suffix, "", nbins, bounds[0], bounds[2])
1209  frame.SetMinimum(bounds[1])
1210  frame.SetMaximum(bounds[3])
1211  frame.GetYaxis().SetLimits(bounds[1], bounds[3])
1212  else:
1213  ybins = len(ybinlabels)
1214  frame = ROOT.TH2F("hframe"+suffix, "", nbins,bounds[0],bounds[2], ybins,bounds[1],bounds[3])
1215  frame.SetMaximum(zmax)
1216 
1217  frame.SetBit(ROOT.TH1.kNoStats)
1218  frame.SetBit(ROOT.kCanDelete)
1219  frame.Draw("")
1220 
1221  xaxis = frame.GetXaxis()
1222  for i in range(nbins):
1223  xaxis.SetBinLabel(i+1, xbinlabels[i])
1224  if xbinlabelsize is not None:
1225  xaxis.SetLabelSize(xbinlabelsize)
1226  if xbinlabeloption is not None:
1227  frame.LabelsOption(xbinlabeloption)
1228 
1229  if ybinlabels is not None:
1230  yaxis = frame.GetYaxis()
1231  for i, lab in enumerate(ybinlabels):
1232  yaxis.SetBinLabel(i+1, lab)
1233  if xbinlabelsize is not None:
1234  yaxis.SetLabelSize(xbinlabelsize)
1235  if xbinlabeloption is not None:
1236  frame.LabelsOption(xbinlabeloption, "Y")
1237 
1238  return frame
const uint16_t range(const Frame &aFrame)
def _drawFrame
Definition: plotting.py:1187
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 459 of file plotting.py.

References _findBoundsY(), _getXmax(), _getXmin(), SiStripPI.max, min(), print(), and str.

Referenced by ntuplePlotting.drawSingle().

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

References _getYmax(), _getYmin(), _getYminIgnoreOutlier(), _getYminMaxAroundMedian(), SiStripPI.max, min(), print(), and str.

Referenced by _findBounds().

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

Definition at line 97 of file plotting.py.

References _getDirectoryDetailed().

Referenced by plotting.PlotterTableItem.create().

97 
98 def _getDirectory(*args, **kwargs):
99  return GetDirectoryCode.codesToNone(_getDirectoryDetailed(*args, **kwargs))
def _getDirectory
Definition: plotting.py:97
def _getDirectoryDetailed
Definition: plotting.py:73
def plotting._getDirectoryDetailed (   tfile,
  possibleDirs,
  subDir = None 
)
private
Get TDirectory from TFile.

Definition at line 73 of file plotting.py.

References join(), and print().

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

73 
74 def _getDirectoryDetailed(tfile, possibleDirs, subDir=None):
75  """Get TDirectory from TFile."""
76  if tfile is None:
78  for pdf in possibleDirs:
79  d = tfile.Get(pdf)
80  if d:
81  if subDir is not None:
82  # Pick associator if given
83  d = d.Get(subDir)
84  if d:
85  return d
86  else:
87  if verbose:
88  print("Did not find subdirectory '%s' from directory '%s' in file %s" % (subDir, pdf, tfile.GetName()))
89 # if "Step" in subDir:
90 # raise Exception("Foo")
92  else:
93  return d
94  if verbose:
95  print("Did not find any of directories '%s' from file %s" % (",".join(possibleDirs), tfile.GetName()))
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def _getDirectoryDetailed
Definition: plotting.py:73
def plotting._getObject (   tdirectory,
  name 
)
private

Definition at line 49 of file plotting.py.

References print().

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

49 
50 def _getObject(tdirectory, name):
51  obj = tdirectory.Get(name)
52  if not obj:
53  if verbose:
54  print("Did not find {obj} from {dir}".format(obj=name, dir=tdirectory.GetPath()))
55  return None
56  return obj
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def _getObject
Definition: plotting.py:49
def plotting._getOrCreateObject (   tdirectory,
  nameOrCreator 
)
private

Definition at line 57 of file plotting.py.

References _getObject().

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

57 
58 def _getOrCreateObject(tdirectory, nameOrCreator):
59  if hasattr(nameOrCreator, "create"):
60  return nameOrCreator.create(tdirectory)
61  return _getObject(tdirectory, nameOrCreator)
def _getObject
Definition: plotting.py:49
def _getOrCreateObject
Definition: plotting.py:57
def plotting._getXmax (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 358 of file plotting.py.

References SiStripPI.max, sistrip::SpyUtilities.range(), and str.

Referenced by _findBounds().

359 def _getXmax(obj, limitToNonZeroContent=False):
360  if isinstance(obj, ROOT.TH1):
361  xaxis = obj.GetXaxis()
362  if limitToNonZeroContent:
363  for i in range(obj.GetNbinsX(), 0, -1):
364  if obj.GetBinContent(i) != 0:
365  return xaxis.GetBinUpEdge(i)
366  # None for all bins being zero
367  return None
368  else:
369  return xaxis.GetBinUpEdge(xaxis.GetLast())
370  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
371  m = max([obj.GetX()[i] for i in range(0, obj.GetN())])
372  return m*1.1 if m > 0 else m*0.9
373  raise Exception("Unsupported type %s" % str(obj))
def _getXmax
Definition: plotting.py:358
const uint16_t range(const Frame &aFrame)
#define str(s)
def plotting._getXmin (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 342 of file plotting.py.

References min(), sistrip::SpyUtilities.range(), and str.

Referenced by _findBounds().

343 def _getXmin(obj, limitToNonZeroContent=False):
344  if isinstance(obj, ROOT.TH1):
345  xaxis = obj.GetXaxis()
346  if limitToNonZeroContent:
347  for i in range(1, obj.GetNbinsX()+1):
348  if obj.GetBinContent(i) != 0:
349  return xaxis.GetBinLowEdge(i)
350  # None for all bins being zero
351  return None
352  else:
353  return xaxis.GetBinLowEdge(xaxis.GetFirst())
354  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
355  m = min([obj.GetX()[i] for i in range(0, obj.GetN())])
356  return m*0.9 if m > 0 else m*1.1
357  raise Exception("Unsupported type %s" % str(obj))
def _getXmin
Definition: plotting.py:342
const uint16_t range(const Frame &aFrame)
T min(T a, T b)
Definition: MathUtil.h:58
#define str(s)
def plotting._getYmax (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 389 of file plotting.py.

References SiStripPI.max, sistrip::SpyUtilities.range(), and str.

Referenced by _findBoundsY().

390 def _getYmax(obj, limitToNonZeroContent=False):
391  if isinstance(obj, ROOT.TH2):
392  yaxis = obj.GetYaxis()
393  return yaxis.GetBinUpEdge(yaxis.GetLast())
394  elif isinstance(obj, ROOT.TH1):
395  if limitToNonZeroContent:
396  lst = [obj.GetBinContent(i) for i in range(1, obj.GetNbinsX()+1) if obj.GetBinContent(i) != 0 ]
397  return max(lst) if len(lst) != 0 else 0
398  else:
399  return obj.GetMaximum()
400  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
401  m = max([obj.GetY()[i] for i in range(0, obj.GetN())])
402  return m*1.1 if m > 0 else m*0.9
403  raise Exception("Unsupported type %s" % str(obj))
def _getYmax
Definition: plotting.py:389
const uint16_t range(const Frame &aFrame)
#define str(s)
def plotting._getYmaxWithError (   th1)
private

Definition at line 404 of file plotting.py.

References SiStripPI.max, and sistrip::SpyUtilities.range().

405 def _getYmaxWithError(th1):
406  return max([th1.GetBinContent(i)+th1.GetBinError(i) for i in range(1, th1.GetNbinsX()+1)])
def _getYmaxWithError
Definition: plotting.py:404
const uint16_t range(const Frame &aFrame)
def plotting._getYmin (   obj,
  limitToNonZeroContent = False 
)
private

Definition at line 374 of file plotting.py.

References min(), sistrip::SpyUtilities.range(), and str.

Referenced by _findBoundsY().

375 def _getYmin(obj, limitToNonZeroContent=False):
376  if isinstance(obj, ROOT.TH2):
377  yaxis = obj.GetYaxis()
378  return yaxis.GetBinLowEdge(yaxis.GetFirst())
379  elif isinstance(obj, ROOT.TH1):
380  if limitToNonZeroContent:
381  lst = [obj.GetBinContent(i) for i in range(1, obj.GetNbinsX()+1) if obj.GetBinContent(i) != 0 ]
382  return min(lst) if len(lst) != 0 else 0
383  else:
384  return obj.GetMinimum()
385  elif isinstance(obj, ROOT.TGraph) or isinstance(obj, ROOT.TGraph2D):
386  m = min([obj.GetY()[i] for i in range(0, obj.GetN())])
387  return m*0.9 if m > 0 else m*1.1
388  raise Exception("Unsupported type %s" % str(obj))
def _getYmin
Definition: plotting.py:374
const uint16_t range(const Frame &aFrame)
T min(T a, T b)
Definition: MathUtil.h:58
#define str(s)
def plotting._getYminIgnoreOutlier (   th1)
private

Definition at line 407 of file plotting.py.

References sistrip::SpyUtilities.range().

Referenced by _findBoundsY().

408 def _getYminIgnoreOutlier(th1):
409  yvals = sorted([n for n in [th1.GetBinContent(i) for i in range(1, th1.GetNbinsX()+1)] if n>0])
410  if len(yvals) == 0:
411  return th1.GetMinimum()
412  if len(yvals) == 1:
413  return yvals[0]
414 
415  # Define outlier as being x10 less than minimum of the 95 % of the non-zero largest values
416  ind_min = len(yvals)-1 - int(len(yvals)*0.95)
417  min_val = yvals[ind_min]
418  for i in range(0, ind_min):
419  if yvals[i] > 0.1*min_val:
420  return yvals[i]
421 
422  return min_val
def _getYminIgnoreOutlier
Definition: plotting.py:407
const uint16_t range(const Frame &aFrame)
def plotting._getYminMaxAroundMedian (   obj,
  coverage,
  coverageRange = None 
)
private

Definition at line 423 of file plotting.py.

References sistrip::SpyUtilities.range(), and str.

Referenced by _findBoundsY().

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

Definition at line 713 of file plotting.py.

References SiStripPI.max.

Referenced by _mergeBinLabelsX(), and _mergeBinLabelsY().

714 def _mergeBinLabels(labelsAll):
715  labels_merged = labelsAll[0]
716  for labels in labelsAll[1:]:
717  diff = difflib.unified_diff(labels_merged, labels, n=max(len(labels_merged), len(labels)))
718  labels_merged = []
719  operation = []
720  for item in diff: # skip the "header" lines
721  if item[:2] == "@@":
722  break
723  for item in diff:
724  operation.append(item[0])
725  lab = item[1:]
726  if lab in labels_merged:
727  # pick the last addition of the bin
728  ind = labels_merged.index(lab)
729  if operation[ind] == "-" and operation[-1] == "+":
730  labels_merged.remove(lab)
731  del operation[ind] # to keep xbinlabels and operation indices in sync
732  elif operation[ind] == "+" and operation[-1] == "-":
733  del operation[-1] # to keep xbinlabels and operation indices in sync
734  continue
735  else:
736  raise Exception("This should never happen")
737  labels_merged.append(lab)
738  # unified_diff returns empty diff if labels_merged and labels are equal
739  # so if labels_merged is empty here, it can be just set to labels
740  if len(labels_merged) == 0:
741  labels_merged = labels
742 
743  return labels_merged
def _mergeBinLabels
Definition: plotting.py:713
def plotting._mergeBinLabelsX (   histos)
private

Definition at line 707 of file plotting.py.

References _mergeBinLabels(), and sistrip::SpyUtilities.range().

Referenced by trackingPlots.TrackingSeedingLayerTable.draw(), and plotting.Plot.draw().

708 def _mergeBinLabelsX(histos):
709  return _mergeBinLabels([[h.GetXaxis().GetBinLabel(i) for i in range(1, h.GetNbinsX()+1)] for h in histos])
const uint16_t range(const Frame &aFrame)
def _mergeBinLabels
Definition: plotting.py:713
def _mergeBinLabelsX
Definition: plotting.py:707
def plotting._mergeBinLabelsY (   histos)
private

Definition at line 710 of file plotting.py.

References _mergeBinLabels(), and sistrip::SpyUtilities.range().

Referenced by plotting.Plot.draw().

711 def _mergeBinLabelsY(histos):
712  return _mergeBinLabels([[h.GetYaxis().GetBinLabel(i) for i in range(1, h.GetNbinsY()+1)] for h in histos])
def _mergeBinLabelsY
Definition: plotting.py:710
const uint16_t range(const Frame &aFrame)
def _mergeBinLabels
Definition: plotting.py:713
def plotting._modifyPadForRatio (   pad,
  ratioFactor 
)
private

Definition at line 119 of file plotting.py.

Referenced by ntuplePlotting.draw(), and ntuplePlotting.drawMany().

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

Definition at line 21 of file plotting.py.

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

Definition at line 744 of file plotting.py.

Referenced by trackingPlots.TrackingSeedingLayerTable.draw(), and plotting.Plot.draw().

745 def _th1IncludeOnlyBins(histos, xbinlabels):
746  histos_new = []
747  for h in histos:
748  h_new = h.Clone(h.GetName()+"_xbinlabels")
749  h_new.SetBins(len(xbinlabels), h.GetBinLowEdge(1), h.GetBinLowEdge(1)+len(xbinlabels))
750  for i, label in enumerate(xbinlabels):
751  bin = h.GetXaxis().FindFixBin(label)
752  if bin >= 0:
753  h_new.SetBinContent(i+1, h.GetBinContent(bin))
754  h_new.SetBinError(i+1, h.GetBinError(bin))
755  else:
756  h_new.SetBinContent(i+1, 0)
757  h_new.SetBinError(i+1, 0)
758  histos_new.append(h_new)
759  return histos_new
760 
def _th1IncludeOnlyBins
Definition: plotting.py:744
def plotting._th1RemoveEmptyBins (   histos,
  xbinlabels 
)
private

Definition at line 607 of file plotting.py.

References sistrip::SpyUtilities.range().

Referenced by trackingPlots.TrackingSeedingLayerTable.draw().

608 def _th1RemoveEmptyBins(histos, xbinlabels):
609  binsToRemove = set()
610  for b in range(1, histos[0].GetNbinsX()+1):
611  binEmpty = True
612  for h in histos:
613  if h.GetBinContent(b) > 0:
614  binEmpty = False
615  break
616  if binEmpty:
617  binsToRemove.add(b)
618 
619  if len(binsToRemove) > 0:
620  # filter xbinlabels
621  xbinlab_new = []
622  for i in range(len(xbinlabels)):
623  if (i+1) not in binsToRemove:
624  xbinlab_new.append(xbinlabels[i])
625  xbinlabels = xbinlab_new
626 
627  # filter histogram bins
628  histos_new = []
629  for h in histos:
630  values = []
631  for b in range(1, h.GetNbinsX()+1):
632  if b not in binsToRemove:
633  values.append( (h.GetXaxis().GetBinLabel(b), h.GetBinContent(b), h.GetBinError(b)) )
634 
635  if len(values) > 0:
636  h_new = h.Clone(h.GetName()+"_empty")
637  h_new.SetBins(len(values), h.GetBinLowEdge(1), h.GetBinLowEdge(1)+len(values))
638  for b, (l, v, e) in enumerate(values):
639  h_new.GetXaxis().SetBinLabel(b+1, l)
640  h_new.SetBinContent(b+1, v)
641  h_new.SetBinError(b+1, e)
642 
643  histos_new.append(h_new)
644  histos = histos_new
645 
646  return (histos, xbinlabels)
def _th1RemoveEmptyBins
Definition: plotting.py:607
const uint16_t range(const Frame &aFrame)
def plotting._th1ToOrderedDict (   th1,
  renameBin = None 
)
private

Definition at line 100 of file plotting.py.

References sistrip::SpyUtilities.range().

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

101 def _th1ToOrderedDict(th1, renameBin=None):
102  values = collections.OrderedDict()
103  for i in range(1, th1.GetNbinsX()+1):
104  binLabel = th1.GetXaxis().GetBinLabel(i)
105  if renameBin is not None:
106  binLabel = renameBin(binLabel)
107  values[binLabel] = (th1.GetBinContent(i), th1.GetBinError(i))
108  return values
def _th1ToOrderedDict
Definition: plotting.py:100
const uint16_t range(const Frame &aFrame)
def plotting._th2RemoveEmptyBins (   histos,
  xbinlabels,
  ybinlabels 
)
private

Definition at line 647 of file plotting.py.

References sistrip::SpyUtilities.range().

648 def _th2RemoveEmptyBins(histos, xbinlabels, ybinlabels):
649  xbinsToRemove = set()
650  ybinsToRemove = set()
651  for ih, h in enumerate(histos):
652  for bx in range(1, h.GetNbinsX()+1):
653  binEmpty = True
654  for by in range(1, h.GetNbinsY()+1):
655  if h.GetBinContent(bx, by) > 0:
656  binEmpty = False
657  break
658  if binEmpty:
659  xbinsToRemove.add(bx)
660  elif ih > 0:
661  xbinsToRemove.discard(bx)
662 
663  for by in range(1, h.GetNbinsY()+1):
664  binEmpty = True
665  for bx in range(1, h.GetNbinsX()+1):
666  if h.GetBinContent(bx, by) > 0:
667  binEmpty = False
668  break
669  if binEmpty:
670  ybinsToRemove.add(by)
671  elif ih > 0:
672  ybinsToRemove.discard(by)
673 
674  if len(xbinsToRemove) > 0 or len(ybinsToRemove) > 0:
675  xbinlabels_new = []
676  xbins = []
677  for b in range(1, len(xbinlabels)+1):
678  if b not in xbinsToRemove:
679  xbinlabels_new.append(histos[0].GetXaxis().GetBinLabel(b))
680  xbins.append(b)
681  xbinlabels = xbinlabels_new
682  ybinlabels_new = []
683  ybins = []
684  for b in range(1, len(ybinlabels)+1):
685  if b not in ybinsToRemove:
686  ybinlabels.append(histos[0].GetYaxis().GetBinLabel(b))
687  ybins.append(b)
688  ybinlabels = xbinlabels_new
689 
690  histos_new = []
691  if len(xbinlabels) == 0 or len(ybinlabels) == 0:
692  return (histos_new, xbinlabels, ybinlabels)
693  for h in histos:
694  h_new = ROOT.TH2F(h.GetName()+"_empty", h.GetTitle(), len(xbinlabels),0,len(xbinlabels), len(ybinlabels),0,len(ybinlabels))
695  for b, l in enumerate(xbinlabels):
696  h_new.GetXaxis().SetBinLabel(b+1, l)
697  for b, l in enumerate(ybinlabels):
698  h_new.GetYaxis().SetBinLabel(b+1, l)
699 
700  for ix, bx in enumerate(xbins):
701  for iy, by in enumerate(ybins):
702  h_new.SetBinContent(ix+1, iy+1, h.GetBinContent(bx, by))
703  h_new.SetBinError(ix+1, iy+1, h.GetBinError(bx, by))
704  histos_new.append(h_new)
705  histos = histos_new
706  return (histos, xbinlabels, ybinlabels)
def _th2RemoveEmptyBins
Definition: plotting.py:647
const uint16_t range(const Frame &aFrame)

Variable Documentation

plotting._gr

Definition at line 243 of file plotting.py.

list plotting._plotStylesColor = [4, 2, ROOT.kBlack, ROOT.kOrange+7, ROOT.kMagenta-3, ROOT.kGreen+2]

Definition at line 1184 of file plotting.py.

list plotting._plotStylesMarker = [21, 20, 22, 34, 33, 23]

Definition at line 1185 of file plotting.py.

plotting._ratio

Definition at line 203 of file plotting.py.

string plotting._ratioYTitle = "Ratio"

Definition at line 19 of file plotting.py.

plotting._th1

Definition at line 195 of file plotting.py.

plotting._uncertainty

Definition at line 196 of file plotting.py.

plotting._xerrshigh

Definition at line 247 of file plotting.py.

plotting._xerrslow

Definition at line 246 of file plotting.py.

plotting._xvalues

Definition at line 245 of file plotting.py.

plotting._yerrshigh

Definition at line 249 of file plotting.py.

plotting._yerrslow

Definition at line 250 of file plotting.py.

plotting._yvalues

Definition at line 248 of file plotting.py.

plotting.verbose = False

Definition at line 18 of file plotting.py.