CMS 3D CMS Logo

List of all members | Public Member Functions | Private Member Functions | Private Attributes
plotting.Plot Class Reference

Public Member Functions

def __init__ (self, name, kwargs)
 
def addToLegend (self, legend, legendLabels, denomUncertainty)
 
def clone (self, kwargs)
 
def create (self, tdirNEvents, requireAllHistograms=False)
 
def draw (self, pad, ratio, ratioFactor, nrows)
 
def drawRatioUncertainty (self)
 
def getName (self)
 
def getNumberOfHistograms (self)
 
def isEmpty (self)
 
def isRatio (self, ratio)
 
def isTGraph2D (self)
 
def setProperties (self, kwargs)
 

Private Member Functions

def _createOne (self, name, index, tdir, nevents)
 
def _normalize (self)
 
def _setStats (self, histos, startingX, startingY)
 

Private Attributes

 _forLegend
 
 _frame
 
 _histograms
 
 _mainAdditional
 
 _name
 
 _ratioAdditional
 
 _ratios
 
 _tmp_histos
 

Detailed Description

Represents one plot, comparing one or more histograms.

Definition at line 1494 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)
outname      -- String for an output name of the plot (default None for the same as 'name')
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)
normalizeToNumberOfEvents -- Normalize histograms to number of events? If yes, the PlotFolder needs 'numberOfEventsHistogram' set to a histogram filled once per event (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)
removeEmptyBins -- Bool for removing empty bins, but only if histogram has bin labels (default False)
printBins    -- Bool for printing bin values, but only if histogram has bin labels (default False)
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)
legend       -- Bool to enable/disable legend (default True)
adjustMarginRight  -- Float for adjusting right margin (default None)
ratio        -- Possibility to disable ratio for this particular plot (default None)
ratioYmin    -- Float for y axis minimum in ratio pad (default: list of values)
ratioYmax    -- Float for y axis maximum in ratio pad (default: list of values)
ratioFit     -- Fit straight line in ratio? (default None)
ratioUncertainty -- Plot uncertainties on ratio? (default True)
ratioCoverageXrange -- Range of x axis values (xmin,xmax) to limit the automatic ratio y axis range calculation to (default None for disabled)
histogramModifier -- Function to be called in create() to modify the histograms (default None)

Definition at line 1496 of file plotting.py.

