Exemple #1
0
	def DrawHistogram( self, h, _LowerEdge, _UpperEdge ):
		CanvasName = h.GetName()
		CanvasName.replace("h_", "c_")
		c = TCanvas(CanvasName+"M%.0lfto%.0lf"%(_LowerEdge, _UpperEdge), "", 800, 800)
		c.cd()
		if (_UpperEdge - _LowerEdge) > 20:
			c.SetLogy()
		c.SetTopMargin(0.03)
		c.SetLeftMargin(0.13)
		c.SetRightMargin(0.05)
		c.SetBottomMargin(0.1)

		if _UpperEdge > 1000:
			c.SetLogx()

		h.Draw()
		h.SetStats(0)
		h.SetMarkerColor(2)
		h.SetLineColor(2) # -- red -- #
		h.SetFillColorAlpha(0, 0) # -- white with 100% transparency -- #
		h.GetXaxis().SetRangeUser( _LowerEdge, _UpperEdge )
		h.GetXaxis().SetMoreLogLabels()
		h.GetXaxis().SetNoExponent()
		h.GetYaxis().SetTitleOffset(1.3)
		h.SetXTitle("m(#mu#mu) [GeV]")
		h.SetYTitle("d#sigma/dm [pb/GeV]")

		latex = TLatex()
		latex.SetTextSize(0.028);
		# if _LowerEdge == 15 and _UpperEdge==3000:
		latex.DrawLatexNDC(0.50, 0.85, "Z/#gamma* #rightarrow #mu#mu @ E_{CM} = 8 TeV")
		latex.DrawLatexNDC(0.50, 0.80, "FEWZ (%s)" % (self.PDF) )
		latex.DrawLatexNDC(0.50, 0.77, "QCD@NNLO, EWK@NLO")

		c.SaveAs(".pdf")
Exemple #2
0
 def draw(self, canvas=None):
     if canvas is None:
         canvas = self
     canvas.Divide(1, 2)
     canvas.cd(1).SetMargin(0.1, 0.1, 0.05, 0.2)
     self._rad.Draw()
     canvas.cd(2).SetMargin(0.1, 0.1, 0.2, 0.05)
     self._ang.Draw()
     canvas.cd()
     canvas.Update()
     for c, axis in [('r', self._rad.GetXaxis()),
                     ('y1', self._rad.GetYaxis()),
                     ('p', self._ang.GetXaxis()),
                     ('y2', self._ang.GetYaxis())]:
         axis.SetLabelSize(0.05)
         axis.SetTitleSize(0.07)
         axis.SetLabelOffset(0.01)
         rng = getattr(self, '_{0}range'.format(c))
         if rng is not None:
             axis.SetRangeUser(rng[0], rng[1])
         ttl = getattr(self, '_{0}title'.format(c))
         if c.startswith('y') and ttl is not None:
             axis.SetTitle(ttl)
         if c.startswith('y'):
             axis.SetTitleOffset(0.6)
             axis.SetNdivisions(505)
     canvas.cd()
     self._pad = TPad('newpad', '', 0, 0, 1, 1)
     self._pad.SetFillStyle(4000)
     self._pad.Draw()
     self._pad.cd()
     if self._drawCMS:
         self.draw_cms()
     text = TLatex()
     text.SetNDC()
     text.SetTextFont(42)
     text.SetTextSize(0.035)
     text.SetTextAlign(13)
     text.SetTextAngle(90)
     if self._rtitle is not None:
         text.DrawLatexNDC(0.905, 0.54, self._rtitle)
     if self._ptitle is not None:
         text.DrawLatexNDC(0.905, 0.115, self._ptitle)
     for obj in self._container_draw:
         obj.Draw('SAME')
     for c in (canvas.cd(1), canvas.cd(2), canvas):
         c.Modified()
         c.Update()
     canvas.cd()
    def show_sample(self,
                    fnameP='/data/Samples/TMSPlane/Dec26/sample_{0:d}.adc',
                    Ns=10,
                    ich=8):
        from ROOT import TGraph, gPad, TLatex
        s1 = SigProc(nSamples=16384, nAdcCh=20, nSdmCh=19, adcSdmCycRatio=5)
        data1 = s1.generate_adcDataBuf()
        data2 = s1.generate_sdmDataBuf()

        data3 = ((s1.ANALYSIS_WAVEFORM_BASE_TYPE * s1.nSamples) * Ns)()
        dataList = []
        for i in range(Ns):
            fname = fnameP.format(i)
            s1.read_data([fname, ''], data1, data2)
            x = array.array('f', range(s1.nSamples))
            #             s1.filters_trapezoidal(data1[ich], data3[i], [100,100,200,-1])
            s1.filters_trapezoidal(data1[ich], data3[i],
                                   [100, 100, 100, 0.000722])
            g1 = TGraph(s1.nSamples, x, data3[i])
            #             g1 = TGraph(s1.nSamples, x, data1[ich])

            opt = 'AP' if i == 0 else "PSame"
            g1.Draw(opt + ' PLC PMC')
            dataList.append(g1)

        lt = TLatex()
        lt.DrawLatexNDC(0.2, 0.8, "Chan={0:d}".format(ich))
        gPad.Update()
        waitRootCmdX()
def Plot2DEfficiency(num, den, plotname, topTitle, xAxisTitle, xAxisRangeLow,
                     xAxisRangeHigh, yAxisTitle, yAxisRangeLow, yAxisRangeHigh,
                     effMin, effMax):

    c = TCanvas("cv", "cv", 800, 800)

    ratio = num.Clone("ratio")
    ratio.Divide(den)

    ratio.Draw("colz")
    ratio.SetMaximum(effMax)
    ratio.SetMinimum(effMin)
    ratio.GetZaxis().SetTitle("Efficiency")
    ratio.GetZaxis().SetTitleSize(0.05)
    ratio.GetZaxis().SetTitleOffset(1.25)
    ratio.Draw("colz")
    ratio.SetStats(0)
    ratio.GetXaxis().SetTitle(xAxisTitle)
    ratio.GetXaxis().SetTitleSize(0.05)
    ratio.GetXaxis().SetTitleOffset(0.90)
    ratio.GetXaxis().SetLabelSize(0.03)
    ratio.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh)
    ratio.GetYaxis().SetTitle(yAxisTitle)
    ratio.GetYaxis().SetTitleSize(0.05)
    ratio.GetYaxis().SetTitleOffset(1.05)
    ratio.GetYaxis().SetLabelSize(0.03)
    ratio.GetYaxis().SetRangeUser(yAxisRangeLow, yAxisRangeHigh)
    c.SetRightMargin(0.18)
    c.SetLeftMargin(0.12)

    title = TLatex()
    title.SetTextSize(0.05)
    #title.SetTextAlign(13);
    title.DrawLatexNDC(.2, .93, topTitle)
    c.SaveAs(plotname + ".gif")
Exemple #5
0
def makeROC(fpr, tpr, thresholds, AUC, outfile, signal_label,
            background_label):

    c = TCanvas("c", "c", 700, 600)
    gPad.SetMargin(0.15, 0.07, 0.15, 0.05)
    gPad.SetLogy(0)
    gPad.SetGrid(1, 1)
    gStyle.SetGridColor(15)

    roc = TGraph(len(fpr), tpr, fpr)

    roc.SetLineColor(2)
    roc.SetLineWidth(2)
    roc.SetTitle(";Signal efficiency (%s); Background efficiency (%s)" %
                 (signal_label, background_label))
    roc.GetXaxis().SetTitleOffset(1.4)
    roc.GetXaxis().SetTitleSize(0.045)
    roc.GetYaxis().SetTitleOffset(1.4)
    roc.GetYaxis().SetTitleSize(0.045)
    roc.GetXaxis().SetRangeUser(0, 1)
    roc.GetYaxis().SetRangeUser(0.000, 1)
    roc.Draw("AL")

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextSize(0.05)
    latex.DrawLatexNDC(0.2, 0.88, 'AUC = %.3f' % AUC)

    c.SaveAs(outfile)
def drawText(x, y, t, isNDC=False):
    text = TLatex()
    text.SetTextColor(1)
    text.SetTextFont(42)
    text.SetTextAlign(23)
    text.SetTextSize(0.04)
    if isNDC: text.DrawLatexNDC(x, y, t)
    else: text.DrawLatex(x, y, t)
    text.Draw()
    return text
Exemple #7
0
def checkStablibity(isensor=8):
    qt1 = QuickTuner(mode=0)
    cd1 = qt1.sensorConfig.cd
    cd1.readBackPars(isensor)

    dataX = []
    for i in range(10):
        time.sleep(1)
        cd1.fetch()
        dataX.append(cd1.adcData[isensor][:])

    max1 = -1
    min1 = 999
    ndata = len(dataX[0])
    gr0 = None
    option = 'AL'
    icolor = 1
    grs = []
    for x in dataX:
        max2 = max(x)
        if max2>max1: max1 = max2
        min2 = min(x)
        if min2<min1: min1 = min2

        gr1 = TGraph(ndata, array('d',[i*0.2*0.001 for i in range(ndata)]), array('d', x))
        gr1.Draw(option)
        if gr0 == None:
            gr0 = gr1
            option = 'L'
        gr1.SetLineColor(icolor)
        icolor += 1
        grs.append(gr1)
#         waitRootCmdX()

    h1 = gr0.GetHistogram()
    print min1, max1
    h1.GetYaxis().SetRangeUser(min1,max1)
    h1.GetYaxis().SetTitle("V")
    h1.GetXaxis().SetTitle("t [ms]")
    h1.Draw("axissame")

    lt = TLatex()
    lt.DrawLatexNDC(0.2,0.92, "C{0:d}: ".format(isensor)+' '.join(['{0:.3f}'.format(x) for x in cd1.inputVs]))

    waitRootCmdX()
    print len(dataX), len(grs)
Exemple #8
0
 def draw_study_label(x=0.5, y=0.9):
     latex = TLatex()
     latex.SetTextAlign(13)
     drawn.append(latex.DrawLatexNDC(x, y, " ".join(study_label)))
