Пример #1
0
    def create_canvas(self, ratio=True):
        if ratio:
            self.canvas = Canvas(width=700, height=700)
            self.canvas.Draw()
            self.canvas.cd()
            self.main_pad = Pad(0., 0.25, 1., 1.)
            self.main_pad.Draw()
            self.canvas.cd()
            self.ratio_pad = Pad(0., 0., 1., 0.25)
            self.ratio_pad.Draw()

            self.main_pad.SetTicks(True)
            self.main_pad.SetBottomMargin(0.)
            self.main_pad.SetLeftMargin(0.15)
            self.main_pad.SetRightMargin(0.15)
            self.ratio_pad.SetLeftMargin(0.15)
            self.ratio_pad.SetRightMargin(0.15)
            self.ratio_pad.SetTopMargin(0.)
            self.ratio_pad.SetGridy()
            self.ratio_pad.SetBottomMargin(0.3)

        else:
            self.canvas = Canvas(width=700, height=700)
            self.canvas.Draw()
            self.canvas.cd()
            self.main_pad = Pad(0., 0., 1., 1.)
            self.main_pad.Draw()
            self.canvas.cd()
            self.ratio_pad = Pad(-1., -1., -.9, -.9)
            self.ratio_pad.Draw()  # put it outside the canvas
            self.main_pad.SetTicks(True)
            self.main_pad.SetTopMargin(0.15)
            self.main_pad.SetBottomMargin(0.15)
            self.main_pad.SetLeftMargin(0.15)
            self.main_pad.SetRightMargin(0.15)
