示例#1
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
示例#2
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
示例#3
0
def storeHistogram(var, lumi, cut, histo, filename):
    # Plotting Data
    # ------------------
    bp = BasicPlot(filename, var)
    bp.addHistogram(histo, 'E', copy=True)
    bp.titles.append(
        "#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}".
        format(lumi / 1000.))
    bp.yVariable = Variable("Events")
    bp.normalizeByBinWidth = False
    bp.showBinWidthY = False
    bp.normalized = False
    bp.logY = False
    bp.yVariable.binning.low = 0  # start y-axis at 0
    bp.draw()
    bp.saveAsAll(os.path.join(outFolder, bp.title))
    # storing histogram in root file
    # ------------------------------
    from ROOT import TFile, TObject
    rootfile = TFile.Open(outFolder + '/' + filename + '.root', 'update')
    if rootfile.IsOpen():
        print "writing in file {}".format(outFolder + '/' + filename + '.root')
        rootfile.cd()
        histogram = histo.Clone('h_' + var.name)
        histogram.SetTitle('h_' + var.name)
        histogram.Write('h_' + var.name, TObject.kOverwrite)
        rootfile.Close()
    else:
        print "Problem opening file {}".format(outFolder + '/' + filename +
                                               '.root')
示例#4
0
def PlotAndStore(var,
                 filename,
                 lumi,
                 h_1,
                 h_2=None,
                 h_3=None,
                 drawOneLine=False,
                 simulation=False,
                 yLabel="Fake Rate",
                 yLow=0,
                 yHigh=None):
    bp = BasicPlot(filename, var)
    # Add histos
    SetHistStyle(h_1, 0)
    bp.addHistogram(h_1, 'E', copy=True)
    if h_2:
        SetHistStyle(h_2, 1)
        bp.addHistogram(h_2, 'E', copy=True)
    if h_3:
        SetHistStyle(h_3, 2)
        bp.addHistogram(h_3, 'E', copy=True)
    # Draw a line at 1 e.g. for SF plots
    if drawOneLine:
        h_tmp = var.createHistogram('')
        for i_bin in range(h_tmp.GetNbinsX() + 2):
            h_tmp.SetBinContent(i_bin, 1)
            h_tmp.SetBinError(i_bin, 0)
        h_tmp.SetLineColor(kGray)
        bp.addHistogram(h_tmp, 'E')
    # Some further settings
    bp.titles.append(
        '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}'.
        format(lumi / 1000.))
    bp.legendDecorator.textSize = 0.045
    if simulation:
        bp.titles.append('Simulation')
    bp.showBinWidthY = False
    bp.logY = False
    bp.normalized = False
    bp.normalizeByBinWidth = False
    bp.yVariable = Variable(yLabel)
    bp.yVariable.binning.low = yLow
    bp.yVariable.binning.up = yHigh
    # Plot and store
    bp.draw()
    bp.saveAsAll(os.path.join(outFolder, bp.title))
示例#5
0
 def __init__(self,
              title='DataMcPlot',
              xVariable=None,
              yVariableUp=var_Events,
              yVariableDown=Variable('Syst/Nom',
                                     binning=Binning(40, 0.6, 1.4)),
              upperFraction=0.7,
              lowerFraction=0.3):
     DoublePlot.__init__(self, title, xVariable, yVariableUp, yVariableDown,
                         upperFraction, lowerFraction)
     from ROOT import TF1
     self.dataHist = None
     self.upMcRatioHist = None
     self.nomMcRatioHist = None
     self.downMcRatioHist = None
     self.upMcHist = None
     self.nomMcHist = None
     self.downMcHist = None
     self.dataMcRatioHist = None
     self.baseLine = TF1('%s_baseLine' % self.title, '1',
                         xVariable.binning.low, xVariable.binning.up)
     self.mcErrorStyle = self.defaultMcErrorStyle
     self.baseLineStyle = self.defaultBaseLineStyle
     self.systlist = []
