Exemple #1
0
def create_X_Zpt_cuts(x):
    name_below = 'dilepton_pt_vect_{}_below'.format(x)
    name_over = 'dilepton_pt_vect_{}_over'.format(x)
    title_below = 'vect. sum of ee-pt below {}'.format(x)
    title_over = 'vect. sum of ee-pt over {}'.format(x)
    sel_below = 'dilepton_vect_sum_pt < {}'.format(x)
    sel_over = 'dilepton_vect_sum_pt > {}'.format(x)
    cut_below = Cut(name_below, title_below, sel_below)
    cut_over = Cut(name_over, title_over, sel_over)
    return [cut_below, cut_over]
Exemple #2
0
 def totalWeight(self, systematicVariation=None, cut=Cut()):
     ## Calculates the total weight expression of all systematics
     #  All systematics use the nominal value. If a systematicVariation is passed that one is used
     #  to replace the corresponding nominal systematics. The cut is used to check wether the systematics
     #  actually apply to the region of interest
     #  @param systematicVariation     SystematicVariation replacing the corresponding nominal
     #  @param cut                     cut defining the region of interest
     #  @return total weight expression
     weightExpression = Cut('')
     for variation in self.getNominalVariations(systematicVariation, cut):
         weightExpression *= variation.weightExpression
     return weightExpression
Exemple #3
0
def create2DHistogramFromTree(tree,
                              xVar,
                              yVar,
                              title='',
                              cut=None,
                              weight=None,
                              profile=False):
    ## Helper method to create a histogram from a TTree and apply a style
    #  @ param tree             TTree object used to create the histogram
    #  @ param xVar             the Variable object defining the xAxis and the draw command
    #  @ param yVar             the Variable object defining the xAxis and the draw command
    #  @ param title            the histogram title
    #  @ param cut              Cut object (optional)
    #  @ param weight           weight expression (optional)
    #  @ param profile          create a profile histogram instead of a 2D histogram
    #  @ return the generated histogram
    from ROOT import TH2D, TProfile
    myCut = cut
    if not myCut:
        myCut = Cut()
    myTitle = title
    if not myTitle:
        myTitle = '%s vs %s' % (yVar.title, xVar.title)
    hName = 'h%s_%s' % (myTitle.replace(' ', '_').replace('(', '').replace(
        ')', ''), uuid.uuid1())
    myCut += xVar.defaultCut + yVar.defaultCut
    if weight:
        if myCut:
            myCut = weight * myCut
        else:
            myCut = Cut(weight)
    opt = 'goff'
    if profile:
        h = xVar.createHistogram(title, True)
        opt += 'prof'
    else:
        h = TH2D(hName, title, xVar.binning.nBins, xVar.binning.low,
                 xVar.binning.up, yVar.binning.nBins, yVar.binning.low,
                 yVar.binning.up)
        xVar.binning.setupAxis(h.GetXaxis())
        xVar.applyToAxis(h.GetXaxis())
        yVar.binning.setupAxis(h.GetYaxis())
        yVar.applyToAxis(h.GetYaxis())
    logger.debug(
        'create2DHistogramFromTree(): calling TTree::Draw( "%s : %s", "%s" )' %
        (yVar.command, xVar.command, myCut.cut))
    tree.Draw('%s : %s >> %s' % (yVar.command, xVar.command, hName), myCut.cut,
              opt)
    logger.debug(
        'create2DHistogramFromTree(): created histogram with %d entries and an integral of %g'
        % (h.GetEntries(), h.Integral()))
    return h
Exemple #4
0
 def createHistogramFromTree(self,
                             tree,
                             title='',
                             cut=None,
                             weight=None,
                             drawOption='',
                             style=None):
     ## Create a histogram from a TTree
     #  Returns the sum of histogram of all contained variables
     #  @ param tree             TTree object used to create the histogram
     #  @ param title            the histogram title
     #  @ param cut              Cut object (optional)
     #  @ param weight           weight expression (optional)
     #  @ param drawOption       draw option used
     #  @ return the generated histogram
     cut = cut if cut else Cut()
     cut += self.defaultCut
     hist = self.createHistogram(title, 'prof' in drawOption)
     if not hist.GetSumw2N():
         hist.Sumw2()
     for variable in self.variables:
         h = variable.createHistogramFromTree(tree, title, cut, weight,
                                              drawOption)
         if h:
             hist.Add(h)
     if hist and style:
         style.apply(hist)
     return hist
