示例#1
0
 def intervalFromValues( self, values, weights ):
     ## Calculates the selected interval from weighted values
     #  Symmetrically removes entries on both side until the desired fraction
     #  of weights remains. Uncertainties are estimated by interpreting the fraction
     #  of entries below and above the limits as an efficiency measurements.
     #  Limits are then given from the 1-sigma confidence interval.
     #  @param values    list of values
     #  @param weights   list of weights (should match length of values)
     #  @result (lower, upper) boundary
     self._reset()
     from ROOT import TEfficiency
     import numpy
     values = numpy.array( values )
     # simply calculate the interval that contains the desired fraction of weights
     self.low, self.up = truncatedInterval( values, self.fraction, weights )
     nTotal = len( values )
     nLow = len( values[values <= self.low] )
     nUp = len( values[values < self.up] )
     # interpret entries below and above as counting experiment
     # for 1-sigma confidence intervals the corresponding percentiles are calculated
     # as an estimate of the uncertainty on the percentile values above
     self.lowLow, self.lowUp, self.upLow, self.upUp = percentiles( values,
                                                                   [ TEfficiency.ClopperPearson( nTotal, nLow, 0.68, False ),
                                                                     TEfficiency.ClopperPearson( nTotal, nLow, 0.68, True ),
                                                                     TEfficiency.ClopperPearson( nTotal, nUp, 0.68, False ),
                                                                     TEfficiency.ClopperPearson( nTotal, nUp, 0.68, True ) ],
                                                                   weights )
     return self.low, self.up
def histsToRoc(hsig, hbg, w_error=False):
    '''Produce ROC curve from 2 input histograms.
    Partly adapted from Giovanni's ttH code.
    '''
    nbins = hsig.GetNbinsX() + 2 - 1 # include under/overflow; remove events not passing selection
    si = [hsig.GetBinContent(i) for i in xrange(nbins+1)]
    bi = [hbg.GetBinContent(i) for i in xrange(nbins+1)]
    del si[1]
    del bi[1]

    if hsig.GetMean() > hbg.GetMean():
        si.reverse()
        bi.reverse()

    sums, sumb = sum(si), sum(bi)
    if sums == 0 or sumb == 0:
        print 'WARNING: Either signal or background histogram empty', sums, sumb
        return None

    for i in xrange(1, nbins):
        si[i] += si[i - 1]
        bi[i] += bi[i - 1]
    fullsi, fullbi = si[:], bi[:]
    si, bi = [], []
    for i in xrange(1, nbins):
        # skip negative weights
        if si and (fullsi[i] < si[-1] or fullbi[i] < bi[-1]):
            continue
        # skip repetitions
        if fullsi[i] != fullsi[i - 1] or fullbi[i] != fullbi[i - 1]:
            si.append(fullsi[i])
            bi.append(fullbi[i])

    if len(si) == 2:
        si = [si[0]]
        bi = [bi[0]]

    bins = len(si)

    if not w_error:
        roc = ROOT.TGraph(bins)
        for i in xrange(bins):
            roc.SetPoint(i, si[i] / sums, bi[i] / sumb)

        return roc

    roc = ROOT.TGraphAsymmErrors(bins)
    for i in xrange(bins):
        interval = 0.683

        e_s_low = si[i] / sums - TEfficiency.ClopperPearson(sums, si[i], interval, False)
        e_s_up = TEfficiency.ClopperPearson(sums, si[i], interval, True) - si[i] / sums
        e_b_low = bi[i] / sumb - TEfficiency.ClopperPearson(sumb, bi[i], interval, False)
        e_b_up = TEfficiency.ClopperPearson(sumb, bi[i], interval, True) - bi[i] / sumb

        roc.SetPoint(i, si[i] / sums, bi[i] / sumb)
        roc.SetPointError(i, e_s_low, e_s_up, e_b_low, e_b_up)

    return roc