Exemple #9
0
def main(reader_name,
         tags,
         lut_path,
         ptmin,
         ptmax,
         ymin=None,
         ymax=None,
         tag_name=None,
         logx=False,
         logy=False,
         leg_pos=[0.74, 0.2, 0.90, 0.4],
         particles=None,
         eta=0,
         dnch_deta=100,
         rmin=None,
         add_eta_label=True,
         add_alice3_label=True,
         save=None,
         background=False,
         use_p_over_z=True,
         aod=None,
         study_label="ALICE 3 study"):
    gROOT.LoadMacro(reader_name)
    gROOT.LoadMacro("style.C")
    reader_name = reader_name.split(".")[-2]
    reader = getattr(__import__('ROOT', fromlist=[reader_name]), reader_name)
    style = getattr(__import__('ROOT', fromlist=["style"]), "style")

    style()

    p = {
        "el": "e",
        "pi": "#pi",
        "ka": "K",
        "pr": "p",
        "de": "d",
        "tr": "t",
        "he3": "^{3}He"
    }
    charge = {"el": 1, "pi": 1, "ka": 1, "pr": 1, "de": 1, "tr": 1, "he3": 2}
    p_colors = {
        "el": "#e41a1c",
        "pi": "#377eb8",
        "ka": "#4daf4a",
        "pr": "#984ea3",
        "de": "#ff7f00",
        "tr": "#999999",
        "he3": "#a65628"
    }

    if particles is not None:
        to_remove = []
        for i in p:
            if i not in particles:
                to_remove.append(i)
        for i in to_remove:
            p.pop(i)

    latex = TLatex()
    latex.SetTextAlign(33)
    canvas = reader_name
    canvas = canvas.replace("lutRead_", "")
    canvas = TCanvas(canvas, canvas, 800, 800)
    canvas.Divide(2, 2)
    drawn = [canvas]
    drawn_graphs = {}
    drawn_frames = {}
    if ymin is None:
        if "_dca" in reader_name:
            ymin = 0.1
        elif "_pt" in reader_name:
            ymin = 1.
        elif "_eff" in reader_name:
            ymin = 0.
    if ymax is None:
        if "_dca" in reader_name:
            ymax = 1e4
        elif "_pt" in reader_name:
            ymax = 100.
        elif "_eff" in reader_name:
            ymax = 115.

    def adjust_pad():
        if logx:
            gPad.SetLogx()
        if logy:
            gPad.SetLogy()

    counter = 1
    leg = None
    if tag_name is not None:
        leg = TLegend(*leg_pos)
        if add_eta_label:
            label = f"#eta = {int(eta)}"
            label += " dN_{Ch}/d#eta ="
            label += f" {int(dnch_deta)}"
            if rmin is not None:
                label += "   R_{min} = " + rmin
            else:
                leg.SetHeader()
            leg.SetHeader(label)
        leg.SetLineColor(0)
        drawn.append(leg)

    def draw_study_label(x=0.5, y=0.9):
        latex = TLatex()
        latex.SetTextAlign(13)
        drawn.append(latex.DrawLatexNDC(x, y, " ".join(study_label)))

    for i in p:
        c = f"{canvas.GetName()}_{i}"
        c = TCanvas(c, c, 800, 800)
        drawn.append(c)
        adjust_pad()

        frame = c.DrawFrame(ptmin, ymin, ptmax, ymax, "")
        frame.SetDirectory(0)
        drawn_frames[i] = frame
        g_list = []
        extra = {}
        cols = [
            '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33'
        ]
        for k, j in enumerate(tags):
            lut = f"{lut_path}/lutCovm.{i}.{j}.dat"
            if j == "":
                lut = f"{lut_path}/lutCovm.{i}.dat"
            if not path.isfile(lut):
                print("LUT file", lut, "does not exist")
                return
            g = reader(lut, eta, dnch_deta)
            if g.GetN() <= 0:
                print("Skipping", g.GetName(), "because empty graph")
                continue
            if len(g_list) == 0:
                frame.GetXaxis().SetTitle(g.GetXaxis().GetTitle())
                frame.GetYaxis().SetTitle(g.GetYaxis().GetTitle())
            if use_p_over_z:
                for j in range(g.GetN()):
                    if "_pt" in reader_name:
                        g.SetPoint(j,
                                   g.GetPointX(j) / charge[i],
                                   g.GetPointY(j) / charge[i])
                    else:
                        g.SetPoint(j,
                                   g.GetPointX(j) / charge[i], g.GetPointY(j))
                frame.GetXaxis().SetTitle("#it{p}_{T}/z (GeV/#it{c})")
            col = TColor.GetColor(cols[len(g_list)])
            g.SetLineColor(col)
            g.SetLineStyle(1)
            g.SetLineWidth(3)
            g.Draw("samel")
            if aod is not None:
                f_aod = TFile(aod, "READ")
                if "_eff" in reader_name:
                    extra[g.GetName()] = f_aod.Get(
                        "qa-tracking-efficiency-kaon/pt/num")
                    extra[g.GetName()].Divide(
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/num"),
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1,
                        "B")
                    extra[g.GetName()].Scale(100)
                    extra[g.GetName()].Draw("SAME")
                    extra[g.GetName()].SetDirectory(0)
                elif "_pt" in reader_name:
                    extra[g.GetName()] = f_aod.Get(
                        "qa-tracking-efficiency-kaon/pt/num")
                    extra[g.GetName()].Divide(
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/num"),
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1,
                        "B")
                    extra[g.GetName()].Scale(100)
                    extra[g.GetName()].Draw("SAME")
                    extra[g.GetName()].SetDirectory(0)
                f_aod.Close()

            print("Drawing", g.GetName())
            if tag_name is not None and counter == 1:
                leg.AddEntry(g, tag_name[k], "l")
            g_list.append(g)
        drawn_graphs[i] = g_list
        if len(g_list) <= 0:
            print("Nothing drawn!")
            continue
        drawn.append(latex.DrawLatexNDC(0.9, 0.9, p[i]))
        if leg is not None:
            leg.Draw()
        draw_study_label(.4, .91)
        gPad.Update()
        canvas.cd(counter)
        clone = c.DrawClonePad()
        if counter != 1:
            l = gPad.GetListOfPrimitives()
            for i in l:
                cn = i.ClassName()
                if cn == "TLegend":
                    l.Remove(i)
                elif cn == "TLatex":
                    if "ALICE" in i.GetTitle():
                        l.Remove(i)
        drawn.append(clone)
        c.SaveAs(f"/tmp/{c.GetName()}.png")
        gPad.Update()
        counter += 1
    canvas_all_species = None
    if len(tags) == 1:
        canvas_all_species = TCanvas("all_spec_" + canvas.GetName(),
                                     "all_spec_" + canvas.GetName(), 800, 800)
        drawn.append(canvas_all_species)
        canvas_all_species.cd()
        drawn_graphs_all_spec = {}
        leg_all_spec = TLegend(*leg_pos)
        leg_all_spec.SetNColumns(2)
        leg_all_spec.SetLineColor(0)
        drawn.append(leg_all_spec)
        for i in drawn_graphs:
            if canvas_all_species.GetListOfPrimitives().GetEntries() == 0:
                drawn_frames[i].Draw()
            g_list = []
            for j in drawn_graphs[i]:
                g_list.append(j.Clone())
                g_list[-1].SetName(g_list[-1].GetName() + "_color")
                g_list[-1].SetLineColor(TColor.GetColor(p_colors[i]))
                g_list[-1].Draw("same")
                leg_all_spec.AddEntry(g_list[-1], p[i], "L")
            drawn_graphs_all_spec[i] = g_list
        for i in drawn_graphs_all_spec:
            drawn_graphs[i + "_allspec"] = drawn_graphs_all_spec[i]
        leg_all_spec.Draw()
        if add_alice3_label:
            draw_study_label()
            latex = TLatex()
            latex.SetTextAlign(13)
            latex.SetTextSize(0.04)
            if tag_name is not None:
                drawn.append(latex.DrawLatexNDC(0.5, 0.80, tag_name[0]))
            drawn.append(
                latex.DrawLatexNDC(
                    0.4, 0.82, f"#eta = {int(eta)}" + "\n dN_{Ch}/d#eta =" +
                    f" {int(dnch_deta)}" +
                    ("\n R_{min} = " + rmin if rmin is not None else "")))

        adjust_pad()
        canvas_all_species.Update()
        canvas_all_species.SaveAs(f"/tmp/{canvas_all_species.GetName()}.png")
    if save is None:
        canvas.SaveAs(f"/tmp/lut_{canvas.GetName()}.root")
    else:
        fo = TFile(save, "RECREATE")
        fo.cd()
        canvas.Write()
        if canvas_all_species is not None:
            canvas_all_species.Write()
        for i in drawn_graphs:
            for j in drawn_graphs[i]:
                j.Write()
    if not background:
        input("Done, press enter to continue")
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")
Exemple #11
0
class QuickTuner:
    def __init__(self, mode=0):
        self.mode = mode # 0: normal, 1: testing
        self.sensorConfig = None
        self.showPlot = True
        self.gainRef = None
        self.tuneRef = [0.6, -1, 0.3, 0.1]
        self.logFile = None
        self.lt = TLatex()
        self.stepI = 0
        self.sDir = sDir
        self.sTag = sTag
        self.autoSave = sDirectly
        self.halfPeriod = 2500
        
        ### To save the results a list of [((),())]
        self.results = None

        self.setup()

    def setupLogFile(self,fname):
        self.logFile = open(fname,'a')

    def setup(self):
        ### get connected
        data_ip_port = "192.168.2.3:1024"
        control_ip_port = "192.168.2.3:1025"
        dataIpPort = data_ip_port.split(':')
        sD = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        ctrlIpPort = control_ip_port.split(':')
        sC = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        cmd = Cmd()
        cd = CommonData(cmd, dataSocket=sD, ctrlSocket=sC)
        cd.aoutBuf = 1 
        cd.x2gain = 2
        cd.sdmMode = 0
        cd.bufferTest = 0

        if self.mode == 0:
            sD.connect((dataIpPort[0],int(dataIpPort[1])))
            sC.connect((ctrlIpPort[0],int(ctrlIpPort[1])))
            self.sensorConfig = SensorConfig(cd)

        cd.getCurrentBest()

        for i in range(len(cd.sensorVcodes)):
            print i, [cd.tms1mmReg.dac_code2volt(vx) for vx in cd.sensorVcodes[i]]

    def get_score(self, data):
        score = 0
        ## is there any structure?
        ### Find the jumps
        nP = 10 # use 10 previous points if exist
        nTh = 4
        pPoints = []
        nPoints = []

        nData = len(data)
        for i in range(nData):
            ### get the average of previous nP points -- these nP should be similar

            av = 0.
            av2 = 0.
            nPp = 0
            for j in range(nP):
                jx = i-1-j
                if jx < 0: break
                jv = data[jx]

                nPp += 1
                av += jv
                av2 += jv*jv
            if nPp <2: continue ### not enough points

            av /= nPp
            av2 /= nPp
            av2 -= av*av
            av2 = sqrt(av2)

            nOut = 0
            for j in range(nP):
                jx = i-1-j
                if jx>=0 and abs(data[jx]-av)/av2 > 4: nOut += 1

            if i<50:
                print i, av, av2, nOut 

            if nOut > 0 or av/av2<2: # not good average
                continue ## skip as we can't judge...

            if (data[i]-av)/av2 > 5: ### good positive point
                pPoints.append((i, data[i]-av))
            elif (data[i]-av)/av2 < -5:
                nPoints.append((i, av-data[i]))
                
         
            ### Compare with current one

        print pPoints
        print nPoints
        ## is it a signal structure?
        ## How good is the signal?

        return score;

#     def assess(self,  isensor=None, inputVs=[1.379, 1.546, 1.626, 1.169, 1.357, 2.458], adjustDecayTime=10):
    def assess(self, isensor=None, inputVs=None, adjustDecayTime=10, adjustRef=True):
        tname = self.__class__.__name__ + ':' + sys._getframe().f_code.co_name

        cd = self.sensorConfig.cd
        cd.updatePars(isensor, inputVs)

        isensor = cd.currentSensor
        self.sensorConfig.update_sensor(isensor) 
        print("Checking:", isensor, cd.inputVs)

        ### get new data
        time.sleep(5)
        data = cd.adcData[isensor]
        a1 = SigInfo()
        a1.sTag = self.sTag

        r = (0,0,0,0,0)
        nTest = 10
        if self.mode==0:
            var = 99
            nTried = 0
            while nTried<4:
                rAva = []
                rL = [0,0,0,0,0]
                for k in range(nTest):
                    cd.fetch()
                    r = a1.getQuickInfo(data)
                    rAva.append(r[1])
                    for i in range(len(r)): rL[i] += r[i]/nTest
                mu,var = getMeanVar(rAva)
#                 print mu, var
                r = tuple(rL)
                if var<0.002:
                    print "Convereged."
                    break

                print "Not stable"
                time.sleep(10)
                nTried += 1 

        if self.logFile:
            infox = "{1:d}> P{0:d}:".format(isensor, self.stepI)
            infox += ', '.join(['{0:.3f}'.format(x) for x in cd.inputVs])
            infox += '->'+' '.join('{0:.4f}'.format(x) for x in r)
            self.logFile.write(infox+'\n')
        self.stepI += 1

        print "temp results: r=", r
        if self.showPlot:
            ref = self.gainRef if self.gainRef else -1
            a1.show(data, "P{1:d}: A={0:.4f} ({2:.4f})".format(r[1],isensor, ref),', '.join(['{0:.3f}'.format(x) for x in cd.inputVs]))

        if self.gainRef and self.gainRef - r[1]>0.002:
            Warning(tname, "Will not fine tune")
            return None

        if adjustRef:
            inputVs_t = cd.inputVs[:]
            if r[0]+r[1]>1.25:
                print '-----r[0]=', r[0], cd.voltsNames[5], ':',cd.inputVs[5],'->',
                cd.inputVs[5] -= 0.01
                print cd.inputVs[5]
                r_t = self.assess(isensor, cd.inputVs, adjustDecayTime, True)

                ### check the results: the gain should not degrade much, the avarage should get smaller
                if r_t[1]-r[1]>-0.002 and r_t[0]<r[0]:
                    r = r_t
                else:
                    cd.inputVs = inputVs_t
                    Error(tname, "Failed to reduce r[0], reverting...")

            elif r[0]<self.tuneRef[0] and cd.inputVs[5]<2.99:
                print '-----r[0]=', r[0], cd.voltsNames[5], ':',cd.inputVs[5],'->',
                cd.inputVs[5] += 0.01
                print cd.inputVs[5]
                r_t = self.assess(isensor, cd.inputVs, adjustDecayTime, True)

                ### check the results
                if r_t[1]-r[1]<-0.002 and r_t[0]>r[0]:
                    r = r_t
                else:
                    cd.inputVs = inputVs_t
                    Error(tname, "Failed to increase r[0], reverting...")

        if adjustDecayTime and r[1]>0.004:
            inputVs_t = cd.inputVs[:]
            adjustDecayTime -= 1
            print r[4], float(abs(r[4])%self.halfPeriod)/self.halfPeriod
            if r[3]>self.tuneRef[3] or r[3]<-0.1 or float(abs(r[4])%self.halfPeriod)/self.halfPeriod>0.1:
                print '-----r[3]=', r[3], cd.voltsNames[4], ':',cd.inputVs[4],'->',
                cd.inputVs[4] += 0.01
                print cd.inputVs[4]
                r_t = self.assess(isensor, cd.inputVs, adjustDecayTime, adjustRef)

                ### check the results
                if r_t and r_t[1]-r[1]<-0.002 and r_t[3]<r[3]:
                    r = r_t
                else:
                    cd.inputVs = inputVs_t
                    Error(tname, "Failed to reduce r[3], reverting...")
            elif r[2]<self.tuneRef[2]:
                print '-----r[2]=', r[2], cd.voltsNames[4], ':',cd.inputVs[4],'->',
                cd.inputVs[4] -= 0.01
                print cd.inputVs[4]
                r_t = self.assess(isensor, cd.inputVs, adjustDecayTime, adjustRef)

                ### check the results
                if r_t and r_t[1]-r[1]<-0.002 and r_t[2]>r[2]:
                    r = r_t
                else:
                    cd.inputVs = inputVs_t
                    Error(tname, "Failed to increase r[2], reverting...")


        return r

    def scanForStructure(self, chan=18, xtag=''):
        self.sTag = "sfs_"+xtag+str(chan)+'_'

        for vdis in range(9):
            for vref in range(10):
                cd = self.sensorConfig.cd
                cd.currentSensor = chan
                cd.readBackPars(chan)
                cd.inputVs[4] = 1.+0.1*vdis
                cd.inputVs[5] = 2.+0.1*vref

                x0 = self.assess(adjustDecayTime=0, adjustRef=False)
    def scanForStructure2(self, chan=18, xtag=''):
        self.sTag = "sfs_"+xtag+str(chan)+'_'

        for vref in range(10):
            for vdis in range(9):
                cd = self.sensorConfig.cd
                cd.currentSensor = chan
                cd.readBackPars(chan)
                cd.inputVs[4] = 1.+0.1*vdis
                cd.inputVs[5] = 2.+0.1*vref

                x0 = self.assess(adjustDecayTime=0, adjustRef=False)



    def scan(self):
        '''Scan the given range with given steps'''

        pass

    def smartScan(self):
        '''Increase the number of points denpending on the situation'''
        pass

    def tryExisting(self):
        '''Try the existing parameters'''
        isendor = cd.currentSensor
#         currentValues = 
#         for i in range(len(cd.sensorVcodes)):
#             print i, [cd.tms1mmReg.dac_code2volt(vx) for vx in cd.sensorVcodes[i]]

        pass

    def tune2(self, chan):
        self.sTag = "plot_{0:d}_".format(chan)

        cd = self.sensorConfig.cd
        cd.currentSensor = chan
        cd.readBackPars(chan) 

        print "starting with pars:", cd.inputVs
        ### check it