Exemple #5
0
def resolutionGraph( tree, xVar, yVar, title, measure, cut='', weightExpression='' ):
    ## Create and fill a resolution graph for this dataset, i.e. resolution of y vs. x
    #  @ param tree              TTree object used to create the histogram
    #  @ param xVar              Variable object defining the xAxis and the draw command
    #  @ param yVar              Variable object defining the xAxis and the draw command
    #  @ param title             histogram title
    #  @param measure            Measure object to evaluate the resolution
    #  @ param cut               Cut object (optional)
    #  @ param weightExpression  weight expression (optional)
    #  @ return the generated histogram
    bins = xVar.binning.bins
    title = '%s vs %s' % (yVar.title, xVar.title) if not title else title
    name = 'h%s_%s' % ( title.replace(' ', '_').replace('(', '').replace(')',''), uuid.uuid1() )
    from ROOT import TGraphAsymmErrors
    graph = TGraphAsymmErrors( xVar.binning.nBins )
    graph.SetNameTitle( name, '%s;%s;%s' % (title, xVar.axisLabel, measure.getDecoratedLabel( yVar ) ) )
    # create a histogram of y for each bin in x and evaluate measure
    for iBin in xrange( xVar.binning.nBins ):
        low = bins[iBin]
        up = bins[iBin+1]
        xMean = low + 0.5 * (up - low)
        xErr = xMean - low
        myCut = (Cut( '%s >= %s && %s < %s' % (xVar.command, low, xVar.command, up) ) + cut) * weightExpression
        values, weights = getValuesFromTree( tree, yVar.command, myCut.cut )
        yMean, yErrLow, yErrUp = measure.calculateFromValues( values, weights )
        graph.SetPoint( iBin, xMean, yMean )
        graph.SetPointError( iBin, xErr, xErr, yErrLow, yErrUp )        
    return graph
Exemple #6
0
 def parse( self, fileName ):
     ## Read all known elements from an input XML
     #  @param fileName       input XML
     self.logger.debug( 'parse(): reading "%s"' % fileName )
     tree = ElementTree.parse( self, fileName )
     
     # read the CrossSectionDB elements
     for element in tree.findall('CrossSectionDB'):
         self.crossSectionDB = CrossSectionDB.fromXML( element )
     
     # read the HistogramStore elements
     for element in tree.findall('HistogramStore'):
         self.histogramStore = HistogramStore.fromXML( element )
     
     # read all Cut elements
     for element in tree.findall('Cut'):
         self.cuts.append( Cut.fromXML( element ) )
         
     # read all Dataset elements
     for element in tree.findall('Dataset'):
         self.datasets.append( Dataset.fromXML( element ) )
         
     # read all PhysicsProcess elements
     for element in tree.findall('PhysicsProcess'):
         self.physicsProcesses.append( PhysicsProcess.fromXML( element ) )
     
     # read all Systematics elements
     for element in tree.findall('Systematics'):
         self.systematicsSet.add( Systematics.fromXML( element ) )
Exemple #7
0
 def fromXML( cls, element ):
     ## Constructor from an XML element
     #  <Variable name="VariableName" command="DrawCommand" title="AxisTitle" unit="Unit" nBins="nBins" low="min" up="max">
     #    <Cut>DefaultCut</Cut>
     #  </Variable>
     #  @param element    the XML element
     #  @return the Variable object
     attributes = element.attrib
     name = attributes[ 'name' ]
     variable = cls( name )
     if attributes.has_key( 'command' ):
         variable.treeName = attributes['command']
     if attributes.has_key( 'title' ):
         variable.title = attributes['title']
     if attributes.has_key( 'unit' ):
         variable.unit = attributes['unit']
     if attributes.has_key( 'nBins' ):
         variable.binning.nBins = int(attributes['nBins'])
     if attributes.has_key( 'low' ):
         variable.binning.low = float(attributes['low'])
     if attributes.has_key( 'up' ):
         variable.binning.up = float(attributes['up'])
     for cutElement in element.findall( 'Cut' ):
         variable.defaultCut += Cut.fromXML( cutElement )
     return variable