示例#3
0
def acceptance(cutlist, labellist):
    basecut = cutlist[0]
    dim = len(cutlist)
    #cutlist.remove(cutlist[:1][0])

    if basecut == 'SSemu':
        basecutstr = '((Lepton_pdgId[0]*Lepton_pdgId[1]==11*13)||(Lepton_pdgId[0]*Lepton_pdgId[1]==-11*-13))'
    elif basecut == 'SSmue':
        basecutstr = '((Lepton_pdgId[0]*Lepton_pdgId[1]==13*11)||(Lepton_pdgId[0]*Lepton_pdgId[1]==-13*-11))'
    elif basecut == 'SSee':
        basecutstr = '((Lepton_pdgId[0]*Lepton_pdgId[1]==11*11)||(Lepton_pdgId[0]*Lepton_pdgId[1]==-11*-11))'
    elif basecut == 'SSmumu':
        basecutstr = '((Lepton_pdgId[0]*Lepton_pdgId[1]==13*13)||(Lepton_pdgId[0]*Lepton_pdgId[1]==-13*-13))'

    cutlist = [basecutstr if x == basecut else x for x in cutlist]

    file = {}
    tree = {}
    effs = {}
    hist = {}
    GrAsym = {}
    yErrorUp = {}
    yErrorDown = {}
    totEve = 0

    #Compute Eff on different triggers
    for i, s in enumerate(signals):
        file[s] = TFile(NTUPLESIG + samples[s]['files'][0] + ".root",
                        "READ")  # Read TFile
        tree[s] = file[s].Get("Events")  # Read TTree
        effs[s] = [0] * (dim + 1)
        yErrorUp[s] = [0] * (dim + 1)
        yErrorDown[s] = [0] * (dim + 1)
        totEve = tree[s].GetEntries(basecutstr)
        GrAsym[s] = TGraphAsymmErrors()
        for j, c in enumerate(cutlist):
            n = tree[s].GetEntries(basecutstr + " && " + cutlist[j])
            effs[s][j] = float(n) / (totEve)
            yErrorUp[s][j] = float(
                TEfficiency.ClopperPearson(totEve, n, 0.68, True) - effs[s][j])
            yErrorDown[s][j] = float(
                effs[s][j] -
                TEfficiency.ClopperPearson(totEve, n, 0.68, False))
            GrAsym[s].SetPoint(j, j + 0.5, effs[s][j])
            # i , exl, exh, eyl, eyh
            GrAsym[s].SetPointError(j, 0, 0, yErrorUp[s][j], yErrorDown[s][j])

        GrAsym[s].SetLineColor(colors[i])
        GrAsym[s].SetLineWidth(3)
        GrAsym[s].SetMarkerStyle(8)
        GrAsym[s].SetMarkerColor(colors[i])

        for k, cs in enumerate(labellist):
            GrAsym[s].GetHistogram().GetXaxis().Set(dim, 0, dim)
            GrAsym[s].GetHistogram().GetXaxis().SetBinLabel(
                k + 1, "%s" % labellist[k])

    leg = TLegend(0.7, 0.9 - 0.035 * len(signals), 0.9, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(1001)
    leg.SetFillColor(0)
    for i, s in enumerate(signals):
        leg.AddEntry(GrAsym[s], s, "l")
        #leg.AddEntry(hist[s], samples[s]['label'][0], "l")

    c1 = TCanvas("c1", "Signals Acceptance", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)

    gStyle.SetOptStat(0)

    GrAsym[signals[0]].SetMaximum(1.3)
    GrAsym[signals[0]].SetMinimum(0.)

    for i, s in enumerate(signals):
        if i == 0:
            GrAsym[s].GetHistogram().GetXaxis().SetTitle("Trigg")
            GrAsym[s].GetHistogram().GetYaxis().SetTitle("Signal Acceptance")
            #hist[s].GetYaxis().SetRangeUser(0., 1.)
        GrAsym[s].Draw("pa" if i == 0 else "SAME p")
    leg.Draw()
    drawCMS(LUMI, "Work In Progress")
    drawRegion(basecut)

    if not os.path.exists('plots/Signal/Acceptance/'):
        os.system('mkdir -p plots/Signal/Acceptance/')
    c1.Print("plots/Signal/Acceptance/Acc_" + basecut + ".png")
    c1.Print("plots/Signal/Acceptance/Acc_" + basecut + ".pdf")

    #if not options.runBash: raw_input("Press Enter to continue...")
    pass
示例#4
0
def significanceSB(cutlist, labellist):

    basecut = labellist[0]
    dim = len(cutlist)
    significance = [0] * (dim + 1)

    file = {}
    tree = {}
    effs = {}
    hist = {}
    GrAsym = {}
    yErrorUp = {}
    yErrorDown = {}
    totEve = 0
    GrAsym = TGraphAsymmErrors()
    cuts = ""

    for j, c in enumerate(cutlist):
        s = 0.
        b = 0.
        cuts += cutlist[0] if j == 0 else " && " + cutlist[j]
        print "cuts = ", cuts
        for num1, v in enumerate(signals):
            #print "Signal = ", v
            for num2, filename in enumerate(samples[v]['files']):
                #print "Signal rootfile read = ",  filename
                file[filename] = TFile(NTUPLESIG + filename + ".root",
                                       "READ")  # Read TFile
                tree[filename] = file[filename].Get("Events")  # Read TTree
                nevents = float(sample[filename]['nevents'])
                xs = float(sample[filename]['xsec']) * float(
                    sample[filename]['kfactor'])
                LumiMC = nevents / xs
                Weight = float(LUMI) / float(LumiMC)

                sig_entries = tree[filename].GetEntries(cuts)
                #print "s = ", float(sig_entries) * float(Weight)
                s += float(sig_entries) * float(Weight)
            print "TOT SIG = ", s

        for num1, k in enumerate(back):
            #print "backgrounds = ", k
            for num2, filename in enumerate(samples[k]['files']):
                #print "backgrounds rootfile read = ",  filename
                file[filename] = TFile(NTUPLEDIR + filename + ".root",
                                       "READ")  # Read TFile
                tree[filename] = file[filename].Get("Events")  # Read TTree
                nevents = float(sample[filename]['nevents'])
                xs = float(sample[filename]['xsec']) * float(
                    sample[filename]['kfactor'])
                LumiMC = nevents / xs
                Weight = float(LUMI) / float(LumiMC)

                bkg_entries = tree[filename].GetEntries(cuts)
                #print "b = ", float(bkg_entries) * float(Weight)
                b += float(bkg_entries) * float(Weight)
            print "TOT BKG = ", b

        ##End of cutlist
        #COMPUTE
        #print "s = ", s
        #print "b = ", b
        #print "sqrt(b) = ",  math.sqrt(b)
        #print "significance = ",  float(s/math.sqrt(b))
        significance[j] = float(s / math.sqrt(b))
        yErrorUp[j] = float(
            TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, True) -
            significance[j])
        yErrorDown[j] = float(
            significance[j] -
            TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, False))
        GrAsym.SetPoint(j, j + 0.5, significance[j])
        GrAsym.SetPointError(j, 0, 0, yErrorUp[j], yErrorDown[j])

    for k, cs in enumerate(labellist):
        GrAsym.GetHistogram().GetXaxis().Set(dim, 0, dim)
        GrAsym.GetHistogram().GetXaxis().SetBinLabel(k + 1,
                                                     "%s" % labellist[k])

    GrAsym.SetLineColor(2)
    GrAsym.SetLineWidth(3)
    GrAsym.SetMarkerStyle(8)
    GrAsym.SetMarkerColor(2)

    c1 = TCanvas("c1", "Signals Acceptance", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)

    gStyle.SetOptStat(0)

    #GrAsym.SetMaximum(1.3)
    #GrAsym.SetMinimum(0.)

    GrAsym.GetHistogram().GetXaxis().SetTitle("")
    GrAsym.GetHistogram().GetYaxis().SetTitle("Significance (S/#sqrt{B})")

    GrAsym.Draw("pa")
    drawCMS(LUMI, "Work In Progress")
    drawRegion(basecut)

    if not os.path.exists('plots/Signal/Significance/'):
        os.system('mkdir -p plots/Signal/Significance/')
    c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".png")
    c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".pdf")
    #if not options.runBash: raw_input("Press Enter to continue...")
    pass
