CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
List of all members | Public Member Functions | Private Member Functions | Private Attributes
plotting.Plot Class Reference

Public Member Functions

def __init__
 
def addToLegend
 
def create
 
def draw
 
def drawRatioUncertainty
 
def getName
 
def getNumberOfHistograms
 
def isEmpty
 
def isTGraph2D
 
def setProperties
 

Private Member Functions

def _calculateRatios
 
def _createOne
 
def _normalize
 
def _setStats
 

Private Attributes

 _forLegend
 
 _frame
 
 _gr
 
 _histograms
 
 _name
 
 _ratio
 
 _ratios
 
 _th1
 
 _tmp_histos
 
 _uncertainty
 
 _xerrshigh
 
 _xerrslow
 
 _xvalues
 
 _yerrshigh
 
 _yerrslow
 
 _yvalues
 

Detailed Description

Represents one plot, comparing one or more histograms.

Definition at line 901 of file plotting.py.

Constructor & Destructor Documentation

def plotting.Plot.__init__ (   self,
  name,
  kwargs 
)
Constructor.

Arguments:
name -- String for name of the plot, or Efficiency object

Keyword arguments:
fallback     -- Dictionary for specifying fallback (default None)
title        -- String for a title of the plot (default None)
xtitle       -- String for x axis title (default None)
xtitlesize   -- Float for x axis title size (default None)
xtitleoffset -- Float for x axis title offset (default None)
xlabelsize   -- Float for x axis label size (default None)
ytitle       -- String for y axis title (default None)
ytitlesize   -- Float for y axis title size (default None)
ytitleoffset -- Float for y axis title offset (default None)
ztitle       -- String for z axis title (default None)
ztitleoffset -- Float for z axis title offset (default None)
xmin         -- Float for x axis minimum (default None, i.e. automatic)
xmax         -- Float for x axis maximum (default None, i.e. automatic)
ymin         -- Float for y axis minimum (default 0)
ymax         -- Float for y axis maximum (default None, i.e. automatic)
xlog         -- Bool for x axis log status (default False)
ylog         -- Bool for y axis log status (default False)
xgrid        -- Bool for x axis grid status (default True)
ygrid        -- Bool for y axis grid status (default True)
stat         -- Draw stat box? (default False)
fit          -- Do gaussian fit? (default False)
statx        -- Stat box x coordinate (default 0.65)
staty        -- Stat box y coordinate (default 0.8)
statyadjust  -- List of floats for stat box y coordinate adjustments (default None)
normalizeToUnitArea -- Normalize histograms to unit area? (default False)
profileX     -- Take histograms via ProfileX()? (default False)
fitSlicesY   -- Take histograms via FitSlicesY() (default False)
rebinX       -- rebin x axis (default None)
scale        -- Scale histograms by a number (default None)
xbinlabels   -- List of x axis bin labels (if given, default None)
xbinlabelsize -- Size of x axis bin labels (default None)
xbinlabeloption -- Option string for x axis bin labels (default None)
drawStyle    -- If "hist", draw as line instead of points (default None)
drawCommand  -- Deliver this to Draw() (default: None for same as drawStyle)
lineWidth    -- If drawStyle=="hist", the width of line (default 2)
legendDx     -- Float for moving TLegend in x direction for separate=True (default None)
legendDy     -- Float for moving TLegend in y direction for separate=True (default None)
legendDw     -- Float for changing TLegend width for separate=True (default None)
legendDh     -- Float for changing TLegend height for separate=True (default None)
adjustMarginRight  -- Float for adjusting right margin (default None)
ratioYmin    -- Float for y axis minimum in ratio pad (default 0.9)
ratioYmax    -- Float for y axis maximum in ratio pad (default 1.1)
ratioUncertainty -- Plot uncertainties on ratio? (default True)
histogramModifier -- Function to be called in create() to modify the histograms (default None)

Definition at line 903 of file plotting.py.

Referenced by plotting.Plot._calculateRatios().