Exemple #8
0
def testHistogramStore():
    from plotting.Cut import Cut
    from plotting.Dataset import Dataset
    from plotting.Variable import Binning, Variable
    from plotting.Systematics import nominalSystematics as s
    # create some required objects
    v = Variable('tau_pt',
                 title='p_{T}^{#tau}',
                 unit='GeV',
                 binning=Binning(20, -3, 3))
    histogramTitle = 'TestHistogram'
    h = v.createHistogram('TestHistogram')
    h.FillRandom('gaus', 1000)
    c = Cut('signal_region', cut='|tau_eta| < 2.5')
    d = Dataset('test_dataset')
    # create a histogram store
    storeFileName = 'testHistogramStore.root'
    store = HistogramStore(storeFileName)
    # store objects by hash value instead of names
    store.useHash = True
    # store a histogram
    store.putHistogram(d, s, v, c, h)
    # close the store
    store.close()
    # retrieve a histogram (automatically opens the file again)
    h = store.getHistogram(d, s, v, c)
    # clean up
    store.close()
    os.remove(storeFileName)
    # check if everything worked and the histograms are actually the same
    return h.GetTitle() == histogramTitle
Exemple #9
0
 def totalScaleFactor(self, systematicVariation=None, cut=Cut()):
     ## Calculates the total scale factor of all systematics
     #  All systematics use the nominal value. If a systematicVariation is passed that one is used
     #  to replace the corresponding nominal systematics. The cut is used to check wether the systematics
     #  actually apply to the region of interest
     #  @param systematicVariation     SystematicVariation replacing the corresponding nominal
     #  @param cut                     cut defining the region of interest
     #  @return total scale factor
     scaleFactor = 1.
     for variation in self.getNominalVariations(systematicVariation, cut):
         scaleFactor *= variation.scale
     return scaleFactor
Exemple #10
0
 def addCut(self,
            title='',
            cut=Cut(),
            weight='',
            drawOption='',
            drawLegend=True,
            style=None,
            tree=None):
     ## Adds a new histogram to the list of objects to be drawn
     #  Can be defined via a Cut, a TTree or both
     self.cutDefinitions.append(
         CutDefinition(title, cut, weight, drawOption, drawLegend, style,
                       tree))
Exemple #11
0
 def __init__(self,
              name,
              title=None,
              unit='',
              binning=Binning(),
              defaultCut=Cut(),
              variables=[]):
     ## Default constructor
     #  @param name        name
     #  @param title       title used for example in axis lables (default uses name)
     #  @param unit        name of the unit
     #  @param binning     binning object
     #  @param defaultCut  cut that should be applied whenever this variable is plotted
     Variable.__init__(self, name, None, title, unit, binning, defaultCut)
     self.variables = variables
Exemple #12
0
    def getNominalVariations(self, systematicVariation=None, cut=Cut()):
        ## Collect all nominal systematic variations. If a systematicVariation is passed that one is used
        #  to replace the corresponding nominal systematics. The cut is used to check wether the systematics
        #  actually apply to the region of interest
        #  @param systematicVariation     SystematicVariation replacing the corresponding nominal
        #  @param cut                     cut defining the region of interest
        #  @return set of relevant variations
        variationsSet = set()
        for systematics in self:
            if systematics.appliesToRegion(cut):
                variationsSet.add(systematics.nominal)
        # replace the corresponding nominal variation with the concrete variation
        if systematicVariation:
            systematics = systematicVariation.systematics
            if systematics and systematics.appliesToRegion(cut):
                variationsSet.discard(systematics.nominal)
                variationsSet.add(systematicVariation)

        return variationsSet