def extract_MET(f_tt, f_qcd, f_wjet):

    # get trees from files
    t_tt = f_tt.Get("Delphes")
    t_qcd = f_qcd.Get("Delphes")
    t_wjet = f_wjet.Get("Delphes")

    # get number of entries
    tt_n_entries = t_tt.GetEntries()
    qcd_n_entries = t_qcd.GetEntries()
    wjet_n_entries = t_wjet.GetEntries()

    # define leaves
    var_tt = "MissingET.MET"
    var_qcd = "MissingET.MET"
    var_wjet = "MissingET.MET"

    leaf_tt = t_tt.GetLeaf(var_tt)
    leaf_qcd = t_qcd.GetLeaf(var_qcd)
    leaf_wjet = t_wjet.GetLeaf(var_wjet)

    # create the histograms
    MET_tt = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_tt', legendstyle='L')
    MET_qcd = Hist(MET_NBINS,
                   MET_NLO,
                   MET_NHI,
                   title='MET_qcd',
                   legendstyle='L')
    MET_wjet = Hist(MET_NBINS,
                    MET_NLO,
                    MET_NHI,
                    title='MET_wjet',
                    legendstyle='L')

    # FILLING THE TREE
    fill_MET_tree(tt_n_entries, t_tt, leaf_tt, MET_tt)
    fill_MET_tree(qcd_n_entries, t_qcd, leaf_qcd, MET_qcd)
    fill_MET_tree(wjet_n_entries, t_wjet, leaf_wjet, MET_wjet)

    #set line colors
    MET_tt.SetLineColor('blue')
    MET_qcd.SetLineColor('green')
    MET_wjet.SetLineColor('red')

    #begin drawing stuff
    c1 = Canvas()
    MET_qcd.SetStats(0)
    MET_qcd.Draw('HIST')
    MET_tt.Draw('HIST SAME')
    MET_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([MET_tt, MET_qcd, MET_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("../plots/MET_plots/MET.pdf")

    #make the plots wait on screen
    wait(True)
Пример #3
0
def draw_efficiency(eff_s, rej_b, field, category, textsize=22):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    eff_s.painted_graph.yaxis.SetRangeUser(0, 1.10)
    eff_s.painted_graph.yaxis.title = 'Efficiency'
    eff_s.painted_graph.xaxis.title = xtitle
    eff_s.painted_graph.Draw('AP')
    rej_b.color = 'red'
    rej_b.markerstyle = 'square'
    rej_b.painted_graph.Draw('sameP')
    right_axis = ROOT.TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(),
                             ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(), 0,
                             1.10, 510, "+L")
    right_axis.SetLineColor(ROOT.kRed)
    right_axis.SetLabelColor(ROOT.kRed)
    right_axis.SetTextColor(ROOT.kRed)
    right_axis.SetTitle('Rejection = 1 - #epsilon_{B}')
    right_axis.Draw('same')
    ROOT.gStyle.SetPadTickY(0)
    ROOT.gPad.Update()
    ROOT.gStyle.SetPadTickY(1)
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend([eff_s, rej_b], pad=c)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Пример #4
0
def draw_DR(DR_tt, DR_qcd, DR_wjet):

    #set line colors
    DR_tt.SetLineColor(4)
    DR_qcd.SetLineColor(8)
    DR_wjet.SetLineColor(2)

    DR_tt.legendstyle = 'L'
    DR_qcd.legendstyle = 'L'
    DR_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    DR_qcd.SetStats(0)
    DR_qcd.Draw('HIST')
    DR_tt.Draw('HIST SAME')
    DR_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([DR_tt, DR_qcd, DR_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("DeltaR.pdf")

    #make the plots wait on screen
    wait(True)
Пример #5
0
def drawStack(stack, legends, foundVariables, sampleType, subset = 'TestA', dataHist = {}):
    """Draw the given stack.
    
    Keyword arguments:
    stack -- the stack to be drawn
    legends -- the accompanying legends
    foundVariables -- the variables in the stack that are being drawn
    sampleType -- signal or bkg
    subset -- acts as extra identifier in the filename (default A)
    dataHist -- the data histograms (default [])
    
    """
    c2 = Canvas()
    c2.cd()
    xcount = 0
    # should create a ratio plot too!!! get teh scaling right...
    for x in stack:
        if dataHist:
            x.Draw()
            xmax = x.GetHistogram().GetMaximum()
            dmax = dataHist['data'][xcount].GetMaximum()
            x.SetMaximum(max(xmax,dmax)*1.1)
            x.Draw('hist')
            dataHist['data'][xcount].Draw('same')
        else:
            x.Draw('hist')
        
        legends[xcount].Draw('same')
        c2.SaveAs(foundVariables[xcount]+str(sampleType)+str(subset)+'Stack.png')
        c2.Write()
        xcount +=1 
Пример #6
0
def plotResults(variable, data, templates, results):

    resCan = Canvas()
    leg = Legend(nTemplates + 2)

    data.Draw('PE')
    leg.AddEntry(data, style='LEP')
    nBins = len(inputTemplates[variable]['data'][whichBinFromFile])
    h_tSumAfter = Hist(nBins, 0, nBins, title='after_' + variable)

    if useT1:
        plotTemplateAfter(templates[tNames['t1']], results[tNames['t1']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT2:
        plotTemplateAfter(templates[tNames['t2']], results[tNames['t2']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT3:
        plotTemplateAfter(templates[tNames['t3']], results[tNames['t3']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT4:
        plotTemplateAfter(templates[tNames['t4']], results[tNames['t4']][0],
                          resCan, leg, h_tSumAfter)
        pass
    leg.Draw()

    h_tSumAfter.SetLineColor(2)
    h_tSumAfter.SetLineStyle(7)
    h_tSumAfter.SetMarkerSize(0)
    h_tSumAfter.Draw('SAME HIST')
    resCan.Update()

    return resCan, h_tSumAfter
Пример #7
0
def makePage( histos, fileName, fileDescr, separateFiles, logscale):
    """
    Prepares a canvas with one histogram per pad
    """
    import rootpy
    from rootpy.plotting import Hist, Canvas
    from ROOT import kBlue,gPad
    log = logging.getLogger('pyroplot')
    cans = {}
    log.info( "Drawing histograms .." )
    for idx, name in enumerate(sorted(histos.keys())):
        if separateFiles:
            log.debug( "Creating new canvas with index %d."%(idx))
            c=Canvas( 600, 800)
            cans[name]=c
            markCanvas(c, fileName, 0.05, y = 0.009, size = 0.025, color = 2 )
        if not separateFiles and (idx)%6 == 0:
            log.debug( "Creating new canvas with index %d."%(idx/6))
            # start a new canvas
            c=Canvas( 600, 800)
            cans[fileName+'/'+name]=c
            c.Divide(2,3)
            markCanvas(c, fileName, 0.05, y = 0.009, size = 0.025, color = 2 )
        # draw the histogram
        hist = histos[name]
        log.debug( "Drawing histogram #" + str(idx%6+1) +": " + hist.GetName() + " (" + hist.__class__.__name__ + ") in canvas #" + str(int(idx/6) ))
        hist.color = kBlue
        if not separateFiles:
            c.cd(idx%6+1)
        if logscale:
            gPad.SetLogy()
        plotHistos(histos=[hist],text=name)
        if fileDescr:
            markPad(text=fileDescr, x=.14, y=.8, size=0.041, color = 2)
    return cans
Пример #8
0
def plotSummary(name, closure, xmin=0, xmax=1, xTitle='m_{vis} [GeV]'):
    histoSmoothRatios = []
    for hname, graph in closure.data['True/Est'].items():
        if 'Histo' in hname and 'Smooth' in hname and not 'Error' in hname:
            histoSmoothRatios.append(graph)
    ################ Plot ratios
    histoDummyRatio = Hist(1, xmin, xmax, type='F')
    values = []
    for ratio in histoSmoothRatios:
        for p in xrange(ratio.GetN()):
            values.append(ratio.GetY()[p])
    maxi = max(values)
    mini = min(values)
    maxi = maxi * 1.1 if maxi > 0 else maxi * 0.9
    mini = mini * 1.1 if mini < 0 else mini * 0.9
    histoDummyRatio.SetAxisRange(mini, maxi, 'Y')
    ##
    for ratio in histoSmoothRatios:
        ratio.SetLineColor(ROOT.kGray + 3)
        ratio.SetLineWidth(1)
    ##
    canvasRatio = Canvas(800, 800)
    canvasRatio.SetName('Ratio_Summary_Canvas')
    histoDummyRatio.SetXTitle(xTitle)
    histoDummyRatio.SetYTitle('Ratio')
    histoDummyRatio.Draw()
    for ratio in histoSmoothRatios:
        ratio.Draw('l same')
    canvasRatio.Print(
        'results/{NAME}_NonClosure_Ratio_Summary.png'.format(NAME=name))
Пример #9
0
def applyacc(wbin, q2bin, iedges, vedges, weights):
    # TODO: clone 2d hists to keep snapshots between steps of acceptance
    # corrections and zero-filling
    vals = ibins2vals(wbin, q2bin)
    (wval, wlo, whi) = (vals[0][0], vals[0][1], vals[0][2])
    (q2val, q2lo, q2hi) = (vals[1][0], vals[1][1], vals[1][2])
    h2s = (hexpsig, hexpsb, h2thr, h2acc) = h2costphis(wbin, q2bin, iedges)
    h2rec_acor = h2thr.Clone('h2r_acor')
    h2rec_acor.Multiply(h2acc)
    inth2r = h2rec_acor.Integral()  # integral of reconstructed simulated events
    h2rec_acor.Divide(h2acc)        # thrown events with acceptance holes
    h2thr.Add(h2rec_acor, -1)       # thrown events IN acceptance holes
    [h2thr.SetBinError(i, j, sqrt(h2thr.GetBinContent(i, j))) for i in range(1, h2thr.GetNbinsX()) for j in range(1, h2thr.GetNbinsY())]
    hexpsb.Scale(weights[0])  # weightsb
    hexpsig.Add(hexpsb, -1)
    inth2e = hexpsig.Integral()/weights[1]  # integral of signal region with 3-sigma cut correction
    hexpsig.Divide(h2acc)
    h2thr.Scale(inth2e/inth2r)
    hexpsig.Add(h2thr)

    cmmp = Canvas(name='hcostphi_%d_%d' % (round(1000*wval), round(1000*q2val)),
                  title='Angular Distributions, W, Q2 = %.3f GeV,%.3f GeV2' % (wval, q2val))
    cmmp.Divide(2, 2)
    for ipad, h2 in enumerate(h2s):
        cmmp.cd(ipad+1)
        r.gPad.Update()
        h2.Draw('colz')

    wait()
    return hexpsig
Пример #10
0
def drawAllTrainStacks(signal, bkg, data, labelCodes, weightsPerSampleA, weightsPerSampleB, corrWeightsA = DEFAULT, corrWeightsB = DEFAULT, subset = 'TrainA'):
    """Draw all train stacks for signal and bkg at once.

    Keyword arguments:
    signal -- the signal sample
    bkg -- the background sample
    labelCodes -- the label codes for the type of sample (W, Z for eg.)
    weightsPerSample -- the XS weight
    subset -- extra identifier for the filename (default TrainA)
    
    """
    if corrWeightsA is DEFAULT:
        corrWeightsA = hstack(signal.returnTestCorrectionWeights('A'), bkg.returnTestCorrectionWeights('A'))
    if corrWeightsB is DEFAULT:
        corrWeightsB = hstack(signal.returnTestCorrectionWeights('B'), bkg.returnTestCorrectionWeights('B'))
    # store all histograms in output.root

    for x in xrange (0, len(signal.train)):
        if x == 0:
            subset = 'A'
            weightsPerSample = weightsPerSampleA
            corrWeights = corrWeightsA
        else:
            subset = 'B'
            weightsPerSample = weightsPerSampleB
            corrWeights = corrWeightsB
        f = ropen('outputTrain'+str(subset)+'.root','recreate')

        c1 = Canvas()
        c1.cd()

        allStack = []
        legendAllStack = []
        # get sigA histograms
        hist, histDictSigA, testAStack, legendSigStack = createHists(signal.returnTrainSample(subset), labelCodes, 'signal', signal.returnTrainSampleLabels(subset), weightsPerSample[0], signal.returnFoundVariables(), allStack, legendAllStack, corrWeights, str('Train'+subset), True)
        # get bkgA histograms
        # how to fix legends????
        hist2, histDictBkgA, testAStackBkg, legendBkgStack  = createHists(bkg.returnTrainSample(subset), labelCodes, 'bkg', bkg.returnTrainSampleLabels(subset), weightsPerSample[1], bkg.returnFoundVariables(), allStack, legendAllStack, corrWeights, str('Train'+subset), True)

        for hist2idx in xrange(0,len(hist)):
            legend = Legend(3)
            legend.AddEntry(hist[hist2idx],'F')
            legend.AddEntry(hist2[hist2idx],'F')
            
            hist[hist2idx].draw('hist')
            hist[hist2idx].Write()
            hist2[hist2idx].draw('histsame')
            hist2[hist2idx].Write()
            
            legend.Draw('same')
            c1.Write()
            #c1.SaveAs(signal.returnFoundVariables()[hist2idx]+".png")
            hist2idx+=1
        
        drawStack(testAStack, legendSigStack, signal.returnFoundVariables(), 'Sig', str('Train'+subset)) # draw histograms
        drawStack(testAStackBkg, legendBkgStack, bkg.returnFoundVariables(), 'Bkg', str('Train'+subset))
        drawStack(allStack, legendAllStack, signal.returnFoundVariables(), 'All', str('Train' + subset))
        
    f.close()
def compare (name1, name2, j) :
    c = Canvas()
    QCD = ROOT.TFile.Open(name1+".root")
    Wjet = ROOT.TFile.Open(name2+".root")
    c.Divide(2,1)
    c.cd(1)
    QCD.Draw("AP")
    Wjet.Draw("AP")
    c.SaveAs("plots/WeightComparison/WjetProbaDecayChannel_"+str(j)+"_WeightComparison.png")    
Пример #12
0
def __prepare_canvas(canvas_args):
    style = gStyle
    style.SetOptStat(0)

    canvas = Canvas(**canvas_args)
    canvas.SetGridx(True)
    canvas.SetGridy(True)
    canvas.title = ""
    return canvas, style
Пример #13
0
def drawSigBkgDistrib(sample, classif, foundVariables):
    idx = 0
    c1 = Canvas()
    c1.cd()
    histidx = 0
    histSig = []
    histBkg = []

    classif, sample = sc.sortMultiple(classif,sample)
    sample2 = transpose(sample)
    binc = bincount(classif)
    numzero = binc[0]
    numone = binc[1]
    global histLimits
    for x in sample2:
        x = transpose(x)
        variableName = foundVariables[histidx]
        histSig.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        histSig[histidx].fill_array(x[:numzero])
        histSig[histidx].scale(1.0/histSig[histidx].integral())

        histSig[histidx].fillcolor='red'
        histSig[histidx].SetFillStyle(3004)
        histSig[histidx].linecolor='red'
        
        histSig[histidx].GetXaxis().SetTitle(foundVariables[histidx])
        histSig[histidx].GetYaxis().SetTitle('# Events Normalised to 1')
        histSig[histidx].SetTitle('Background')
#        histSig[histidx].fillstyle='solid'
        histSig[histidx].SetStats(0)
        

        histBkg.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        histBkg[histidx].fill_array(x[numzero:])
        histBkg[histidx].scale(1.0/histBkg[histidx].integral())

        histBkg[histidx].fillcolor='blue'
        histBkg[histidx].linecolor='blue'
        histBkg[histidx].SetFillStyle(3005)
        
        histBkg[histidx].GetXaxis().SetTitle(foundVariables[histidx])
        histBkg[histidx].GetYaxis().SetTitle('# Events Normalised to 1')
        histBkg[histidx].SetTitle('Signal')
#        histBkg[histidx].fillstyle='solid'
        histBkg[histidx].SetStats(0)

        leg = Legend(2)
        leg.AddEntry(histBkg[histidx],'F')
        leg.AddEntry(histSig[histidx],'F')

        histBkg[histidx].draw('hist')
        histSig[histidx].draw('histsame')
        leg.Draw('same')
        c1.SaveAs(variableName+"SigBkgComparison.png")
        histidx+=1
Пример #14
0
def plot(params, efficiency):
    canvas = Canvas(width=500, height=500)
    draw_axes(params)
    draw_efficiency(params, efficiency)
    draw_lines(params)
    HGCAL_label(text='HGCAL Simulation', pad=canvas)
    draw_legends(params)
    canvas.RedrawAxis()
    canvas.Print('%s.png' % params.name)
    canvas.Print('%s.pdf' % params.name)
    canvas.Print('%s.C' % params.name)
    return canvas
Пример #15
0
def plot_comparisons(input_file, comparison_plots):
  with root_open(input_file) as file:
    for name,histo_config in comparison_plots.items():
      canvas = Canvas(1200,700)
      canvas.SetLeftMargin(0.08)
      canvas.SetRightMargin(0.12)
      histogram = file.Get(histo_config.name)
      if len(histo_config.range)==2:
        histogram.SetAxisRange(histo_config.range[0], histo_config.range[1], 'X')
      histogram.color = histo_config.color
      histogram.markerstyle = histo_config.marker
      histogram.Draw()
      canvas.Print('./plots/{}.png'.format(name))
Пример #16
0
def draw_curve_7(_func, name, title, ylow, yhigh):
    """ Draw 7TeV trigger efficiency curves """
    graphs = []
    for (trigger, color) in triggers:
        tool = ROOT.TauTriggerCorrections(
            os.path.join(base, 'triggerSF_%s.root' % trigger))
        func = getattr(tool, _func)
        eff = map(lambda x: func(x, 0), pt)
        eff_low = map(lambda x: func(x, -1), pt)
        eff_high = map(lambda x: func(x, 1), pt)
        graph = Graph(len(pt), name=trigger)
        for i, (p, e, e_low,
                e_high) in enumerate(zip(pt, eff, eff_low, eff_high)):
            graph.SetPoint(i, p / 1000, e)
            graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e)
        graph.linecolor = color
        graph.linewidth = 2
        graph.fillstyle = '/'
        graph.fillcolor = color
        graphs.append(graph)
    c = Canvas()
    leg = Legend(len(graphs),
                 pad=c,
                 topmargin=0.4,
                 leftmargin=0.3,
                 textsize=25,
                 margin=0.2)
    for i, g in enumerate(graphs):
        if i == 0:
            g.Draw('3AC')
            g.xaxis.title = '#font[52]{p}_{T} [GeV]'
            g.xaxis.SetLimits(20, 100)
            g.yaxis.SetLimits(ylow, yhigh)
            g.yaxis.SetRangeUser(ylow, yhigh)
            g.yaxis.title = title
        else:
            g.Draw('3C SAME')
        leg.AddEntry(g, g.name, 'L')
    leg.Draw()
    lines = []
    for thresh in (25, 35):
        line = Line(thresh, ylow, thresh, yhigh)
        line.linestyle = 'dashed'
        line.linewidth = 2
        line.Draw()
        lines.append(line)
    c.SaveAs('trigger_{0}.png'.format(name))
    c.SaveAs('trigger_{0}.eps'.format(name))
Пример #17
0
def plot_event(name, canvas):
  primitives = canvas.GetListOfPrimitives()
  histo = None
  point = None
  for primitive in primitives:
    if primitive.InheritsFrom(TH2Poly.Class()):
      histo = primitive
    if primitive.InheritsFrom(TMarker.Class()):
      point = primitive
  histo.SetXTitle('x [cm]')
  histo.SetYTitle('y [cm]')
  canvas_new = Canvas(700, 700)
  histo.SetAxisRange(77,100,'X')
  histo.Draw('colz')
  point.Draw()
  canvas_new.SetLogz()
  canvas_new.Print('./plots/event_{}.png'.format(name))
Пример #18
0
 def plot_distribution(self, output_file):
     f = r.TFile.Open(os.path.join(self.input_directory, output_file),
                      'read')
     intuple = f.Get('pythia8-Geant4')
     h = Hist2D(100, 0, 350, 100, 0, 6)
     for muon in intuple:
         px = muon.px
         py = muon.py
         pz = muon.pz
         p = np.sqrt(px**2 + py**2 + pz**2)
         pt = np.sqrt(px**2 + py**2)
         h.Fill(p, pt)
     c = Canvas()
     r.gStyle.SetOptStat(11111111)
     h.Draw("colz")
     c.Draw()
     c.SaveAs(os.path.join(self.input_directory, "p_dist.png"))
Пример #19
0
def checkOnMC(unfolding, method):
    global bins, nbins
    RooUnfold.SVD_n_toy = 1000
    pulls = []
    for sub in range(1,9):
        inputFile2 = File('../data/unfolding_merged_sub%d.root' % sub, 'read')
        h_data = asrootpy(inputFile2.unfoldingAnalyserElectronChannel.measured.Rebin(nbins, 'measured', bins))
        nEvents = inputFile2.EventFilter.EventCounter.GetBinContent(1)
        lumiweight = 164.5 * 5050 / nEvents
#        print sub, nEvents
        h_data.Scale(lumiweight)
        doUnfoldingSequence(unfolding, h_data, method, '_sub%d' %sub)
        pull = unfolding.pull_inputErrorOnly()
#        unfolding.printTable()
        pulls.append(pull)
        unfolding.Reset()
    allpulls = []

    for pull in pulls:
        allpulls.extend(pull)
    h_allpulls = Hist(100,-30,30)
    filling = h_allpulls.Fill
    for entry in allpulls:
        filling(entry)
    fit = h_allpulls.Fit('gaus', 'WWS')
    h_fit = asrootpy(h_allpulls.GetFunction("gaus").GetHistogram())
    canvas = Canvas(width=1600, height=1000)
    canvas.SetLeftMargin(0.15)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.10)
    canvas.SetRightMargin(0.05)
    h_allpulls.Draw()
    fit.Draw('same')
    canvas.SaveAs('plots/Pull_allBins_withFit.png')
    
    
    
    plt.figure(figsize=(16, 10), dpi=100)
    rplt.errorbar(h_allpulls, label=r'Pull distribution for all bins',  emptybins=False)
    rplt.hist(h_fit, label=r'fit')
    plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
    plt.ylabel('entries', CMS.y_axis_title)
    plt.title('Pull distribution for all bins', CMS.title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.legend(numpoints=1)
    plt.savefig('plots/Pull_allBins.png')
    
    #individual bins
    for bin_i in range(nbins):
        h_pull = Hist(100,-30,30)
        for pull in pulls:
            h_pull.Fill(pull[bin_i])
        plt.figure(figsize=(16, 10), dpi=100)
        rplt.errorbar(h_pull, label=r'Pull distribution for bin %d' % (bin_i + 1), emptybins=False)
        plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
        plt.ylabel('entries', CMS.y_axis_title)
        plt.title('Pull distribution for  bin %d' % (bin_i + 1), CMS.title)
        plt.savefig('Pull_bin_%d.png' % (bin_i + 1))
Пример #20
0
def draw_efficiencies(effs, field, category, textsize=22):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    if not isinstance(effs, (list, tuple)):
        effs = [effs]

    h = Hist(10, effs[0].painted_graph.xaxis.min,
             effs[0].painted_graph.xaxis.max)
    h.yaxis.SetRangeUser(0.0, 1.1)
    h.Draw('HIST')
    h.yaxis.title = 'Efficiency'
    h.xaxis.title = xtitle

    colors = [
        'black',
        'red',
        'orange',
        'blue',
        'green',
        'purple',
        'yellow',
        'pink',
    ]
    if len(effs) > len(colors):
        colors = len(effs) * colors
    for eff, col in zip(effs, colors):
        eff.color = col
        eff.color = col
        eff.painted_graph.legendstyle = 'l'
        eff.painted_graph.Draw('SAMEP')
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend(effs, pad=c, textsize=20)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Пример #21
0
def draw_stuff():
    ROOT.TH1.AddDirectory(ROOT.kFALSE)
    #TH1.SetDirectory(0)
    f = root_open(
        "/eos/cms/store/group/dpg_dt/comm_dt/dtRootple2015/DTTree_Run259685.root",
        "r")
    f2 = root_open("tmp.root", "RECREATE")
    for path, dirs, objects in f.walk():
        print(objects)
    tree = f.DTTree
    #for branch in f.DTTree.branchnames:
    #  print branch
    canvas = Canvas()
    hist = Hist(100, 0.0, 1E3, name='h' + '_' + '_IPchi2', type='D')

    #tree.Draw('Ndigis', '', '', hist)
    selection = "digi_wheel==-1 & digi_station==4 & digi_sector==4 & digi_sl==1 & digi_layer==1 & (digi_time < 300 | digi_time > 700)"  # & digi_wire=='wire0'"
    h = tree.Draw('timestamp', selection=selection, create_hist=True)
    #h.SetDirectory(0)
    canvas.SaveAs("test.png")
Пример #22
0
def bkg_fitting(filename):

    if filename[-5:] == '.root':
        filename = filename[:-5]

    s_root_path = './data/%s.root' % filename

    f_integral = root_open(s_root_path, 'read')

    conversion_to_num_electrons = 1. / (
        250e6) / 50. / 10. / 1.6e-19 * 2. / 2**12

    # find fit limits
    l_percentiles = [10, 90]
    lb_fit, ub_fit = -30, 30

    # grab histogram
    h_bkg = f_integral.bkgd_data_integral_hist

    c_fit = Canvas()
    h_bkg.Draw()

    fit_func = root.TF1('fit_func', 'gaus', lb_fit, ub_fit)
    h_bkg.Fit('fit_func', 'MELSR')

    fit_func.Draw('same')
    c_fit.Update()

    d_fit = {}
    d_fit['bkg_mean'] = fit_func.GetParameter(1) * conversion_to_num_electrons
    d_fit['bkg_std'] = fit_func.GetParameter(2) * conversion_to_num_electrons
    d_fit['bkg_mean_unc'] = fit_func.GetParError(
        1) * conversion_to_num_electrons
    d_fit['bkg_std_unc'] = fit_func.GetParError(
        2) * conversion_to_num_electrons

    print d_fit

    raw_input('Press enter to continue...')

    pickle.dump(d_fit, open('./bkg_results/bkg_%s.p' % (file), 'w'))
Пример #23
0
def draw_hists(hists,
               field,
               category,
               textsize=22,
               logy=False,
               unit_area=False):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    c.SetLogy(logy)

    if not isinstance(hists, (list, tuple)):
        hists = [hists]

    if unit_area:
        for h in hists:
            if h.integral() != 0:
                h /= h.integral()

    hists[0].xaxis.title = xtitle
    hists[0].yaxis.title = 'Arbitrary Unit'

    y_max = get_ymax(hists)
    hists[0].yaxis.SetRangeUser(0., 1.05 * y_max)
    hists[0].Draw('HIST')

    colors = [
        'black',
        'red',
        'orange',
        'blue',
        'green',
        'purple',
        'yellow',
        'pink',
    ]
    if len(hists) > len(colors):
        colors = len(hists) * colors
    for hist, col in zip(hists, colors):
        hist.color = col
        hist.color = col
        hist.fillstyle = 'hollow'
        hist.markersize = 0
        hist.linewidth = 2
        hist.linestyle = 'solid'
        hist.drawstyle = 'hist E0'
        hist.legendstyle = 'l'
        hist.Draw('SAMEHIST')
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend(hists, pad=c, textsize=20)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Пример #24
0
def draw(event, vects, radii=None, colors=None, etamin=-5, etamax=5, phimin=-math.pi, phimax=math.pi):
    """
    This function creates a 2D view of an event over eta and phi
    """
    c = Canvas()
    display = Hist2D(100, etamin, etamax, 100, phimin, phimax)
    display.SetXTitle('#eta')
    display.SetYTitle('#phi')
    display.Draw()
    things = []
    for i, vect in enumerate(vects):
        radius = .4
        if radii:
            radius = radii[i]
        thing = Ellipse(vect.Eta(), vect.Phi(), radius, radius)
        thing.SetLineWidth(3)
        if colors:
            thing.SetLineColor(colors[i])
            thing.SetFillStyle(0)
        thing.Draw()
        things.append(thing)
    c.SaveAs('eventviews/event_%i.png' % event.EventNumber)
Пример #25
0
def plot_distributions(input_file, distribution_plots):
  with root_open(input_file) as file:
    for name,histo_configs in distribution_plots.items():
      canvas = Canvas(700,700)
      legend = Legend(len(histo_configs), leftmargin=0.4, margin=0.3)
      histograms = []
      for histo_config in histo_configs:
        histogram = file.Get(histo_config.name)
        if len(histo_config.range)==2:
          histogram.SetAxisRange(histo_config.range[0], histo_config.range[1], 'X')
        histogram.color = histo_config.color
        histogram.markerstyle = histo_config.marker
        legend.AddEntry(histogram, label=histo_config.legend, style='ep')
        histograms.append(histogram)
      xmin, xmax, ymin, ymax = get_limits(histograms, logy=False)
      option = ''
      for histogram in histograms:
        histogram.SetAxisRange(ymin,ymax,'Y')
        histogram.Draw(option)
        option += ' same'
      legend.Draw()
      canvas.Print('plots/{}.png'.format(name))
Пример #26
0
    def draw_channel(self, channelNumber):
        print '\n\n---------- Draw channel ' + str(
            channelNumber) + ' ----------\n\n'

        assert channelNumber >= 1 and channelNumber <= 17 and type(
            channelNumber) == type(
                1), 'Improper channel number given - please check input'

        failStatus = -1

        # grab required histograms
        bkgFile = self.lProcessedRootFiles[0]
        signalFile = self.lProcessedRootFiles[self.dLightLevels[channelNumber]]

        hSignal = signalFile.Get('spe_' + str(channelNumber))
        hSignal.DrawStyle = 'hist'

        c1 = Canvas()
        hSignal.Draw('')
        c1.Update()

        raw_input('Please press enter when finished...')
Пример #27
0
def draw_MT(MT_tt, MT_qcd, MT_wjet):

    #set line colors
    MT_tt.SetLineColor(4)
    MT_qcd.SetLineColor(8)
    MT_wjet.SetLineColor(2)

    MT_tt.legendstyle = 'L'
    MT_qcd.legendstyle = 'L'
    MT_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    MT_qcd.SetStats(0)
    MT_qcd.Draw('HIST')
    MT_tt.Draw('HIST SAME')
    MT_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([MT_tt, MT_qcd, MT_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("MT.pdf")
Пример #28
0
def draw_HT(HT_tt, HT_qcd, HT_wjet):

    #set line colors
    HT_tt.SetLineColor(4)
    HT_qcd.SetLineColor(8)
    HT_wjet.SetLineColor(2)

    HT_tt.legendstyle = 'L'
    HT_qcd.legendstyle = 'L'
    HT_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    HT_wjet.SetStats(0)
    HT_wjet.Draw('HIST')
    HT_tt.Draw('HIST SAME')
    HT_qcd.Draw('HIST SAME')

    #make legend
    l1 = Legend([HT_tt, HT_qcd, HT_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("HT.pdf")
Пример #29
0
def draw_DPHImj(DPHI_tt, DPHI_qcd, DPHI_wjet):

    #set line colors
    DPHI_tt.SetLineColor(4)
    DPHI_qcd.SetLineColor(8)
    DPHI_wjet.SetLineColor(2)

    DPHI_tt.legendstyle = 'L'
    DPHI_qcd.legendstyle = 'L'
    DPHI_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    DPHI_qcd.SetStats(0)
    DPHI_qcd.Draw('HIST')
    DPHI_tt.Draw('HIST SAME')
    DPHI_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([DPHI_tt, DPHI_qcd, DPHI_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("DPHI_metjet.pdf")
Пример #30
0
def plot(params, rates):
    canvas = Canvas(width=500, height=500)
    draw_axes(params)
    draw_rates(params, rates)
    HGCAL_label(text='HGCAL Simulation', pad=canvas)
    canvas.SetLogy()
    canvas.RedrawAxis()
    canvas.Print('%s.png' % params.name)
    canvas.Print('%s.pdf' % params.name)
    canvas.Print('%s.C' % params.name)
Пример #31
0
def test_cmstdr():

    style = get_style('CMSTDR')
    with style:
        canvas = Canvas()
        hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution")
        ROOT.gRandom.SetSeed()
        for i in xrange(1000):
            hpx.Fill(ROOT.gRandom.Gaus())
        hpx.GetXaxis().SetTitle("random variable [unit]")
        hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]")
        hpx.SetMaximum(100.)
        hpx.Draw()
        CMS_label("Testing 2050", sqrts=100)
        if INTERACTIVE:
            wait()
Пример #32
0
def test_lhcb():
    style = get_style('LHCb')

    with style:
        canvas = Canvas()
        hpx = Hist(100, -4, 4, name="hpx", title="This is the px distribution")
        ROOT.gRandom.SetSeed()
        for i in xrange(1000):
            hpx.Fill(ROOT.gRandom.Gaus())
        hpx.GetXaxis().SetTitle("random variable [unit]")
        hpx.GetYaxis().SetTitle("#frac{dN}{dr} [unit^{-1}]")
        hpx.SetMaximum(80.)
        hpx.Draw()
        LHCb_label("R", "preliminary")
        if INTERACTIVE:
            wait()
Пример #33
0
def main(args):

    fileName = '/data/nawoods/lepsForSIP/lepsForSIP_M2500.root'

    checker = MuonCandMatchChecker('Check PF cand matching', [fileName])

    checker.processSample()

    h = checker.hists['pfCandPt']

    h.Sumw2()
    h.drawstyle = 'HIST'
    h.legendstyle = 'L'
    h.linewidth = 2
    h.color = 'red'

    c = Canvas(1000, 1000)
    (xax, yax), lims = draw(
        h,
        c,
        ytitle='PF Cands',
        xtitle='PF Cand p_T',
    )
    xax.SetTitleSize(0.4 * xax.GetTitleSize())
    xax.SetTitleOffset(1.6)
    xax.SetLabelSize(0.7 * xax.GetLabelSize())
    c.Print('/afs/cern.ch/user/n/nawoods/www/ptStudy/matchedCandPt.png')

    h2 = checker.hists['pfCandPtVsGenPt']
    c2 = Canvas(1000, 1000)
    h2.xaxis.SetTitleOffset(1.8)
    h2.yaxis.SetTitleOffset(1.7)
    h2.xaxis.SetTitleSize(0.5 * h2.xaxis.GetTitleSize())
    h2.yaxis.SetTitleSize(0.5 * h2.yaxis.GetTitleSize())
    h2.xaxis.SetLabelSize(0.6 * h2.xaxis.GetLabelSize())
    h2.yaxis.SetLabelSize(0.6 * h2.yaxis.GetLabelSize())
    h2.xaxis.SetTitle("Gen #mu p_{T}")
    h2.yaxis.SetTitle("PF cand p_{T}")
    h2.Draw("COLZ")
    c2.Print(
        '/afs/cern.ch/user/n/nawoods/www/ptStudy/matchedCandPtVsGenPt.png')

    print "Out of {} good muons, {} failed PF ID ({}%).".format(
        checker.nTot, checker.nFailPF,
        100. * float(checker.nFailPF) / checker.nTot)
    print(
        "Out of those failing PF, {} shared a track with a PF charged hadron "
        "({}%, {}% of the total)").format(
            checker.nPFMatched, 100. * checker.nPFMatched / checker.nFailPF,
            100. * checker.nPFMatched / checker.nTot)
Пример #34
0
def makePage(histos, fileName, fileDescr, separateFiles, logscale):
    """
    Prepares a canvas with one histogram per pad
    """
    import rootpy
    from rootpy.plotting import Hist, Canvas
    from ROOT import kBlue, gPad
    log = logging.getLogger('pyroplot')
    cans = {}
    log.info("Drawing histograms ..")
    for idx, name in enumerate(sorted(histos.keys())):
        if separateFiles:
            log.debug("Creating new canvas with index %d." % (idx))
            c = Canvas(600, 800)
            cans[name] = c
            markCanvas(c, fileName, 0.05, y=0.009, size=0.025, color=2)
        if not separateFiles and (idx) % 6 == 0:
            log.debug("Creating new canvas with index %d." % (idx / 6))
            # start a new canvas
            c = Canvas(600, 800)
            cans[fileName + '/' + name] = c
            c.Divide(2, 3)
            markCanvas(c, fileName, 0.05, y=0.009, size=0.025, color=2)
        # draw the histogram
        hist = histos[name]
        log.debug("Drawing histogram #" + str(idx % 6 + 1) + ": " +
                  hist.GetName() + " (" + hist.__class__.__name__ +
                  ") in canvas #" + str(int(idx / 6)))
        hist.color = kBlue
        if not separateFiles:
            c.cd(idx % 6 + 1)
        if logscale:
            gPad.SetLogy()
        plotHistos(histos=[hist], text=name)
        if fileDescr:
            markPad(text=fileDescr, x=.14, y=.8, size=0.041, color=2)
    return cans
Пример #35
0
def pvalue_plot(poi, pvalues, pad=None,
                xtitle='X', ytitle='P_{0}',
                linestyle=None,
                linecolor=None,
                yrange=None,
                verbose=False):
    """
    Draw a pvalue plot

    Parameters
    ----------
    poi : list
        List of POI values tested
    pvalues : list
        List of p-values or list of lists of p-values to overlay
        multiple p-value curves
    pad : Canvas or Pad, optional (default=None)
        Pad to draw onto. Create new pad if None.
    xtitle : str, optional (default='X')
        The x-axis label (POI name)
    ytitle : str, optional (default='P_{0}')
        The y-axis label
    linestyle : str or list, optional (default=None)
        Line style for the p-value graph or a list of linestyles for
        multiple p-value graphs.
    linecolor : str or list, optional (default=None)
        Line color for the p-value graph or a list of linestyles for
        multiple p-value graphs.

    Returns
    -------
    pad : Canvas
        The pad.
    graphs : list of Graph
        The p-value graphs

    """
    if not pvalues:
        raise ValueError("pvalues is empty")
    if not poi:
        raise ValueError("poi is empty")
    # determine if pvalues is list or list of lists
    if not isinstance(pvalues[0], (list, tuple)):
        pvalues = [pvalues]
    if linecolor is not None:
        if not isinstance(linecolor, list):
            linecolor = [linecolor]
        linecolor = cycle(linecolor)
    if linestyle is not None:
        if not isinstance(linestyle, list):
            linestyle = [linestyle]
        linestyle = cycle(linestyle)

    with preserve_current_canvas():
        if pad is None:
            pad = Canvas()
        pad.cd()
        pad.SetLogy()

        # create the axis
        min_poi, max_poi = min(poi), max(poi)
        haxis = Hist(1000, min_poi, max_poi)
        xaxis = haxis.xaxis
        yaxis = haxis.yaxis
        xaxis.SetRangeUser(min_poi, max_poi)
        haxis.Draw('AXIS')

        min_pvalue = float('inf')
        graphs = []
        for ipv, pv in enumerate(pvalues):
            graph = Graph(len(poi), linestyle='dashed',
                          drawstyle='L', linewidth=2)
            for idx, (point, pvalue) in enumerate(zip(poi, pv)):
                graph.SetPoint(idx, point, pvalue)
            if linestyle is not None:
                graph.linestyle = linestyle.next()
            if linecolor is not None:
                graph.linecolor = linecolor.next()
            graphs.append(graph)
            curr_min_pvalue = min(pv)
            if curr_min_pvalue < min_pvalue:
                min_pvalue = curr_min_pvalue

        if verbose:
            for graph in graphs:
                log.info(['{0:1.1f}'.format(xval) for xval in list(graph.x())])
                log.info(['{0:0.3f}'.format(yval) for yval in list(graph.y())])

        # automatically handles axis limits
        axes, bounds = draw(graphs, pad=pad, same=True, logy=True,
             xtitle=xtitle, ytitle=ytitle,
             xaxis=xaxis, yaxis=yaxis, ypadding=(0.2, 0.1),
             logy_crop_value=1E-300)

        if yrange is not None:
            xaxis, yaxis = axes
            yaxis.SetLimits(*yrange)
            yaxis.SetRangeUser(*yrange)
            min_pvalue = yrange[0]

        # draw sigma levels up to minimum of pvalues
        line = Line()
        line.SetLineStyle(2)
        line.SetLineColor(2)
        latex = ROOT.TLatex()
        latex.SetNDC(False)
        latex.SetTextSize(20)
        latex.SetTextColor(2)
        sigma = 0
        while True:
            pvalue = gaussian_cdf_c(sigma)
            if pvalue < min_pvalue:
                break
            keepalive(pad, latex.DrawLatex(max_poi, pvalue, " {0}#sigma".format(sigma)))
            keepalive(pad, line.DrawLine(min_poi, pvalue, max_poi, pvalue))
            sigma += 1

        pad.RedrawAxis()
        pad.Update()
    return pad, graphs
Пример #36
0
        plots_path = None
        topLevelPath = h.path
        while True:
          # non-empty dict, so break
          if plots_paths.get(topLevelPath, {}):
            break
          topLevelPath = os.path.dirname(topLevelPath)
          # top level path empty so break
          if not topLevelPath:
            break
        plots_path = plots_paths.get(topLevelPath, {})

        # create new canvas
        canvasConfigs = copy.copy(plots_config.get('canvas', {}))
        canvasConfigs.update(plots_path.get('canvas', {}))
        canvas = Canvas(canvasConfigs.get('width', 500), canvasConfigs.get('height', 500))

        canvas.SetRightMargin(canvasConfigs.get('rightmargin', 0.1))
        canvas.SetBottomMargin(canvasConfigs.get('bottommargin', 0.2))
        canvas.SetLeftMargin(canvasConfigs.get('leftmargin', 0.2))

        if canvasConfigs.get('logy', False) == True:
          canvas.set_logy()

        # create a legend (an entry for each group)
        legendConfigs = copy.copy(plots_config.get('legend', {}))
        legendConfigs.update(plots_path.get('legend', {}))
        legend = Legend(len(h), **legendConfigs)

        # scale the histograms before doing anything else
        for hgroup in h:
Пример #37
0
        plots_path = None
        topLevelPath = h.path
        while True:
          # non-empty dict, so break
          if plots_paths.get(topLevelPath, {}):
            break
          topLevelPath = os.path.dirname(topLevelPath)
          # top level path empty so break
          if not topLevelPath:
            break
        plots_path = plots_paths.get(topLevelPath, {})

        # create new canvas
        canvasConfigs = copy.copy(plots_config.get('canvas', {}))
        canvasConfigs.update(plots_path.get('canvas', {}))
        canvas = Canvas(canvasConfigs.get('width', 500), canvasConfigs.get('height', 500))

        canvas.SetRightMargin(canvasConfigs.get('rightmargin', 0.1))
        canvas.SetBottomMargin(canvasConfigs.get('bottommargin', 0.2))
        canvas.SetLeftMargin(canvasConfigs.get('leftmargin', 0.2))

        if canvasConfigs.get('logy', False) == True:
          canvas.set_logy()

        # create a legend (an entry for each group)
        legendConfigs = copy.copy(plots_config.get('legend', {}))
        legendConfigs.update(plots_path.get('legend', {}))
        legend_numColumns = legendConfigs.pop('num columns', 1)
        legend = Legend(len(h), **legendConfigs)
        legend.SetNColumns(legend_numColumns)
Пример #38
0
def do_stuff(file_name, plot=True):
    tiq_data = TIQData(file_name)
    NFRAMES = 100
    LFRAMES = 1024

    tiq_data.read(nframes=NFRAMES, lframes=LFRAMES, sframes=1)
    center = tiq_data.center

    # do fft
    ff, pp, _ = tiq_data.get_fft()

    freq_lower = center + ff[0] / 1e6
    freq_upper = center + ff[-1] / 1e6

    # create hist
    h1 = Hist(NFRAMES * LFRAMES, freq_lower, freq_upper, name='h1', title='Frequency Spectrum',
              drawstyle='hist',
              legendstyle='F',
              fillstyle='/',
              linecolor='green')

    for i in range(len(pp)):
        h1.set_bin_content(i, pp[i])

    # set visual attributes
    h1.GetXaxis().SetTitle('Freuqency [MHz]')
    h1.linecolor = 'green'
    # h1.fillcolor = 'green'
    # h1.fillstyle = '/'

    if plot:
        # plot
        c = Canvas(name='c1', width=700, height=500)
        c.set_left_margin(0.15)
        c.set_bottom_margin(0.15)
        c.set_top_margin(0.10)
        c.set_right_margin(0.05)
        c.toggle_editor()
        c.toggle_event_status()
        c.toggle_tool_bar()
        # c.set_crosshair()

        h1.Draw()

        # create the legend
        legend = Legend([h1], pad=c,
                        header='Header',
                        leftmargin=0.05,
                        rightmargin=0.5)
        legend.Draw()

        # wait for key press
        wait()
Пример #39
0

x1A = vstack((sigTestA, bkgTestA))
y1A = hstack((onesInt(len(sigTestA)), zerosInt(len(bkgTestA))))
y1A = transpose(y1A)


from rootpy.interactive import wait
from rootpy.plotting import Canvas, Hist, Hist2D, Hist3D, Legend
from rootpy.io import root_open as ropen, DoesNotExist
from rootpy.plotting import HistStack
import ROOT
ROOT.gROOT.SetBatch(True)
  
f = ropen('output.root','recreate')
c1 = Canvas()
c1.cd()

histDictSigA = {'W':[],'Z':[],'WW':[],'ZZ':[],'st':[],'ttbar':[],'WZ':[],'WH125':[]}
histDictBkgA = {'W':[],'Z':[],'WW':[],'ZZ':[],'st':[],'ttbar':[],'WZ':[],'WH125':[]}


coloursForStack = ['blue', 'green', 'red', 'yellow', 'black', 'pink', 'magenta', 'cyan']
colourDict = {'W':0,'Z':1,'WW':2,'ZZ':3,'st':4,'ttbar':5,'WZ':6,'WH125':7}

lblcount = 0

sigTestA = transpose(sigTestA)
bkgTestA = transpose(bkgTestA)

sigtemp1B = cutTree(sig,False,len(sig)/2,'B')
Пример #40
0
def makeComparisionPage( histodicts , fileNames, fileDescr, separateFiles):
    """
    Prepares a canvas comparing multiple histograms: plotting all in one pad and their ratios in the second
    """
    import rootpy
    from rootpy.plotting import Hist, Canvas, Legend
    import ROOT
    from ROOT import gPad
    log = logging.getLogger('pyroplot')
    cans = {}
    colors = [ROOT.kBlue, ROOT.kRed+1,ROOT.kViolet-1, ROOT.kOrange+7,ROOT.kGreen-7,ROOT.kOrange-6,
              ROOT.kPink-9,ROOT.kTeal-6,ROOT.kBlue+4,ROOT.kAzure+2]
    log.info( "Drawing histograms .." )
    # prepare set of histograms to compare to the reference on (the first)
    # loop over the reference set of histos (sorted by key):
    for hidx, refname in enumerate(sorted(histodicts[0].keys())):
        # prepare canvas
        if separateFiles:
            log.debug( "Creating new canvas with index %d."%(hidx))
            c=Canvas( 600, 270)
            cans[refname] = c
            c.Divide(3,1)
            c.cd(1)
        if not separateFiles and (hidx)%4 == 0:
            log.debug( "Creating new canvas with index %d."%(hidx/3))
            # start a new canvas
            c=Canvas( 600, 800)
            cans[refname] = c
            c.Divide(3,4)
        # prepare histograms for drawing
        log.debug( "Drawing histogram #" + str(hidx+1) +" (" + refname + ") on canvas #" + str(len(cans)) )
        hists = []
        ratiohists = []
        hiter = iter (histodicts)
        # special treatment for tprofile: prepare the reference projection for the ratio
        if histodicts[0][refname].__class__.__name__=="Profile":
            refProj = histodicts[0][refname].ProjectionX()
            refProj.SetName("reference_proj")
        for idx, h in enumerate(hiter):
            # make sure we have this histogram loaded:
            if not refname in h:
                continue
            # access the corresponding histogram of the other files at the same hidx as used for ref
            h[refname].color = colors[idx]
            h[refname].linestyle = idx
            hists.append (h[refname])
            # prepare ratio is this is not the first (i.e. reference) histogram
            if idx:
                # special treatment for TProfile:
                if h[refname].__class__.__name__=="Profile":
                    myratio = Hist(h[refname].nbins(), h[refname].lowerbound(), h[refname].upperbound()) #dummy hist
                    myratioproj = h[refname].ProjectionX()
                    myratioproj.SetName("cmp_hist_proj"+str(idx))
                    try:
                        myratio.divide(myratioproj,refProj)
                    except rootpy.ROOTError, e:
                        log.error("Calculation of ratio for histogram %s caused ROOTError exception ('%s')"%(h[refname].GetName(),e.msg))
                        break
                    myratio.color = colors[idx]
                else:
                    myratio = h[refname].clone() # make sure that the ratio has the right type
                    try:
                        myratio.Divide(h[refname], histodicts[0][refname]) # divide by reference hist
                    except rootpy.ROOTError, e:
                        log.error("Calculation of ratio for histogram %s caused ROOTError exception ('%s')"%(h[refname].GetName(),e.msg))
                        break
                myratio.yaxis.SetTitle("(h_{cmp} - h_{ref})/h_{ref}")
                myratio.SetTitle("ratio to reference")
                myratio.SetMaximum(2)
                myratio.SetMinimum(0)
                myratio.SetStats(0)
                ratiohists.append(myratio)
Пример #41
0
fakes_myhist = asrootpy(plotter.get_histogram(
    'Zjets',
    'emt/skimCounter',
))
styling.apply_style(fakes_myhist, **samplestyles.SAMPLE_STYLES['ztt'])

fakes = asrootpy(fakes_myhist.th1)

data = asrootpy(plotter.get_histogram(
    'data_DoubleMu',
    'emt/skimCounter',
).th1)


canvas = Canvas(800, 800)
canvas.SetRightMargin(0.05)

legend = ROOT.TLegend(0.55, 0.60, 0.9, 0.90, "", "brNDC")
legend.SetFillStyle(0)
legend.SetBorderSize(0)

data.SetMarkerSize(2)
data.SetTitle("data")
data.SetLineWidth(2)
legend.AddEntry(data,  "Observed", "lp")
signal.SetLineStyle(1)
signal.SetLineWidth(3)
signal.SetTitle("(5#times) m_{H}=120 GeV")
signal.SetLineColor(ROOT.EColor.kRed)
signal.SetFillStyle(0)
Пример #42
0
data0 = "normal_small", np.random.normal(0.5, 1, 200)
data1 = "normal", np.random.normal(0.5, 1, 100000)
data2 = "uniform", np.random.random(100000)
data3 = "normal+uniform", np.concatenate((data1[1], 10 * data2[1]))
data4 = "normal+normal", np.concatenate((data1[1], np.random.normal(2.5, 0.1, 100000)))

if ROOT.gROOT.IsBatch():
    datas = (data0, data1)
else:
    datas = (data0, data1, data2, data3, data4)

recipes = (
    "manual1", "sturges", "sturges-doane", "scott", "sqrt",
    "doane", "freedman-diaconis", "risk", "knuth")
objs = []
canvas = Canvas()
canvas.Divide(len(recipes), len(datas), 1E-3, 1E-3)
print '-' * 57
print '\t\t{0:<20s}{1:>10s}   {2:<6s}'.format('method', 'bins', 'time [s]')
print '-' * 57
for id, (dataname, d) in enumerate(datas):
    print dataname
    for ir, r in enumerate(recipes):
        canvas.cd(id * len(recipes) + ir + 1)
        timer = Timer()
        if r == "manual1":
            with timer:
                bins, h = histogram(d, 50, np.min(d), np.max(d),
                                    drawstyle='hist')
        else:
            with timer:
def Hist_comp_ratios (dec, bkg) :
#    weights = pickle.load( open( "weights_train.pck", "rb" ) ) 
#    probas = pickle.load( open( "class_proba.pck", "rb" ) ) 
#    mt_dec = pickle.load( open( "inputs_train.pck", "rb" ) )    
#    classes = pickle.load( open( "targets_train.pck", "rb" ) )

    weights = pickle.load( open( "weights.pck", "rb" ) ) 
    probas = pickle.load( open( "class_probaWholeSample.pck", "rb" ) ) 
    mt_dec = pickle.load( open( "inputs.pck", "rb" ) )    
    classes = pickle.load( open( "classes.pck", "rb" ) )
 

   
    
    #put mt_dec weights and the RELEVANT class probability together
    class_num = (GetClassIndex(bkg)-1)
    all_data = np.transpose(np.vstack((mt_dec[:,0],mt_dec[:,1], classes, weights, probas[:,class_num])))
    all_data = np.array(filter(lambda x: x[2] == class_num, all_data))
    
    
    #extract the relevant values for the specific decay channel
    Filter = np.array(filter(lambda x: x[1] == dec, all_data))
    MT = Filter[:,0]    
    Weight = Filter[:,3]
    Prob_bkg = Filter[:,4] 

           
    
    SumProbXweight = np.multiply(Prob_bkg,Weight)
    
   
    h1 = TH1D("h1","SumProbXweight_"+bkg+str(dec), 25 , 0.0 ,250.)
    root_open("plots/ROOTfiles/H1_SumProbXweight_"+bkg+str(dec)+"Samptot.root", 'recreate')
    fill_hist(h1,MT, weights=SumProbXweight)
    h1.Write()
    h2 = TH1D("h2","SumWeight_"+bkg+str(dec), 25 , 0.0 ,250.)
    root_open("plots/ROOTfiles/H1_SumWeight_"+bkg+str(dec)+"Samptot.root", 'recreate')
    fill_hist(h2,MT,weights=Weight)
    h2.Write()
    
    h3 = h1.Clone("h3")
    h3.Divide(h2)
    
    if (dec == 0.0) :
        Filter2 = np.array(filter(lambda x: x[1] == 1.0, all_data))
        MT2 = Filter2[:,0]    
        Weight2 = Filter2[:,3]
        Prob_bkg2 = Filter2[:,4]
        SumProbXweight2 = np.multiply(Prob_bkg2,Weight2)
        h12 = TH1D("h12","SumProbXweight_"+bkg+str(1.0), 25 , 0.0 ,250.)
        root_open("plots/ROOTfiles/H1_SumProbXweight_"+bkg+str(1.0)+"Samptot.root", 'recreate')
        fill_hist(h12,MT2, weights=SumProbXweight2)
        h12.Write()
        h22 = TH1D("h22","SumWeight_"+bkg+str(1.0), 25 , 0.0 ,250.)
        root_open("plots/ROOTfiles/H1_SumWeight_"+bkg+str(1.0)+"Samptot.root", 'recreate')
        fill_hist(h22,MT2,weights=Weight2)
        h22.Write()
        
        h32 = h12.Clone("h32")
        h32.Divide(h22)
        
        h12.SetStats(0)
        h22.SetStats(0)
        h32.SetStats(0)
        h12.SetLineColor(2)
        h22.SetLineColor(2)
       
        h32.SetLineColor(0)
        h32.SetMarkerStyle(23)
        h32.SetMarkerColor(2)
        h32.SetMarkerSize(1.2)
        
        
    #create Canvas and save the plot as png
    c = Canvas()
    c.Divide(2,2)
    c.cd(1)
    h1.SetStats(0)
    if (dec == 0.0) :
        if (h1.GetMaximum() > h12.GetMaximum()) :
            print "h1"
            h12.GetYaxis().SetRangeUser(0.,h1.GetMaximum())
        else :
            print "h12"
            h12.GetYaxis().SetRangeUser(0.,h12.GetMaximum())
        h12.Draw("HIST")
    h1.Draw("HIST SAME")

    c.cd(2)
    h2.SetStats(0)         
    if (dec == 0.0) :
        if (h2.GetMaximum() > h22.GetMaximum()) :
            h22.GetYaxis().SetRangeUser(0.,h2.GetMaximum())
        else :
            h22.GetYaxis().SetRangeUser(0.,h22.GetMaximum())
        h22.Draw("HIST")
    h2.Draw("HIST SAME")
    c.cd(3)
         
    f1 = root_open(GetClassProbaPath(bkg))
    #get the 2 histograms for the 2 decay channels: 1 track & 3 tracks
    H1 = f1.Get("h_w_2d")
    if (dec == 10.0) :
        #3 tracks
        h_data = Hist(list(H1.xedges()))
        h_data[:] = H1[:,2]
    else :
        #1 track
        h_data = Hist(list(H1.xedges()))
        h_data[:] = H1[:,1]
     
    h_data.GetXaxis().SetRangeUser(0.,250.)
    h_data.GetYaxis().SetRangeUser(0.,1.)
    h_data.fillstyle = '/'
    h_data.fillcolor = (255,255,0) #yellow
    h_data.SetStats(0)    
    h_data.Draw("HIST")
     
#    h3.SetFillColor(4) #blue
#    h3.SetFillStyle(3005)
    h3.SetLineColor(0)
    h3.SetMarkerStyle(21)
    h3.SetMarkerColor(4)
    h3.SetMarkerSize(1.2)
    h3.SetStats(0)    
    h3.SetTitle(bkg+str(dec))
    h3.GetXaxis().SetTitle("m_{T}")
    h3.GetYaxis().SetTitle("Class probability")        
         
         
    h3.Draw("HIST P SAME")
    if (dec == 0.0) :
        h32.Draw("HIST P SAME")
    c.Update()    
    
    
    if (dec == 0.0) :        
        legend = Legend(3, leftmargin=0.45, margin=0.3)
        legend.AddEntry(h3, "training, no #pi^{0}", style='P')
        legend.AddEntry(h32, "training, with #pi^{0}", style='P')
        legend.AddEntry(h_data, "data", style='F')
        legend.Draw()
    else :    
        legend = Legend(2, leftmargin=0.45, margin=0.3)
        legend.AddEntry(h3, "training", style='P')
        legend.AddEntry(h_data, "data", style='F')
        legend.Draw()
    
    c.SaveAs("plots/H1_"+bkg+str(dec)+"_RatioCompSamptot.png")
Пример #44
0
Draw a Quantile-Quantile Plot and Confidence Band
=================================================

This is an example of drawing a quantile-quantile plot with a
confidential level (CL) band, originally by Zhiyi Liu, [email protected]
"""
import ROOT
from rootpy.interactive import wait
from rootpy.plotting import Hist, Canvas, Legend
from rootpy.plotting.contrib.quantiles import qqgraph

ROOT.gROOT.SetStyle("Plain")
ROOT.gStyle.SetOptStat(0)
ROOT.gStyle.SetOptTitle(0)

c = Canvas(width=1000, height=300)
c.Divide(2, 1, 1e-3, 1e-3)

rand = ROOT.TRandom3()
h1 = Hist(100, -5, 5, name="h1", title="Histogram 1", linecolor='red')
h1.Sumw2()
h1.SetLineColor(ROOT.kRed)
h2 = Hist(100, -5, 5, name="h2", title="Histogram 2", linecolor='blue')
h2.SetLineColor(ROOT.kBlue)

for ievt in xrange(10000):
    #some test histograms:
    #1. let 2 histograms screwed
    #h1.Fill(rand.Gaus(0.5, 0.8))
    #h2.Fill(rand.Gaus(0, 1))
Пример #45
0
	try:
		stack.sum.Integral()
	except:
		print "stack has no integral!"
		continue

	if plotWithMPL:
		gs = mpl.gridspec.GridSpec(2,1,height_ratios=[4,1])
		gs.update(wspace=0.00, hspace=0.00)
		axes = plt.subplot(gs[0])
		axes_ratio = plt.subplot(gs[1], sharex=axes)
		plt.setp(axes.get_xticklabels(), visible=False)


	if plotWithROOT:
		c = Canvas(700,700)
		c.cd()
		pad1 = Pad( 0, 0.3, 1, 1.0)
		pad1.SetBottomMargin(0); # Upper and lower plot are joined
		pad1.SetGrid();         # Vertical grid
		pad1.Draw();             # Draw the upper pad: pad1
		c.cd()
		pad2 = Pad( 0, 0.05, 1, 0.3);
		pad2.SetTopMargin(0); # Upper and lower plot are joined
		pad2.SetBottomMargin(0.3); # Upper and lower plot are joined
		pad2.SetGrid();         # Vertical grid
		pad2.Draw();             # Draw the upper pad: pad1

		pad1.cd();               # pad1 becomes the current pad
		rootstack = ROOT.THStack(stack)
		rootstack.Draw('HIST')
Пример #46
0
def createHists(sample, labelCodes, nameOfType, labelsForSample, weightsPerSample, foundVariables, allHistStack, allLegendStack, corrWeights, subset = 'TestA', createLog = False):
    """Create all of the histograms for each sample and save them to file.
    
    Keyword arguments:
    sample -- the sample from which the histograms are created
    labelCodes -- the codes for all of the labels (0 == W, for eg.)
    nameOfType -- signal or bkg (default bkg)
    labelsForSample -- the labels of all the entries in the sample
    weightsPerSample -- the XS weight
    foundVariables -- the variables in the order in which they were found
    allHistStack -- the histogram stack of all of the samples
    allLegendStack -- the legends for all samples and entries to go on the stack
    subset -- extra label for the output file (default A)
    createLog -- create a log for the output (default False)
    
    """
    global histLimits
    #TODO: These should really be read in from a settings file
    #histDict = {'W':[],'Z':[],'WW':[],'ZZ':[],'st':[],'ttbar':[],'WZ':[],'WH125':[]}
    histDict = {'Wl':[],'Wcc':[],'Wc':[],'Wb':[],'Zb':[],'Z':[],'WW':[],'ZZ':[],'stop':[],'ttbar':[],'WZ':[],'WH125':[]}
    #coloursForStack = ['Green', 'Blue', 'Orange', 'Orange', 'Orange-2', 'Yellow', 'Pink', 'Red']
    coloursForStack = [3, 4, 800, 800, 795, 5, 6, 2]
    #colourDict = {'W':0,'Z':1,'WW':2,'ZZ':3,'st':4,'ttbar':5,'WZ':6,'WH125':7}
    colourDict = {'Wl':0,'Wcc':0,'Wc':0,'Wb':0,'Zb':1,'Z':1,'WW':2,'ZZ':3,'stop':4,'ttbar':5,'WZ':6,'WH125':7}

    if nameOfType == 'signal':
        fillcol = 'blue'
    else:
        fillcol = 'red'
    hist = []
    histidx = 0

    log = open(nameOfType+subset+'.log','w')
    
    c1 = Canvas()
    c1.cd()
    log.write('########################### '+ nameOfType +' ###########################\n')
    for c in sample:
        variableName = foundVariables[histidx]
        #hist.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        hist.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        hist[histidx].fill_array(c)
        hist[histidx].scale(1.0/hist[histidx].integral())
        
        hist[histidx].fillcolor=fillcol
        hist[histidx].linecolor=fillcol
        
        hist[histidx].GetXaxis().SetTitle(foundVariables[histidx])
        hist[histidx].GetYaxis().SetTitle('# Events Normalised to 1')
        hist[histidx].SetTitle(nameOfType)
        hist[histidx].fillstyle='solid'
        hist[histidx].SetStats(0)
        lblcount = 0
        for k in histDict.iterkeys():
            #histDict[k].append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
            histDict[k].append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
            #histDict[k][histidx].fillcolor = coloursForStack[int(colourDict[k])]
            histDict[k][histidx].SetFillColor(int(coloursForStack[int(colourDict[k])]))
            histDict[k][histidx].fillstyle = 'solid'
            histDict[k][histidx].SetOption('hist')
            histDict[k][histidx].SetTitle(str(k))# + str(foundVariables[histidx]))
            histDict[k][histidx].SetStats(0)
            histDict[k][histidx].GetXaxis().SetTitle(foundVariables[histidx])
            histDict[k][histidx].GetYaxis().SetTitle('# Events')
        for i in c:
            lbl = labelCodes[int(labelsForSample[lblcount])]
            if lbl in histDict.keys():
                histDict[lbl][histidx].fill(i,corrWeights[histidx])
                #histDict[lbl][histidx].scale(corrWeights[histidx])
            lblcount += 1
            
        histidx+=1

    # create stacks and legends
    histStack = []
    legendStack = []
    if not allHistStack:
        initStack = True
    else:
        initStack = False
    for st in foundVariables:
        if initStack == True:
            allHistStack.append(HistStack(st,st))
            allLegendStack.append(Legend(7))
        histStack.append(HistStack(st,st))
        legendStack.append(Legend(7))
    rwcount_outer = 0
    for rw in histDict.iterkeys():
        log.write(rw + ' length: '+str(len(histDict[rw]))+'\n')
        for rwcount in xrange(0,len(histDict[rw])):
            if histDict[rw][rwcount].GetEntries() > 0:
                if rw in weightsPerSample:
                    histDict[rw][rwcount].scale(weightsPerSample[rw])
                histStack[rwcount].Add(histDict[rw][rwcount].Clone())
                allHistStack[rwcount].Add(histDict[rw][rwcount].Clone())
                histStack[rwcount].Draw()
                allHistStack[rwcount].Draw()
                histDict[rw][rwcount].draw('hist')
                histStack[rwcount].GetXaxis().SetTitle(histDict[rw][rwcount].GetXaxis().GetTitle())
                histStack[rwcount].GetYaxis().SetTitle('# Events')
                allHistStack[rwcount].GetXaxis().SetTitle(histDict[rw][rwcount].GetXaxis().GetTitle())
                allHistStack[rwcount].GetYaxis().SetTitle('# Events')
                legendStack[rwcount].AddEntry( histDict[rw][rwcount], 'F')
                allLegendStack[rwcount].AddEntry( histDict[rw][rwcount], 'F')
                #c1.SaveAs("histDict"+str(nameOfType)+str(subset)+str(rwcount)+".png")
                log.write(rw + '['+str(rwcount)+'] entries: ' + str(histDict[rw][rwcount].GetEntries())+'\n')
        rwcount_outer += 1
    log.close()

    return hist,histDict,histStack,legendStack
h_t1.SetLineColor(4)
h_t2.SetLineColor(8)
h_t3.SetLineColor(6)
h_t4.SetLineColor(7)
h_data.SetLineColor(1)
h_data.SetMarkerColor(1)

ymax = getMax( [h_data, h_t1, h_t2, h_t3] )
ymax = ymax*1.1
h_data.GetYaxis().SetRangeUser(0,ymax)
h_t1.GetYaxis().SetRangeUser(0,ymax)
h_t2.GetYaxis().SetRangeUser(0,ymax)
h_t3.GetYaxis().SetRangeUser(0,ymax)
h_t4.GetYaxis().SetRangeUser(0,ymax)

c = Canvas()
c.Divide(2)
c.cd(1)
h_data.Draw('PE')
h_t1.Draw('SAME HIST')
h_t2.Draw('SAME HIST')
h_t3.Draw('SAME HIST')
h_t4.Draw('SAME HIST')

templates = {
             }
if useT1: templates['t1'] = h_t1
if useT2: templates['t2'] = h_t2
if useT3: templates['t3'] = h_t3
if useT4: templates['t4'] = h_t4
Пример #48
0
                # aesthetics
                heff.linecolor = colours[j]
                heff.markercolor = colours[j]
                heff.markersize = 0.2
                heff.SetMaximum(6)
                heff.SetMinimum(0)
                heff.SetStats(False)
                hists[i].append(heff)

    ## Plots
    nvars = len(variables)
    ncuts = len(mva_cuts)

    # ROOT
    canvas = Canvas(800, 400, 500, 10)
    canvas.Divide(2, 1)
    for i, var in enumerate(variables):
        for j in (0, 1):        # sig, bkg
            canvas.cd(j+1)
            for k, cut in enumerate(mva_cuts):
                opts = 'e1' if k == 0 else 'e1 same'
                hists[j][i*ncuts + k].Draw(opts)
        canvas.Modified()
        canvas.Update()
        if doprint:
            for typ in ['png']: #, 'pdf']:
                canvas.Print('{}_bkg_sig_eff_{}.{}'.format(var, n, typ))
    del tmp, canvas             # clean up

    # Matplotlib
Пример #49
0
from rootpy.plotting.style import set_style
from rootpy.plotting import Hist, Legend, Canvas

from FireROOT.Analysis.Utils import *

fn = os.path.join(
    os.getenv('CMSSW_BASE'),
    'src/FireROOT/Analysis/python/outputs/rootfiles/modules/leptonjetCosmicVeto.root'
)
outdir = os.path.join(
    os.getenv('CMSSW_BASE'),
    'src/FireROOT/Analysis/python/etc/plots/leptonjetCosmicVetoCutEfficiency')
if not os.path.isdir(outdir): os.makedirs(outdir)

set_style(MyStyle())
c = Canvas()

f = root_open(fn)


def routine(chan, varname, title):
    hs = []
    effs = OrderedDict()
    chandir = getattr(f, 'ch' + chan)
    for it, sigtag in enumerate(sigTAGS):
        h = getattr(getattr(chandir.sig, sigtag), varname)  # Hist
        h_total = h.integral(overflow=True)

        h_ = h.clone()
        for i in range(1, h.nbins() + 1):
            h_[i] = h.integral(xbin1=i, overflow=True) / h_total
Пример #50
0
def drawAll( m, c, eff = True ) :
    can = Canvas( width=600, height=3000 )
    pad = 2;
    can.Divide( 1, 6 )
    
    if ( eff ) :
        can.cd(pad)
        pad+=1
        yePi = f.tofEff.Get( "eff_Pi_"+m+"_"+c )
        yeK = f.tofEff.Get( "eff_K_"+m+"_"+c )
        yeP = f.tofEff.Get( "eff_P_"+m+"_"+c )

        yePi.Draw()
        yePi.SetTitle( "Fit Yields; P [GeV]; dN/(P dP)" )
        yePi.GetYaxis().SetRangeUser(  0.0, 1.7 )
        yeK.SetMarkerColor( R.kRed )
        yeK.Draw( "same")
        yeP.SetMarkerColor( R.kBlue )
        yeP.Draw("same")

    
    
    ############################################
    # zb mu
    can.cd(pad)
    pad+=1

    R.gPad.SetLogy(0)
    piMu = f.Pi_zbMu.Get( "mu_Pi_"+ m +"_" + c  )
    kMu = f.K_zbMu.Get( "mu_K_"+ m +"_" + c  )
    pMu = f.P_zbMu.Get( "mu_P_"+ m +"_" + c  )

    pidMu = f.Pi_zbMu.Get( "deltamu_Pi_"+ m +"_" + c ).Clone( "pisdmu" )
    kdMu = f.K_zbMu.Get( "deltamu_K_"+ m +"_" + c ).Clone( "ksdmu" )
    pdMu = f.P_zbMu.Get( "deltamu_P_"+ m +"_" + c ).Clone( "psdmu" )

    piMu.SetTitle( "<zb_{fit}> - <zb_{exp}>; P [GeV]" )
    R.gPad.SetLogy(0)
    piMu.GetYaxis().SetRangeUser( -0.2, 0.2)
    piMu.Draw()
    kMu.Draw("same")
    kMu.SetMarkerColor( R.kRed )
    pMu.Draw("same")
    pMu.SetMarkerColor( R.kBlue )

    pidMu.Scale(10);
    pidMu.SetMarkerStyle( R.kOpenCircle )
    pidMu.Draw("same")
    kdMu.Scale(10);
    kdMu.SetMarkerColor( R.kRed )
    kdMu.SetMarkerStyle( R.kOpenCircle )
    kdMu.Draw("same")
    pdMu.Scale(10);
    pdMu.SetMarkerColor( R.kBlue )
    pdMu.SetMarkerStyle( R.kOpenCircle )
    pdMu.Draw("same")



    #######################################################
    #zd mu
    try : 
        can.cd(pad)
        pad+=1
        R.gPad.SetLogy(0)
        piMu = f.Pi_zdMu.Get( "mu_Pi_"+ m +"_" + c )
        kMu = f.K_zdMu.Get( "mu_K_"+ m +"_" + c )
        pMu = f.P_zdMu.Get( "mu_P_"+ m +"_" + c )

        pidMu = f.Pi_zbMu.Get( "deltamu_Pi_"+ m +"_" + c ).Clone( "zdpisdmu" )
        kdMu = f.K_zbMu.Get( "deltamu_K_"+ m +"_" + c ).Clone( "zdksdmu" )
        pdMu = f.P_zbMu.Get( "deltamu_P_"+ m +"_" + c ).Clone( "zdpsdmu" )

        piMu.SetTitle( "<zd_{fit}> - <zd_{exp}>" )
        piMu.Draw()
        zdSig = 0.08
        piMu.GetYaxis().SetRangeUser( -zdSig * 5.0, zdSig * 5.0)
        kMu.Draw("same")
        kMu.SetMarkerColor( R.kRed )
        pMu.Draw("same")
        pMu.SetMarkerColor( R.kBlue )

        pidMu.Scale(10);
        pidMu.SetMarkerStyle( R.kOpenCircle )
        pidMu.Draw("same")
        kdMu.Scale(10);
        kdMu.SetMarkerColor( R.kRed )
        kdMu.SetMarkerStyle( R.kOpenCircle )
        kdMu.Draw("same")
        pdMu.Scale(10);
        pdMu.SetMarkerColor( R.kBlue )
        pdMu.SetMarkerStyle( R.kOpenCircle )
        pdMu.Draw("same")
    except :
        print "no"
    
    ##########################################################
    #zbSig
    try : 
        can.cd(pad)
        pad+=1
        R.gPad.SetLogy(0)
        piMu = f.Pi_zbSigma.Get( "sigma_Pi_"+ m +"_" + c  )
        kMu = f.K_zbSigma.Get( "sigma_K_"+ m +"_" + c )
        pMu = f.P_zbSigma.Get( "sigma_P_"+ m +"_" + c  )

        piMu.SetTitle( "#sigma zb_{fit}" )
        piMu.Draw()
        piMu.GetYaxis().SetRangeUser( 0.000, 0.055)
        kMu.Draw("same")
        kMu.SetMarkerColor( R.kRed )
        pMu.Draw("same")
        pMu.SetMarkerColor( R.kBlue )
        R.gPad.SetGrid(1, 1)
    except :
        print "no"
    
    ##########################################################
    #zdSig
    can.cd(pad)
    try :
        pad+=1
        R.gPad.SetLogy(0)
        piMu = f.Pi_zdSigma.Get( "sigma_Pi_"+ m +"_" + c  )
        kMu = f.K_zdSigma.Get( "sigma_K_"+ m +"_" + c  )
        pMu = f.P_zdSigma.Get( "sigma_P_"+ m +"_" + c  )

        piMu.SetTitle( "#sigma zd_{fit}" )
        piMu.Draw()
        piMu.GetYaxis().SetRangeUser( 0.0, 0.09)
        kMu.Draw("same")
        kMu.SetMarkerColor( R.kRed )
        pMu.Draw("same")
        pMu.SetMarkerColor( R.kBlue )
        R.gPad.SetGrid(1,1)
    except :
        print "no"
    
    ##########################################################
    #Yield
    can.cd(1)
    yPi = f.Pi_yield.Get( "yield_Pi_"+m+"_"+c )
    yK = f.K_yield.Get( "yield_K_"+m+"_"+c )
    yP = f.P_yield.Get( "yield_P_"+m+"_"+c )

    yPi.Draw()
    yPi.SetTitle( "Fit Yields; P [GeV]; dN/(P dP)" )
    yPi.GetYaxis().SetRangeUser( 1e-6, yPi.GetMaximum() *10 )
    yK.SetMarkerColor( R.kRed )
    yK.Draw( "same")
    yP.SetMarkerColor( R.kBlue )
    yP.Draw("same")
    R.gPad.SetLogy(1)
    return can
Пример #51
0
fn = os.path.join(
    os.getenv('CMSSW_BASE'),
    'src/FireROOT/Analysis/python/outputs/rootfiles/centralSig/validategen.root'
)
outdir = os.path.join(os.getenv('CMSSW_BASE'),
                      'src/FireROOT/Analysis/python/etc/plots/validategen')
if not os.path.isdir(outdir): os.makedirs(outdir)

set_style(MyStyle())

f = root_open(fn)

#################################################
# dark photon lxy
c = Canvas()
masstag = 'mXX-1000_mA-1p2'

mxx, ma = masstag.split('_')
mxx = mxx.split('-')[-1]
ma = ma.split('-')[1].replace('p', '.')

massdir = getattr(f.ch4mu, masstag)
lxytags = [x.name for x in massdir.keys()]  # lxy-0p3_ctau-0p0025

hsd = {}
for tag in lxytags:
    lxy_, ctau_ = tag.split('_')
    lxy = lxy_.split('-')[1].replace('p', '.')
    ctau = ctau_.split('-')[1].replace('p', '.')
    h = getattr(massdir, tag).dplxy
Пример #52
0
def createHistsData(sample, foundVariables, allHistStack, allLegendStack, subset = 'TestA', createLog = False):
    """Create histograms for data.
    
    Keyword arguments:
    sample -- the input data sample
    foundVariables -- the variables in the sample, in order
    allHistStack -- the histogram stack for all other samples
    subset -- an extra identifier for the filename (default TestA)
    createLog -- create a log (default False)
    
    """
    histDict = {'data':[]}
    coloursForStack = ['blue', 'green', 'red', 'yellow', 'black', 'pink', 'magenta', 'cyan']
    global histLimits 
    fillcol = 'black'

    hist = []
    histidx = 0
    log = open('data'+str(subset)+'.log','w')
    
    c1 = Canvas()
    c1.cd()
    log.write('########################### DATA  ###########################\n')
    for c in sample:
        variableName = foundVariables[histidx]
        #hist.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        hist.append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        hist[histidx].fill_array(c)
        hist[histidx].scale(1.0/hist[histidx].integral())
        
        hist[histidx].fillcolor=fillcol
        hist[histidx].linecolor=fillcol
        
        hist[histidx].GetXaxis().SetTitle(foundVariables[histidx])
        hist[histidx].GetYaxis().SetTitle('# Events Normalised to 1')
        hist[histidx].SetTitle('data')
        hist[histidx].fillstyle='solid'
        hist[histidx].SetStats(0)
        
        #histDict['data'].append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        histDict['data'].append(Hist(50,int(histLimits[variableName][0]),int(histLimits[variableName][1])))
        histDict['data'][histidx].fillcolor=fillcol
        histDict['data'][histidx].linecolor=fillcol
        histDict['data'][histidx].SetOption('hist')
        histDict['data'][histidx].SetTitle('data')
        histDict['data'][histidx].GetXaxis().SetTitle(foundVariables[histidx])
        histDict['data'][histidx].GetYaxis().SetTitle("# Events")
        histDict['data'][histidx].SetStats(0)
        for i in c:
            histDict['data'][histidx].fill(i)
    
        histidx+=1

    # create stacks and legends
    histStack = []
    legendStack = []

    for st in foundVariables:
        histStack.append(HistStack(st,st))
        legendStack.append(Legend(7))


    for rw in histDict.keys():
        log.write(rw + ' length: '+str(len(histDict[rw]))+'\n')
        for rwcount in xrange(0,len(histDict[rw])):
            if histDict[rw][rwcount].GetEntries() > 0:
                histStack[rwcount].Add(histDict[rw][rwcount].Clone())
                histStack[rwcount].Draw()
                histStack[rwcount].GetXaxis().SetTitle(histDict[rw][rwcount].GetXaxis().GetTitle())
                histStack[rwcount].GetYaxis().SetTitle('# Events')
                histDict[rw][rwcount].draw('hist')
                legendStack[rwcount].AddEntry( histDict[rw][rwcount], 'F')
                allLegendStack[rwcount].AddEntry(histDict[rw][rwcount], 'F')
                #c1.SaveAs("histDictData"+str(subset)+str(rwcount)+".png")
                log.write(rw + '['+str(rwcount)+'] entries: ' + str(histDict[rw][rwcount].GetEntries())+'\n')
    log.close()

    return hist,histDict,histStack,legendStack