def Plot1DEfficiency(num, den, plotname, topTitle, xAxisTitle, xAxisRangeLow,
                     xAxisRangeHigh):

    nbins = num.GetXaxis().GetNbins()
    x = list()
    y = list()
    xErrLow = list()
    xErrHigh = list()
    yErrLow = list()
    yErrHigh = list()

    for b in range(1, nbins):

        xtemp = num.GetXaxis().GetBinCenter(b + 1)
        xerrlow = num.GetXaxis().GetBinCenter(
            b + 1) - num.GetXaxis().GetBinLowEdge(b + 1)
        xerrhigh = num.GetXaxis().GetBinUpEdge(
            b + 1) - num.GetXaxis().GetBinCenter(b + 1)

        ratio = 0
        errLow = 0
        errHigh = 0

        n1 = int(num.GetBinContent(b + 1))
        n2 = int(den.GetBinContent(b + 1))
        print "numerator: " + str(n1) + " and denominator: " + str(n2)
        if (n1 > n2):
            n1 = n2

        if (n2 > 0):
            ratio = float(n1) / float(n2)
            if (ratio > 1):
                ratio = 1
            errLow = ratio - TEfficiency.ClopperPearson(
                n2, n1, 0.68269, False)
            errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio

        print " done bin " + str(
            b) + " " + str(xtemp) + " : " + str(n1) + "(" + str(
                num.GetBinContent(b + 1)) + ")" + " / " + str(n2) + "(" + str(
                    den.GetBinContent(b + 1)) + ")" + " = " + str(
                        ratio) + " " + str(errLow) + " " + str(errHigh)
        ytemp = ratio
        yerrlowtemp = errLow
        yerrhightemp = errHigh

        print "x: " + str(xtemp) + " and y: " + str(ytemp)

        x.append(xtemp)
        y.append(ytemp)
        xErrLow.append(xerrlow)
        xErrHigh.append(xerrhigh)
        yErrLow.append(yerrlowtemp)
        yErrHigh.append(yerrhightemp)

    c = TCanvas("cv", "cv", 800, 800)
    c.SetLeftMargin(0.12)

    #must convert list into array for TGraphAsymmErrors to work
    xArr = array.array('f', x)
    yArr = array.array('f', y)
    xErrLowArr = array.array('f', xErrLow)
    xErrHighArr = array.array('f', xErrHigh)
    yErrLowArr = array.array('f', yErrLow)
    yErrHighArr = array.array('f', yErrHigh)

    effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr,
                                 yErrLowArr, yErrHighArr)
    effGraph.Draw("APE")
    effGraph.SetTitle("")
    effGraph.GetXaxis().SetTitle(xAxisTitle)
    effGraph.GetXaxis().SetTitleSize(0.05)
    effGraph.GetXaxis().SetTitleOffset(0.90)
    effGraph.GetXaxis().SetLabelSize(0.03)
    effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh)
    effGraph.GetYaxis().SetTitle("Efficiency")
    effGraph.GetYaxis().SetTitleSize(0.05)
    effGraph.GetYaxis().SetTitleOffset(1.05)
    effGraph.GetYaxis().SetLabelSize(0.03)

    title = TLatex()
    title.SetTextSize(0.05)
    title.DrawLatexNDC(.2, .93, topTitle)
    c.Update()
    c.SaveAs(plotname + ".gif")