Exemple #13
0
 def createHistogramFromTree( self, tree, title='', cut=None, weight=None, drawOption='', style=None ):
     ## Create a histogram of this variable from a TTree
     #  @ param tree             TTree object used to create the histogram
     #  @ param title            the histogram title
     #  @ param cut              Cut object (optional)
     #  @ param weight           weight expression (optional)
     #  @ param drawOption       draw option used
     #  @ return the generated histogram
     cut = cut if cut else Cut()
     cut += self.defaultCut
     if weight:
         cut *= weight
     opt = drawOption + 'goff'
     # create an empty histogram
     h = self.createHistogram( title, 'prof' in drawOption )
     # no range set, need to determine from values
     if self.binning.low is None or self.binning.up is None:
         self.logger.debug( 'createHistogramFromTree(): missing range from binning - determining range automatically.' )
         tree.Draw( '%s >> temp(%d)' % ( self.command, 1000 ), cut.cut, opt )
         hTemp = tree.GetHistogram()
         if hTemp:
             low = max(hTemp.GetXaxis().GetXmin(), hTemp.GetMean()-3*hTemp.GetStdDev()) if self.binning.low is None else self.binning.low
             up = min(hTemp.GetXaxis().GetXmax(), hTemp.GetMean()+3*hTemp.GetStdDev()) if self.binning.up is None else self.binning.up
             # reset axis with the new limits
             h.GetXaxis().Set( self.binning.nBins, low, up )
         else:
             self.logger.error( 'createHistogramFromTree(): no histogram created from TTree::Draw( "%s", "%s" )' % (self.command, cut.cut) )
     self.logger.debug( 'createHistogramFromTree(): calling TTree::Draw( "%s", "%s", "%s" )' % (self.command, cut.cut, drawOption) )
     tree.Draw( '%s >> %s' % (self.command, h.GetName()), cut.cut, opt )
     if not h.GetSumw2N():
         h.Sumw2()
     if h:
         self.logger.debug( 'createHistogramFromTree(): created histogram with %d entries and an integral of %g' % (h.GetEntries(), h.Integral()) )
     else:
         self.logger.error( 'createHistogramFromTree(): no histogram created from TTree::Draw( "%s", "%s" )' % (self.command, cut.cut) )
     if h and style:
         style.apply( h )
     return h
Exemple #14
0
 def __init__(self,
              title='',
              cut=Cut(),
              weight='',
              drawOption='',
              drawLegend=True,
              style=None,
              tree=None):
     ## Default constructor
     #  @param title         title used to define the legend entry
     #  @param cut           Cut object defining the cut
     #  @param weight        the weight expression
     #  @param drawOption    draw option specific to this cut
     #  @param drawLegend    should this histogram be added to the legend?
     #  @param style         the style object associated with this cut
     #  @param tree          the tree associated with this plot
     self.title = title if title else cut.GetName()
     self.cut = cut
     self.weight = weight
     self.drawOption = drawOption
     self.drawLegend = drawLegend
     self.tree = tree
     self.style = style