#         x0 = self.assess(adjustDecayTime=0, adjustRef=False)
        x0 = self.assess()
        self.gainRef = x0[1]

        inputVs0 = cd.inputVs[:]
        for i in range(cd.nCh):
            if cd.isGood[i]:
                cd.sensorVcodes[chan] = cd.sensorVcodes[i][:]
#                 xi = self.assess(adjustDecayTime=0, adjustRef=False)
                xi = self.assess()
                if xi[1]>self.gainRef:
                    cd.readBackPars(chan)
                    self.gainRef = xi[1]
                    print "find better starting point:", cd.inputVs, 'with gain:',self.gainRef
                    if self.logFile: self.logFile.write('# new base\n')
                else:
                    cd.sensorVcodes[chan] = inputVs0
                    print "worse gain:", xi[1], "going back to the old one"

        ### first step: get high gain with loose shape requirement
        ### scan all parameters execpt VDIS
        self.tuneRef = [0.6, -1, 0.2, 0.1] ## loose requirement for high gain
#         changeList = [0.001, 0.001, 0.003, 0.005, 0.02, 0.03, 0.05, 0.2, 0.3, 0.5]
        changeList = [0.001, 0.001, 0.002, 0.003, 0.005, 0.02, 0.03, 0.05, 0.1, 0.1, 0.1,0.1, 0.1, 0.1, 0.2]
        tunePars = [5,1,2,0,3]

        updated = True
        tuned = []
        tuneVref = (5 not in tunePars)
        for ipar in growList(tunePars):
            if ipar == -1: break ### reach the end of the list
            print "===> Start tune", cd.voltsNames[ipar]
          
            ### find the best point
            updated = False
            while True:
                direction = 0
                inputVs0 = cd.inputVs[:]
                while direction == 0:
                    print '------', cd.voltsNames[ipar], '[U]:',cd.inputVs[ipar],'->',
                    for d in changeList:
                        cd.inputVs[ipar] += d
                        if(cd.inputVs[ipar]>3): break
                        print cd.inputVs[ipar],
                        x1 = self.assess(adjustRef=tuneVref)
                        if x1 is None: continue
                        print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
                        print x0, x1, self.gainRef
                        if abs(x1[1]-self.gainRef)>0.001: break
                    if (x1 is None) or x1[1]<self.gainRef+0.0008:
                        cd.inputVs = inputVs0
                        print 'reverting...'
                        break
                    x0 = x1
                    self.gainRef = x0[1]
                    print 'Good. Moving on...'
                    if self.logFile: self.logFile.write('# new base\n')
                    direction = 1
                inputVs0 = cd.inputVs[:]
                while direction == 0:
                    print '------', cd.voltsNames[ipar], '[D]:',cd.inputVs[ipar],'->',
                    for d in changeList:
                        cd.inputVs[ipar] -= d
                        if(cd.inputVs[ipar]<0): break
                        print cd.inputVs[ipar],
                        x1 = self.assess(adjustRef=tuneVref)
#                         x1 = self.assess()
                        if x1 is None: continue
                        print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
                        print x0, x1, self.gainRef
                        if abs(x1[1]-self.gainRef)>0.001: break
                    if (x1 is None) or x1[1]<self.gainRef+0.0008:
                        cd.inputVs = inputVs0
                        print 'reverting...'
                        break
                    x0 = x1
                    self.gainRef = x0[1]
                    print 'Good. Moving on...'
                    if self.logFile: self.logFile.write('# new base\n')
                    direction = -1
                if direction != 0:
                    updated = True
                else: break

            ### redo other parameters if 
            if updated:
                tunePars += tuned ### if the parameter changed, the tuned ones need to be revisited
                tuned = []
            else:
                tuned.append(ipar)

        print "gain tune done:", cd.inputVs
#         x1 = self.assess()
#         print x1
#         print ['{0:.3f}'.format(x) for x in cd.inputVs]
        print "------------------------"
 
#         ### second step: tune the [VDIS, VREF, VCASN, VBIASN] with loose gain requirement
#         self.tuneRef = [0.6, -1, 0.4, 0.05] ## loose requirement for high gain
# #         changeList = [0.001, 0.001, 0.003, 0.005, 0.02, 0.03, 0.05, 0.2, 0.3, 0.5]
#         changeList = [0.001, 0.001, 0.002, 0.003, 0.005, 0.02, 0.03, 0.05, 0.1, 0.1, 0.1,0.1, 0.1, 0.1, 0.2]
#         tunePars = [4,0,2,5]
# 
#         updated = True
#         tuned = []
#         tuneVref = (5 in tunePars)
#         tuneDT = 0 if 4 in tunePars else 10
#         for ipar in growList(tunePars):
#             if ipar == -1: break ### reach the end of the list
#             print "===> Start tune", cd.voltsNames[ipar]
#           
#             ### find the best point
#             updated = False
#             while True:
#                 direction = 0
#                 inputVs0 = cd.inputVs[:]
#                 while direction == 0:
#                     print '------', cd.voltsNames[ipar], '[U]:',cd.inputVs[ipar],'->',
#                     for d in changeList:
#                         cd.inputVs[ipar] += d
#                         if(cd.inputVs[ipar]>3): break
#                         print cd.inputVs[ipar],
#                         x1 = self.assess(adjustDecayTime=tuneDT, adjustRef=tuneVref)
#                         if x1 is None: continue
#                         print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
#                         print x0, x1, self.gainRef
#                         if abs(x1[1]-self.gainRef)>0.001: break
#                     if (x1 is None) or x1[1]<x0[1]+0.0008:
#                         cd.inputVs = inputVs0
#                         print 'reverting...'
#                         break
#                     x0 = x1
#                     self.gainRef = x0[1]
#                     print 'Good. Moving on...'
#                     if self.logFile: self.logFile.write('# new base\n')
#                     direction = 1
#                 inputVs0 = cd.inputVs[:]
#                 while direction == 0:
#                     print '------', cd.voltsNames[ipar], '[D]:',cd.inputVs[ipar],'->',
#                     for d in changeList:
#                         cd.inputVs[ipar] -= d
#                         if(cd.inputVs[ipar]<0): break
#                         print cd.inputVs[ipar],
#                         x1 = self.assess(adjustDecayTime=tuneDT, adjustRef=tuneVref)
# #                         x1 = self.assess()
#                         if x1 is None: continue
#                         print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
#                         print x0, x1, self.gainRef
#                         if abs(x1[1]-self.gainRef)>0.001: break
#                     if (x1 is None) or x1[1]<x0[1]+0.0008:
#                         cd.inputVs = inputVs0
#                         print 'reverting...'
#                         break
#                     x0 = x1
#                     self.gainRef = x0[1]
#                     print 'Good. Moving on...'
#                     if self.logFile: self.logFile.write('# new base\n')
#                     direction = -1
#                 if direction != 0:
#                     updated = True
#                 else: break
# 
#             ### redo other parameters if 
#             if updated:
#                 tunePars += tuned ### if the parameter changed, the tuned ones need to be revisited
#                 tuned = []
#             else:
#                 tuned.append(ipar)

        print "final:", cd.inputVs
        x1 = self.assess(adjustDecayTime=0, adjustRef=False)
        print x1
        print ['{0:.3f}'.format(x) for x in cd.inputVs]

    def tune(self, chan):
        ## give a set of parameters and get a quantity of goodness
        ### pass the parameters and get data
        ### assess the data -- what's good? What's better?
        ## Move the next set of parameters
        cd = self.sensorConfig.cd
        cd.currentSensor = chan
        cd.readBackPars(chan) 
#         cd.inputVs = [1.029,1.106,1.676,1.169,0.8,2.99]

        print "starting with pars:", cd.inputVs
        ### check it
        x0 = self.assess()
        self.gainRef = x0[1]

        ## tune the first four VDIS for higher gain
        tuned = []
        px = [None]*6 ## to save the results of the 6 parameters
        mx = 0
        updated = True
        changeList = [0.001, 0.001, 0.003, 0.005, 0.02, 0.03, 0.05, 0.2, 0.3, 0.5]
        tunePars = [5,1,2,0,3]

        for ipar in growList(tunePars):
            if ipar == -1: break ### reach the end of the list
            print "===> Start tune", cd.voltsNames[ipar]
          
            ### find the best point
            updated = False
            while True:
                direction = 0
                inputVs0 = cd.inputVs[:]
                while direction == 0:
                    print '------', cd.voltsNames[ipar], '[U]:',cd.inputVs[ipar],'->',
                    for d in changeList:
                        cd.inputVs[ipar] += d
                        if(cd.inputVs[ipar]>3): break
                        print cd.inputVs[ipar],
                        x1 = self.assess()
                        if x1 is None: continue
                        print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
                        print x0, x1, self.gainRef
                        if abs(x1[1]-self.gainRef)>0.001: break
                    if (x1 is None) or x1[1]<x0[1]+0.0008:
                        cd.inputVs = inputVs0
                        print 'reverting...'
                        break
                    x0 = x1
                    self.gainRef = x0[1]
                    print 'Good. Moving on...'
                    direction = 1
                inputVs0 = cd.inputVs[:]
                while direction == 0:
                    print '------', cd.voltsNames[ipar], '[D]:',cd.inputVs[ipar],'->',
                    for d in changeList:
                        cd.inputVs[ipar] -= d
                        if(cd.inputVs[ipar]<0): break
                        print cd.inputVs[ipar],
                        x1 = self.assess()
                        if x1 is None: continue
                        print "dx=", cd.inputVs[ipar]-inputVs0[ipar],", dA=", x1[1]-x0[1],
                        print x0, x1, self.gainRef
                        if abs(x1[1]-self.gainRef)>0.001: break
                    if (x1 is None) or x1[1]<x0[1]+0.0008:
                        cd.inputVs = inputVs0
                        print 'reverting...'
                        break
                    x0 = x1
                    self.gainRef = x0[1]
                    print 'Good. Moving on...'
                    direction = -1
                if direction != 0:
                    updated = True
                else: break

            ### redo other parameters if 
            if updated:
                tunePars += tuned ### if the parameter changed, the tuned ones need to be revisited
            else:
                tuned.append(ipar)

        print "final:", cd.inputVs
        x1 = self.assess()
        print x1
        print ['{0:.3f}'.format(x) for x in cd.inputVs]

    def handTune(self, chan):
        self.sensorConfig.cd.currentSensor = chan
        inputVs = None
        while True:
            ### check it
            x0 = self.assess(None, inputVs)
            print x0
            args = raw_input("inputVs:")
            if args in ['e','q','exit','quit','.q']:
                break
            inputVs = [float(x) for x in args.split(',')]

    def test(self):
        print "testing"
        dat1 = None
        ichan = 5 if len(sys.argv)<2 else int(sys.argv[1])
        with open('adc_test.dat') as f1:
            dat1 = [float(l.split()[ichan]) for l in f1.readlines() if l.find('#')==-1]
#         a1 = SigInfo(dat1)
        a1 = SigInfo()
        print a1.getQuickInfo(dat1, 20)
#         self.get_score(dat1)
#         self.check(dat1)

    def fullTune(self):
        '''Do everything automatically'''
        ### First find the initial values for fine tune
        ### Dead channels will be marked
        self.getInitialValues()

        ### Continue with the fine tune
        ## Could be done in prallel in future
        nChan = 19 # number of channels
        for i in range(nChan):
            # don't waste time on the dead ones
            if self.isDead[i]: continue
            self.tune2(i)

        ### Finish. The output is a list of parameters and the characteristics
        ### Where to save the output? Inside the class, or return from this method? -- save to the method.

    def compareInputs(self, chan, inputs, dt=10, info=None, saveName='testing'):
        '''Compare a list of inputs
        Each input is a tuple: (tag, tex, [pars]), tex will be shown in the legend and tag should plain text used to distinguish the entry.
        For each entry, a TGraph will be made.
        '''
        cd1 = self.sensorConfig.cd

        grs = []
        dataX = []
        ic = 1
        max0 = -1
        min0 = 999
        lg = TLegend(0.7,0.8,0.9,0.9)
        lg.SetFillStyle(0)

        for ip in inputs:
            cd1.updatePars(chan, ip[2])
            print ip[2]
            self.sensorConfig.update_sensor(chan)
            print("Checking:", cd1.currentSensor, cd1.inputVs)
            time.sleep(dt)
            cd1.fetch()
#             dataX.append(cd1.adcData[chan][:])
            dataX = cd1.adcData[chan][:]
            for i in range(10): print dataX[i]

#             ndata = len(dataX[-1])
#             gr1 = TGraph(ndata, array('d',[i*0.2*0.001 for i in range(ndata)]), array('d', dataX[-1]))
            ndata = len(dataX)
            gr1 = TGraph(ndata, array('d',[i*0.2*0.001 for i in range(ndata)]), array('d', dataX))
            gr1.SetLineColor(ic)
            gr1.SetMarkerColor(ic)
            gr1.SetMarkerStyle(20+ic)
            ic += 1

            lg.AddEntry(gr1, ip[1],'lp')

            grs.append(gr1)

#             max0 = max([max0, max(dataX[-1])])
#             min0 = min([min0, min(dataX[-1])])
            max0 = max([max0, max(dataX)])
            min0 = min([min0, min(dataX)])

#             gr1.Draw("AP")
#             waitRootCmdX()

        gr0 = grs[0]
        gr0.Draw("AP")
        dm = max0 - min0
        h1 = gr0.GetHistogram()
        h1.GetYaxis().SetRangeUser(min([min0*0.8,min0-0.1*dm]), max([max0*1.2,max0+0.1*dm]))
        h1.GetXaxis().SetTitle("t [ms]")
        h1.GetYaxis().SetTitle("V_{out} [V]")
        for gr in grs[1:]: gr.Draw("Psame")
        h1.Draw('axissame')

        lg.Draw()

        if info:
            self.lt.DrawLatexNDC(0.2,0.8, info)

        waitRootCmdX(self.sDir+self.sTag+saveName, self.autoSave)