904  def __init__(self, name, **kwargs):
905  """ Constructor.
906 
907  Arguments:
908  name -- String for name of the plot, or Efficiency object
909 
910  Keyword arguments:
911  fallback -- Dictionary for specifying fallback (default None)
912  title -- String for a title of the plot (default None)
913  xtitle -- String for x axis title (default None)
914  xtitlesize -- Float for x axis title size (default None)
915  xtitleoffset -- Float for x axis title offset (default None)
916  xlabelsize -- Float for x axis label size (default None)
917  ytitle -- String for y axis title (default None)
918  ytitlesize -- Float for y axis title size (default None)
919  ytitleoffset -- Float for y axis title offset (default None)
920  ztitle -- String for z axis title (default None)
921  ztitleoffset -- Float for z axis title offset (default None)
922  xmin -- Float for x axis minimum (default None, i.e. automatic)
923  xmax -- Float for x axis maximum (default None, i.e. automatic)
924  ymin -- Float for y axis minimum (default 0)
925  ymax -- Float for y axis maximum (default None, i.e. automatic)
926  xlog -- Bool for x axis log status (default False)
927  ylog -- Bool for y axis log status (default False)
928  xgrid -- Bool for x axis grid status (default True)
929  ygrid -- Bool for y axis grid status (default True)
930  stat -- Draw stat box? (default False)
931  fit -- Do gaussian fit? (default False)
932  statx -- Stat box x coordinate (default 0.65)
933  staty -- Stat box y coordinate (default 0.8)
934  statyadjust -- List of floats for stat box y coordinate adjustments (default None)
935  normalizeToUnitArea -- Normalize histograms to unit area? (default False)
936  profileX -- Take histograms via ProfileX()? (default False)
937  fitSlicesY -- Take histograms via FitSlicesY() (default False)
938  rebinX -- rebin x axis (default None)
939  scale -- Scale histograms by a number (default None)
940  xbinlabels -- List of x axis bin labels (if given, default None)
941  xbinlabelsize -- Size of x axis bin labels (default None)
942  xbinlabeloption -- Option string for x axis bin labels (default None)
943  drawStyle -- If "hist", draw as line instead of points (default None)
944  drawCommand -- Deliver this to Draw() (default: None for same as drawStyle)
945  lineWidth -- If drawStyle=="hist", the width of line (default 2)
946  legendDx -- Float for moving TLegend in x direction for separate=True (default None)
947  legendDy -- Float for moving TLegend in y direction for separate=True (default None)
948  legendDw -- Float for changing TLegend width for separate=True (default None)
949  legendDh -- Float for changing TLegend height for separate=True (default None)
950  adjustMarginRight -- Float for adjusting right margin (default None)
951  ratioYmin -- Float for y axis minimum in ratio pad (default 0.9)
952  ratioYmax -- Float for y axis maximum in ratio pad (default 1.1)
953  ratioUncertainty -- Plot uncertainties on ratio? (default True)
954  histogramModifier -- Function to be called in create() to modify the histograms (default None)
955  """
956  self._name = name
957 
958  def _set(attr, default):
959  setattr(self, "_"+attr, kwargs.get(attr, default))
960 
961  _set("fallback", None)
962 
963  _set("title", None)
964  _set("xtitle", None)
965  _set("xtitlesize", None)
966  _set("xtitleoffset", None)
967  _set("xlabelsize", None)
968  _set("ytitle", None)
969  _set("ytitlesize", None)
970  _set("ytitleoffset", None)
971  _set("ztitle", None)
972  _set("ztitleoffset", None)
973 
974  _set("xmin", None)
975  _set("xmax", None)
976  _set("ymin", 0.)
977  _set("ymax", None)
978 
979  _set("xlog", False)
980  _set("ylog", False)
981  _set("xgrid", True)
982  _set("ygrid", True)
983 
984  _set("stat", False)
985  _set("fit", False)
986 
987  _set("statx", 0.65)
988  _set("staty", 0.8)
989  _set("statyadjust", None)
990 
991  _set("normalizeToUnitArea", False)
992  _set("profileX", False)
993  _set("fitSlicesY", False)
994  _set("rebinX", None)
995 
996  _set("scale", None)
997  _set("xbinlabels", None)
998  _set("xbinlabelsize", None)
999  _set("xbinlabeloption", None)
1000 
1001  _set("drawStyle", "EP")
1002  _set("drawCommand", None)
1003  _set("lineWidth", 2)
1004 
1005  _set("legendDx", None)
1006  _set("legendDy", None)
1007  _set("legendDw", None)
1008  _set("legendDh", None)
1009 
1010  _set("adjustMarginRight", None)
1011 
1012  _set("ratioYmin", 0.9)
1013  _set("ratioYmax", 1.1)
1014  _set("ratioUncertainty", True)
1015 
1016  _set("histogramModifier", None)
1018  self._histograms = []

Member Function Documentation

def plotting.Plot._calculateRatios (   self,
  histos 
)
private
Calculate the ratios for a list of histograms

Definition at line 1355 of file plotting.py.

References plotting.Plot.__init__(), funct.abs(), cond::serialization.equal(), and bookConverter.max.