1496  def __init__(self, name, **kwargs):
1497  """ Constructor.
1498 
1499  Arguments:
1500  name -- String for name of the plot, or Efficiency object
1501 
1502  Keyword arguments:
1503  fallback -- Dictionary for specifying fallback (default None)
1504  outname -- String for an output name of the plot (default None for the same as 'name')
1505  title -- String for a title of the plot (default None)
1506  xtitle -- String for x axis title (default None)
1507  xtitlesize -- Float for x axis title size (default None)
1508  xtitleoffset -- Float for x axis title offset (default None)
1509  xlabelsize -- Float for x axis label size (default None)
1510  ytitle -- String for y axis title (default None)
1511  ytitlesize -- Float for y axis title size (default None)
1512  ytitleoffset -- Float for y axis title offset (default None)
1513  ztitle -- String for z axis title (default None)
1514  ztitleoffset -- Float for z axis title offset (default None)
1515  xmin -- Float for x axis minimum (default None, i.e. automatic)
1516  xmax -- Float for x axis maximum (default None, i.e. automatic)
1517  ymin -- Float for y axis minimum (default 0)
1518  ymax -- Float for y axis maximum (default None, i.e. automatic)
1519  xlog -- Bool for x axis log status (default False)
1520  ylog -- Bool for y axis log status (default False)
1521  xgrid -- Bool for x axis grid status (default True)
1522  ygrid -- Bool for y axis grid status (default True)
1523  stat -- Draw stat box? (default False)
1524  fit -- Do gaussian fit? (default False)
1525  statx -- Stat box x coordinate (default 0.65)
1526  staty -- Stat box y coordinate (default 0.8)
1527  statyadjust -- List of floats for stat box y coordinate adjustments (default None)
1528  normalizeToUnitArea -- Normalize histograms to unit area? (default False)
1529  normalizeToNumberOfEvents -- Normalize histograms to number of events? If yes, the PlotFolder needs 'numberOfEventsHistogram' set to a histogram filled once per event (default False)
1530  profileX -- Take histograms via ProfileX()? (default False)
1531  fitSlicesY -- Take histograms via FitSlicesY() (default False)
1532  rebinX -- rebin x axis (default None)
1533  scale -- Scale histograms by a number (default None)
1534  xbinlabels -- List of x axis bin labels (if given, default None)
1535  xbinlabelsize -- Size of x axis bin labels (default None)
1536  xbinlabeloption -- Option string for x axis bin labels (default None)
1537  removeEmptyBins -- Bool for removing empty bins, but only if histogram has bin labels (default False)
1538  printBins -- Bool for printing bin values, but only if histogram has bin labels (default False)
1539  drawStyle -- If "hist", draw as line instead of points (default None)
1540  drawCommand -- Deliver this to Draw() (default: None for same as drawStyle)
1541  lineWidth -- If drawStyle=="hist", the width of line (default 2)
1542  legendDx -- Float for moving TLegend in x direction for separate=True (default None)
1543  legendDy -- Float for moving TLegend in y direction for separate=True (default None)
1544  legendDw -- Float for changing TLegend width for separate=True (default None)
1545  legendDh -- Float for changing TLegend height for separate=True (default None)
1546  legend -- Bool to enable/disable legend (default True)
1547  adjustMarginRight -- Float for adjusting right margin (default None)
1548  ratio -- Possibility to disable ratio for this particular plot (default None)
1549  ratioYmin -- Float for y axis minimum in ratio pad (default: list of values)
1550  ratioYmax -- Float for y axis maximum in ratio pad (default: list of values)
1551  ratioFit -- Fit straight line in ratio? (default None)
1552  ratioUncertainty -- Plot uncertainties on ratio? (default True)
1553  ratioCoverageXrange -- Range of x axis values (xmin,xmax) to limit the automatic ratio y axis range calculation to (default None for disabled)
1554  histogramModifier -- Function to be called in create() to modify the histograms (default None)
1555  """
1556  self._name = name
1557 
1558  def _set(attr, default):
1559  setattr(self, "_"+attr, kwargs.get(attr, default))
1560 
1561  _set("fallback", None)
1562  _set("outname", None)
1563 
1564  _set("title", None)
1565  _set("xtitle", None)
1566  _set("xtitlesize", None)
1567  _set("xtitleoffset", None)
1568  _set("xlabelsize", None)
1569  _set("ytitle", None)
1570  _set("ytitlesize", None)
1571  _set("ytitleoffset", None)
1572  _set("ztitle", None)
1573  _set("ztitleoffset", None)
1574 
1575  _set("xmin", None)
1576  _set("xmax", None)
1577  _set("ymin", 0.)
1578  _set("ymax", None)
1579 
1580  _set("xlog", False)
1581  _set("ylog", False)
1582  _set("xgrid", True)
1583  _set("ygrid", True)
1584 
1585  _set("stat", False)
1586  _set("fit", False)
1587 
1588  _set("statx", 0.65)
1589  _set("staty", 0.8)
1590  _set("statyadjust", None)
1591 
1592  _set("normalizeToUnitArea", False)
1593  _set("normalizeToNumberOfEvents", False)
1594  _set("profileX", False)
1595  _set("fitSlicesY", False)
1596  _set("rebinX", None)
1597 
1598  _set("scale", None)
1599  _set("xbinlabels", None)
1600  _set("xbinlabelsize", None)
1601  _set("xbinlabeloption", None)
1602  _set("removeEmptyBins", False)
1603  _set("printBins", False)
1604 
1605  _set("drawStyle", "EP")
1606  _set("drawCommand", None)
1607  _set("lineWidth", 2)
1608 
1609  _set("legendDx", None)
1610  _set("legendDy", None)
1611  _set("legendDw", None)
1612  _set("legendDh", None)
1613  _set("legend", True)
1614 
1615  _set("adjustMarginRight", None)
1616 
1617  _set("ratio", None)
1618  _set("ratioYmin", [0, 0.2, 0.5, 0.7, 0.8, 0.9, 0.95])
1619  _set("ratioYmax", [1.05, 1.1, 1.2, 1.3, 1.5, 1.8, 2, 2.5, 3, 4, 5])
1620  _set("ratioFit", None)
1621  _set("ratioUncertainty", True)
1622  _set("ratioCoverageXrange", None)
1623 
1624  _set("histogramModifier", None)
1625 
1626  self._histograms = []
1627 
def __init__(self, name, kwargs)
Definition: plotting.py:1496