def Plot1DEfficiencyWithBkgSubtraction(tree, num, den, axis, pixel, plotname,
                                       topTitle, xAxisTitle, xAxisRangeLow,
                                       xAxisRangeHigh):

    #make amp histogram
    c = TCanvas("c", "c", 800, 800)

    #Each pixel has slightly different time distribution and efficiency of time window cut differs a bit
    #We derive corresponding efficiency corrections for each pixel
    timeWindowCutEfficiency = 1.0
    if (pixel == "5_3"):
        timeWindowCutEfficiency = 0.989
    if (pixel == "5_4"):
        timeWindowCutEfficiency = 0.9478
    if (pixel == "5_10"):
        timeWindowCutEfficiency = 0.9643

    #ampHist = TH1F("ampHist",";Amplitude [mV]; Number of Events", 25,0,50)
    #tree.Draw("amp[3]>>ampHist"," x_dut[2] > 19.6 && x_dut[2] < 19.7 && y_dut[2] > 23.5 && y_dut[2] < 24.0 && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16)")

    nbins = num.GetXaxis().GetNbins()
    x = list()
    y = list()
    xErrLow = list()
    xErrHigh = list()
    yErrLow = list()
    yErrHigh = list()

    for b in range(1, nbins):

        xtemp = num.GetXaxis().GetBinCenter(b + 1)
        xerrlow = num.GetXaxis().GetBinCenter(
            b + 1) - num.GetXaxis().GetBinLowEdge(b + 1)
        xerrhigh = num.GetXaxis().GetBinUpEdge(
            b + 1) - num.GetXaxis().GetBinCenter(b + 1)

        #Noise templates:
        #Pixel 5,3 : amp <= 6mV gives 0.4417 of the total and has 0 signal contamination
        #Pixel 5,4 : amp <= 10mV gives 0.0404 of the total and has 0 signal contamination
        #Pixel 5,10 : amp < gives 0. of the total and has 0 signal contamination
        #We will assume that bins 0+1+2 (0-6mV) do not contain ANY signal.
        #We count the number of events in those bins and divide by 0.4417 to get
        #the total number of noise events. We subtract those from the numerator.

        #Noise template is made from this data (outside of sensor region AND outside of time window):
        #/eos/uscms/store/user/cmstestbeam/2019_04_April_CMSTiming/KeySightScope/RecoData/TimingDAQRECO/RecoWithTracks/v6_CACTUSSkim/Completed/Data_CACTUSAnalog_Pixel5_3_16216-16263.root
        #pulse->Draw("amp[3]>>ampHist(25,0,50)","!(x_dut[2] > 19.4 && x_dut[2] < 20.6 && y_dut[2] > 23.4 && y_dut[2] < 24.1) && !((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16)")

        noiseSelection = ""
        noiseSelectionCRFraction = 1
        xPositionSelection = ""
        yPositionSelection = ""
        if (pixel == "5_3"):
            noiseSelection = " && amp[3] <= 6"
            noiseSelectionCRFraction = 0.4417
            xPositionSelection = " && x_dut[2] > 19.5 && x_dut[2] < 20.5 "
            yPositionSelection = " && y_dut[2] > 23.5 && y_dut[2] < 24.0 "
        if (pixel == "5_4"):
            noiseSelection = " && amp[3] <= 14"
            noiseSelectionCRFraction = 0.4053
            xPositionSelection = " && x_dut[2] > 18.5 && x_dut[2] < 19.5 "
            yPositionSelection = " && y_dut[2] > 23.5 && y_dut[2] < 24.0 "
        if (pixel == "5_10"):
            noiseSelection = " && amp[3] <= 13"
            noiseSelectionCRFraction = 0.3802
            xPositionSelection = " && x_dut[2] > 19.5 && x_dut[2] < 20.5 "
            yPositionSelection = " && y_dut[2] > 23.0 && y_dut[2] < 23.5 "

        print "noise selection = " + noiseSelection + " " + str(
            noiseSelectionCRFraction)

        positionSelectionString = ""
        if (axis == "x"):
            positionSelectionString = " && x_dut[2] > " + str(
                num.GetXaxis().GetBinLowEdge(b + 1)) + " && x_dut[2] < " + str(
                    num.GetXaxis().GetBinUpEdge(b + 1)) + yPositionSelection
        if (axis == "y"):
            positionSelectionString = xPositionSelection + " && y_dut[2] > " + str(
                num.GetXaxis().GetBinLowEdge(b + 1)) + " && y_dut[2] < " + str(
                    num.GetXaxis().GetBinUpEdge(b + 1)) + " "

        print "numerator: " + "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16)"

        ampHist = TH1F("ampHist" + "_" + str(b),
                       ";Amplitude [mV]; Number of Events", 25, 0, 50)
        denominatorCount = tree.GetEntries(
            "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " +
            positionSelectionString + " ")
        tmpNumeratorTotalCount = tree.GetEntries(
            "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " +
            positionSelectionString +
            " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16)"
        )
        tmpNumeratorNoiseControlRegionCount = tree.GetEntries(
            "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " +
            positionSelectionString +
            " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16) "
            + noiseSelection)
        tmpNumeratorSignalCount = tmpNumeratorTotalCount - tmpNumeratorNoiseControlRegionCount / noiseSelectionCRFraction

        print "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16) " + noiseSelection

        ratio = 0
        errLow = 0
        errHigh = 0

        n1 = int(tmpNumeratorSignalCount)
        n2 = int(denominatorCount)
        print "numerator: " + str(n1) + " and denominator: " + str(n2)
        if (n1 > n2):
            n1 = n2

        if (n2 > 0):
            ratio = float(n1) / float(n2)
            if (ratio > 1):
                ratio = 1
            errLow = ratio - TEfficiency.ClopperPearson(
                n2, n1, 0.68269, False)
            errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio

        print " done bin " + str(b) + " : " + str(
            num.GetXaxis().GetBinLowEdge(b + 1)) + " - " + str(
                num.GetXaxis().GetBinUpEdge(b + 1))
        print " num = " + str(n1) + " = " + str(
            tmpNumeratorTotalCount) + " - " + str(
                tmpNumeratorNoiseControlRegionCount) + " / " + str(
                    noiseSelectionCRFraction) + " | den = " + str(n2)
        print "ratio = " + str(ratio) + " " + str(errLow) + " " + str(errHigh)
        ytemp = ratio / timeWindowCutEfficiency  #here we correct for the time window cut inefficiency
        yerrlowtemp = errLow
        yerrhightemp = errHigh

        print "x: " + str(xtemp) + " and y: " + str(ytemp)

        x.append(xtemp)
        y.append(ytemp)
        xErrLow.append(xerrlow)
        xErrHigh.append(xerrhigh)
        yErrLow.append(yerrlowtemp)
        yErrHigh.append(yerrhightemp)

    c = TCanvas("cv", "cv", 800, 800)
    c.SetLeftMargin(0.12)

    #must convert list into array for TGraphAsymmErrors to work
    xArr = array.array('f', x)
    yArr = array.array('f', y)
    xErrLowArr = array.array('f', xErrLow)
    xErrHighArr = array.array('f', xErrHigh)
    yErrLowArr = array.array('f', yErrLow)
    yErrHighArr = array.array('f', yErrHigh)

    effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr,
                                 yErrLowArr, yErrHighArr)
    effGraph.Draw("APE")
    effGraph.SetTitle("")
    effGraph.GetXaxis().SetTitle(xAxisTitle)
    effGraph.GetXaxis().SetTitleSize(0.05)
    effGraph.GetXaxis().SetTitleOffset(0.90)
    effGraph.GetXaxis().SetLabelSize(0.03)
    effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh)
    effGraph.GetYaxis().SetTitle("Efficiency")
    effGraph.GetYaxis().SetTitleSize(0.05)
    effGraph.GetYaxis().SetTitleOffset(1.05)
    effGraph.GetYaxis().SetLabelSize(0.03)

    title = TLatex()
    title.SetTextSize(0.05)
    title.DrawLatexNDC(.2, .93, topTitle)
    c.Update()
    c.SaveAs(plotname + ".gif")