1356  def _calculateRatios(self, histos):
1357  """Calculate the ratios for a list of histograms"""
1358 
1359  def _divideOrZero(numerator, denominator):
1360  if denominator == 0:
1361  return 0
1362  return numerator/denominator
1363 
1364  def equal(a, b):
1365  if a == 0. and b == 0.:
1366  return True
1367  return abs(a-b)/max(abs(a),abs(b)) < 1e-3
1368 
1369  def findBins(wrap, bins_xvalues):
1370  ret = []
1371  currBin = wrap.begin()
1372  i = 0
1373  while i < len(bins_xvalues) and currBin < wrap.end():
1374  (xcenter, xlow, xhigh) = bins_xvalues[i]
1375  xlowEdge = xcenter-xlow
1376  xupEdge = xcenter+xhigh
1377 
1378  (curr_center, curr_low, curr_high) = wrap.xvalues(currBin)
1379  curr_lowEdge = curr_center-curr_low
1380  curr_upEdge = curr_center+curr_high
1381 
1382  if equal(xlowEdge, curr_lowEdge) and equal(xupEdge, curr_upEdge):
1383  ret.append(currBin)
1384  currBin += 1
1385  i += 1
1386  elif curr_upEdge <= xlowEdge:
1387  currBin += 1
1388  elif curr_lowEdge >= xupEdge:
1389  ret.append(None)
1390  i += 1
1391  else:
1392  ret.append(None)
1393  currBin += 1
1394  i += 1
1395  if len(ret) != len(bins_xvalues):
1396  ret.extend([None]*( len(bins_xvalues) - len(ret) ))
1397  return ret
1398 
1399  # Define wrappers for TH1/TGraph/TGraph2D to have uniform interface
1400  # TODO: having more global wrappers would make some things simpler also elsewhere in the code
1401  class WrapTH1:
1402  def __init__(self, th1, uncertainty):
1403  self._th1 = th1
1404  self._uncertainty = uncertainty
1405 
1406  xaxis = th1.GetXaxis()
1407  xaxis_arr = xaxis.GetXbins()
1408  if xaxis_arr.GetSize() > 0: # unequal binning
1409  lst = [xaxis_arr[i] for i in xrange(0, xaxis_arr.GetSize())]
1410  arr = array.array("d", lst)
1411  self._ratio = ROOT.TH1F("foo", "foo", xaxis.GetNbins(), arr)
1412  else:
1413  self._ratio = ROOT.TH1F("foo", "foo", xaxis.GetNbins(), xaxis.GetXmin(), xaxis.GetXmax())
1414  _copyStyle(th1, self._ratio)
1415  self._ratio.SetStats(0)
1416  self._ratio.SetLineColor(ROOT.kBlack)
1417  self._ratio.SetLineWidth(1)
1418  def draw(self, style=None):
1419  st = style
1420  if st is None:
1421  if self._uncertainty:
1422  st = "EP"
1423  else:
1424  st = "HIST P"
1425  self._ratio.Draw("same "+st)
1426  def begin(self):
1427  return 1
1428  def end(self):
1429  return self._th1.GetNbinsX()+1
1430  def xvalues(self, bin):
1431  xval = self._th1.GetBinCenter(bin)
1432  xlow = xval-self._th1.GetXaxis().GetBinLowEdge(bin)
1433  xhigh = self._th1.GetXaxis().GetBinUpEdge(bin)-xval
1434  return (xval, xlow, xhigh)
1435  def yvalues(self, bin):
1436  yval = self._th1.GetBinContent(bin)
1437  yerr = self._th1.GetBinError(bin)
1438  return (yval, yerr, yerr)
1439  def y(self, bin):
1440  return self._th1.GetBinContent(bin)
1441  def divide(self, bin, scale):
1442  self._ratio.SetBinContent(bin, _divideOrZero(self._th1.GetBinContent(bin), scale))
1443  self._ratio.SetBinError(bin, _divideOrZero(self._th1.GetBinError(bin), scale))
1444  def makeRatio(self):
1445  pass
1446 
1447  class WrapTGraph:
1448  def __init__(self, gr, uncertainty):
1449  self._gr = gr
1450  self._uncertainty = uncertainty
1451  self._xvalues = []
1452  self._xerrslow = []
1453  self._xerrshigh = []
1454  self._yvalues = []
1455  self._yerrshigh = []
1456  self._yerrslow = []
1457  def draw(self, style=None):
1458  if self._ratio is None:
1459  return
1460  st = style
1461  if st is None:
1462  if self._uncertainty:
1463  st = "PZ"
1464  else:
1465  st = "PX"
1466  self._ratio.Draw("same "+st)
1467  def begin(self):
1468  return 0
1469  def end(self):
1470  return self._gr.GetN()
1471  def xvalues(self, bin):
1472  return (self._gr.GetX()[bin], self._gr.GetErrorXlow(bin), self._gr.GetErrorXhigh(bin))
1473  def yvalues(self, bin):
1474  return (self._gr.GetY()[bin], self._gr.GetErrorYlow(bin), self._gr.GetErrorYhigh(bin))
1475  def y(self, bin):
1476  return self._gr.GetY()[bin]
1477  def divide(self, bin, scale):
1478  # Ignore bin if denominator is zero
1479  if scale == 0:
1480  return
1481  # No more items in the numerator
1482  if bin >= self._gr.GetN():
1483  return
1484  # denominator is missing an item
1485  xvals = self.xvalues(bin)
1486  xval = xvals[0]
1487 
1488  self._xvalues.append(xval)
1489  self._xerrslow.append(xvals[1])
1490  self._xerrshigh.append(xvals[2])
1491  yvals = self.yvalues(bin)
1492  self._yvalues.append(yvals[0] / scale)
1493  if self._uncertainty:
1494  self._yerrslow.append(yvals[1] / scale)
1495  self._yerrshigh.append(yvals[2] / scale)
1496  else:
1497  self._yerrslow.append(0)
1498  self._yerrshigh.append(0)
1499  def makeRatio(self):
1500  if len(self._xvalues) == 0:
1501  self._ratio = None
1502  return
1503  self._ratio = ROOT.TGraphAsymmErrors(len(self._xvalues), array.array("d", self._xvalues), array.array("d", self._yvalues),
1504  array.array("d", self._xerrslow), array.array("d", self._xerrshigh),
1505  array.array("d", self._yerrslow), array.array("d", self._yerrshigh))
1506  _copyStyle(self._gr, self._ratio)
1507  class WrapTGraph2D(WrapTGraph):
1508  def __init__(self, gr, uncertainty):
1509  WrapTGraph.__init__(self, gr, uncertainty)
1510  def xvalues(self, bin):
1511  return (self._gr.GetX()[bin], self._gr.GetErrorX(bin), self._gr.GetErrorX(bin))
1512  def yvalues(self, bin):
1513  return (self._gr.GetY()[bin], self._gr.GetErrorY(bin), self._gr.GetErrorY(bin))
1514 
1515  def wrap(o):
1516  if isinstance(o, ROOT.TH1):
1517  return WrapTH1(o, self._ratioUncertainty)
1518  elif isinstance(o, ROOT.TGraph):
1519  return WrapTGraph(o, self._ratioUncertainty)
1520  elif isinstance(o, ROOT.TGraph2D):
1521  return WrapTGraph2D(o, self._ratioUncertainty)
1522 
1523  wrappers = [wrap(h) for h in histos]
1524  ref = wrappers[0]
1525 
1526  wrappers_bins = []
1527  ref_bins = [ref.xvalues(b) for b in xrange(ref.begin(), ref.end())]
1528  for w in wrappers:
1529  wrappers_bins.append(findBins(w, ref_bins))
1530 
1531  for i, bin in enumerate(xrange(ref.begin(), ref.end())):
1532  (scale, ylow, yhigh) = ref.yvalues(bin)
1533  for w, bins in zip(wrappers, wrappers_bins):
1534  if bins[i] is None:
1535  continue
1536  w.divide(bins[i], scale)
1537 
1538  for w in wrappers:
1539  w.makeRatio()
1540 
1541  return wrappers
bool equal(const T &first, const T &second)
Definition: Equal.h:34
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
#define end
Definition: vmac.h:37
def _copyStyle
Definition: plotting.py:889
#define begin
Definition: vmac.h:30
def _calculateRatios
Definition: plotting.py:1355
auto wrap(F iFunc) -> decltype(iFunc())
def plotting.Plot._createOne (   self,
  name,
  index,
  tdir 
)
private
Create one histogram from a TDirectory.