Member Function Documentation

def plotting.Plot._createOne (   self,
  name,
  index,
  tdir,
  nevents 
)
private
Create one histogram from a TDirectory.

Definition at line 1672 of file plotting.py.

References plotting._getOrCreateObject().

Referenced by plotting.Plot.create().

1672  def _createOne(self, name, index, tdir, nevents):
1673  """Create one histogram from a TDirectory."""
1674  if tdir == None:
1675  return None
1676 
1677  # If name is a list, pick the name by the index
1678  if isinstance(name, list):
1679  name = name[index]
1680 
1681  h = _getOrCreateObject(tdir, name)
1682  if h is not None and self._normalizeToNumberOfEvents and nevents is not None and nevents != 0:
1683  h.Scale(1.0/nevents)
1684  return h
1685 
def _getOrCreateObject(tdirectory, nameOrCreator)
Definition: plotting.py:53
def _createOne(self, name, index, tdir, nevents)
Definition: plotting.py:1672
def plotting.Plot._normalize (   self)
private
Normalise histograms to unit area

Definition at line 1777 of file plotting.py.

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

Referenced by plotting.Plot.draw().

1777  def _normalize(self):
1778  """Normalise histograms to unit area"""
1779 
1780  for h in self._histograms:
1781  if h is None:
1782  continue
1783  i = h.Integral()
1784  if i == 0:
1785  continue
1786  if h.GetSumw2().fN <= 0: # to suppress warning
1787  h.Sumw2()
1788  h.Scale(1.0/i)
1789 
def _normalize(self)
Definition: plotting.py:1777
def plotting.Plot._setStats (   self,
  histos,
  startingX,
  startingY 
)
private
Set stats box.

Definition at line 1736 of file plotting.py.

References DTSC._stat, and DTTrigGeom._stat.

1736  def _setStats(self, histos, startingX, startingY):
1737  """Set stats box."""
1738  if not self._stat:
1739  for h in histos:
1740  if h is not None and hasattr(h, "SetStats"):
1741  h.SetStats(0)
1742  return
1743 
1744  def _doStats(h, col, dy):
1745  if h is None:
1746  return
1747  h.SetStats(True)
1748 
1749  if self._fit and h.GetEntries() > 0.5:
1750  h.Fit("gaus", "Q")
1751  f = h.GetListOfFunctions().FindObject("gaus")
1752  if f == None:
1753  h.SetStats(0)
1754  return
1755  f.SetLineColor(col)
1756  f.SetLineWidth(1)
1757  h.Draw()
1758  ROOT.gPad.Update()
1759  st = h.GetListOfFunctions().FindObject("stats")
1760  if self._fit:
1761  st.SetOptFit(0o010)
1762  st.SetOptStat(1001)
1763  st.SetX1NDC(startingX)
1764  st.SetX2NDC(startingX+0.3)
1765  st.SetY1NDC(startingY+dy)
1766  st.SetY2NDC(startingY+dy+0.15)
1767  st.SetTextColor(col)
1768 
1769  dy = 0.0
1770  for i, h in enumerate(histos):
1771  if self._statyadjust is not None and i < len(self._statyadjust):
1772  dy += self._statyadjust[i]
1773 
1774  _doStats(h, _plotStylesColor[i], dy)
1775  dy -= 0.19
1776 
def _setStats(self, histos, startingX, startingY)
Definition: plotting.py:1736
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 2080 of file plotting.py.

References RunHistogramManager._histograms, plotting.Plot._histograms, and ComparisonHelper.zip().