Exemple #15
0
def testSystematicsCalculator():
    from plotting.AtlasStyle import Style
    from plotting.Cut import Cut
    from plotting.Dataset import Dataset
    from plotting.DataMcRatioPlot import DataMcRatioPlot
    from plotting.DoublePlot import DoublePlot
    from plotting.HistogramStore import HistogramStore
    from plotting.Systematics import Systematics
    from plotting.Tools import divideGraphs
    from plotting.Variable import Binning, Variable
    from ROOT import TF1, kViolet, kCyan, kBlack, kDashed

    cut = Cut()
    luminosity = 36.2

    f_zpeak = TF1('z-peak', 'TMath::Voigt((1./[0])*x-91.2, [1], 2.5)')
    f_zpeak.SetParNames('TES', 'TER')
    f_zpeak.SetParameter('TES', 1.0)
    f_zpeak.SetParameter('TER', 10.)

    f_cont = TF1('continuum', '[0]*1./x')
    f_cont.SetParNames('TES')
    f_cont.SetParameter('TES', 1.0)
    f_zpeak.SetParameter('TER', 10.)

    var = Variable('dimuon_mass',
                   title='#it{m_{#tau#tau}}',
                   unit='GeV',
                   binning=Binning(20, 50., 150.))

    store = HistogramStore('testHistogramStore.root')
    z_jets = Dataset('z_jets',
                     '#it{Z}+jets',
                     style=Style(kCyan),
                     crossSection=0.0004)
    continuum = Dataset('continuum',
                        'Others',
                        style=Style(kViolet),
                        crossSection=0.002)
    sysLumi = Systematics.scaleSystematics('sysLumi', 'Lumi', 1.031, 0.968,
                                           1.0)
    sysTES = Systematics.treeSystematics('sysTES', 'TES', 'tes_up', 'tes_down')
    sysTER = Systematics.treeSystematics('sysTER', 'TER', 'ter_up', 'ter_down')

    mcStat = 500000
    datasets = [continuum, z_jets]
    functions = {z_jets: f_zpeak, continuum: f_cont}
    for dataset in datasets:
        dataset.addSystematics(sysTES)
        dataset.addSystematics(sysLumi)
        h = var.createHistogram(dataset.title)
        f = functions[dataset]
        h.FillRandom(f.GetName(), mcStat)
        store.putHistogram(dataset, dataset.nominalSystematics, var, cut, h)
        h.Reset()
        f.SetParameter('TES', 1.02)
        h.FillRandom(f.GetName(), mcStat)
        store.putHistogram(dataset, sysTES.up, var, cut, h)
        h.Reset()
        f.SetParameter('TES', 0.98)
        h.FillRandom(f.GetName(), mcStat)
        store.putHistogram(dataset, sysTES.down, var, cut, h)
        f.SetParameter('TES', 1.0)

    z_jets.addSystematics(sysTER)
    h.Reset()
    f_zpeak.SetParameter('TER', 13)
    h.FillRandom(f_zpeak.GetName(), mcStat)
    store.putHistogram(z_jets, sysTER.up, var, cut, h)
    h.Reset()
    f.SetParameter('TER', 7)
    h.FillRandom(f_zpeak.GetName(), mcStat)
    store.putHistogram(z_jets, sysTER.down, var, cut, h)

    p = DataMcRatioPlot('testPlot', var)
    for dataset in datasets:
        dataset.histogramStore = store
        p.addHistogram(
            dataset.getHistogram(var, cut=cut, luminosity=luminosity))
    systGraph = calculateSystematicsGraph(datasets, var, luminosity=luminosity)
    systGraph.SetTitle('Combined Systematics')
    p.defaultCombinedErrorStyle.apply(systGraph)
    p.setMCSystematicsGraph(systGraph)
    p.draw()
    p.saveAs('test.pdf')

    p1 = DoublePlot('testPlot1',
                    var,
                    yVariableDown=Variable('Ratio',
                                           binning=Binning(low=0.8, up=1.2)))
    p1.plotDown.yVariable.binning.nDivisions = 205
    nominalHist = None
    systematicsSet = SystematicsSet()
    for dataset in datasets:
        systematicsSet |= dataset.combinedSystematicsSet
        h = dataset.getHistogram(var, cut=cut, luminosity=luminosity)
        if nominalHist:
            nominalHist.Add(h)
        else:
            nominalHist = h
    nominalHist.SetLineColor(kBlack)
    nominalHist.SetTitle('Nominal')
    p1.plotUp.addGraph(systGraph, '2')
    p1.plotUp.addHistogram(nominalHist)
    rSystGraph = systGraph.Clone()
    rSystGraph.SetTitle()
    p1.plotDown.addGraph(rSystGraph, '2')
    divideGraphs(rSystGraph, nominalHist)
    lineColor = 1
    for systematics in systematicsSet:
        lineColor += 1
        upHist = None
        downHist = None
        # collect all up and down histograms for all datasets
        for dataset in datasets:
            upH = dataset.getHistogram(var,
                                       cut=cut,
                                       luminosity=luminosity,
                                       systematicVariation=systematics.up)
            downH = dataset.getHistogram(var,
                                         cut=cut,
                                         luminosity=luminosity,
                                         systematicVariation=systematics.down)
            downH.SetLineColor(lineColor)
            downH.SetLineStyle(kDashed)
            if upH:
                if upHist:
                    upHist.Add(upH)
                else:
                    upHist = upH
            if downH:
                if downHist:
                    downHist.Add(downH)
                else:
                    downHist = downH
        upHist.SetLineColor(lineColor)
        upHist.SetTitle(systematics.title)
        downHist.SetLineColor(lineColor)
        downHist.SetLineStyle(kDashed)
        downHist.SetTitle('')
        rUpHist = upHist.Clone()
        rUpHist.Divide(nominalHist)
        rUpHist.SetTitle('')
        rDownHist = downHist.Clone()
        rDownHist.Divide(nominalHist)
        rDownHist.SetTitle('')
        p1.plotUp.addHistogram(upHist)
        p1.plotUp.addHistogram(downHist)
        p1.plotDown.addHistogram(rUpHist)
        p1.plotDown.addHistogram(rDownHist)
    p1.draw()

    raw_input()