Definition at line 1049 of file plotting.py.

References plotting._getOrCreateObject().

Referenced by plotting.Plot.create().

1050  def _createOne(self, name, index, tdir):
1051  """Create one histogram from a TDirectory."""
1052  if tdir == None:
1053  return None
1054 
1055  # If name is a list, pick the name by the index
1056  if isinstance(name, list):
1057  name = name[index]
1058 
1059  return _getOrCreateObject(tdir, name)
def _getOrCreateObject
Definition: plotting.py:22
def plotting.Plot._normalize (   self)
private
Normalise histograms to unit area

Definition at line 1151 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

Referenced by plotting.Plot.draw().

1152  def _normalize(self):
1153  """Normalise histograms to unit area"""
1154 
1155  for h in self._histograms:
1156  if h is None:
1157  continue
1158  i = h.Integral()
1159  if i == 0:
1160  continue
1161  h.Sumw2()
1162  h.Scale(1.0/i)
def plotting.Plot._setStats (   self,
  histos,
  startingX,
  startingY 
)
private
Set stats box.

Definition at line 1110 of file plotting.py.

References DTSC._stat, and DTTrigGeom._stat.

1111  def _setStats(self, histos, startingX, startingY):
1112  """Set stats box."""
1113  if not self._stat:
1114  for h in histos:
1115  if h is not None and hasattr(h, "SetStats"):
1116  h.SetStats(0)
1117  return
1118 
1119  def _doStats(h, col, dy):
1120  if h is None:
1121  return
1122  h.SetStats(True)
1123 
1124  if self._fit and h.GetEntries() > 0.5:
1125  h.Fit("gaus", "Q")
1126  f = h.GetListOfFunctions().FindObject("gaus")
1127  if f == None:
1128  h.SetStats(0)
1129  return
1130  f.SetLineColor(col)
1131  f.SetLineWidth(1)
1132  h.Draw()
1133  ROOT.gPad.Update()
1134  st = h.GetListOfFunctions().FindObject("stats")
1135  if self._fit:
1136  st.SetOptFit(0o010)
1137  st.SetOptStat(1001)
1138  st.SetX1NDC(startingX)
1139  st.SetX2NDC(startingX+0.3)
1140  st.SetY1NDC(startingY+dy)
1141  st.SetY2NDC(startingY+dy+0.15)
1142  st.SetTextColor(col)
1143 
1144  dy = 0.0
1145  for i, h in enumerate(histos):
1146  if self._statyadjust is not None and i < len(self._statyadjust):
1147  dy += self._statyadjust[i]
1148 
1149  _doStats(h, _plotStylesColor[i], dy)
1150  dy -= 0.19
def plotting.Plot.addToLegend (   self,
  legend,
  legendLabels,
  denomUncertainty 
)
Add histograms to a legend.