def Plot1DEfficiencyWithFit(tree, plotname, topTitle, xAxisTitle,
                            xAxisRangeLow, xAxisRangeHigh):

    #make amp histogram
    c = TCanvas("c", "c", 800, 800)

    ampHist = TH1F("ampHist", ";Amplitude [mV]; Number of Events", 25, 0, 50)
    tree.Draw(
        "amp[3]>>ampHist",
        " x_dut[2] > 19.6 && x_dut[2] < 19.7 && y_dut[2] > 23.5 && y_dut[2] < 24.0 && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9  < 16)"
    )

    # create function for fitting
    fitFunction = TF1("NoisePlusLandauGaus", NoisePlusLandauGaus, 0, 50, 5)

    fitFunction.SetParameters(10, 0.95, 20.0, 2.5, 3.0)
    fitFunction.SetParNames("a", "f", "mpv", "sigmaLandau", "sigmaGaus")
    #fitFunction.SetParLimits(0,   -1,   -4)
    #fitFunction.SetParLimits(1, 0.01,  0.2)
    #fitFunction.SetParLimits(2,    0,    2)
    #fitFunction.SetParLimits(3,    0, 1000)

    ampHist.Fit("NoisePlusLandauGaus")

    c.SaveAs("fit.gif")

    return

    nbins = num.GetXaxis().GetNbins()
    x = list()
    y = list()
    xErrLow = list()
    xErrHigh = list()
    yErrLow = list()
    yErrHigh = list()

    for b in range(1, nbins):

        xtemp = num.GetXaxis().GetBinCenter(b + 1)
        xerrlow = num.GetXaxis().GetBinCenter(
            b + 1) - num.GetXaxis().GetBinLowEdge(b + 1)
        xerrhigh = num.GetXaxis().GetBinUpEdge(
            b + 1) - num.GetXaxis().GetBinCenter(b + 1)

        ratio = 0
        errLow = 0
        errHigh = 0

        n1 = int(num.GetBinContent(b + 1))
        n2 = int(den.GetBinContent(b + 1))
        print "numerator: " + str(n1) + " and denominator: " + str(n2)
        if (n1 > n2):
            n1 = n2

        if (n2 > 0):
            ratio = float(n1) / float(n2)
            if (ratio > 1):
                ratio = 1
            errLow = ratio - TEfficiency.ClopperPearson(
                n2, n1, 0.68269, False)
            errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio

        print " done bin " + str(
            b) + " " + str(xtemp) + " : " + str(n1) + "(" + str(
                num.GetBinContent(b + 1)) + ")" + " / " + str(n2) + "(" + str(
                    den.GetBinContent(b + 1)) + ")" + " = " + str(
                        ratio) + " " + str(errLow) + " " + str(errHigh)
        ytemp = ratio
        yerrlowtemp = errLow
        yerrhightemp = errHigh

        print "x: " + str(xtemp) + " and y: " + str(ytemp)

        x.append(xtemp)
        y.append(ytemp)
        xErrLow.append(xerrlow)
        xErrHigh.append(xerrhigh)
        yErrLow.append(yerrlowtemp)
        yErrHigh.append(yerrhightemp)

    c = TCanvas("cv", "cv", 800, 800)
    c.SetLeftMargin(0.12)

    #must convert list into array for TGraphAsymmErrors to work
    xArr = array.array('f', x)
    yArr = array.array('f', y)
    xErrLowArr = array.array('f', xErrLow)
    xErrHighArr = array.array('f', xErrHigh)
    yErrLowArr = array.array('f', yErrLow)
    yErrHighArr = array.array('f', yErrHigh)

    effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr,
                                 yErrLowArr, yErrHighArr)
    effGraph.Draw("APE")
    effGraph.SetTitle("")
    effGraph.GetXaxis().SetTitle(xAxisTitle)
    effGraph.GetXaxis().SetTitleSize(0.05)
    effGraph.GetXaxis().SetTitleOffset(0.90)
    effGraph.GetXaxis().SetLabelSize(0.03)
    effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh)
    effGraph.GetYaxis().SetTitle("Efficiency")
    effGraph.GetYaxis().SetTitleSize(0.05)
    effGraph.GetYaxis().SetTitleOffset(1.05)
    effGraph.GetYaxis().SetLabelSize(0.03)

    title = TLatex()
    title.SetTextSize(0.05)
    title.DrawLatexNDC(.2, .93, topTitle)
    c.Update()
    c.SaveAs(plotname + ".gif")