Exemple #16
0

if __name__ == '__main__':
    from analysis.hadhad.cuts import cutLVeto, cutOS, cutDR, cutMET, cutMETPhiCentrality
    from plotting.Cut import Cut
    from plotting.Dataset import Dataset
    import logging

    basePath = '/afs/cern.ch/user/c/cgrefe/eos_cgrefe/xTau-NTuples/hhsm_25.v8/'
    weightExpression = 'weight_total'
    #logging.root.setLevel( logging.DEBUG )

    # define some cuts
    cutTau0Selection = Cut(
        'Tau0Selection',
        cut=
        'ditau_tau0_pt > 40 && (ditau_tau0_n_tracks==1 || ditau_tau0_n_tracks==3) && abs(ditau_tau0_q)==1 && ditau_tau0_jet_bdt_medium == 1'
    )
    cutTau1Selection = Cut(
        'Tau1Selection',
        cut=
        'ditau_tau1_pt > 30 && (ditau_tau1_n_tracks==1 || ditau_tau1_n_tracks==3) && abs(ditau_tau1_q)==1 && ditau_tau1_jet_bdt_medium == 1'
    )
    cutTauSelection = (cutTau0Selection + cutTau1Selection).setNameTitle(
        'TauSelection', 'TauSelection')

    # we have some cuts that are not simply an addition to the previous cut so we need to add all cuts by hand instead for full control
    cut1 = (
        cutTauSelection +
        'n_taus_medium==2 && ditau_tau0_jet_bdt_tight+ditau_tau1_jet_bdt_tight>0'
    ).setNameTitle('2 medium, >0 tight', '2 medium, >0 tight')
Exemple #17
0
from plotting.Cut import Cut

#======#
# Cuts #
#======#
cut_none		= Cut( 'NoCut',			'No Cut',				'1' )
cut_even		= Cut( 'Even',			'Even Events',				'event_number % 2 == 0'	)
cut_odd			= Cut( 'Odd',			'Odd Events',				'event_number % 2 == 1'	)

#----------------
# lepton criteria
#----------------
cut_lep_id_loose	= Cut( 'lepId_loose',		'Lepton ID loose',			'lep_0_id_loose && lep_1_id_loose' )
cut_lep_id_lm_mix	= Cut( 'lepId_lm_mix',		'Lepton ID 1 med & 1 loose',		'(lep_0_id_loose && lep_1_id_medium) || (lep_0_id_medium && lep_1_id_loose)' )
cut_lep_id_medium	= Cut( 'lepId_medium',		'Lepton ID medium',			'lep_0_id_medium && lep_1_id_medium' )
cut_lep_id_tight	= Cut( 'lepId_tight',		'Lepton ID tight',			'lep_0_id_tight && lep_1_id_tight' )