Arguments:
legend       -- TLegend
legendLabels -- List of strings for the legend labels

Definition at line 1334 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

1335  def addToLegend(self, legend, legendLabels, denomUncertainty):
1336  """Add histograms to a legend.
1337 
1338  Arguments:
1339  legend -- TLegend
1340  legendLabels -- List of strings for the legend labels
1341  """
1342  first = denomUncertainty
1343  for h, label in zip(self._histograms, legendLabels):
1344  if h is None:
1345  first = False
1346  continue
1347  if first:
1348  self._forLegend = h.Clone()
1349  self._forLegend.SetFillStyle(1001)
1350  self._forLegend.SetFillColor(ROOT.kGray)
1351  entry = legend.AddEntry(self._forLegend, label, "lpf")
1352  first = False
1353  else:
1354  legend.AddEntry(h, label, "LP")
def plotting.Plot.create (   self,
  tdirs,
  requireAllHistograms = False 
)
Create histograms from list of TDirectories

Definition at line 1060 of file plotting.py.

References plotting.Plot._createOne(), RunHistogramManager._histograms, plotting.Plot._histograms, FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, L1TMuon::PtAssignmentUnit._name, L1TMuon::PtRefinementUnit._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, hcaldqm::Container._name, citk::IsolationConeDefinitionBase._name, hcaldqm::DQModule._name, Logger._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, CutApplicatorBase._name, ElectronMVAEstimatorRun2Phys14NonTrig._name, PhotonMVAEstimatorRun2Spring15NonTrig._name, PhotonMVAEstimatorRun2Phys14NonTrig._name, ElectronMVAEstimatorRun2Spring15Trig._name, GeometricDetExtra._name, ElectronMVAEstimatorRun2Spring15NonTrig._name, HistoParams< TH2F >._name, HistoParams< TProfile2D >._name, plotting.Subtract._name, plotting.FakeDuplicate._name, plotting.AggregateBins._name, Vispa.Views.PropertyView.Property._name, SequenceTypes.SequencePlaceholder._name, plotting.AggregateHistos._name, plotting.ROC._name, plotting.Plot._name, plotting.AggregateBins._scale, Vispa.Gui.VispaWidget.VispaWidget._scale, HistoParams< T >._title, HistoParams< TProfile >._title, HistoParams< TH1F >._title, hcaldqm::axis::Axis._title, HistoParams< TH2F >._title, HistoParams< TProfile2D >._title, plotting.Subtract._title, plotting.FakeDuplicate._title, html.PageSet._title, and html.HtmlReport._title.

1061  def create(self, tdirs, requireAllHistograms=False):
1062  """Create histograms from list of TDirectories"""
1063  self._histograms = [self._createOne(self._name, i, tdir) for i, tdir in enumerate(tdirs)]
1064 
1065  if self._fallback is not None:
1066  profileX = [self._profileX]*len(self._histograms)
1067  for i in xrange(0, len(self._histograms)):
1068  if self._histograms[i] is None:
1069  self._histograms[i] = self._createOne(self._fallback["name"], i, tdirs[i])
1070  profileX[i] = self._fallback.get("profileX", self._profileX)
1071 
1072  if self._histogramModifier is not None:
1073  self._histograms = self._histogramModifier(self._histograms)
1074 
1075  if len(self._histograms) > len(_plotStylesColor):
1076  raise Exception("More histograms (%d) than there are plot styles (%d) defined. Please define more plot styles in this file" % (len(self._histograms), len(_plotStylesColor)))
1077 
1078  # Modify histograms here in case self._name returns numbers
1079  # and self._histogramModifier creates the histograms from
1080  # these numbers
1081  def _modifyHisto(th1, profileX):
1082  if th1 is None:
1083  return None
1084 
1085  if profileX:
1086  th1 = th1.ProfileX()
1087 
1088  if self._fitSlicesY:
1089  ROOT.TH1.AddDirectory(True)
1090  th1.FitSlicesY()
1091  th1 = ROOT.gDirectory.Get(th1.GetName()+"_2")
1092  th1.SetDirectory(None)
1093  #th1.SetName(th1.GetName()+"_ref")
1094  ROOT.TH1.AddDirectory(False)
1095 
1096  if self._title is not None:
1097  th1.SetTitle(self._title)
1098 
1099  if self._scale is not None:
1100  th1.Scale(self._scale)
1101 
1102  return th1
1103 
1104  if self._fallback is not None:
1105  self._histograms = map(_modifyHisto, self._histograms, profileX)
1106  else:
1107  self._histograms = map(lambda h: _modifyHisto(h, self._profileX), self._histograms)
1108  if requireAllHistograms and None in self._histograms:
1109  self._histograms = [None]*len(self._histograms)
def plotting.Plot.draw (   self,
  pad,
  ratio,
  ratioFactor,
  nrows 
)
Draw the histograms using values for a given algorithm.