2080  def addToLegend(self, legend, legendLabels, denomUncertainty):
2081  """Add histograms to a legend.
2082 
2083  Arguments:
2084  legend -- TLegend
2085  legendLabels -- List of strings for the legend labels
2086  """
2087  first = denomUncertainty
2088  for h, label in zip(self._histograms, legendLabels):
2089  if h is None:
2090  first = False
2091  continue
2092  if first:
2093  self._forLegend = h.Clone()
2094  self._forLegend.SetFillStyle(1001)
2095  self._forLegend.SetFillColor(ROOT.kGray)
2096  entry = legend.AddEntry(self._forLegend, label, "lpf")
2097  first = False
2098  else:
2099  legend.AddEntry(h, label, "LP")
2100 
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
def addToLegend(self, legend, legendLabels, denomUncertainty)
Definition: plotting.py:2080
def plotting.Plot.clone (   self,
  kwargs 
)
def plotting.Plot.create (   self,
  tdirNEvents,
  requireAllHistograms = False 
)
Create histograms from list of TDirectories

Definition at line 1686 of file plotting.py.

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

1686  def create(self, tdirNEvents, requireAllHistograms=False):
1687  """Create histograms from list of TDirectories"""
1688  self._histograms = [self._createOne(self._name, i, tdirNEvent[0], tdirNEvent[1]) for i, tdirNEvent in enumerate(tdirNEvents)]
1689 
1690  if self._fallback is not None:
1691  profileX = [self._profileX]*len(self._histograms)
1692  for i in xrange(0, len(self._histograms)):
1693  if self._histograms[i] is None:
1694  self._histograms[i] = self._createOne(self._fallback["name"], i, tdirNEvents[i][0], tdirNEvents[i][1])
1695  profileX[i] = self._fallback.get("profileX", self._profileX)
1696 
1697  if self._histogramModifier is not None:
1698  self._histograms = self._histogramModifier(self._histograms)
1699 
1700  if len(self._histograms) > len(_plotStylesColor):
1701  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)))
1702 
1703  # Modify histograms here in case self._name returns numbers
1704  # and self._histogramModifier creates the histograms from
1705  # these numbers
1706  def _modifyHisto(th1, profileX):
1707  if th1 is None:
1708  return None
1709 
1710  if profileX:
1711  th1 = th1.ProfileX()
1712 
1713  if self._fitSlicesY:
1714  ROOT.TH1.AddDirectory(True)
1715  th1.FitSlicesY()
1716  th1 = ROOT.gDirectory.Get(th1.GetName()+"_2")
1717  th1.SetDirectory(None)
1718  #th1.SetName(th1.GetName()+"_ref")
1719  ROOT.TH1.AddDirectory(False)
1720 
1721  if self._title is not None:
1722  th1.SetTitle(self._title)
1723 
1724  if self._scale is not None:
1725  th1.Scale(self._scale)
1726 
1727  return th1
1728 
1729  if self._fallback is not None:
1730  self._histograms = map(_modifyHisto, self._histograms, profileX)
1731  else:
1732  self._histograms = map(lambda h: _modifyHisto(h, self._profileX), self._histograms)
1733  if requireAllHistograms and None in self._histograms:
1734  self._histograms = [None]*len(self._histograms)
1735 
def create(self, tdirNEvents, requireAllHistograms=False)
Definition: plotting.py:1686
def _createOne(self, name, index, tdir, nevents)
Definition: plotting.py:1672
def plotting.Plot.draw (   self,
  pad,
  ratio,
  ratioFactor,
  nrows 
)
Draw the histograms using values for a given algorithm.

Definition at line 1790 of file plotting.py.

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