Exemple #12
0
def scanX(chans=[i for i in range(19)]):
    '''Used to test the scan of one or more parameters'''
    nChips = 19 # the magic number
    nChan = len(chans)

    iP = 1
    fixedPars = [1.5, 1.5]
    cd = CommonData()
    cd.setupConnection()
    inputs = cd.inputVs
    sc1 = SensorConfig(cd)

    ### setup the style list
    mkColors = [2,3,4,6,7,8]
    mkMarkers = [20,25,23,26,21,22,24,27,32]
    styleList = [(None,None)]*nChips
    for i,j in sc1.tms1mmX19chainSensors.iteritems():
        for k,l in enumerate(j):
            styleList[l] = (mkColors[i],mkMarkers[k])

    ### get list of chains to be updated
    chains = set([sc1.tms1mmX19chainSensors[sc1.tms1mmX19sensorInChain[c]][0] for c in chans])
    print chains

    ### setup the elements for plotting 
    lg = TLegend(0.84,0.11,0.998,0.89)
    lg.SetFillStyle(0)

    grs = [TGraphErrors() for chan in chans]
    for ic in range(len(chans)):
        chan = chans[ic]
        grs[ic].SetMarkerColor(styleList[chan][0])
        grs[ic].SetLineColor(styleList[chan][0])
        grs[ic].SetMarkerStyle(styleList[chan][1])
        lg.AddEntry(grs[ic],str(chan),'lp')

    ### variables to store the results
    pValues = [None]*nChan
    changeP = [(None,None)]*nChan ## save (where, how_large) for each channel

    ### perform the scan
    max1 = -1
    min1 = 999
    for ir in range(11): ## run ir
        vr = 0.33*ir
        ### update channels
        for chan in chans:
            cd.readBackPars(chan)
            for f in range(len(fixedPars)):
                if fixedPars[f] is not None: inputs[f] = fixedPars[f]

            inputs[iP] = vr
            cd.updatePars(chan, inputs, False)

        for c in chains: sc1.update_sensor(c)
        time.sleep(2)
        cd.fetch()

#         x = ''
#         while x!='m':
#             cd.fetch()
#             a1 = SigInfo()
#             a1.showMore(dat1)
#             x = raw_input("'m' to move to next|")

        for ic in range(len(chans)):
            chan = chans[ic]
            m,v = getMeanVar(cd.adcData[chan])
            if m+v>max1: max1 = m+v
            if m-v<min1: min1 = m-v
            print chan, m,v
            grs[ic].SetPoint(ir, vr, m)
            grs[ic].SetPointError(ir, 0, v)

            ### get the values
            if pValues[ic] is not None:
                if (changeP[ic][1] is None) or (m - pValues[ic] < changeP[ic][1]):
                    changeP[ic] = (ir, m - pValues[ic])
            pValues[ic] = m

    gr1 = grs[0]
    print gr1.GetN()
    gr1.Draw("APL")
    h1 = gr1.GetHistogram()
    h1.GetXaxis().SetTitle(cd.voltsNames[iP]+' [V]')
    h1.GetYaxis().SetTitle('V_{out} [V]')
    dm = 0.05*(max1-min1)    
    h1.GetYaxis().SetRangeUser(min1-dm,max1+dm)

    for gr in grs[1:]: gr.Draw("PLsame")
    lg.Draw("same")


    ### add info of other parameters
    inputT = ''
    for i,x in enumerate(fixedPars):
        if i == iP: continue
        if x is not None: inputT += cd.voltsNames[i]+'='+str(x)
    lt = TLatex()
    lt.DrawLatexNDC(0.2,0.92,' '.join(inputT))

#     inputT = ['{0:.3f}'.format(x) for x in inputs]
#     inputT[iP] = '--'
#     lt.DrawLatexNDC(0.2,0.92,' '.join(inputT))

    for x in changeP: print x

    waitRootCmdX()
Exemple #13
0
def GetAndDrawHistograms(DataFileName,
                         DataTreeName,
                         MCFileName,
                         MCTreeName,
                         noStack=True):
    fMC = TFile(MCFileName)
    tMC = fMC.Get(MCTreeName)
    fData = TFile(DataFileName)
    tData = fData.Get(DataTreeName)

    histoListe = setupHistograms()
    HistDic = {}

    for i, h in enumerate(histoListe):
        legende = TLegend(0.7, 0.7, 0.89, 0.89)
        CanvasName = "c" + str(i)
        CanvasName = TCanvas(CanvasName, 'Defining histogram size')
        g = THStack("", "")

        #tMC.Draw(histoListe[i][3],CutMC)
        #hist_MC = tMC.GetHistogram().Clone("hist_MC")
        #hist_MC.SetLineColor(6)
        #hist_MC.SetLineWidth(1)
        ##hist_MC.SetMarkerStyle(21)
        #legende.AddEntry(hist_MC, "MC", "lp")
        #hist_MC.GetXaxis().SetTitle(h[1])
        #hist_MC.GetYaxis().SetTitle(h[2])
        #hist_MC.Scale(1/hist_MC.Integral())
        #MaxMC = hist_MC.GetMaximum()
        #g.Add(hist_MC)

        tData.Draw(histoListe[i][3], CutData)
        hist_data = tData.GetHistogram().Clone("hist_data")
        hist_data.SetLineColor(9)
        hist_data.SetLineWidth(1)
        #hist_data.SetMarkerStyle(21)
        legende.AddEntry(hist_data, "Data", "lp")
        hist_data.GetXaxis().SetTitle(h[1])
        hist_data.GetYaxis().SetTitle(h[2])
        #hist_data.Scale(1/hist_data.Integral())
        MaxData = hist_data.GetMaximum()
        g.Add(hist_data)

        #tData.Draw(histoListe[i][3],CutData_RS)
        #hist_RS = tData.GetHistogram().Clone("hist_RS")
        #hist_RS.SetLineColor(4)
        #hist_RS.SetLineWidth(1)
        ##hist_RS.SetMarkerStyle(21)
        #legende.AddEntry(hist_RS, "Data RS", "lp")
        #hist_RS.Scale(1/hist_RS.Integral())
        #MaxRS = hist_RS.GetMaximum()
        #g.Add(hist_RS)

        #if noStack:
        #    if (MaxMC > MaxData):
        #        g.SetMaximum(MaxMC*1.1)
        #    else:
        #        g.SetMaximum(MaxData*1.1)
        #    g.Draw("nostackhist")
        #else:
        #    g.SetMaximum(g.GetMaximum()*1.1)
        #    g.Draw("hist")
        g.SetMaximum(MaxData * 1.1)
        g.Draw("hist")
        #legende.Draw()
        g.GetXaxis().SetTitle(h[1])
        g.GetYaxis().SetTitle(h[2])
        g.GetYaxis().SetTitleOffset(1.4)
        g.GetXaxis().SetTitleOffset(1.1)
        my_Latex = TLatex()
        my_Latex.SetTextSize(0.04)
        my_Latex.DrawLatexNDC(0.13, 0.85, "LHCb Data 2012")
        CanvasName.Update()

        outDir = '/sps/lhcb/volle/BMass'
        if not os.path.isdir(outDir):
            os.makedirs(outDir)
        CanvasName.SaveAs("{}/{}_{}.pdf".format(outDir, histoListe[i][0],
                                                comment))
        CanvasName.SaveAs("{}/{}_{}.png".format(outDir, histoListe[i][0],
                                                comment))
Exemple #14
0
    for i, h in histories.iteritems():
        histos["q_peak"].Fill(max([e.Q for i, e in h.iteritems()]))
    canvases["q_peak"] = TCanvas("q_peak", "Peak of quarantines", 400, 400)
    histos["q_peak"].SetStats(0)
    histos["q_peak"].SetTitle("; Maximum of quarantined people; A.U.")
    histos["q_peak"].SetLineColor(1)
    histos["q_peak"].SetLineWidth(2)
    histos["q_peak"].GetYaxis().SetRangeUser(
        0, 1.5 * histos["q_peak"].GetMaximum())
    histos["q_peak"].Draw()
    canvases["q_peak"].SetBottomMargin(0.15)
    canvases["q_peak"].SetTopMargin(0.05)
    canvases["q_peak"].SetRightMargin(0.05)
    canvases["q_peak"].SetLeftMargin(0.12)
    latex.DrawLatexNDC(
        0.2, 0.85,
        "Max. quarantined people = " + str(int(histos["q_peak"].GetMean())) +
        " #pm " + str(int(histos["q_peak"].GetRMS())))

    canvases["q_peak"].SaveAs(plot_dir + "QuarantinePeak.pdf")

    #
    # time of peak of quarantined
    #
    histos["tq_peak"] = TH1F("tq_peak", "", 20, 30, 50)
    for i, h in histories.iteritems():
        max_q = max([e.Q for i, e in h.iteritems()])
        for i, e in h.iteritems():
            if e.Q == max_q:
                histos["tq_peak"].Fill(e.time)
                break
    canvases["tq_peak"] = TCanvas("tq_peak", "Peak of quarantines", 400, 400)
Exemple #15
0
def DrawSplotHistograms(DataFileName,
                        DataTreeName,
                        SFileName,
                        STreeName,
                        noStack=True):
    fData = TFile(DataFileName)
    tData = fData.Get(DataTreeName)

    tData.AddFriend(STreeName, SFileName)
    histoListe = setupHistograms()
    HistDic = {}

    for i, h in enumerate(histoListe):
        legende = TLegend(0.75, 0.83, 0.97, 0.97)
        CanvasName = "c" + str(i)
        CanvasName = TCanvas(CanvasName, 'Defining histogram size')
        g = THStack("", "")

        #tMC.Draw(histoListe[i][3],CutMC)
        #hist_MC = tMC.GetHistogram().Clone("hist_MC")
        #hist_MC.SetLineColor(6)
        #hist_MC.SetLineWidth(1)
        ##hist_MC.SetMarkerStyle(21)
        #legende.AddEntry(hist_MC, "MC", "lp")
        #hist_MC.GetXaxis().SetTitle(h[1])
        #hist_MC.GetYaxis().SetTitle(h[2])
        #hist_MC.Scale(1/hist_MC.Integral())
        #MaxMC = hist_MC.GetMaximum()
        #g.Add(hist_MC)

        tData.Draw(histoListe[i][3], "B_M>5300")
        hist_data = tData.GetHistogram().Clone("hist_data")
        hist_data.SetLineColor(5)
        hist_data.SetLineWidth(1)
        #hist_data.SetMarkerStyle(21)
        legende.AddEntry(hist_data, "Data", "lp")
        hist_data.GetXaxis().SetTitle(h[1])
        hist_data.GetYaxis().SetTitle(h[2])
        MaxData = hist_data.GetMaximum()
        g.Add(hist_data)

        tData.Draw(histoListe[i][3], "nsig_sw")
        hist_sw = tData.GetHistogram().Clone("hist_sw")
        hist_sw.SetLineColor(4)
        hist_sw.SetLineWidth(1)
        ##hist_RS.SetMarkerStyle(21)
        legende.AddEntry(hist_sw, "sweighted Data", "lp")
        MaxSW = hist_sw.GetMaximum()
        g.Add(hist_sw)

        if noStack:
            if (MaxSW > MaxData):
                g.SetMaximum(MaxSW * 1.2)
            else:
                g.SetMaximum(MaxData * 1.2)
            g.Draw("nostackhist")
        else:
            g.SetMaximum(g.GetMaximum() * 1.2)
            g.Draw("hist")

        legende.Draw()
        g.GetXaxis().SetTitle(h[1])
        g.GetYaxis().SetTitle(h[2])
        g.GetYaxis().SetTitleOffset(1.4)
        g.GetXaxis().SetTitleOffset(1.1)
        my_Latex = TLatex()
        my_Latex.SetTextSize(0.04)
        my_Latex.DrawLatexNDC(0.13, 0.85, "LHCb Data 2012")
        CanvasName.Update()

        outDir = '/sps/lhcb/volle/FitBMass/v1_Min5120'
        if not os.path.isdir(outDir):
            os.makedirs(outDir)
        CanvasName.SaveAs("{}/{}_both.pdf".format(outDir,
                                                  histoListe[i][0]))  #_both
        CanvasName.SaveAs("{}/{}_both.png".format(outDir,
                                                  histoListe[i][0]))  #_both
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")
Exemple #18
0
h_sumDiboson.SetLineColor(923)
h_sumDiboson.GetXaxis().SetTitle("Double b score")
h_sumDiboson.GetYaxis().SetTitle("Events/Bin")
leg.AddEntry(h_sumDiboson, "Diboson", "f")

#-------Draw Histogram in c1---------#

h_TopMatchFinal.Draw("hist")
h_WmatchFinal.Draw("histsame")
h_unmatchFinal.Draw("histsame")
h_sumWJetsFinal.Draw("histsame")
h_sumDiboson.Draw("histsame")
leg.Draw()

lt = TLatex()
lt.DrawLatexNDC(0.23, 0.85,
                "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Preliminary}}}")
lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e)}}")
lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.0 fb^{-1} (13 TeV)}}")

c1.cd()
c1.Modified()
c1.Update()
c1.SaveAs("test.pdf")

#------------Overlap histograms in c2-------------#