Definition at line 1163 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, plotting.Plot._normalize(), Node.getName(), HistoData.getName(), PhysicsTools::Source.getName(), ecaldqm::DBReaderWorker.getName(), CocoaMaterialElementary.getName(), LikelihoodSpecies.getName(), EcalLogicID.getName(), PCaloHit.getName(), pftools::SpaceManager.getName(), ecaldqm::DBWriterWorker.getName(), LikelihoodPdf.getName(), TkOfflineVariables.getName(), FieldHandlerBase< TOutput >.getName(), AnyMVAEstimatorRun2Base.getName(), FittedEntry.getName(), HPDNoiseDataCatalog.getName(), jsoncollector::JsonMonitorable.getName(), CSGAction.getName(), L1TUtmAlgorithm.getName(), L1TUtmScale.getName(), DTTPGLutFile.getName(), PhysicsTools::MVATrainer.getName(), L1TriggerLutFile.getName(), QCriterion.getName(), L1TUtmCondition.getName(), SeedMergerPixelLayer.getName(), pos::PixelPortcardMap.getName(), GenericMVAComputer::TaggingVariableIterator< Iter_t >::Value.getName(), L1MuGMTReg.getName(), GEMStation.getName(), PhysicsTools::Variable::Value.getName(), pftools::SpaceVoxel.getName(), ecaldqm::DQWorker.getName(), L1TUtmObject.getName(), PhotonMVAEstimatorRun2Spring15NonTrig.getName(), PhotonMVAEstimatorRun2Phys14NonTrig.getName(), L1TUtmTriggerMenu.getName(), L1TUtmCut.getName(), ElectronMVAEstimatorRun2Phys14NonTrig.getName(), edm::ELslProxy< ELgen >.getName(), L1MuGMTRegMMConfig.getName(), PhysicsTools::MVAModuleHelper< Record, Object, Filler >::Value.getName(), ElectronMVAEstimatorRun2Spring15Trig.getName(), ElectronMVAEstimatorRun2Spring15NonTrig.getName(), cscdqm::HistoDef.getName(), FourVectorHLT::PathInfo.getName(), jsoncollector::DataPoint.getName(), MonitorElement.getName(), edm::ELseverityLevel.getName(), PhysicsTools::Variable.getName(), PhysicsTools::TrainerMonitoring::Object.getName(), L1MuGMTRegSortRankOffset.getName(), L1MuGMTRegCDLConfig.getName(), cscdqm::CSCHistoDef.getName(), plotting.Plot.getName(), and plotting.Plot.isTGraph2D().