1790  def draw(self, pad, ratio, ratioFactor, nrows):
1791  """Draw the histograms using values for a given algorithm."""
1792 # if len(self._histograms) == 0:
1793 # print "No histograms for plot {name}".format(name=self._name)
1794 # return
1795 
1796  isTGraph2D = self.isTGraph2D()
1797  if isTGraph2D:
1798  # Ratios for the TGraph2Ds is not that interesting
1799  ratioOrig = ratio
1800  ratio = False
1801 
1802  if self._normalizeToUnitArea:
1803  self._normalize()
1804 
1805  if self._rebinX is not None:
1806  for h in self._histograms:
1807  h.Rebin(self._rebinX)
1808 
1809  def _styleMarker(h, msty, col):
1810  h.SetMarkerStyle(msty)
1811  h.SetMarkerColor(col)
1812  h.SetMarkerSize(0.7)
1813  h.SetLineColor(1)
1814  h.SetLineWidth(1)
1815 
1816  def _styleHist(h, msty, col):
1817  _styleMarker(h, msty, col)
1818  h.SetLineColor(col)
1819  h.SetLineWidth(self._lineWidth)
1820 
1821  # Use marker or hist style
1822  style = _styleMarker
1823  if "hist" in self._drawStyle.lower():
1824  style = _styleHist
1825  if len(self._histograms) > 0 and isinstance(self._histograms[0], ROOT.TGraph):
1826  if "l" in self._drawStyle.lower():
1827  style = _styleHist
1828 
1829  # Apply style to histograms, filter out Nones
1830  histos = []
1831  for i, h in enumerate(self._histograms):
1832  if h is None:
1833  continue
1834  style(h, _plotStylesMarker[i], _plotStylesColor[i])
1835  histos.append(h)
1836  if len(histos) == 0:
1837  if verbose:
1838  print "No histograms for plot {name}".format(name=self.getName())
1839  return
1840 
1841  # Extract x bin labels, make sure that only bins with same
1842  # label are compared with each other
1843  histosHaveBinLabels = len(histos[0].GetXaxis().GetBinLabel(1)) > 0
1844  xbinlabels = self._xbinlabels
1845  if xbinlabels is None:
1846  if histosHaveBinLabels:
1847  xbinlabels = [histos[0].GetXaxis().GetBinLabel(i) for i in xrange(1, histos[0].GetNbinsX()+1)]
1848  # Merge bin labels with difflib
1849  for h in histos[1:]:
1850  labels = [h.GetXaxis().GetBinLabel(i) for i in xrange(1, h.GetNbinsX()+1)]
1851  diff = difflib.unified_diff(xbinlabels, labels, n=max(len(xbinlabels), len(labels)))
1852  xbinlabels = []
1853  operation = []
1854  for item in diff: # skip the "header" lines
1855  if item[:2] == "@@":
1856  break
1857  for item in diff:
1858  operation.append(item[0])
1859  lab = item[1:]
1860  if lab in xbinlabels:
1861  # pick the last addition of the bin
1862  ind = xbinlabels.index(lab)
1863  if operation[ind] == "-" and operation[-1] == "+":
1864  xbinlabels.remove(lab)
1865  del operation[ind] # to keep xbinlabels and operation indices in sync
1866  elif operation[ind] == "+" and operation[-1] == "-":
1867  del operation[-1] # to keep xbinlabels and operation indices in sync
1868  continue
1869  else:
1870  raise Exception("This should never happen")
1871  xbinlabels.append(lab)
1872  # unified_diff returns empty diff if xbinlabels and labels are equal
1873  # so if xbinlabels is empty here, it can be just set to labels
1874  if len(xbinlabels) == 0:
1875  xbinlabels = labels
1876 
1877  histos_new = []
1878  for h in histos:
1879  h_new = h.Clone(h.GetName()+"_xbinlabels")
1880  h_new.SetBins(len(xbinlabels), h.GetBinLowEdge(1), h.GetBinLowEdge(1)+len(xbinlabels))
1881  for i, label in enumerate(xbinlabels):
1882  bin = h.GetXaxis().FindFixBin(label)
1883  if bin >= 0:
1884  h_new.SetBinContent(i+1, h.GetBinContent(bin))
1885  h_new.SetBinError(i+1, h.GetBinError(bin))
1886  else:
1887  h_new.SetBinContent(i+1, 0)
1888  h_new.SetBinError(i+1, 0)
1889  histos_new.append(h_new)
1890  self._tmp_histos = histos_new # need to keep these in memory too ...
1891  histos = histos_new
1892 
1893  # Remove empty bins, but only if histograms have bin labels
1894  if self._removeEmptyBins and histosHaveBinLabels:
1895  # at this point, all histograms have been "equalized" by their x binning and labels
1896  # therefore remove bins which are empty in all histograms
1897  binsToRemove = set()
1898  for b in xrange(1, histos[0].GetNbinsX()+1):
1899  binEmpty = True
1900  for h in histos:
1901  if h.GetBinContent(b) > 0:
1902  binEmpty = False
1903  break
1904  if binEmpty:
1905  binsToRemove.add(b)
1906 
1907  if len(binsToRemove) > 0:
1908  # filter xbinlabels
1909  xbinlab_new = []
1910  for i in xrange(len(xbinlabels)):
1911  if (i+1) not in binsToRemove:
1912  xbinlab_new.append(xbinlabels[i])
1913  xbinlabels = xbinlab_new
1914 
1915  # filter histogram bins
1916  histos_new = []
1917  for h in histos:
1918  values = []
1919  for b in xrange(1, h.GetNbinsX()+1):
1920  if b not in binsToRemove:
1921  values.append( (h.GetXaxis().GetBinLabel(b), h.GetBinContent(b), h.GetBinError(b)) )
1922 
1923  if len(values) > 0:
1924  h_new = h.Clone(h.GetName()+"_empty")
1925  h_new.SetBins(len(values), h.GetBinLowEdge(1), h.GetBinLowEdge(1)+len(values))
1926  for b, (l, v, e) in enumerate(values):
1927  h_new.GetXaxis().SetBinLabel(b+1, l)
1928  h_new.SetBinContent(b+1, v)
1929  h_new.SetBinError(b+1, e)
1930 
1931  histos_new.append(h_new)
1932 
1933  self._tmp_histos = histos_new # need to keep these in memory too ...
1934  histos = histos_new
1935  if len(histos) == 0:
1936  if verbose:
1937  print "No histograms with non-empty bins for plot {name}".format(name=self.getName())
1938  return
1939 
1940  if self._printBins and histosHaveBinLabels:
1941  print "####################"
1942  print self._name
1943  width = max([len(l) for l in xbinlabels])
1944  tmp = "%%-%ds " % width
1945  for b in xrange(1, histos[0].GetNbinsX()+1):
1946  s = tmp % xbinlabels[b-1]
1947  for h in histos:
1948  s += "%.3f " % h.GetBinContent(b)
1949  print s
1950  print
1951 
1952  bounds = _findBounds(histos, self._ylog,
1953  xmin=self._xmin, xmax=self._xmax,
1954  ymin=self._ymin, ymax=self._ymax)
1955 
1956  # need to keep these in memory
1959 
1960  if ratio:
1961  self._ratios = _calculateRatios(histos, self._ratioUncertainty) # need to keep these in memory too ...
1962  ratioHistos = filter(lambda h: h is not None, [r.getRatio() for r in self._ratios[1:]])
1963 
1964  if len(ratioHistos) > 0:
1965  ratioBoundsY = _findBoundsY(ratioHistos, ylog=False, ymin=self._ratioYmin, ymax=self._ratioYmax, coverage=0.68, coverageRange=self._ratioCoverageXrange)
1966  else:
1967  ratioBoundsY = (0.9, 1,1) # hardcoded default in absence of valid ratio calculations
1968 
1969  if self._ratioFit is not None:
1970  for i, rh in enumerate(ratioHistos):
1971  tf_line = ROOT.TF1("line%d"%i, "[0]+x*[1]")
1972  tf_line.SetRange(self._ratioFit["rangemin"], self._ratioFit["rangemax"])
1973  fitres = rh.Fit(tf_line, "RINSQ")
1974  tf_line.SetLineColor(rh.GetMarkerColor())
1975  tf_line.SetLineWidth(2)
1976  self._ratioAdditional.append(tf_line)
1977  box = PlotTextBox(xmin=self._ratioFit.get("boxXmin", 0.14), ymin=None, # None for automatix
1978  xmax=self._ratioFit.get("boxXmax", 0.35), ymax=self._ratioFit.get("boxYmax", 0.09),
1979  color=rh.GetMarkerColor(), font=43, size=11, lineheight=0.02)
1980  box.move(dx=(box.width()+0.01)*i)
1981  #box.addText("Const: %.4f" % fitres.Parameter(0))
1982  #box.addText("Slope: %.4f" % fitres.Parameter(1))
1983  box.addText("Const: %.4f#pm%.4f" % (fitres.Parameter(0), fitres.ParError(0)))
1984  box.addText("Slope: %.4f#pm%.4f" % (fitres.Parameter(1), fitres.ParError(1)))
1985  self._mainAdditional.append(box)
1986 
1987 
1988  # Create bounds before stats in order to have the
1989  # SetRangeUser() calls made before the fit
1990  #
1991  # stats is better to be called before frame, otherwise get
1992  # mess in the plot (that frame creation cleans up)
1993  if ratio:
1994  pad.cd(1)
1995  self._setStats(histos, self._statx, self._staty)
1996 
1997  # Create frame
1998  if isTGraph2D:
1999  frame = FrameTGraph2D(pad, bounds, histos, ratioOrig, ratioFactor)
2000  else:
2001  if ratio:
2002  ratioBounds = (bounds[0], ratioBoundsY[0], bounds[2], ratioBoundsY[1])
2003  frame = FrameRatio(pad, bounds, ratioBounds, ratioFactor, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption)
2004  else:
2005  frame = Frame(pad, bounds, nrows, xbinlabels, self._xbinlabelsize, self._xbinlabeloption)
2006 
2007  # Set log and grid
2008  frame.setLogx(self._xlog)
2009  frame.setLogy(self._ylog)
2010  frame.setGridx(self._xgrid)
2011  frame.setGridy(self._ygrid)
2012 
2013  # Construct draw option string
2014  opt = "sames" # s for statbox or something?
2015  ds = ""
2016  if self._drawStyle is not None:
2017  ds = self._drawStyle
2018  if self._drawCommand is not None:
2019  ds = self._drawCommand
2020  if len(ds) > 0:
2021  opt += " "+ds
2022 
2023  # Set properties of frame
2024  frame.setTitle(histos[0].GetTitle())
2025  if self._xtitle is not None:
2026  frame.setXTitle(self._xtitle)
2027  if self._xtitlesize is not None:
2028  frame.setXTitleSize(self._xtitlesize)
2029  if self._xtitleoffset is not None:
2030  frame.setXTitleOffset(self._xtitleoffset)
2031  if self._xlabelsize is not None:
2032  frame.setXLabelSize(self._xlabelsize)
2033  if self._ytitle is not None:
2034  frame.setYTitle(self._ytitle)
2035  if self._ytitlesize is not None:
2036  frame.setYTitleSize(self._ytitlesize)
2037  if self._ytitleoffset is not None:
2038  frame.setYTitleOffset(self._ytitleoffset)
2039  if self._ztitle is not None:
2040  frame.setZTitle(self._ztitle)
2041  if self._ztitleoffset is not None:
2042  frame.setZTitleOffset(self._ztitleoffset)
2043  if self._adjustMarginRight is not None:
2044  frame.adjustMarginRight(self._adjustMarginRight)
2045  elif "z" in opt:
2046  frame.adjustMarginLeft(0.03)
2047  frame.adjustMarginRight(0.08)
2048 
2049  # Draw histograms
2050  if ratio:
2051  frame._pad.cd()
2052 
2053  for h in histos:
2054  h.Draw(opt)
2055 
2056  for addl in self._mainAdditional:
2057  addl.Draw("same")
2058 
2059  # Draw ratios
2060  if ratio and len(histos) > 0:
2061  frame._padRatio.cd()
2062  firstRatio = self._ratios[0].getRatio()
2063  if self._ratioUncertainty and firstRatio is not None:
2064  firstRatio.SetFillStyle(1001)
2065  firstRatio.SetFillColor(ROOT.kGray)
2066  firstRatio.SetLineColor(ROOT.kGray)
2067  firstRatio.SetMarkerColor(ROOT.kGray)
2068  firstRatio.SetMarkerSize(0)
2069  self._ratios[0].draw("E2")
2070  frame._padRatio.RedrawAxis("G") # redraw grid on top of the uncertainty of denominator
2071  for r in self._ratios[1:]:
2072  r.draw()
2073 
2074  for addl in self._ratioAdditional:
2075  addl.Draw("same")
2076 
2077  frame.redrawAxis()
2078  self._frame = frame # keep the frame in memory for sure
2079 
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 _calculateRatios(histos, ratioUncertainty=False)
Definition: plotting.py:144
def _setStats(self, histos, startingX, startingY)
Definition: plotting.py:1736
def draw(self, pad, ratio, ratioFactor, nrows)
Definition: plotting.py:1790
Definition: style.py:1
def _normalize(self)
Definition: plotting.py:1777
def isTGraph2D(self)
Definition: plotting.py:1649
def getName(self)
Definition: plotting.py:1660
def plotting.Plot.drawRatioUncertainty (   self)
Return true if the ratio uncertainty should be drawn