c2 = TCanvas("c2", "c2", 900, 700)  #width-height
c2.SetLeftMargin(0.15)
gStyle.SetOptStat(0)
Exemple #19
0
def mistagSFtopEMu(year_, ana_):
    if year_ == 2017:
        dir = "monohbb.v06.00.05.2017_NCU/withSingleTop/" + ana_ + "/"
    if year_ == 2018:
        dir = "monohbb.v06.00.05.2018_NCU/withSingleTop/" + ana_ + "/"

    print "Top Electron Region"
    print " "

    openfile1 = TFile(dir + "TopE.root")  #

    topmatchTopE = openfile1.Get("h_TopMatch")
    WmatchTopE = openfile1.Get("h_Wmatch")
    unmatchTopE = openfile1.Get("h_unmatch")
    wjetsTopE = openfile1.Get("h_sumWJets")
    dibosonTopE = openfile1.Get("h_sumDiboson")
    unsubtractedDataTopE = openfile1.Get("h_Data")

    failMCsubtractTopE = openfile1.Get("h_ttFailed")
    passMCsubtractTopE = openfile1.Get("h_ttPassed")
    subtractedDataTopE = openfile1.Get("SubtractedData")

    datafailTopE = openfile1.Get("SubtractedDataFailed")
    datapassTopE = openfile1.Get("SubtractedDataPassed")  #
    totaldataTopE = openfile1.Get("h_totaldata")
    totalMCtopE = openfile1.Get("h_tt")

    passedTopEdataBfrSubtract = openfile1.Get("h_Data_Passed")
    wjetsTopEpassed = openfile1.Get("h_sumWJetsPassed")
    dibosonTopEpassed = openfile1.Get("h_sumDibosonPassed")

    failedTopEdataBfrSubtract = openfile1.Get("h_Data_Failed")
    wjetsTopEfailed = openfile1.Get("h_sumWJetsFailed")
    dibosonTopEfailed = openfile1.Get("h_sumDibosonFailed")

    stTopE = openfile1.Get("h_sumST")
    stTopEpassed = openfile1.Get("h_sumSTPassed")
    stTopEfailed = openfile1.Get("h_sumSTFailed")

    print "Top Muon Region"
    print " "

    openfile2 = TFile(dir + "TopMu.root")  #

    topmatchTopMu = openfile2.Get("h_TopMatch")
    WmatchTopMu = openfile2.Get("h_Wmatch")
    unmatchTopMu = openfile2.Get("h_unmatch")
    wjetsTopMu = openfile2.Get("h_sumWJets")
    dibosonTopMu = openfile2.Get("h_sumDiboson")
    unsubtractedDataTopMu = openfile2.Get("h_Data")

    failMCsubtractTopMu = openfile2.Get("h_ttFailed")
    passMCsubtractTopMu = openfile2.Get("h_ttPassed")
    subtractedDataTopMu = openfile2.Get("SubtractedData")

    datafailTopMu = openfile2.Get("SubtractedDataFailed")
    datapassTopMu = openfile2.Get("SubtractedDataPassed")  #
    totaldataTopMu = openfile2.Get("h_totaldata")
    totalMCtopMu = openfile2.Get("h_tt")

    passedTopMudataBfrSubtract = openfile2.Get("h_Data_Passed")
    wjetsTopMupassed = openfile2.Get("h_sumWJetsPassed")
    dibosonTopMupassed = openfile2.Get("h_sumDibosonPassed")

    failedTopMudataBfrSubtract = openfile2.Get("h_Data_Failed")
    wjetsTopMufailed = openfile2.Get("h_sumWJetsFailed")
    dibosonTopMufailed = openfile2.Get("h_sumDibosonFailed")

    stTopMu = openfile2.Get("h_sumST")
    stTopMupassed = openfile2.Get("h_sumSTPassed")
    stTopMufailed = openfile2.Get("h_sumSTFailed")

    print "get histograms from root files: done"
    print " "

    SubtractedDataPassedTopE = datapassTopE.Clone("SubtractedDataPassedTopE")
    SubtractedDataPassedTopMu = datapassTopMu.Clone(
        "SubtractedDataPassedTopMu")

    #merge histogram"
    print "merge histograms"
    print " "

    topmatchMerge = topmatchTopE + topmatchTopMu
    WmatchMerge = WmatchTopE + WmatchTopMu
    unmatchMerge = unmatchTopE + unmatchTopMu
    wjetsMerge = wjetsTopE + wjetsTopMu
    stMerge = stTopE + stTopMu
    dibosonMerge = dibosonTopE + dibosonTopMu
    unsubtractedDataMerge = unsubtractedDataTopE + unsubtractedDataTopMu

    failMCsubtractMerge = failMCsubtractTopE.Clone("failMCsubtractMerge")
    failMCsubtractMerge = failMCsubtractMerge + failMCsubtractTopMu
    passMCsubtractMerge = passMCsubtractTopE.Clone("passMCsubtractMerge")
    passMCsubtractMerge = passMCsubtractMerge + passMCsubtractTopMu
    subtractedDataMerge = subtractedDataTopE + subtractedDataTopMu

    ttData_fraction = arr.array('d')
    ttData_error = arr.array('d')

    totaldataMerge = totaldataTopE + totaldataTopMu
    totaldata = totaldataMerge.Integral()
    totaldataMerge.Rebin(14)

    datafailMerge = datafailTopE + datafailTopMu
    faildata = datafailMerge.Integral()
    datafailMerge.Rebin(14)
    datafailMerge.Sumw2()
    datafailMerge.Divide(totaldataMerge)
    frac_ttData_fail = datafailMerge.Integral()
    ttData_fraction.append(frac_ttData_fail)
    ttData_error.append(datafailMerge.GetBinError(1))

    datapassMerge = datapassTopE + datapassTopMu
    passdata = datapassMerge.Integral()
    datapassMerge.Rebin(14)
    datapassMerge.Sumw2()
    datapassMerge.Divide(totaldataMerge)
    frac_ttData_pass = datapassMerge.Integral()
    ttData_fraction.append(frac_ttData_pass)
    ttData_error.append(datapassMerge.GetBinError(1))

    ttMC_fraction = arr.array('d')
    ttMC_error = arr.array('d')

    totalMCmerge = totalMCtopE + totalMCtopMu
    totalMCmerge.Rebin(14)

    MCfailTopE = failMCsubtractTopE.Clone("MCfailTopE")
    MCfailTopMu = failMCsubtractTopMu.Clone("MCfailTopMu")
    MCfailMerge = MCfailTopE + MCfailTopMu
    MCfailMerge.Rebin(14)
    MCfailMerge.Sumw2()
    MCfailMerge.Divide(totalMCmerge)
    frac_Failed_fin = MCfailMerge.Integral()
    ttMC_fraction.append(frac_Failed_fin)
    ttMC_error.append(MCfailMerge.GetBinError(1))

    MCpassTopE = passMCsubtractTopE.Clone("MCpassTopE")
    MCpassTopMu = passMCsubtractTopMu.Clone("MCpassTopMu")
    MCpassMerge = MCpassTopE + MCpassTopMu
    MCpassMerge.Rebin(14)
    MCpassMerge.Sumw2()
    MCpassMerge.Divide(totalMCmerge)
    frac_Passed_fin = MCpassMerge.Integral()
    ttMC_fraction.append(frac_Passed_fin)
    ttMC_error.append(MCpassMerge.GetBinError(1))

    #print "\nttMC_fraction:", ttMC_fraction
    #print "ttMC_error:", ttMC_error

    sfMerge = datapassMerge.Clone("sfMerge")
    sfMerge.Sumw2()
    sfMerge.Divide(MCpassMerge)

    stacklist = []
    stacklist.append(dibosonMerge)
    stacklist.append(stMerge)
    stacklist.append(wjetsMerge)
    stacklist.append(unmatchMerge)
    stacklist.append(WmatchMerge)
    stacklist.append(topmatchMerge)

    print "merge histograms: done"
    print " "

    print "draw histograms"
    print " "
    #----------------------- canvas 1 -----------------------#

    c1 = TCanvas("c1", "", 800, 900)  #width-height
    c1.SetTopMargin(0.4)
    c1.SetBottomMargin(0.05)
    c1.SetRightMargin(0.1)
    c1.SetLeftMargin(0.15)
    gStyle.SetOptStat(0)

    binvalues1 = []
    for i in range(14):
        binvalue = unsubtractedDataMerge.GetBinContent(i)
        binvalues1.append(binvalue)
    totalmax = max(binvalues1) + 100

    padMain = TPad("padMain", "", 0.0, 0.25, 1.0, 0.97)
    padMain.SetTopMargin(0.4)
    padMain.SetRightMargin(0.05)
    padMain.SetLeftMargin(0.17)
    padMain.SetBottomMargin(0.03)
    padMain.SetTopMargin(0.1)

    padRatio = TPad("padRatio", "", 0.0, 0.0, 1.0, 0.25)
    padRatio.SetRightMargin(0.05)
    padRatio.SetLeftMargin(0.17)
    padRatio.SetTopMargin(0.05)
    padRatio.SetBottomMargin(0.3)
    padMain.Draw()
    padRatio.Draw()

    padMain.cd()

    gPad.GetUymax()
    leg1 = myLegend(coordinate=[0.45, 0.57, 0.65, 0.6])

    unsubtractedDataMerge.SetMaximum(totalmax)
    unsubtractedDataMerge.SetLineColor(1)
    unsubtractedDataMerge.SetMarkerStyle(20)
    unsubtractedDataMerge.SetMarkerSize(1.5)
    unsubtractedDataMerge.GetXaxis().SetLabelSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitleSize(0)
    unsubtractedDataMerge.GetXaxis().SetTitle("DDB")
    unsubtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg1.AddEntry(unsubtractedDataMerge, "Data", "lep")
    unsubtractedDataMerge.Draw("e1")

    stackhisto = myStack(colorlist_=[627, 800, 854, 813, 822, 821],
                         backgroundlist_=stacklist,
                         legendname_=[
                             "Diboson", "Single Top", "W+Jets",
                             "Top (unmtch.)", "Top (W-mtch.)", "Top (mtch.)"
                         ])
    stackhisto[0].Draw("histsame")
    unsubtractedDataMerge.Draw("e1same")
    stackhisto[1].Draw()
    leg1.Draw()

    lt = TLatex()
    lt.DrawLatexNDC(0.23, 0.85,
                    "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    if ana_ == "Inclusive":
        lt.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt.DrawLatexNDC(0.17, 0.92,
                            "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt.DrawLatexNDC(0.71, 0.92,
                        "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    padRatio.cd()

    gPad.GetUymax()

    h_totalBkg = topmatchMerge.Clone("h_totalBkg")
    h_totalBkg = h_totalBkg + WmatchMerge + unmatchMerge + wjetsMerge + dibosonMerge
    ratio = dataPredRatio(data_=unsubtractedDataMerge, totalBkg_=h_totalBkg)
    ratio.SetLineColor(1)
    ratio.SetLineWidth(3)
    ratio.SetMarkerSize(1.5)
    ratio.GetXaxis().SetLabelSize(0.13)
    ratio.GetXaxis().SetTitleOffset(1)
    ratio.GetXaxis().SetTitleSize(0.13)
    ratio.GetXaxis().SetTickLength(0.1)
    ratio.GetYaxis().SetLabelSize(0.12)
    ratio.GetYaxis().SetTitleOffset(0.5)
    ratio.GetYaxis().SetTitleSize(0.13)
    ratio.GetYaxis().SetNdivisions(405)
    ratio.GetYaxis().SetTitle("#frac{Data-Pred}{Pred}")
    ratio.GetXaxis().SetTitle("DDB")
    ratio.Draw("e1")

    c1.SaveAs(dir + "Merge_all.pdf")  #

    #----------------------- canvas 2 -----------------------#

    c2 = myCanvas(c="c2")
    gPad.GetUymax()
    leg2 = myLegend()

    binvalues2 = []
    for i in range(14):
        binvalue = subtractedDataMerge.GetBinContent(i)
        binvalues2.append(binvalue)
    ttmax = max(binvalues2) + 50

    failMCsubtractMerge.SetMaximum(ttmax)
    failMCsubtractMerge.SetFillColor(821)
    failMCsubtractMerge.SetLineColor(821)  #922
    failMCsubtractMerge.GetXaxis().SetTitle("DDB")
    failMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(failMCsubtractMerge, "t#bar{t}", "f")

    passMCsubtractMerge.SetFillColor(622)
    passMCsubtractMerge.SetLineColor(622)
    #passMCsubtractMerge.GetXaxis().SetTitle("DDB")
    #passMCsubtractMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(passMCsubtractMerge, "t#bar{t} mistag", "f")

    subtractedDataMerge.SetLineColor(1)
    subtractedDataMerge.SetMarkerStyle(20)
    subtractedDataMerge.SetMarkerSize(1.5)
    #subtractedDataMerge.GetXaxis().SetTitle("DDB")
    #subtractedDataMerge.GetYaxis().SetTitle("Events/Bin")
    leg2.AddEntry(subtractedDataMerge, "Subtracted Data", "lep")

    failMCsubtractMerge.Draw("hist")
    passMCsubtractMerge.Draw("histsame")
    subtractedDataMerge.Draw("e1same")
    leg2.Draw()

    lt2 = TLatex()
    if ana_ == "Inclusive":
        lt2.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt2.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt2.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt2.DrawLatexNDC(0.23, 0.85,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt2.DrawLatexNDC(0.23, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt2.DrawLatexNDC(0.23, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt2.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt2.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")

    c2.SaveAs(dir + "Merged_subtrac.pdf")  #

    #----------------------- canvas 3 -----------------------#

    c3 = myCanvas(c="c3", size=[700, 900])

    pad1 = TPad("pad1", "", 0.01, 0.25, 0.93, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetRightMargin(0.05)
    pad1.SetLeftMargin(0.17)
    pad1.SetBottomMargin(0.05)

    pad2 = TPad("pad2", "", 0.0, 0.0, 0.375, 0.24)
    pad2.SetTopMargin(0.0)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.0)
    pad2.SetBottomMargin(0.0)

    pad3 = TPad("pad3", "", 0.38, 0.025, 0.94, 0.25)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin(0.0)
    pad2.SetLeftMargin(0.45)
    pad2.SetBottomMargin(0.2)

    pad1.Draw()
    pad2.Draw()
    pad3.Draw()

    #* Pad 1 *#
    pad1.cd()
    leg3 = myLegend(coordinate=[0.65, 0.4, 0.75, 0.5])

    xaxisname = arr.array('d', [1, 2])
    zero1 = np.zeros(2)

    gPad.Modified()
    gPad.SetGridy()

    gr1 = TGraphErrors(2, xaxisname, ttMC_fraction, zero1, ttMC_error)
    gr1.SetTitle("t#bar{t}")
    gr1.SetLineColor(870)
    gr1.SetLineWidth(3)
    gr1.SetMarkerStyle(20)
    gr1.SetMarkerColor(870)
    leg3.AddEntry(gr1, "t#bar{t}", "lep")

    gr2 = TGraphErrors(2, xaxisname, ttData_fraction, zero1, ttData_error)
    gr2.SetTitle("t#bar{t} Data")
    gr2.SetLineColor(1)
    gr2.SetLineWidth(2)
    gr2.SetMarkerStyle(20)
    gr2.SetMarkerColor(1)
    leg3.AddEntry(gr2, "t#bar{t} Data", "lep")

    mg = TMultiGraph("mg", "")
    mg.Add(gr1)
    mg.Add(gr2)
    mg.GetHistogram().SetMaximum(1.5)
    mg.GetHistogram().SetMinimum(0)
    mg.GetYaxis().SetTitle("Fraction")
    mg.GetXaxis().SetLimits(0, 3)
    mg.GetXaxis().SetTickLength(0.03)
    mg.GetXaxis().SetNdivisions(103)
    mg.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Fail")
    mg.GetXaxis().ChangeLabel(1, -1, 0)
    mg.GetXaxis().ChangeLabel(-1, -1, 0)
    mg.GetXaxis().ChangeLabel(3, -1, -1, -1, -1, -1, "Pass")
    mg.Draw("AP")
    leg3.Draw()

    lt3 = TLatex()
    if ana_ == "Inclusive":
        lt3.DrawLatexNDC(0.17, 0.92, "#scale[0.7]{#bf{" + ana_ + "}}")
    if ana_ == "PT-200-350" or ana_ == "PT-350-500" or ana_ == "PT-500-2000":
        words = ana_.split("-")
        if words[2] == "2000":
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-Inf GeV}}")
        else:
            lt3.DrawLatexNDC(
                0.17, 0.92, "#scale[0.7]{#bf{p_{T} " + words[1] + "-" +
                words[2] + " GeV}}")
    else:
        words = ana_.split("-")
        lt3.DrawLatexNDC(
            0.17, 0.92, "#scale[0.7]{#bf{" + words[0] + " " + words[1] + "-" +
            words[2] + " GeV}}")
    lt3.DrawLatexNDC(0.19, 0.855,
                     "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
    lt3.DrawLatexNDC(0.19, 0.805, "#scale[0.7]{#bf{t#bar{t} CR (e+#mu)}}")
    lt3.DrawLatexNDC(0.19, 0.755, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
    if year_ == 2017:
        lt3.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")
    if year_ == 2018:
        lt3.DrawLatexNDC(0.71, 0.92,
                         "#scale[0.7]{#bf{58.827 fb^{-1} (13 TeV)}}")
    lt3.Draw()

    pad1.Update()

    #* Pad 2 *#
    pad2.cd()

    MCpassMerge.SetFillColor(0)
    MCpassMerge.SetLineColor(870)
    MCpassMerge.SetLineWidth(3)
    MCpassMerge.SetMarkerColor(870)
    MCpassMerge.SetMarkerStyle(20)
    MCpassMerge.GetYaxis().SetTitle("Fraction")
    MCpassMerge.GetYaxis().SetTitleSize(0.09)
    MCpassMerge.GetYaxis().SetLabelSize(0.1)
    MCpassMerge.GetYaxis().SetNdivisions(404)
    MCpassMerge.SetMaximum(0.3)
    MCpassMerge.SetMinimum(0.0)
    MCpassMerge.GetXaxis().SetTitle("")
    MCpassMerge.GetXaxis().SetLabelOffset(0.02)
    MCpassMerge.GetXaxis().SetLabelSize(0.09)
    MCpassMerge.GetXaxis().SetNdivisions(104)
    MCpassMerge.GetXaxis().ChangeLabel(2, -1, -1, -1, -1, -1, "Pass")
    MCpassMerge.GetXaxis().ChangeLabel(1, -1, 0)
    MCpassMerge.GetXaxis().ChangeLabel(-1, -1, 0)

    datapassMerge.SetFillColor(0)
    datapassMerge.SetLineColor(1)
    datapassMerge.SetLineWidth(2)
    datapassMerge.SetMarkerColor(1)
    datapassMerge.SetMarkerStyle(20)

    MCpassMerge.Draw("e1")
    datapassMerge.Draw("e1histsame")

    #* Pad 3 *#
    pad3.cd()

    SF = sfMerge.Integral()
    print "******"
    print "mistag SF:", SF

    SFfinal = round(SF, 3)
    SFtext = "SF = " + str(SFfinal)

    mistagSFmax = SF + 0.2
    mistagSFmin = SF - 0.2

    sfMerge.SetLineColor(797)
    sfMerge.SetMarkerColor(797)
    sfMerge.SetLineWidth(3)
    sfMerge.SetMaximum(mistagSFmax)
    sfMerge.SetMinimum(mistagSFmin)
    sfMerge.GetXaxis().SetTitle(" ")
    sfMerge.GetXaxis().SetLabelOffset(999)
    sfMerge.GetXaxis().SetLabelSize(0)
    sfMerge.GetXaxis().SetTickLength(0)
    sfMerge.GetYaxis().SetLabelSize(0.1)
    sfMerge.GetYaxis().SetNdivisions(404)
    sfMerge.GetYaxis().SetTitle(" ")

    sfMerge.Draw("e1hist")

    pt = TPaveText(0.21, 0.72, 0.31, 0.8, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.1)
    pt.AddText(SFtext)
    pt.Draw()

    c3.SaveAs(dir + "Merge_SF.pdf")  #

    passedBfrSubtactDataMerge = (passedTopEdataBfrSubtract +
                                 passedTopMudataBfrSubtract).Integral()
    failedBfrSubtractDataMerge = (failedTopEdataBfrSubtract +
                                  failedTopMudataBfrSubtract).Integral()

    passbackground = (wjetsTopEpassed + wjetsTopMupassed + dibosonTopEpassed +
                      dibosonTopMupassed + stTopEpassed +
                      stTopMupassed).Integral()
    failbackground = (wjetsTopEfailed + wjetsTopMufailed + dibosonTopEfailed +
                      dibosonTopMufailed + stTopEfailed +
                      stTopMufailed).Integral()
    totalbackground = (wjetsMerge + dibosonMerge + stMerge).Integral()

    #get the statistical uncertainty#

    dx = ttData_error[1]
    print "data efficiency error", dx

    dy = ttMC_error[1]
    print "MC efficiency error", dy

    x = datapassMerge.Integral()
    y = MCpassMerge.Integral()

    statUnc = TMath.Sqrt(((dx**2) / (y**2)) + ((x**2) * (dy**2) / (y**4)))
    #print "statistical Uncertainty in Top (e+muon) CR", statUnc
    #print " "
    print "relative statistical Uncertainty in Top (e+muon) CR", statUnc / SF * 100, " %"
    print " "

    print "DDB Mistag SF and stat: ", round(SF, 3), " +- ", round(statUnc,
                                                                  3), " (stat)"
    #print "theoretical statistical uncertainty of data efficiency", TMath.Sqrt((x*(1-x))/(subtractedDataMerge.Integral()))
    #print "theoretical statistical uncertainty of MC efficiency", TMath.Sqrt((y*(1-y))/(totalMCmerge.Integral()))
    #print " "

    header = ["Process", "Number of Events", "Top (e+muon)"]
    row1 = [
        " ", "DDB mistag SF",
        str(SFfinal) + " +- " + str(round(statUnc, 3)) + " (stat)"
    ]
    row2 = ["tt MC", "Pass (not normalized)", ""]
    row3 = [
        " ", "Pass (normalized)",
        str(round(passMCsubtractMerge.Integral(), 2))
    ]
    row4 = [" ", "Fail (not normalized)", ""]
    row5 = [
        " ", "Fail (normalized)",
        str(round(failMCsubtractMerge.Integral(), 2))
    ]
    row6 = [" ", "Total (not normalized)", ""]
    row7 = [" ", "Total (normalized)", str(round(totalMCmerge.Integral(), 2))]

    inforMC = [row2, row3, row4, row5, row6, row7]

    row8 = [
        "tt DATA", "Pass (before subtraction)",
        str(round(passedBfrSubtactDataMerge, 2))
    ]
    row9 = [" ", "Pass (after subtraction)", str(round(passdata, 2))]
    row10 = [
        " ", "Fail (before subtraction)",
        str(round(failedBfrSubtractDataMerge, 2))
    ]
    row11 = [" ", "Fail (after subtraction)", str(round(faildata, 2))]
    row12 = [
        " ", "Total (before subtraction)",
        str(round(unsubtractedDataMerge.Integral(), 2))
    ]
    row13 = [" ", "Total (after subtraction)", str(round(totaldata, 2))]

    inforDATA = [row8, row9, row10, row11, row12, row13]

    row14 = ["Background", "Pass (normalized)", str(round(passbackground, 2))]
    row15 = [" ", "Fail (normalized)", str(round(failbackground, 2))]
    row16 = [" ", "Total (normalized)", str(round(totalbackground, 2))]

    inforBKG = [row14, row15, row16]

    DDB_mistagSF.makeTable(header, row1, inforMC, inforDATA, inforBKG)
Exemple #20
0
def drawLatex(x=0.5, y=0.50, text="text", size=0.035, font=132, color=1):
    tl = TLatex(x, y, text)
    tl.SetTextSize(size)
    tl.SetTextFont(font)
    tl.SetTextColor(color)
    tl.DrawLatexNDC(x, y, text)
Exemple #21
0
def scanKK():
    '''Used to test the scan of one or more parameters'''
    nChips = 19 # the magic number
#     nChan = len(chans)

    iP = 1
    cd = CommonData()
    cd.setupConnection()
    sc1 = SensorConfig(cd)

    ### get list of chains to be updated
#     chains = set([sc1.tms1mmX19chainSensors[sc1.tms1mmX19sensorInChain[c]][0] for c in chans])

    chan = 5
#     cd.inputVs = [3., 0., 3., 0., 0., 0.]
#     cd.inputVs = [3., 0., 0.732, 1.68, 0., 0.]
#     cd.inputVs = [0.75, 2.15, 0.7, 0., 0., 0.]

    show = True
    g1 = None
    if show:
        g1 = TGraphErrors()

    xj = open('scan_KK_6.ttl','w')

    ### point insert scan
    ipar = 2
    pts = [(0.,None),(3.,None)]
    while True:
        print pts
        pt, xy, r1, k = insertPoint(pts)
        print '-'*30
        print pt,xy,r1, k
        print '-'*30
        if xy<3 and (r1<0.01 or xy/r1<0.1 or k<0.007): break

        cd.inputVs[ipar] = pt
        cd.updatePars(chan, None, False)
        sc1.update_sensor(chan)
        time.sleep(3)
        cd.fetch()

        m,v = getMeanVar(cd.adcData[chan])
        print ' '.join([str(x) for x in [chan, m, v]+cd.inputVs])
        xj.write(' '.join([str(x) for x in [chan, m, v]+cd.inputVs])+'\n')

        if g1:
            n1 = g1.GetN()
            g1.SetPoint(n1, pt, m)
            g1.SetPointError(n1, 0, v)

        if xy == 999:
            pts[r1] = (pt,m)
        else:
            pts.append((pt,m))

    ### simple scan
#     while cd.inputVs[0]>0.001:
#         cd.updatePars(chan, None, False)
#         sc1.update_sensor(chan)
#         time.sleep(2)
#         cd.fetch()
# 
#         m,v = getMeanVar(cd.adcData[chan])
#         print ' '.join([str(x) for x in [chan, m, v]+cd.inputVs])
#         xj.write(' '.join([str(x) for x in [chan, m, v]+cd.inputVs])+'\n')
# 
#         if g1:
#             g1.SetPoint(g1.GetN(), cd.inputVs[0], m)
#         cd.inputVs[0] *= 2./3
    if g1:
        g1.SetMarkerStyle(4)
        g1.SetMarkerColor(2)
        g1.SetLineColor(2)
        g1.Draw("AP")
        h1 = g1.GetHistogram()
        h1.GetXaxis().SetTitle(cd.voltsNames[ipar]+' [V]')
        h1.GetYaxis().SetTitle("V_{out} [V]")
        lt = TLatex()
        lt.DrawLatexNDC(0.2,0.92,"Chip %d"%chan)
        waitRootCmdX()
Exemple #22
0
class encChecker:
    def __init__(self):
        self.dataFiles = None
        self.bins = (50, 0, 1)
        self.Info = None
        self.lt = TLatex()

    def showENC(self):
        tree1 = TTree()
        header = 'idX/i:vL/F:vH:A:D/i:R:W'
        first = True
        for f in self.dataFiles:
            if first: tree1.ReadFile(f, header)
            else: tree1.ReadFile(f)

        p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', self.bins[0],
                      tree1.GetMinimum('vH-vL') * 0.8,
                      tree1.GetMaximum('vH-vL') * 1.2)
        tree1.Draw("D:(vH-vL)>>p1", "", "profE")

        ### change it to tgraph
        g1 = TGraphErrors()
        for i in range(p1.GetNbinsX() + 2):
            N = p1.GetBinEntries(i)
            if N > 0:
                print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                    i), p1.GetBinError(i)
                n = g1.GetN()
                g1.SetPoint(n,
                            p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
                g1.SetPointError(n, 0, p1.GetBinError(i))

        p1.Draw("axis")
        g1.Draw('Psame')

        fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
                   0.05, 0.3)
        fun1.SetParameter(0, 0.155)
        fun1.SetParameter(1, 0.005)

        g1.Fit(fun1)
        fun1a = g1.GetFunction('fun1')

        fun1a.SetLineColor(2)

        v0 = fun1a.GetParameter(0)
        e0 = fun1a.GetParError(0)
        v1 = fun1a.GetParameter(1)
        e1 = fun1a.GetParError(1)

        print v0, v1

        fUnit = 1000.
        self.lt.DrawLatexNDC(
            0.185, 0.89,
            '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
        self.lt.DrawLatexNDC(
            0.185, 0.84,
            '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))
        if self.Info:
            self.lt.DrawLatexNDC(0.185, 0.6, self.Info)

        print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
        fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
        fun2.SetLineColor(4)
        fun2.SetLineStyle(2)
        fun2.Draw('same')

        lg = TLegend(0.7, 0.4, 0.95, 0.5)
        lg.SetFillStyle(0)
        lg.AddEntry(p1, 'Measurement', 'p')
        lg.AddEntry(fun1a, 'Fit', 'l')
        lg.AddEntry(fun2, 'Gaus', 'l')
        lg.Draw()

        waitRootCmdX()
Exemple #23
0
class SigInfo:
    def __init__(self, data=None):
        self.resp = [] # [(t0, dT, tM, A),]
        self.lt = TLatex()
        self.sTag = sTag
        self.sDir = sDir
        self.autoSave = sDirectly
        if data:
            self.extract(data)
        else:
            self.bkgMu = None
            self.bkgVar = None
            self.quality = None
    def show(self, data, info=None, info2=None):
        x = [0.2*i for i in range(len(data))]
        g0 = TGraph(len(data), array('d',x), array('d',data))
        g0.Draw("AP")
        g0.GetHistogram().GetYaxis().SetTitle("V_{out} [V]")
        g0.GetHistogram().GetXaxis().SetTitle("t [#mus]")
#         g0.GetHistogram().GetYaxis().SetRangeUser(0.9, 1.4)

        if info: self.lt.DrawLatexNDC(0.2,0.8,info)
        if info2: self.lt.DrawLatexNDC(0.2,0.93,info2)

        global plot_count
        plot_count += 1

        waitRootCmdX(self.sDir+self.sTag+str(plot_count), self.autoSave)


    def showMore(self, data, info=None, info2=None):
        x = [0.2*i for i in range(len(data))]
        g0 = TGraph(len(data), array('d',x), array('d',data))
        g0.Draw("AP")
        g0.GetHistogram().GetYaxis().SetTitle("V_{out} [V]")
        g0.GetHistogram().GetXaxis().SetTitle("t [#mus]")
#         g0.GetHistogram().GetYaxis().SetRangeUser(0.9, 1.4)

        if info: self.lt.DrawLatexNDC(0.2,0.8,info)
        if info2: self.lt.DrawLatexNDC(0.2,0.93,info2)

        ### add info
        n1=500; n2=2000; np=20
        maxI, mx = max(enumerate(data[:-n2+np]), key=lambda p:p[1])
        minI, mn = min(enumerate(data[:-n2+np]), key=lambda p:p[1])
        dx = 0.5*(mx-mn)
        dn1 = sum(data[maxI+n1:maxI+n1+np])/np
        dn2 = sum(data[maxI+n2:maxI+n2+np])/np

        ## we want large dx, large #2 and small #3
#         return (0.5*(mx+mn), dx, 1-(mx-dn1)/dx, 1-(mx-dn2)/dx, maxI-minI)

        ### A line for the mean
        fun1 = TF1("fun1",str(0.5*(mx+mn)), 0, 99999999)
        fun1.SetLineColor(3)
        fun1.SetLineStyle(2)
        fun1.Draw("same")
        ### Draw 2 circles for max and min
        gr1 = TGraph()
        gr1.SetPoint(0, maxI*0.2, mx)
        gr1.SetMarkerColor(2)
        gr1.SetMarkerStyle(24)
        gr1.Draw("Psame")

        gr2 = TGraph()
        gr2.SetPoint(0, minI*0.2, mn)
        gr2.SetMarkerColor(4)
        gr2.SetMarkerStyle(24)
        gr2.Draw("Psame")
        ### Add two arrows for the the n50 and n2000
        gr3 = TGraph()
        gr3.SetPoint(0, (maxI+n1)*0.2, dn1)
        gr3.SetMarkerColor(2)
        gr3.SetMarkerStyle(23)
        gr3.Draw("Psame")

        gr4 = TGraph()
        gr4.SetPoint(0, (maxI+n2)*0.2, dn2)
        gr4.SetMarkerColor(4)
        gr4.SetMarkerStyle(23)
        gr4.Draw("Psame")
       
        global plot_count
        plot_count += 1

        waitRootCmdX(self.sDir+self.sTag+str(plot_count), self.autoSave)

    def getQuickInfo(self, data, n1=500, n2=2000, np=20):
        '''Get some useful infomation quickly'''
        maxI, mx = max(enumerate(data[:-n2+np]), key=lambda p:p[1])
        minI, mn = min(enumerate(data[:-n2+np]), key=lambda p:p[1])
        dx = 0.5*(mx-mn)
        dn1 = sum(data[maxI+n1:maxI+n1+np])/np
        dn2 = sum(data[maxI+n2:maxI+n2+np])/np
#         dn1 = max(data[maxI+n1:maxI+n1+np])
#         dn2 = max(data[maxI+n2:maxI+n2+np])
#         print mx, dn1, dn2, dx,

#         avarged = [sum(data[50*t:min([50*t+50,len(data)])] for t in range(len(data)/50))]

        ## we want large dx, large #2 and small #3
        return (0.5*(mx+mn), dx, 1-(mx-dn1)/dx, 1-(mx-dn2)/dx, maxI-minI)

    def extract(self, data):
        self.resp = []
        nData = len(data)
        muS = 0
        var2S = 0
        for i in range(nData):
            muS += data[i]
            var2S += data[i]*data[i]

        ### remove the outliers one by one
        minMs = 3*3

        data2 = data[:]
        mu = muS/nData
        var2 = var2S/nData - mu*mu

        for i in range(nData):
            ## get max and idex
            mI, ms = max(enumerate([(x and pow(x-mu,2)/var2) for x in data2]), key=lambda p:p[1])
            data2[mI] = None
            idata = nData-i-1
            if isDebug: print mI, 'removed', idata, 'left. Max Zn=', ms 

            if ms<minMs: break
            mV = data[mI]

            var2S -= mV*mV
            muS -= mV

            mu = muS/idata
            var2 = var2S/idata - mu*mu

        self.bkgMu = mu
        self.bkgVar = sqrt(var2)

        ### get fragments
        iStart = None
        nLow = 0
        for i in range(nData):
            if data2[i] is not None and iStart is not None:
                if nLow == 0:
                    nLow += 1
                    if i+1<nData and data2[i+1] is None: continue ## require at least two consective None
                    if i+2<nData and data2[i+2] is None: continue ## require at least two consective None

                if i-iStart > 10:
                    mI, mx = max(enumerate(data[iStart:i]), key=lambda p:abs(p[1]-mu))
                    self.resp.append((iStart, i-iStart, mI, mx-mu))
                iStart = None
                nLow = 0
            elif iStart is None and data2[i] is None:
                iStart = i
        ### remove low quality peaks
        if len(self.resp) > 0:
            self.quality = max([abs(x[3]) for x in self.resp])
#         mx = max(self.resp, key=lambda p:abs(p[3]))
#         self.resp = [x for x in self.resp if abs(x[3])>0.3*mx[3]]
#         print mx


        if isDebug:
            print self.resp, self.quality
            print mu, var2, len([x for x in data2 if x is not None])

        x = [0.2*i for i in range(nData)]
        g0 = TGraph(nData, array('d',x), array('d',data))
        g0.Draw("AP")
        g0.GetHistogram().GetYaxis().SetTitle("V_{out} [V]")
        g0.GetHistogram().GetXaxis().SetTitle("t [#mus]")

        g1 = TGraph(nData, array('d',[x[0]*0.2 for x in enumerate(data2) if x[1] is not None]), array('d',[x[1] for x in enumerate(data2) if x[1] is not None]))
        g1.SetMarkerColor(2)
        g1.Draw('Psame')
        
        waitRootCmdX()
    pt.SetTextSize(0.04)

    for imult, iplot in enumerate(plotbinMB):
        if not iplot:
            continue
        cfPrompt.cd(imult+1).DrawFrame(0, 0, 25, 1.05, \
                                       ";#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} %s" % name)
        grfPrompt = fileres_MB[imult].Get("gFcConservative")
        grfPrompt.SetTitle(";#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} %s" %
                           name)
        grfPrompt.SetLineColor(colors[imult % len(colors)])
        grfPrompt.SetMarkerColor(colors[imult % len(colors)])
        grfPrompt.SetMarkerStyle(21)
        grfPrompt.SetMarkerSize(0.5)
        grfPrompt.Draw("ap")
        pt.DrawLatexNDC(0.15, 0.15, "%.1f #leq %s < %.1f (MB)" % \
                     (binsmin[imult], latexbin2var, binsmax[imult]))

    for imult, iplot in enumerate(plotbinHM):
        if not iplot:
            continue
        cfPrompt.cd(imult+1).DrawFrame(0, 0, 25, 1.05, \
                                       ";#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} %s" % name)
        grfPromptHM = fileres_trig[imult].Get("gFcConservative")
        grfPromptHM.SetTitle(";#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} %s" %
                             name)
        grfPromptHM.SetLineColor(colors[imult % len(colors)])
        grfPromptHM.SetMarkerColor(colors[imult % len(colors)])
        grfPromptHM.SetMarkerStyle(21)
        grfPromptHM.SetMarkerSize(0.5)
        grfPromptHM.Draw("ap")
        pt.DrawLatexNDC(0.15, 0.15, "%.1f #leq %s < %.1f (HM)" % \
Exemple #25
0
def showENC():
    fname1 = '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat'

    tree1 = TTree()
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat',
        'idX/i:vL/F:vH:A:D/i:R:W')
    tree1.ReadFile(
        '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan2_mod.dat'
    )

    tree1.Show(500)

    p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', 50, 0.12, 0.2)
    tree1.Draw("D:(vH-vL)>>p1", "", "profE")

    ### change it to tgraph
    g1 = TGraphErrors()
    for i in range(p1.GetNbinsX() + 2):
        N = p1.GetBinEntries(i)
        if N > 0:
            print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(
                i), p1.GetBinError(i)
            n = g1.GetN()
            g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i))
            g1.SetPointError(n, 0, p1.GetBinError(i))


#     g1.SetMarkerColor(3)
#     g1.SetLineColor(3)

    p1.Draw("axis")
    g1.Draw('Psame')

    fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))',
               0.05, 0.3)
    fun1.SetParameter(0, 0.155)
    fun1.SetParameter(1, 0.005)

    g1.Fit(fun1)
    fun1a = g1.GetFunction('fun1')

    #     p1.Fit(fun1)
    #     fun1a = p1.GetFunction('fun1')
    fun1a.SetLineColor(2)

    #     p1.Draw("Esame")

    v0 = fun1a.GetParameter(0)
    e0 = fun1a.GetParError(0)
    v1 = fun1a.GetParameter(1)
    e1 = fun1a.GetParError(1)

    print v0, v1

    fUnit = 1000.
    lt = TLatex()
    lt.DrawLatexNDC(
        0.185, 0.89,
        '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit))
    lt.DrawLatexNDC(
        0.185, 0.84,
        '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit))

    print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)
    fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1))
    fun2.SetLineColor(4)
    fun2.SetLineStyle(2)
    fun2.Draw('same')

    lg = TLegend(0.7, 0.4, 0.95, 0.5)
    lg.SetFillStyle(0)
    lg.AddEntry(p1, 'Measurement', 'p')
    lg.AddEntry(fun1a, 'Fit', 'l')
    lg.AddEntry(fun2, 'Gaus', 'l')
    lg.Draw()

    waitRootCmdX()