def getEffandError(num, den):
    eff = 0 if den == 0 else num / den
    hi = TEfficiency.ClopperPearson(int(den), int(num), sigma, True)
    lo = TEfficiency.ClopperPearson(int(den), int(num), sigma, False)
    return (eff, (eff - lo) / eff, (hi - eff) / eff)
示例#9
0
    wvl = 4.135667516e-15 * 299792458.0 / e * 1e3
    wvl_min = min(wvl)
    wvl_max = max(wvl)
    nbins = int((wvl_max - wvl_min) / args.bin_width)
    eff = TEfficiency("%d-pass" % i, "%d-eff" % i, nbins, wvl_min, wvl_max)
    eff.SetUseWeightedEvents()
    eff.SetStatisticOption(TEfficiency.kFNormal)
    for wvli, ni in zip(wvl, n):
        eff.FillWeighted(True, ni, wvli)
        eff.FillWeighted(False, n_particles - ni, wvli)
    x = np.array(
        [eff.GetTotalHistogram().GetBinCenter(i) for i in xrange(nbins)])
    y = np.array([eff.GetEfficiency(i) for i in xrange(nbins)]) * 100.0
    yerr_low = np.array([
        eff.ClopperPearson(int(n_particles),
                           int(eff.GetEfficiency(i) * n_particles), 0.68,
                           False) for i in xrange(nbins)
    ]) * 100.0
    yerr_up = np.array([
        eff.ClopperPearson(int(n_particles),
                           int(eff.GetEfficiency(i) * n_particles), 0.68, True)
        for i in xrange(nbins)
    ]) * 100.0
    # Plot bin statistics.
    label = ("%s +%.1f V" % (name, v_ov * 1e6))
    # Plot PDE
    ax.errorbar(x, y, yerr=(y - yerr_low, yerr_up - y), fmt=".", label=label)