Definition at line 1668 of file plotting.py.

1669  """Return true if the ratio uncertainty should be drawn"""
1670  return self._ratioUncertainty
1671 
def drawRatioUncertainty(self)
Definition: plotting.py:1668
def plotting.Plot.getName (   self)

Definition at line 1660 of file plotting.py.

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

Referenced by plotting.Plot.draw().

1660  def getName(self):
1661  if self._outname is not None:
1662  return self._outname
1663  if isinstance(self._name, list):
1664  return str(self._name[0])
1665  else:
1666  return str(self._name)
1667 
def getName(self)
Definition: plotting.py:1660
def plotting.Plot.getNumberOfHistograms (   self)
Return number of existing histograms.

Definition at line 1641 of file plotting.py.

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

Referenced by plotting.Plot.isEmpty().

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

Definition at line 1645 of file plotting.py.

References plotting.Plot.getNumberOfHistograms().

Referenced by plotting.Plot.clone().

1645  def isEmpty(self):
1646  """Return true if there are no histograms created for the plot"""
1647  return self.getNumberOfHistograms() == 0
1648 
def getNumberOfHistograms(self)
Definition: plotting.py:1641
def isEmpty(self)
Definition: plotting.py:1645
def plotting.Plot.isRatio (   self,
  ratio 
)