Exemple #26
0
def DrawBazil(diagonal=175, doData=False, pname='limits'):
    import numpy as np
    # 'mstop','mlsp','sm2','sm1','central','sp1','sp2', 'data'
    d = GetDic(pname + '.p', diagonal)
    x = np.array(d['mstop'])
    e = np.array(d['exp'])
    y1max = np.array(d['s+1'])
    y2max = np.array(d['s+2'])
    y1min = np.array(d['s-1'])
    y2min = np.array(d['s-2'])
    # observed
    if (doData): o = np.array(d['obs'])
    else: o = np.array(d['exp'])

    c1 = TCanvas("c1", "CL", 10, 10, 800, 600)
    #c1.SetGrid();

    ymax = 7.5
    ymin = 0.3
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        ymax = 3.1
        ymin = 0.30
    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        ymax = 2.5
        ymin = 0.15

    #c1.DrawFrame(min(x)-2,min(d['sp2']+d['sm2'])-0.2,max(x)+2,max(d['sp2']+d['sm2'])+0.2);
    c1.DrawFrame(min(x), ymin, max(x), ymax)

    n = len(e)
    gr1min = TGraph(n, x, y1min)
    gr1max = TGraph(n, x, y1max)
    gr2min = TGraph(n, x, y2min)
    gr2max = TGraph(n, x, y2max)
    gro = TGraph(n, x, o)
    gre = TGraph(n, x, e)
    gh = TGraph(n, x, np.linspace(0.999, 1, n))
    gr1shade = TGraph(2 * n)
    gr2shade = TGraph(2 * n)

    #color1shade = 3; color2shade = 5;
    color1shade = kOrange
    color2shade = kGreen + 1
    for i in range(n):
        gr1shade.SetPoint(i, x[i], y1max[i] * scalefact)
        gr1shade.SetPoint(n + i, x[n - i - 1], y1min[n - i - 1] * scalefact)
        gr2shade.SetPoint(i, x[i], y2max[i] * scalefact)
        gr2shade.SetPoint(n + i, x[n - i - 1], y2min[n - i - 1] * scalefact)
        gre.SetPoint(i, x[i], e[i] * scalefact)
        gh.SetPoint(i, x[i], np.linspace(0.999, 1, n)[i] * scalefact)
        gro.SetPoint(i, x[i], o[i] * scalefact if doData else e[i] * scalefact)

    gr2shade.SetFillColor(color2shade)
    gr2shade.Draw("f")
    gr1shade.SetFillColor(color1shade)
    gr1shade.Draw("f")
    gh.SetLineWidth(2)
    gh.SetMarkerStyle(0)
    gh.SetLineColor(46)
    gh.SetLineStyle(2)
    gh.Draw("LP")
    gro.SetLineWidth(2)
    gro.SetMarkerStyle(20)
    gro.SetMarkerSize(0.7)
    gro.SetLineColor(1)
    if doData: gro.Draw("LP")
    gre.SetLineWidth(2)
    gre.SetMarkerStyle(0)
    gre.SetLineColor(1)
    gre.SetLineStyle(6)
    gre.Draw("LP")

    gre.SetTitle("Expected")
    gro.SetTitle("Observed")
    gr1shade.SetTitle("Expected 1#sigma")
    gr2shade.SetTitle("Expected 2#sigma")

    leg = TLegend(.1, .65, .4, .9)
    leg.AddEntry(gro)
    leg.AddEntry(gre)
    leg.AddEntry(gr1shade, '', 'f')
    leg.AddEntry(gr2shade, '', 'f')
    leg.SetFillColor(0)
    leg.Draw("same")

    gre.SetFillColor(0)
    gro.SetFillColor(0)
    gr1shade.SetLineColor(color1shade)
    gr2shade.SetLineColor(color2shade)

    tit = "m_{#tilde{t}_{1}} - m_{#tilde{#chi}_{1}^{0}} = "
    dm = "0"
    ymax = 4.1
    ymin = 0.3
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        tit += "182.5 GeV"  #" + 7.5 GeV"
        dm = "m7p5"
        ymax = 2.2
        ymin = 0.15

    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        tit += "167.5 GeV"  #" - 7.5 GeV"
        dm = "7p5"
        ymax = 3.3
        ymin = 0.30
    else:
        tit += "175 GeV"
    Title = TLatex()
    Title.SetTextSize(0.060)
    Title.DrawLatexNDC(.42, .84, tit)
    Xaxis = TLatex()
    Xaxis.SetTextFont(42)
    Xaxis.DrawLatexNDC(0.8, 0.03, "m_{#tilde{t}_{1}} (GeV)")
    Yaxis = TLatex()
    Yaxis.SetTextFont(42)
    Yaxis.SetTextAngle(90)
    Yaxis.DrawLatexNDC(0.05, 0.15, "95% CL limit on signal strength")
    textCMS = TLatex()
    textCMS.SetTextSize(0.06)
    textCMS.SetTextSizePixels(22)
    textCMS.SetTextAlign(12)
    textCMS.DrawLatexNDC(.12, .93, "CMS")
    textLumi = TLatex()
    textLumi.SetTextFont(42)
    textLumi.SetTextSize(0.06)
    textLumi.SetTextSizePixels(22)
    textLumi.DrawLatexNDC(.58, .91, "%1.1f fb^{-1} (13 TeV)" % (lumi))  #35.9

    name = "brazil_%i" % diagonal
    name = "brazil_%s" % pname
    for form in ['pdf', 'png']:
        c1.Print(outputdir + name + '.%s' % form)