# Z-mass: 91.1876(21) GeV [pdg2015]
# Z-width: 2.4952(23) GeV [pdg2015]
cut_Z_window_4		= Cut( 'ZMassWindow_4',		'm_{Z} #pm ~4 GeV',			'dilepton_vis_mass > 87.188 && dilepton_vis_mass < 95.188' )
cut_Z_window_5		= Cut( 'ZMassWindow_5',		'm_{Z} #pm ~5 GeV',			'dilepton_vis_mass > 86.188 && dilepton_vis_mass < 96.188' )
cut_Z_window_8		= Cut( 'ZMassWindow_8',		'm_{Z} #pm ~8 GeV',			'dilepton_vis_mass > 83.188 && dilepton_vis_mass < 99.188' )
cut_Z_window_10		= Cut( 'ZMassWindow_10',	'm_{Z} #pm ~10 GeV',			'dilepton_vis_mass > 81.188 && dilepton_vis_mass < 101.188' )
cut_Z_window_nominal	= cut_Z_window_5
cut_Z_window_down	= cut_Z_window_4
cut_Z_window_up		= cut_Z_window_8

cut_lep_OS		= Cut( 'lepton_OS',		'OS for leptons',			'lep_0_q * lep_1_q < 0'	)
cut_di_ele		= Cut( 'dielectron',		'dielectron event',			'lep_0 == 2 && lep_1 == 2' )
cut_no_muon		= Cut( 'no_muon', 		'no muon in the event', 		'n_muons == 0')
Exemple #18
0
def createHistogramFromTree(tree,
                            xVar,
                            title='',
                            cut=None,
                            weight=None,
                            drawOption='',
                            style=None):
    ## Helper method to create a histogram from a TTree and apply a style
    #  @ param tree             TTree object used to create the histogram
    #  @ param xVar             the Variable object defining the xAxis and the draw command
    #  @ param title            the histogram title
    #  @ param cut              Cut object (optional)
    #  @ param weight           weight expression (optional)
    #  @ param drawOption       draw option used
    #  @ param style            Style object which is used
    #  @ return the generated histogram
    myCut = cut
    if not myCut:
        myCut = Cut()
    if xVar.defaultCut:
        myCut = myCut + xVar.defaultCut
    if weight:
        if myCut:
            myCut = weight * myCut
        else:
            myCut = Cut(weight)
    opt = drawOption + 'goff'
    # create an empty histogram
    h = xVar.createHistogram(title, 'prof' in drawOption)
    # no range set, need to determine from values
    if xVar.binning.low is None or xVar.binning.up is None:
        logger.debug(
            'createHistogramFromTree(): missing range from binning - determining range automatically.'
        )
        tree.Draw('%s >> temp(%d)' % (xVar.command, 1000), myCut.cut, opt)
        hTemp = tree.GetHistogram()
        if hTemp:
            low = max(hTemp.GetXaxis().GetXmin(),
                      hTemp.GetMean() - 3 * hTemp.GetStdDev()
                      ) if xVar.binning.low is None else xVar.binning.low
            up = min(hTemp.GetXaxis().GetXmax(),
                     hTemp.GetMean() + 3 * hTemp.GetStdDev()
                     ) if xVar.binning.up is None else xVar.binning.up
            # reset axis with the new limits
            h.GetXaxis().Set(xVar.binning.nBins, low, up)
        else:
            logger.error(
                'createHistogramFromTree(): no histogram created from TTree::Draw( "%s", "%s" )'
                % (xVar.command, myCut.cut))
    logger.debug(
        'createHistogramFromTree(): calling TTree::Draw( "%s", "%s", "%s" )' %
        (xVar.command, myCut.cut, drawOption))
    tree.Draw('%s >> %s' % (xVar.command, h.GetName()), myCut.cut, opt)
    if not h.GetSumw2N():
        h.Sumw2()
    if style:
        style.apply(h)
    if h:
        logger.debug(
            'createHistogramFromTree(): created histogram with %d entries and an integral of %g'
            % (h.GetEntries(), h.Integral()))
    else:
        logger.error(
            'createHistogramFromTree(): no histogram created from TTree::Draw( "%s", "%s" )'
            % (xVar.command, myCut.cut))
    return h