Definition at line 1655 of file plotting.py.

1655  def isRatio(self, ratio):
1656  if self._ratio is None:
1657  return ratio
1658  return ratio and self._ratio
1659 
def isRatio(self, ratio)
Definition: plotting.py:1655
def plotting.Plot.isTGraph2D (   self)

Definition at line 1649 of file plotting.py.

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

Referenced by plotting.Plot.draw().

1649  def isTGraph2D(self):
1650  for h in self._histograms:
1651  if isinstance(h, ROOT.TGraph2D):
1652  return True
1653  return False
1654 
def isTGraph2D(self)
Definition: plotting.py:1649
def plotting.Plot.setProperties (   self,
  kwargs 
)

Definition at line 1628 of file plotting.py.

1628  def setProperties(self, **kwargs):
1629  for name, value in kwargs.iteritems():
1630  if not hasattr(self, "_"+name):
1631  raise Exception("No attribute '%s'" % name)
1632  setattr(self, "_"+name, value)
1633 
def setProperties(self, kwargs)
Definition: plotting.py:1628

Member Data Documentation

plotting.Plot._forLegend
private

Definition at line 2093 of file plotting.py.

plotting.Plot._frame
private

Definition at line 2078 of file plotting.py.

plotting.Plot._histograms
private
plotting.Plot._mainAdditional
private

Definition at line 1957 of file plotting.py.

plotting.Plot._name
private
plotting.Plot._ratioAdditional
private

Definition at line 1958 of file plotting.py.

plotting.Plot._ratios
private

Definition at line 1961 of file plotting.py.

plotting.Plot._tmp_histos
private

Definition at line 1890 of file plotting.py.