Exemple #27
0
leg.AddEntry(h_MET, "Data", "lep")

#-------Draw Histogram in Full Canvas---------#

h_TopMatchFinal.Draw("hist")
h_WmatchFinal.Draw("histsame")
h_unmatchFinal.Draw("histsame")
#h_ttHadFinal.Draw("histsame")
#h_ttLepFinal.Draw("histsame")
h_sumWJetsFinal.Draw("histsame")
h_sumDiboson.Draw("histsame")
h_MET.Draw("e1same")
leg.Draw()

lt = TLatex()
lt.DrawLatexNDC(0.24, 0.85,
                "#scale[0.8]{CMS} #scale[0.65]{#bf{#it{Internal}}}")
lt.DrawLatexNDC(0.24, 0.8, "#scale[0.7]{#bf{t#bar{t} CR (#mu)}}")
lt.DrawLatexNDC(0.24, 0.75, "#scale[0.5]{#bf{2-prong (bq) enriched}}")
lt.DrawLatexNDC(0.71, 0.92, "#scale[0.7]{#bf{41.5 fb^{-1} (13 TeV)}}")

padRatio.cd()

gPad.GetUymax()

ratio = dataPredRatio(data_=h_MET, totalBkg_=h_TopMatchFinal)
ratio.SetLineColor(1)
ratio.SetLineWidth(3)
ratio.SetMarkerSize(1.5)
ratio.GetXaxis().SetLabelSize(0.13)
ratio.GetXaxis().SetTitleOffset(1)
ratio.GetXaxis().SetTitleSize(0.13)
Exemple #28
0
effGraph.SetTitle("")
effGraph.GetXaxis().SetTitle("X [mm]")
effGraph.GetXaxis().SetTitleSize(0.05)
effGraph.GetXaxis().SetTitleOffset(0.90)
effGraph.GetXaxis().SetLabelSize(0.03)
#effGraph.GetXaxis().SetRangeUser(23.0,25.0)
effGraph.GetYaxis().SetTitle("Mean #Delta t [ns]")
effGraph.GetYaxis().SetTitleSize(0.05)
effGraph.GetYaxis().SetTitleOffset(0.92)
effGraph.GetYaxis().SetLabelSize(0.03)
effGraph.GetYaxis().SetRangeUser(-2, 2)