# Set legend titles.
ax.set_xlabel("wavelength / nm")
ax.set_ylabel("photon detection efficiency / %")
示例#10
0
    def makeCombinedEtaPlot(self, tight=False):
        hist = self.makeL1TimeVsEtaPlot(('tight_' if tight else '') +
                                        'dtOnly_bxidVsEta')[2]
        countsInL1 = []
        for x in np.arange(-.95, 1.05, 0.1):
            totalCounter = 0
            zeroCount = 0
            for y in range(-2, 3):
                totalCounter += hist.GetBinContent(hist.FindBin(x, y))
                if y == 0:
                    zeroCount = hist.GetBinContent(hist.FindBin(x, y))
            countsInL1.append({
                'total': totalCounter,
                'zero': zeroCount,
                'eta': x
            })

        #Graph for results
        graph1 = TEfficiency(hist.GetName(), "", 8, -9.195, -.5)
        graph2 = TEfficiency(hist.GetName(), "", 8, .5, 9.195)

        for item in countsInL1:
            if item['total'] == 0:
                continue
            print item['total'], item['zero'], item['eta']
            if item['eta'] < 0:
                graph1.SetTotalEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph1.SetPassedEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['zero']))
            else:
                graph2.SetTotalEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph2.SetPassedEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['zero']))

        histHo = None
        if tight:
            histHo = self.plotTightHoTimeVsEta()[3][1]
        else:
            histHo = self.plotHoTimeVsEta()[3][1]

        histHo.SetTitle(('Tight ' if tight else '') + 'Unmatched DT + HO')

        canvas = TCanvas(
            'combinedPlot' + ('Tight ' if tight else '') + hist.GetName(),
            'combinedPlot')
        canvas.cd().SetTopMargin(.15)
        histHo.Draw('ap')
        canvas.Update()
        canvas.cd().SetTicks(0, 0)

        histHo.SetMarkerStyle(2)
        histHo.SetLineColor(colorRwthDarkBlue)
        histHo.SetMarkerColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetRangeUser(-12, 12)
        histHo.GetPaintedGraph().GetXaxis().SetLabelColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetTitleColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetAxisColor(colorRwthDarkBlue)
        yMax = gPad.GetFrame().GetY2()
        yMin = gPad.GetFrame().GetY1()

        #Print average Fraction excluding iEta +/-2
        x = Double(0)
        y = Double(0)
        mean = 0
        var = 0
        for i in range(0, histHo.GetPaintedGraph().GetN()):
            histHo.GetPaintedGraph().GetPoint(i, x, y)
            if abs(x) == 2:
                continue
            mean += y
            var += histHo.GetPaintedGraph().GetErrorY(
                i) * histHo.GetPaintedGraph().GetErrorY(i)

        mean /= histHo.GetPaintedGraph().GetN() - 2
        sigma = sqrt(var / (histHo.GetPaintedGraph().GetN() - 2))

        self.debug(
            "Average fraction excluding iEta +/- 2 %s: %5.2f%% +/- %5.2f%%" %
            ('[Tight]' if tight else '', mean * 100, sigma * 100))

        nTotal = 0
        nPassed = 0
        for item in countsInL1:
            if fabs(item['eta']) == 2 or fabs(item['eta'] == 0):
                continue
            nTotal += item['total']
            nPassed += item['zero']

        #Print again with ClopperPearson uncertainty, the counts are for L1!!!
        mean = nPassed / nTotal * 100
        sigmaPlus = TEfficiency.ClopperPearson(int(nTotal), int(nPassed), .68,
                                               1) * 100 - mean
        sigmaMinus = mean - TEfficiency.ClopperPearson(
            int(nTotal), int(nPassed), .68, 0) * 100
        #self.debug("Average fraction excluding iEta +/- 2 %s with Clop.Pear.: %5.2f%% +%5.2f%% -%5.2f%%"
        #		% ('[Tight]' if tight else '',mean,sigmaPlus,sigmaMinus))

        #Left axis part
        f1 = TF1("f1", "x", -0.87, 0)
        A1 = TGaxis(-10, yMax, -0.5, yMax, "f1", 010, "-")
        A1.SetLineColor(colorRwthRot)
        A1.SetLabelColor(colorRwthRot)
        A1.Draw()

        #Right axis part
        f2 = TF1("f2", "x", 0, 0.87)
        A2 = TGaxis(0.5, yMax, 10, yMax, "f2", 010, "-")
        A2.SetLineColor(colorRwthRot)
        A2.SetLabelColor(colorRwthRot)
        A2.Draw()

        #Box for shading out 0
        box = TBox(-.5, yMin, 0.5, yMax)
        box.SetLineColor(colorRwthDarkGray)
        box.SetFillColor(colorRwthDarkGray)
        box.SetFillStyle(3013)
        box.Draw('same')

        #Left L1 eta
        graph1.SetMarkerColor(colorRwthRot)
        graph1.SetLineColor(colorRwthRot)
        graph1.SetMarkerStyle(20)
        graph1.Draw('same,p')

        #Right L1Eta
        graph2.SetMarkerColor(colorRwthRot)
        graph2.SetLineColor(colorRwthRot)
        graph2.SetMarkerStyle(20)
        graph2.Draw('same,p')

        #Label for extra axis
        axisLabel = TPaveText(0.83, 0.85, 0.89, 0.9, "NDC")
        axisLabel.AddText('#eta_{L1}')
        axisLabel.SetBorderSize(0)
        axisLabel.SetFillStyle(0)
        axisLabel.SetTextColor(colorRwthRot)
        axisLabel.SetTextSize(0.05)
        axisLabel.Draw()

        #Legend
        legend = getLegend(x1=0.1, y1=0.1, x2=0.4, y2=.35)
        legend.AddEntry(histHo, 'HO #in #pm12.5 ns', 'pe')
        legend.AddEntry(graph1, ('Tight ' if tight else '') + 'L1 BXID = 0',
                        'pe')
        legend.Draw()

        canvas.Update()
        self.storeCanvas(canvas,
                         "combinedFractionL1AndHo" +
                         ('Tight' if tight else ''),
                         drawMark=False)

        return histHo, graph1, canvas, A1, f1, A2, f2, box, graph2, axisLabel, legend