示例#6
0
 def __init__(self,
              title='DataMcPlot',
              xVariable=None,
              yVariableUp=var_Events,
              yVariableDown=Variable('Data/MC',
                                     binning=Binning(40, 0.6, 1.4)),
              upperFraction=0.7,
              lowerFraction=0.3):
     DoublePlot.__init__(self, title, xVariable, yVariableUp, yVariableDown,
                         upperFraction, lowerFraction)
     from ROOT import TF1
     #@param dataHist        Data on main plot (need to change to TAsymErrors?)
     #@param sumMcHist       MC error on main plot
     #@param sumMcRatioHist  MC error on ratio plot
     #@param dataMcRatioHist Data on ratio plot
     self.dataHist = None
     self.sumMcHist = None
     self.sumSystMcHist = None
     self.sumMcRatioHist = None
     self.dataMcRatioHist = None
     self.baseLine = TF1('%s_baseLine' % self.title, '1',
                         xVariable.binning.low, xVariable.binning.up)
     self.mcErrorStyle = self.defaultMcErrorStyle
     self.baseLineStyle = self.defaultBaseLineStyle
示例#7
0
                                 "Region 2",
                                 cut=selections[0] +
                                 sel_p[i_p] +
                                 cut_option_region2,
                                 luminosity=lumi,
                                 weight=tmp_weight)
 sys.stdout.write('.')
 sys.stdout.flush()
 h_var_r1.SetLineColor(kRed)
 h_var_r1.SetMarkerColor(kRed)
 h_var_r2.SetLineColor(kBlue)
 h_var_r2.SetMarkerColor(kBlue)
 bp = BasicPlot(
     'Q-G-Separation' + sel_p_suffix[i_p] + '_' +
     var.name + cut_option_suffix, var)
 bp.yVariable = Variable("Events with quark match")
 bp.yVariable.binning.low = 0
 bp.yVariable.binning.up = None
 bp.showBinWidthY = False
 bp.addHistogram(h_var_r1, 'E', copy=True)
 bp.addHistogram(h_var_r2, 'E', copy=True)
 bp.titles.append(
     '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}, '
     .format(lumi / 1000.))
 bp.draw()
 bp.saveAsAll(os.path.join("plots/", bp.title))
 # print quark rate
 h_var_tot_r1 = process.getHistogram(var,
                                     "Region 1",
                                     cut=selections[3] +
                                     sel_p[i_p] +
示例#8
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()
示例#9
0
         # subtract other backgrounds from data
         h_tmp = process.getHistogram(
             var,
             process.title,
             luminosity=lumi,
             cut=selection,
             weightExpression=weight_expression)
         sys.stdout.write('.')
         sys.stdout.flush()
         h_data.Add(h_tmp, -1)
 print "read all histograms for {0}".format(var.name)
 # calculating scale factor data/MC for the given Variable
 h_sf = var.createHistogram('SF')
 h_sf.Divide(h_data, h_mc, 1, 1, 'B')
 # plotting the scale factor
 bp_sf = BasicPlot('SF_' + var.name, var, Variable('Scale Factor'))
 bp_sf.titles.append(
     '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}, '
     .format(lumi / 1000.))
 bp_sf.addHistogram(h_sf, 'E', copy=True)
 bp_sf.draw()
 bp_sf.saveAsAll(os.path.join(outFolder, bp_sf.title))
 # storing histogram in root file
 from ROOT import TFile, TObject
 filename = outFolder + '/SF_' + var.name + '.root'
 rootfile = TFile.Open(filename, 'update')
 if rootfile.IsOpen():
     print "writing in file {}".format(filename)
     rootfile.cd()
     histogram = h_sf.Clone(var.name)
     histogram.SetTitle(var.name)
示例#10
0
from plotting.BasicPlot import BasicPlot, LegendElement
from plotting.DoublePlot import DoublePlot
from plotting.Variable import Binning, Variable, var_Events
from plotting.Tools import histToGraph, combineStatsAndSystematics, addGraphs, divideGraphs, resetGraph,\
    divideHistograms, createOutOfRangeArrows
import uuid
from copy import copy

var_dataMc = Variable('Data / Model', binning=Binning(low=0.7, up=1.3))
var_dataMc.binning.nDivisions = 205


class DataMcRatioPlot(DoublePlot):

    from AtlasStyle import Style
    from ROOT import kRed, kSpring, kGray, TColor
    defaultStatErrorTitle = 'Stat. Uncertainty'
    defaultSystErrorTitle = 'Syst. Uncertainty'
    defaultCombinedErrorTitle = 'Stat #oplus Syst'
    defaultStatErrorStyle = Style(TColor.GetColorTransparent(kSpring, 0.3),
                                  lineWidth=0,
                                  fillStyle=1000,
                                  markerStyle=0)
    defaultSystErrorStyle = Style(kGray + 3,
                                  lineWidth=0,
                                  fillStyle=3354,
                                  markerStyle=0)
    defaultCombinedErrorStyle = Style(kGray + 3,
                                      lineWidth=0,
                                      fillStyle=3354,
                                      markerStyle=0)
示例#11
0
		for i_set in range(n_sets): # data or mc plot ?
		    if i_type == 2: # SF plots have a different naming convention
			bp = BasicPlot( 'FakeRate_'+var.name+name_type[i_type]+sel_p_suffix[p], var )
		    else:
			bp = BasicPlot( 'FakeRate_'+var.name+name_type[i_type]+sel_p_suffix[p]+name_set[i_set], var )
		    bp.showBinWidthY = False
		    if name_type[i_type] == '_SF': # Draw a line at 1 for SF plots
			h_tmp = var.createHistogram( '' )
			for i_bin in range( h_tmp.GetNbinsX() + 2 ):
			    h_tmp.SetBinContent( i_bin, 1 )
			    h_tmp.SetBinError( i_bin, 0 )
			h_tmp.SetLineColor( kGray )
			bp.addHistogram( h_tmp, 'E' )
		    for i in range(id_range[i_type]): # Loop over different IDs
			histo_set[len(name_set)*i_type+i_set][i].SetLineColor( sel_colors[i] )
			histo_set[len(name_set)*i_type+i_set][i].SetMarkerColor( sel_colors[i] )
			histo_set[len(name_set)*i_type+i_set][i].SetMarkerStyle( sel_marker[i] )
			bp.addHistogram( histo_set[len(name_set)*i_type+i_set][i], 'E', copy=True )
		    bp.titles.append( '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}'.format(lumi/1000.) )
		    bp.legendDecorator.textSize = 0.045
		    bp.normalizeByBinWidth = normByWidth[i_type]
		    bp.yVariable = Variable( yLabel[i_type] )
		    bp.logY = logScale[i_type]
		    bp.normalized = False
		    if i_type == 1 or i_type == 2: # For FR and SF plots start y-axis at 0
			bp.yVariable.binning.low = 0
		    bp.draw()
		    bp.saveAsAll( os.path.join( "plots/", bp.title ) )
    # --------------------
    print 'everything is done!'
示例#12
0
    # create some dummy tree
    rndm = TRandom3()
    size = array('f', [0])
    energy = array('f', [0])
    t = TTree('tree', 'My Tree')
    t.Branch('size', size, 'size/F')
    t.Branch('energy', energy, 'energy/F')
    for entry in xrange(10000):
        size[0] = rndm.Poisson(3)
        energy[0] = rndm.Landau(size[0] * 2.5, size[0])
        t.Fill()

    # define a variable object for each branch
    sizeVar = Variable('size',
                       title='Cluster Size',
                       binning=Binning(10, 1, 11, range(1, 11)))
    energyVar = Variable('energy',
                         title='Hit Energy',
                         unit='MeV',
                         binning=Binning(50, 0, 100))

    # 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()
示例#13
0
                        h_mc.append(h_id)
                        sys.stdout.write('.')
                        sys.stdout.flush()
            print "\tgot all{0} histograms for {1}".format(
                sel_p_names[p], var.name)
            # Plotting
            # --------
            if do_plots:
                bp = BasicPlot(var.name + sel_p_suffix[p], var)
                bp.legendDecorator.textSize = 0.045
                bp.showBinWidthY = False
                for i in range(
                        len(selections)):  # Loop over different selections
                    h_mc[i].SetLineColor(sel_colors[i])
                    h_mc[i].SetMarkerColor(sel_colors[i])
                    h_mc[i].SetMarkerStyle(sel_marker[i])
                    bp.addHistogram(h_mc[i], 'E', copy=True)
                bp.titles.append(
                    'Simulation, #sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}'
                    .format(lumi / 1000.))
                bp.normalizeByBinWidth = False
                bp.normalized = True
                bp.yVariable = Variable('Normalized')
                #bp.yVariable = Variable( 'Events' )
                bp.logY = logBool[i_var]
                bp.draw()
                bp.saveAsAll(os.path.join(outFolder, bp.title))
        print "\t\tDone plotting {0}".format(var.name)
    # --------------------
    print 'everything is done!'
示例#14
0
    h1 = TH1D('hTest1', 'First Test', 40, -4, 4)
    h1.FillRandom('gaus', 1000)
    h1.SetLineColor(kRed)

    h2 = TH1D('hTest2', 'Second Test', 40, -4, 4)
    h2.FillRandom('gaus', 500)
    h2.SetLineColor(kBlue)

    h3 = TH1D('hTest3', 'Data', 40, -4, 4)
    h3.FillRandom('gaus', 1500)
    h3.SetLineColor(kBlack)

    f = TF1('fTest', 'gaus', -4, 4)
    f.SetLineColor(kGreen + 2)

    xVar = Variable('Invariant Mass', unit='GeV')

    basicTest = BasicPlot('basicTest', xVar, var_Normalized)
    h = basicTest.addHistogram(h1, 'HIST', copy=True)
    basicTest.addHistogram(h2, 'E0', copy=True)
    basicTest.addFitFunction(h, f, legendTitle='Fit to First')
    basicTest.titles.append('My title')
    basicTest.titles.append('My second title')
    basicTest.normalized = True
    basicTest.draw()
    basicTest.saveIn()

    stackedTest = BasicPlot('stackedTest', xVar)
    stackedTest.addHistogram(h3, 'E')
    stackedTest.addHistogram(h1, stacked=True)
    stackedTest.addHistogram(h2, stacked=True)
示例#15
0
def TemplateFit(filename,
                data,
                mc_q,
                mc_g,
                w_q=None,
                w_g=None,
                pull_widths=[1, 1],
                doPlots=True):
    n_mc = 2

    # Define MC samples
    mc = TObjArray(n_mc)
    mc.Add(mc_q)
    mc.Add(mc_g)

    # Names
    mc_type = []
    mc_type.append('Quarks')
    mc_type.append('Gluons')

    # Perform Fit
    fit = TFractionFitter(data, mc, "q")
    if w_q and w_g:
        fit.SetWeight(0, w_q)
        fit.SetWeight(1, w_g)
    fit.Constrain(0, 0.0, 1.0)  #quarks
    fit.Constrain(1, 0.0, 1.0)  #gluons
    fit.Fit()

    # Printing results
    val_q = ROOT.Double()
    err_q = ROOT.Double()
    val_g = ROOT.Double()
    err_g = ROOT.Double()
    fit.GetResult(0, val_q, err_q)
    fit.GetResult(1, val_g, err_g)
    err_q = err_q * pull_widths[
        0]  # correcting the error for the width of the pull plot
    err_g = err_g * pull_widths[
        1]  # correcting the error for the width of the pull plot
    for i in range(n_mc):
        val = ROOT.Double()
        err = ROOT.Double()
        fit.GetResult(i, val, err)
        out_file.write("fit result {}: {}, {}\n".format(mc_type[i], val, err))
    out_file.write("X2 = {}\n".format(fit.GetChisquare()))
    out_file.write("NDF = {}\n".format(fit.GetNDF()))
    red_chi = fit.GetChisquare() / fit.GetNDF()
    out_file.write("red. X2 = {}\n".format(red_chi))
    out_file.write("\n")

    if doPlots:
        print "storing plot as {}".format(filename)
        # Preparing Histograms
        h_fit = fit.GetPlot()
        h_q = fit.GetMCPrediction(0)
        h_g = fit.GetMCPrediction(1)
        h_fit.SetTitle("Fit")
        h_q.SetTitle("Quarks")
        h_g.SetTitle("Gluons")
        h_fit.SetLineColor(kGreen)
        h_q.SetLineColor(kRed)
        h_g.SetLineColor(kBlue)
        h_q.SetMarkerColor(kRed)
        h_g.SetMarkerColor(kBlue)

        # Scaling to the fit result
        int_fit = h_fit.Integral()
        int_q = h_q.Integral()
        int_g = h_g.Integral()
        h_q.Sumw2()
        h_g.Sumw2()
        h_q.Scale(val_q * int_fit / int_q)
        h_g.Scale(val_g * int_fit / int_g)

        # Checking fit vs. templates
        h_check = h_fit.Clone('Fit - Templates Check')
        h_check.Add(h_q, -1)
        h_check.Add(h_g, -1)
        check_maxBin = h_check.GetMaximumBin()
        out_file.write(
            "Maximal bin of fit minus templates divided by content of that bin in fit: {} / {}\n\n"
            .format(h_fit.GetBinContent(check_maxBin),
                    h_check.GetBinContent(check_maxBin)))

        # Plotting results
        bp = BasicPlot(filename, var_tau0_width)
        bp.addHistogram(h_q, 'E', copy=True)
        bp.addHistogram(h_g, 'E', copy=True)
        bp.addHistogram(h_fit, 'HIST', copy=True)
        bp.addHistogram(data, 'E', copy=True)
        bp.titles.append(
            'Quarks: {:.3} #pm {:.2}, Gluons: {:.3} #pm {:.2}'.format(
                val_q, err_q, val_g, err_g))
        bp.titles.append(
            '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}'.
            format(lumi / 1000.))
        bp.titles.append('#chi^{{2}}/ndf: {:.3}'.format(red_chi))
        bp.yVariable = Variable("Events")
        bp.legendDecorator.textSize = 0.045
        bp.normalizeByBinWidth = False
        bp.showBinWidthY = False
        bp.normalized = False
        bp.logY = False
        bp.yVariable.binning.low = 0  # start y-axis at 0
        bp.draw()
        bp.saveAsAll(os.path.join(outFolder, bp.title))

    return fit
示例#16
0
    barLength = 20
    fraction = current / float(total)
    nBlocks = int(round(barLength * fraction))
    t = '\r[{0}] ({1}/{2}) {3:50}'.format(
        '#' * nBlocks + '-' * (barLength - nBlocks), current, total, text)
    sys.stdout.write(t)
    sys.stdout.flush()
    if fraction >= 1:
        print ''


if __name__ == '__main__':
    from plotting.Variable import Variable, Binning
    from plotting.BasicPlot import BasicPlot
    var = Variable(
        'ditau_tau0_decay_mode', 'ditau_tau0_decay_mode',
        'Decay Mode (#tau_{0})', '',
        Binning(6, 0, 6, ['1p0n', '1p1n', '1pXn', '3p0n', '3pXn', 'Other']))

    h = var.createHistogram('h_test')
    h.Fill(2)
    h.Fill(3)
    h.Fill(2)
    h.Fill(0)
    h.Fill(2)

    g = histToGraph(h, 'g_test')
    g.SetLineColor(2)

    #g = addGraphs( g, g, True )

    p = BasicPlot('test', var)
示例#17
0
def PullPlot(filename,
             h_data,
             h_quarks,
             h_gluons,
             w_quarks=None,
             w_gluons=None,
             pull_widths=[1, 1]):
    # Creating a pull-plot
    # --------------------
    ratio_q = []
    error_q = []
    ratio_g = []
    error_g = []
    n_runs = 10000
    # getting fit results for toy experiments
    for i in range(1, n_runs + 1):
        if i == 1: print "    starting loop"
        h_tmp = var.createHistogram(str(i))
        h_tmp.FillRandom(h_data)
        filename_tmp = filename + '_' + str(i)
        out_file.write(str(i) + ":\n")

        fit = TemplateFit(filename,
                          h_tmp,
                          h_quarks,
                          h_gluons,
                          w_quarks,
                          w_gluons,
                          pull_widths,
                          doPlots=False)

        val_q = ROOT.Double()
        err_q = ROOT.Double()
        val_g = ROOT.Double()
        err_g = ROOT.Double()
        fit.GetResult(0, val_q, err_q)
        fit.GetResult(1, val_g, err_g)
        del fit
        err_q = err_q * pull_widths[
            0]  # correcting the error for the width of the pull plot
        err_g = err_g * pull_widths[
            1]  # correcting the error for the width of the pull plot

        ratio_q.append(val_q)
        error_q.append(err_q)
        ratio_g.append(val_g)
        error_g.append(err_g)

        if i % (n_runs / 10) == 0 or i == 1 or i == n_runs:
            print "    {}\tQ: {} +- {}\tG: {} +- {}".format(
                i, val_q, err_q, val_g, err_g)

    # creating pull histogram for quarks
    h_pull = var_pull.createHistogram()
    ratio_q_mean = sum(ratio_q) / len(ratio_q)
    for i in range(n_runs):
        tmp = (ratio_q[i] - ratio_q_mean) / error_q[i]
        h_pull.Fill(tmp)

    fit_result = h_pull.Fit('gaus', 'QS')
    f_gaus = h_pull.GetFunction('gaus')
    v_q_mu = fit_result.Parameter(1)
    v_q_mu_err = fit_result.ParError(1)
    v_q_sigma = fit_result.Parameter(2)
    v_q_sigma_err = fit_result.ParError(2)
    chi = fit_result.Chi2()
    ndf = fit_result.Ndf()
    #red_chi = chi / ndf

    filename_tmp = filename + '_PullPlot_q'
    bp = BasicPlot(filename_tmp, var_pull)
    bp.titles.append(
        'Fit Results: #mu = {:05.3f}#pm{:05.3f}, #sigma = {:05.3f}#pm{:05.3f}'.
        format(v_q_mu, v_q_mu_err, v_q_sigma, v_q_sigma_err))
    bp.titles.append('#chi^{{2}}/ndf: {:.3}/{}'.format(chi, ndf))
    bp.addHistogram(h_pull, 'E', copy=True)
    bp.yVariable = Variable("Events")
    bp.normalizeByBinWidth = False
    bp.showBinWidthY = False
    bp.normalized = False
    bp.logY = False
    bp.yVariable.binning.low = 0  # start y-axis at 0
    bp.draw()
    bp.saveAsAll(os.path.join(outFolder, bp.title))

    del h_pull
    del bp

    # creating pull histogram for gluons
    h_pull = var_pull.createHistogram()
    ratio_g_mean = sum(ratio_g) / len(ratio_g)
    for i in range(n_runs):
        tmp = (ratio_g[i] - ratio_g_mean) / error_g[i]
        h_pull.Fill(tmp)

    fit_result = h_pull.Fit('gaus', 'QS')
    f_gaus = h_pull.GetFunction('gaus')
    v_g_mu = fit_result.Parameter(1)
    v_g_mu_err = fit_result.ParError(1)
    v_g_sigma = fit_result.Parameter(2)
    v_g_sigma_err = fit_result.ParError(2)
    chi = fit_result.Chi2()
    ndf = fit_result.Ndf()
    #red_chi = chi / ndf

    filename_tmp = filename + '_PullPlot_g'
    bp = BasicPlot(filename_tmp, var_pull)
    bp.titles.append(
        'Fit Results: #mu = {:05.3f}#pm{:05.3f}, #sigma = {:05.3f}#pm{:05.3f}'.
        format(v_g_mu, v_g_mu_err, v_g_sigma, v_g_sigma_err))
    bp.titles.append('#chi^{{2}}/ndf: {:.3}/{}'.format(chi, ndf))
    bp.addHistogram(h_pull, 'E', copy=True)
    bp.yVariable = Variable("Events")
    bp.normalizeByBinWidth = False
    bp.showBinWidthY = False
    bp.normalized = False
    bp.logY = False
    bp.yVariable.binning.low = 0  # start y-axis at 0
    bp.draw()
    bp.saveAsAll(os.path.join(outFolder, bp.title))

    return [v_q_sigma, v_g_sigma]
示例#18
0
    from array import array
    rndm = TRandom3()
    pT0 = array('f', [0])
    pT1 = array('f', [0])
    t = TTree('tree', 'tree')
    t.Branch('tau_0_pt', pT0, 'tau_0_pt/F')
    t.Branch('tau_1_pt', pT1, 'tau_1_pt/F')
    sumOfWeights = 0.
    for entry in xrange(10000):
        pT0[0] = rndm.Gaus(60, 15)
        pT1[0] = rndm.Gaus(50, 10)
        t.Fill()

    binning = Binning(50, 0, 100)
    var_tau_0_pt = Variable('tau_0_pt',
                            title='p_{T}(#tau_{0})',
                            unit='GeV',
                            binning=binning)
    var_tau_1_pt = Variable('tau_1_pt',
                            title='p_{T}(#tau_{1})',
                            unit='GeV',
                            binning=binning)
    var_tau_pt = CombinedVariable('tau_0_pt',
                                  'p_{T}(#tau)',
                                  'GeV',
                                  binning,
                                  variables=[var_tau_0_pt, var_tau_1_pt])

    p = BasicPlot('Test Plot', var_tau_pt)
    p.addHistogram(
        var_tau_pt.createHistogramFromTree(t, 'Any Tau', style=blackLine),
        'E0')
示例#19
0
if __name__ == '__main__':
    from ROOT import TTree, TRandom3
    from array import array
    from plotting.Variable import Variable, Binning
    from AtlasStyle import redLine, blueLine, greenLine
    
    # create some dummy tree
    rndm = TRandom3()
    size = array( 'f', [0] )
    energy = array( 'f', [0] )
    t = TTree( 'tree', 'My Tree' )
    t.Branch( 'size', size, 'size/F' )
    t.Branch( 'energy', energy, 'energy/F' )
    for entry in xrange( 10000 ):
        size[0] = rndm.Poisson( 3 )
        energy[0] = rndm.Landau( size[0]*2.5, size[0] )
        t.Fill()
    
    # define a variable object for each branch
    sizeVar = Variable( 'size', title='Cluster Size', binning=Binning(10, 1, 11, range(1,11)) )
    energyVar = Variable( 'energy', title='Hit Energy', unit='MeV', binning=Binning(50, 0, 100) )

    p = BasicPlot( 'test', sizeVar, Variable( 'RMS(E)', unit = 'MeV' ) )
    measure = HalfWidth()
    measure.selection = Truncate( 0.68 )
    g = p.addGraph( resolutionGraph( t, sizeVar, energyVar, '', measure ) )
    p.draw()

    g.Draw()
    
    raw_input( 'Continue?' )
示例#20
0
bin_pt_lino = VariableBinning([50, 80, 120])
bin_pt_equal = Binning(10, 20, 120)
bin_pt_fine = Binning(24, 0, 120)

bin_eta = VariableBinning(
    [-2.5, -1.52, -1.37, -1.1, -0.05, 0.05, 1.1, 1.37, 1.52, 2.5])
bin_eta_equal = Binning(15, -3, 3)

bin_phi = Binning(11, -3.15, 3.15)
bin_bdt = Binning(20, 0, 1)

#===========#
# Variables #
#===========#
#			  Variable( name,				variable,				x-axis title,					unit,		binning				)
var_run_number = Variable('run_number', 'run_number', 'Run Number', '',
                          Binning(100, 250000, 350000))
var_pull = Variable('pull', 'pull', 'Pull', '', Binning(70, -3.5, 3.5))

var_weight_mc = Variable('weight_mc', 'weight_mc', 'weight (MC)', '',
                         Binning(500, -2500, 2500))
var_weight_pileup = Variable('weight_pileup', 'weight_pileup',
                             'weight (Pileup)', '', Binning(11, -5, 5))
var_weight_total = Variable('weight_total', 'weight_total', 'weight (Total)',
                            '', Binning(500, -2500, 2500))
var_weight_ZptSF = Variable('weight_ZptSF', 'SF_dilepton_pt_vect',
                            'weight (ZptSF)', '', Binning(40, 0, 2))

var_n_jets = Variable('n_jets', 'n_jets', '# jets', '',
                      Binning(13, -0.5, 12.5))
var_n_electrons = Variable('n_electrons', 'n_electrons', '# electrons', '',
                           Binning(13, -0.5, 12.5))