title = TLatex()
title.SetTextSize(0.05)
#title.SetTextAlign(13);
title.DrawLatexNDC(.2, .93, "CACTUS Pixel " + pixelName + " Analog")
c.Update()
c.SaveAs("CACTUS_DeltaTMeanVsX" + outputLabel + ".gif")

##########################
#1D MPV Vs Y
##########################
yLeftBoundary = yMin
yRightBoundary = yMax
yBinWidth = 0.1
yNBins = int((yRightBoundary - yLeftBoundary) / yBinWidth)

tmpHist2D = TH2F("tmpHist2D", ";Y [mm];Amplitude [mV]; NEvt", yNBins,
                 yLeftBoundary, yRightBoundary, 100, -10, 10)

tree.Draw(
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1],
                text_="",
                x_=0.5,
                y_=0.5,
                legendloc=[0.53, 0.13, 0.93, 0.39]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    #gStyle.SetTitleOffset(1.1,"Y");
    #gStyle.SetTitleOffset(0.9,"X");
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []

    ## Legend
    legpos = legendloc
    leg = TLegend(legpos[0], legpos[1], legpos[2], legpos[3])
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.049)

    from PlotTemplates import myCanvas1D
    c = myCanvas1D()
    c.SetLogy(logstatus[1])
    c.SetLogx(logstatus[0])
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)

    #c1_2 = TPad("c1_2","newpad",0.04,0.13,1,0.994)
    #c1_2.Draw()

    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()
    #c1_2.SetBottomMargin(0.013)
    #c1_2.SetLogy(logstatus[1])
    #c1_2.SetLogx(logstatus[0])

    #c1_2.cd()
    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])

    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            #print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            #histList[ii].Scale(1.0/histList[ii].Integral())
            maximum.append(histList[ii].GetMaximum())
            maximum.sort()
            ii = ii + 1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(100)  #1.4 for log
            histList[ih].SetMinimum(0.00001)  #1.4 for log
        if logstatus[1] is 0:
            histList[ih].SetMaximum(1.4)  #1.4 for log
            histList[ih].SetMinimum(0.001)  #1.4 for log
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("APL")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("PL same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("hist same")

        if tt is TGraphAsymmErrors:
            histList[ih].SetMaximum(10)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.052)
        histList[ih].GetYaxis().SetTitleOffset(1.08)
        histList[ih].GetYaxis().SetLabelSize(.052)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.14)
        #histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetNdivisions(508)
        from PlotTemplates import SetCMSAxis
        histList[ih] = SetCMSAxis(histList[ih], 1.0, 1.15)
        #histList[ih].GetXaxis().SetMoreLogLabels();
        #histList[ih].GetXaxis().SetNoExponent();
        #histList[ih].GetTGaxis().SetMaxDigits(3);

        i = i + 1
    '''
    pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.2,0.5,"CMS Internal")
    '''
    from PlotTemplates import drawenergy1D
    pt_ = drawenergy1D(False)
    for ipt in pt_:
        ipt.Draw()
    '''
    if len(text_) >0:
        ltx = TLatex()
        ltx.SetTextFont(42)
        ltx.SetTextSize(0.049)
        #text_f = "#font[42]{Phase Scan}"
        ltx.DrawTextNDC(x_,y_,text_)
    '''

    from PlotTemplates import ExtraText
    text_ex = ExtraText(text_, x_, y_)
    text_ex.Draw()

    ExtraText("ECAL Endcaps", 0.4, 0.85)
    ltx_ = TLatex()
    ltx_.SetTextFont(42)
    ltx_.SetTextSize(0.049)
    ltx_.DrawLatexNDC(0.32, 0.81, "L1 e-#gamma object p_{T} > 10 GeV")

    #text_ex.Draw()
    #pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC")
    #text = pt.AddText(0.65,0.5,"Phase Scan data #sqrt{s} = 13 TeV (2018)")
    #pt.Draw()

    #    t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC")
    #    t2a.SetBorderSize(0)
    #    t2a.SetFillStyle(0)
    #    t2a.SetTextSize(0.040)
    #    t2a.SetTextAlign(12)
    #    t2a.SetTextFont(62)
    #    histolabel1= str(fileVec[(len(fileVec)-1)])
    #    text1 = t2a.AddText(0.06,0.5,"CMS Internal")
    #    t2a.Draw()
    leg.SetHeader("Matched TP energy")
    leg.Draw()
    #
    #    c.cd()
    outputdirname = './'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
Exemple #30
0
def plotCorrelation(channel,var,DM,year,*parameters,**kwargs):
    """Calculate and plot correlation between parameters."""
    if DM=='DM0' and 'm_2' in var: return
    print green("\n>>> plotCorrelation %s, %s"%(DM, var))
    if len(parameters)==1 and isinstance(parameters[0],list): parameters = parameters[0]
    parameters  = [p.replace('$CAT',DM).replace('$CHANNEL',channel) for p in list(parameters)]
    
    title       = kwargs.get('title',     ""                )
    name        = kwargs.get('name',      ""                )
    indir       = kwargs.get('indir',     "output_%d"%year  )
    outdir      = kwargs.get('outdir',    "postfit_%d"%year )
    tag         = kwargs.get('tag',       ""                )
    plotlabel   = kwargs.get('plotlabel', ""                )
    order       = kwargs.get('order',     False             )
    era         = "%d-13TeV"%year
    filename    = '%s/higgsCombine.%s_%s-%s%s-%s.MultiDimFit.mH90.root'%(indir,channel,var,DM,tag,era)
    ensureDirectory(outdir)
    print '>>>   file "%s"'%(filename)
    
    # HISTOGRAM
    parlist = getParameters(filename,parameters)
    if order:
      parlist.sort(key=lambda x: -x.sigma)
    N       = len(parlist)     
    hist    = TH2F("corr","corr",N,0,N,N,0,N)
    
    for i in xrange(N): # diagonal
      hist.SetBinContent(i+1,N-i,1.0)
      hist.GetXaxis().SetBinLabel(1+i,parlist[i].title)
      hist.GetYaxis().SetBinLabel(N-i,parlist[i].title)
    for xi, yi in combinations(range(N),2): # off-diagonal
      r = parlist[xi].corr(parlist[yi])
      hist.SetBinContent(1+xi,N-yi,r)
      hist.SetBinContent(1+yi,N-xi,r)
      #print "%20s - %20s: %5.3f"%(par1,par2,r)
      #hist.Fill(par1.title,par2.title,r)
      #hist.Fill(par2.title,par1.title,r)
    
    # SCALE
    canvasH  = 160+64*max(10,N)
    canvasW  = 300+70*max(10,N)
    scaleH   =  800./canvasH
    scaleW   = 1000./canvasW
    scaleF   = 640./(canvasH-160)
    tmargin  = 0.06
    bmargin  = 0.14
    lmargin  = 0.22
    rmargin  = 0.12
    
    canvas = TCanvas('canvas','canvas',100,100,canvasW,canvasH)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(  tmargin ); canvas.SetBottomMargin( bmargin )
    canvas.SetLeftMargin( lmargin ); canvas.SetRightMargin( rmargin )
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    canvas.cd()
    
    frame = hist
    frame.GetXaxis().SetLabelSize(0.054*scaleF)
    frame.GetYaxis().SetLabelSize(0.072*scaleF)
    frame.GetZaxis().SetLabelSize(0.034)
    frame.GetXaxis().SetLabelOffset(0.005)
    frame.GetYaxis().SetLabelOffset(0.003)
    frame.GetXaxis().SetNdivisions(508)
    #gStyle.SetPalette(kBlackBody)
    #frame.SetContour(3);
    gStyle.SetPaintTextFormat(".2f")
    frame.SetMarkerSize(1.5*scaleF)
    #frame.SetMarkerColor(kRed)
    
    hist.Draw('COLZ TEXT')
    
    # TEXT
    if title:
      latex = TLatex()
      latex.SetTextSize(0.045)
      latex.SetTextAlign(33)
      latex.SetTextFont(42)
      latex.DrawLatexNDC(0.96*lmargin,0.80*bmargin,title)
    
    CMS_lumi.relPosX = 0.14
    CMS_lumi.CMS_lumi(canvas,13,0)
    gPad.SetTicks(1,1)
    gPad.Modified()
    frame.Draw('SAMEAXIS')
    
    canvasname = "%s/postfit-correlation_%s_%s%s%s"%(outdir,var,DM,tag,plotlabel)
    canvas.SaveAs(canvasname+".png")
    if args.pdf: canvas.SaveAs(canvasname+".pdf")
    canvas.Close()