1164  def draw(self, pad, ratio, ratioFactor, nrows):
1165  """Draw the histograms using values for a given algorithm."""
1166 # if len(self._histograms) == 0:
1167 # print "No histograms for plot {name}".format(name=self._name)
1168 # return
1169 
1170  isTGraph2D = self.isTGraph2D()
1171  if isTGraph2D:
1172  # Ratios for the TGraph2Ds is not that interesting
1173  ratioOrig = ratio
1174  ratio = False
1175 
1176  if self._normalizeToUnitArea:
1177  self._normalize()
1178 
1179  if self._rebinX is not None:
1180  for h in self._histograms:
1181  h.Rebin(self._rebinX)
1182 
1183  def _styleMarker(h, msty, col):
1184  h.SetMarkerStyle(msty)
1185  h.SetMarkerColor(col)
1186  h.SetMarkerSize(0.7)
1187  h.SetLineColor(1)
1188  h.SetLineWidth(1)
1189 
1190  def _styleHist(h, msty, col):
1191  _styleMarker(h, msty, col)
1192  h.SetLineColor(col)
1193  h.SetLineWidth(self._lineWidth)
1194 
1195  # Use marker or hist style
1196  style = _styleMarker
1197  if "hist" in self._drawStyle.lower():
1198  style = _styleHist
1199  if len(self._histograms) > 0 and isinstance(self._histograms[0], ROOT.TGraph):
1200  if "l" in self._drawStyle.lower():
1201  style = _styleHist
1202 
1203  # Apply style to histograms, filter out Nones
1204  histos = []
1205  for i, h in enumerate(self._histograms):
1206  if h is None:
1207  continue
1208  style(h, _plotStylesMarker[i], _plotStylesColor[i])
1209  histos.append(h)
1210  if len(histos) == 0:
1211  if verbose:
1212  print "No histograms for plot {name}".format(name=self.getName())
1213  return
1214 
1215  # Extract x bin labels, make sure that only bins with same
1216  # label are compared with each other
1217  xbinlabels = self._xbinlabels
1218  if xbinlabels is None:
1219  if len(histos[0].GetXaxis().GetBinLabel(1)) > 0:
1220  xbinlabels = [histos[0].GetXaxis().GetBinLabel(i) for i in xrange(1, histos[0].GetNbinsX()+1)]
1221  # Merge bin labels with difflib
1222  for h in histos[1:]:
1223  labels = [h.GetXaxis().GetBinLabel(i) for i in xrange(1, h.GetNbinsX()+1)]
1224  diff = difflib.ndiff(xbinlabels, labels)
1225  xbinlabels = []
1226  for item in diff:
1227  xbinlabels.append(item[2:])
1228 
1229  histos_new = []
1230  for h in histos:
1231  h_new = h.Clone(h.GetName()+"_xbinlabels")
1232  h_new.SetBins(len(xbinlabels), h.GetBinLowEdge(1), h.GetBinLowEdge(1)+len(xbinlabels))
1233  for i, label in enumerate(xbinlabels):
1234  bin = h.GetXaxis().FindFixBin(label)
1235  if bin >= 0:
1236  h_new.SetBinContent(i+1, h.GetBinContent(bin))
1237  h_new.SetBinError(i+1, h.GetBinError(bin))
1238  else:
1239  h_new.SetBinContent(i+1, 0)
1240  h_new.SetBinError(i+1, 0)
1241  histos_new.append(h_new)
1242  self._tmp_histos = histos_new # need to keep these in memory too ...
1243  histos = histos_new
1244 
1245  bounds = _findBounds(histos, self._ylog,
1246  xmin=self._xmin, xmax=self._xmax,
1247  ymin=self._ymin, ymax=self._ymax)
1248 
1249  # Create bounds before stats in order to have the
1250  # SetRangeUser() calls made before the fit
1251  #
1252  # stats is better to be called before frame, otherwise get
1253  # mess in the plot (that frame creation cleans up)
1254  if ratio:
1255  pad.cd(1)
1256  self._setStats(histos, self._statx, self._staty)
1257 
1258  # Create frame
1259  if isTGraph2D:
1260  frame = FrameTGraph2D(pad, bounds, histos, ratioOrig, ratioFactor)
1261  else:
1262  if ratio:
1263  ratioBounds = (bounds[0], self._ratioYmin, bounds[2], self._ratioYmax)
1264  frame = FrameRatio(pad, bounds, ratioBounds, ratioFactor, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption)
1265  else:
1266  frame = Frame(pad, bounds, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption)
1267 
1268  # Set log and grid
1269  frame.setLogx(self._xlog)
1270  frame.setLogy(self._ylog)
1271  frame.setGridx(self._xgrid)
1272  frame.setGridy(self._ygrid)
1273 
1274  # Construct draw option string
1275  opt = "sames" # s for statbox or something?
1276  ds = ""
1277  if self._drawStyle is not None:
1278  ds = self._drawStyle
1279  if self._drawCommand is not None:
1280  ds = self._drawCommand
1281  if len(ds) > 0:
1282  opt += " "+ds
1283 
1284  # Set properties of frame
1285  frame.setTitle(histos[0].GetTitle())
1286  if self._xtitle is not None:
1287  frame.setXTitle(self._xtitle)
1288  if self._xtitlesize is not None:
1289  frame.setXTitleSize(self._xtitlesize)
1290  if self._xtitleoffset is not None:
1291  frame.setXTitleOffset(self._xtitleoffset)
1292  if self._xlabelsize is not None:
1293  frame.setXLabelSize(self._xlabelsize)
1294  if self._ytitle is not None:
1295  frame.setYTitle(self._ytitle)
1296  if self._ytitlesize is not None:
1297  frame.setYTitleSize(self._ytitlesize)
1298  if self._ytitleoffset is not None:
1299  frame.setYTitleOffset(self._ytitleoffset)
1300  if self._ztitle is not None:
1301  frame.setZTitle(self._ztitle)
1302  if self._ztitleoffset is not None:
1303  frame.setZTitleOffset(self._ztitleoffset)
1304  if self._adjustMarginRight is not None:
1305  frame.adjustMarginRight(self._adjustMarginRight)
1306  elif "z" in opt:
1307  frame.adjustMarginLeft(0.03)
1308  frame.adjustMarginRight(0.08)
1309 
1310  # Draw histograms
1311  if ratio:
1312  frame._pad.cd()
1313 
1314  for h in histos:
1315  h.Draw(opt)
1316 
1317  # Draw ratios
1318  if ratio and len(histos) > 0:
1319  frame._padRatio.cd()
1320  self._ratios = self._calculateRatios(histos) # need to keep these in memory too ...
1321  if self._ratioUncertainty and self._ratios[0]._ratio is not None:
1322  self._ratios[0]._ratio.SetFillStyle(1001)
1323  self._ratios[0]._ratio.SetFillColor(ROOT.kGray)
1324  self._ratios[0]._ratio.SetLineColor(ROOT.kGray)
1325  self._ratios[0]._ratio.SetMarkerColor(ROOT.kGray)
1326  self._ratios[0]._ratio.SetMarkerSize(0)
1327  self._ratios[0].draw("E2")
1328  frame._padRatio.RedrawAxis("G") # redraw grid on top of the uncertainty of denominator
1329  for r in self._ratios[1:]:
1330  r.draw()
1331 
1332  frame.redrawAxis()
1333  self._frame = frame # keep the frame in memory for sure
def _findBounds
Definition: plotting.py:138
def _calculateRatios
Definition: plotting.py:1355
def plotting.Plot.drawRatioUncertainty (   self)
Return true if the ratio uncertainty should be drawn

Definition at line 1045 of file plotting.py.

1046  def drawRatioUncertainty(self):
1047  """Return true if the ratio uncertainty should be drawn"""
1048  return self._ratioUncertainty
def drawRatioUncertainty
Definition: plotting.py:1045
def plotting.Plot.getName (   self)