Exemple #19
0
    def datasetsFromXML(cls, element):
        ## Constructor from an XML element
        #  <Datasets basepath="" treeName="" isData="" isSignal="" weightExpression="">
        #    <Style color="5"/>
        #    <DSIDS> 1234, 4321, 3412 </DSIDS>
        #    <AddCuts>
        #      <Cut> Cut1 </Cut>
        #      <Cut> Cut2 </Cut>
        #    </AddCuts>
        #    <IgnoreCuts>
        #      <Cut> Cut3 </Cut>
        #      <Cut> Cut4 </Cut>
        #    </IgnoreCuts>
        #  </Dataset>
        #  @param element    the XML element
        #  @return a list of Dataset objects
        attributes = element.attrib

        datasets = []
        treeName = None
        isData = False
        isSignal = False
        isBSMSignal = False
        weighExpression = None
        if attributes.has_key('basePath'):
            basePath = attributes['basePath']
        else:
            cls.logger.warning(
                'datasetsFromXML(): Datasets XML element is missing "basePath" attribute. No datasets created.'
            )
            return datasets
        if attributes.has_key('treeName'):
            treeName = attributes['treeName']
        if attributes.has_key('isData'):
            isData = string2bool(attributes['isData'])
        if attributes.has_key('isSignal'):
            isSignal = string2bool(attributes['isSignal'])
        if attributes.has_key('isBSMSignal'):
            isBSMSignal = string2bool(attributes['isBSMSignal'])
        if attributes.has_key('weightExpression'):
            weightExpression = attributes['weightExpression']
        style = Style.fromXML(element.find('Style')) if element.find(
            'Style') is not None else None
        addCuts = []
        ignoreCuts = []
        if element.find('AddCuts'):
            for cutElement in element.find('AddCuts').findall('Cut'):
                addCuts.append(Cut.fromXML(cutElement))
        if element.find('IgnoreCuts'):
            for cutElement in element.find('IgnoreCuts').findall('Cut'):
                ignoreCuts.append(Cut.fromXML(cutElement))
        if element.find('DSIDS') is not None:
            dsids = element.text.split(',')
            for dsid in dsids:
                dataset = cls.datasetFromDSID(basePath, int(dsid),
                                              dsid.strip(), treeName, style,
                                              weightExpression)
                dataset.isData = isData
                dataset.isSignal = isSignal
                dataset.isBSMSignal = isBSMSignal
                dataset.addCuts += addCuts
                dataset.ignoreCuts += ignoreCuts
        else:
            cls.logger.warning(
                'datasetsFromXML(): Datasets XML element is missing "DSIDS" element. No datasets created.'
            )
            return datasets
        return datasets
Exemple #20
0
    # create a plot using the TreePlot class
    treePlotTest = TreePlot('TreePlot Test',
                            sizeVar,
                            Variable('Entries'),
                            tree=t)
    treePlotTest.addCut('No Cut')
    treePlotTest.addCut('Energy > 15 MeV', 'energy > 15')
    treePlotTest.draw()

    # create a plot using the BasicPlot class
    testBasicPlot = BasicPlot('BasicPlot test', energyVar, Variable('Entries'))
    testBasicPlot.addHistogram(
        createHistogramFromTree(t,
                                energyVar,
                                'Size > 1',
                                Cut('size > 1'),
                                style=redLine), 'E0')
    testBasicPlot.addHistogram(
        createHistogramFromTree(t,
                                energyVar,
                                'Size > 3',
                                Cut('size > 3'),
                                style=blueLine), 'E0')
    testBasicPlot.addHistogram(
        createHistogramFromTree(t,
                                energyVar,
                                'Size > 6',
                                Cut('size > 6'),
                                style=greenLine), 'E0')
    testBasicPlot.logY = True
    testBasicPlot.draw()
Exemple #21
0
 def __init__( self, name, command=None, title=None, unit='', binning=Binning(), defaultCut=Cut() ):
     ## Default contructor
     #  @param name        the name, also used for draw command and title if not specified
     #  @param command     command used in TTree::Draw (default uses name)
     #  @param title       title used for example in axis lables (default uses name)
     #  @param unit        name of the unit
     #  @param binning     binning object
     #  @param defaultCut  cut that should be applied whenever this variable is plotted
     self.name = name
     self.command = command if command is not None else name
     self.title = title if title is not None else name
     self.unit = unit
     self.binning = binning
     self.defaultCut = defaultCut
     self.matchedVariable = None
     self.periodicity = None
     self.isBlinded = True
     self._blindingScheme = {}