Definition at line 1039 of file plotting.py.

References FP420HitsObject._name, TrackerHitsObject._name, PGeometricDet::Item._name, LikelihoodSpecies._name, L1TMuon::PtAssignmentUnit._name, L1TMuon::PtRefinementUnit._name, LikelihoodPdfProduct._name, LikelihoodPdf._name, hcaldqm::Container._name, citk::IsolationConeDefinitionBase._name, hcaldqm::DQModule._name, Logger._name, DrellYanValidation._name, WValidation._name, HistoParams< T >._name, CutApplicatorBase._name, ElectronMVAEstimatorRun2Phys14NonTrig._name, PhotonMVAEstimatorRun2Spring15NonTrig._name, PhotonMVAEstimatorRun2Phys14NonTrig._name, GeometricDetExtra._name, ElectronMVAEstimatorRun2Spring15Trig._name, ElectronMVAEstimatorRun2Spring15NonTrig._name, HistoParams< TH2F >._name, HistoParams< TProfile2D >._name, plotting.Subtract._name, plotting.FakeDuplicate._name, plotting.AggregateBins._name, Vispa.Views.PropertyView.Property._name, SequenceTypes.SequencePlaceholder._name, plotting.AggregateHistos._name, plotting.ROC._name, and plotting.Plot._name.

Referenced by plotting.Plot.draw().

1040  def getName(self):
1041  if isinstance(self._name, list):
1042  return str(self._name[0])
1043  else:
1044  return str(self._name)
def plotting.Plot.getNumberOfHistograms (   self)
Return number of existing histograms.

Definition at line 1025 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, and alcazmumu_cfi.filter.

Referenced by plotting.Plot.isEmpty().

1026  def getNumberOfHistograms(self):
1027  """Return number of existing histograms."""
1028  return len(filter(lambda h: h is not None, self._histograms))
def getNumberOfHistograms
Definition: plotting.py:1025
def plotting.Plot.isEmpty (   self)
Return true if there are no histograms created for the plot

Definition at line 1029 of file plotting.py.

References plotting.Plot.getNumberOfHistograms().

1030  def isEmpty(self):
1031  """Return true if there are no histograms created for the plot"""
1032  return self.getNumberOfHistograms() == 0
def getNumberOfHistograms
Definition: plotting.py:1025
def plotting.Plot.isTGraph2D (   self)

Definition at line 1033 of file plotting.py.

References RunHistogramManager._histograms, and plotting.Plot._histograms.

Referenced by plotting.Plot.draw().

1034  def isTGraph2D(self):
1035  for h in self._histograms:
1036  if isinstance(h, ROOT.TGraph2D):
1037  return True
1038  return False
def plotting.Plot.setProperties (   self,
  kwargs 
)

Definition at line 1019 of file plotting.py.

1020  def setProperties(self, **kwargs):
1021  for name, value in kwargs.iteritems():
1022  if not hasattr(self, "_"+name):
1023  raise Exception("No attribute '%s'" % name)
1024  setattr(self, "_"+name, value)
def setProperties
Definition: plotting.py:1019

Member Data Documentation

plotting.Plot._forLegend
private

Definition at line 1347 of file plotting.py.

plotting.Plot._frame
private

Definition at line 1332 of file plotting.py.

plotting.Plot._gr
private

Definition at line 1448 of file plotting.py.

plotting.Plot._histograms
private

Definition at line 1017 of file plotting.py.

Referenced by plotting.Plot._normalize(), plotting.Plot.addToLegend(), plotting.Plot.create(), plotting.Plot.draw(), plotting.Plot.getNumberOfHistograms(), and plotting.Plot.isTGraph2D().

plotting.Plot._name
private

Definition at line 955 of file plotting.py.

Referenced by plotting.PlotGroup._drawSeparate(), plotting.PlotGroup._save(), plotting.Plot.create(), plotting.PlotGroup.draw(), plotting.Plot.getName(), plotting.PlotGroup.getName(), plotting.PlotterFolder.getName(), plotting.PlotterItem.getName(), plotting.PlotterFolder.getSelectionNameIterator(), validation.SimpleSample.name(), trackingPlots.Iteration.name(), plotting.PlotterItem.readDirs(), and plotting.PlotGroup.remove().

plotting.Plot._ratio
private

Definition at line 1410 of file plotting.py.

plotting.Plot._ratios
private

Definition at line 1319 of file plotting.py.

plotting.Plot._th1
private

Definition at line 1402 of file plotting.py.

plotting.Plot._tmp_histos
private

Definition at line 1241 of file plotting.py.

plotting.Plot._uncertainty
private

Definition at line 1403 of file plotting.py.

plotting.Plot._xerrshigh
private

Definition at line 1452 of file plotting.py.

plotting.Plot._xerrslow
private

Definition at line 1451 of file plotting.py.

plotting.Plot._xvalues
private

Definition at line 1450 of file plotting.py.

plotting.Plot._yerrshigh
private

Definition at line 1454 of file plotting.py.

plotting.Plot._yerrslow
private

Definition at line 1455 of file plotting.py.

plotting.Plot._yvalues
private

Definition at line 1453 of file plotting.py.