def writeFullUnc(pred_file):
    ''' Update the input root file, add a hist with total prediction and full uncertainty. '''
    f = rt.TFile(pred_file, 'UPDATE')
    h = TGraphAsymmErrors(f.Get(pred_total_name).Clone('bkgtotal_unc_sr'))
    h_pieces = {}
    for hname, sample in zip(graph_names, all_samples):
        h_pieces[sample] = TGraphAsymmErrors(
            f.Get(hname).Clone(sample + '_unc_sr'))
    print "%30s %10s %16s" % ('bin', 'total pred', 'total unc.')
    for ibin in xrange(0, h.GetN()):
        bin = binlist[ibin]
        val = h.GetY()[ibin]
        e_low, e_up = fullUnc[bin]
        h.SetPointEYlow(ibin, e_low)
        h.SetPointEYhigh(ibin, e_up)
        print "%30s %10.2f +%8.2f -%8.2f" % (bin, val, e_up, e_low)
        allVals[bin] = {'bkg': (val, e_low, e_up)}
        for sample in all_samples:
            val = yields[bin][sample]
            e_low, e_up = fullUnc_pieces[sample][bin]
            h_pieces[sample].SetPointEYlow(ibin, e_low)
            h_pieces[sample].SetPointEYhigh(ibin, e_up)
            allVals[bin][sample] = (val, e_low, e_up)
    h.Write('bkgtotal_unc_sr', rt.TObject.kOverwrite)
    for sample in all_samples:
        h_pieces[sample].Write(sample + '_unc_sr', rt.TObject.kOverwrite)
    f.Close()
Example #2
0
def GetTGraphAsymmErrors(histo, offset):

    graph_in = TGraphAsymmErrors(histo)
    graph_in.SetName(histo.GetName() + '_tmp')
    graph_out = TGraphAsymmErrors(histo)
    graph_out.SetName(histo.GetName() + '_offset')

    for i in range(graph_in.GetN()):
        graph_out.GetX()[i] = graph_in.GetX()[i] + offset
        graph_out.GetEXlow()[i] = graph_in.GetEXlow()[i] + offset
        graph_out.GetEXhigh()[i] = graph_in.GetEXhigh()[i] - offset

    x_min = graph_out.GetX()[0] - graph_out.GetEXlow()[0]
    if (x_min > 0): x_min = 0
    x_max = graph_out.GetX()[graph_out.GetN() -
                             1] + graph_out.GetEXhigh()[graph_out.GetN() - 1]
    graph_out.GetXaxis().SetLimits(x_min, x_max)

    return graph_out
Example #3
0
def writeFullUnc(pred_file):
    ''' Update the input root file, add a hist with total prediction and full uncertainty. '''
    f = rt.TFile(pred_file, 'UPDATE')
    h = TGraphAsymmErrors(f.Get(pred_total_name).Clone('bkgtotal_unc_sr'))
    h_syst = TGraphAsymmErrors(
        f.Get(pred_total_name).Clone('bkgtotal_syst_unc_sr'))
    h_pieces = {}
    h_syst_pieces = {}
    for hname, sample in zip(graph_names, all_samples):
        h_pieces[sample] = TGraphAsymmErrors(
            f.Get(hname).Clone(sample + '_unc_sr'))
        h_syst_pieces[sample + "_up"] = TH1F(sample + '_syst_up',
                                             sample + '_syst_up', 183, 0, 183)
        h_syst_pieces[sample + "_dn"] = TH1F(sample + '_syst_dn',
                                             sample + '_syst_dn', 183, 0, 183)
    print "%30s %10s %16s" % ('bin', 'total pred', 'total unc.')
    for ibin in xrange(0, h.GetN()):
        bin = binlist[ibin]
        val = h.GetY()[ibin]
        e_low, e_up = fullUnc[bin]
        h.SetPointEYlow(ibin, e_low)
        h.SetPointEYhigh(ibin, e_up)
        print "%30s %10.4f +%8.4f -%8.4f" % (bin, val, e_up, e_low)
        allVals[bin] = {'bkg': (val, e_low, e_up)}
        # Test for only syst histograms
        val = h_syst.GetY()[ibin]
        e_low, e_up = systUnc[bin]
        h_syst.SetPointEYlow(ibin, e_low)
        h_syst.SetPointEYhigh(ibin, e_up)
        for sample in all_samples:
            val = yields[bin][sample]
            e_low, e_up = fullUnc_pieces[sample][bin]
            #print "%11s %30s %10.4f +%8.4f -%8.4f" % (sample, bin, val, e_up, e_low)
            h_pieces[sample].SetPointEYlow(ibin, e_low)
            h_pieces[sample].SetPointEYhigh(ibin, e_up)
            allVals[bin][sample] = (val, e_low, e_up)
            # Test for only syst histograms
            e_low, e_up = systUnc_rel_pieces[sample][bin]
            #if sample in test_samp and bin in test_bin and type in test_type and debug:
            #if 'TTZ' in sample and e_up > 8:
            #    print("%11s %30s %10.4f +%8.4f -%8.4f" % (sample, bin, val, e_up, e_low))
            h_syst_pieces[sample + "_up"].SetBinContent(ibin + 1, e_up)
            h_syst_pieces[sample + "_dn"].SetBinContent(ibin + 1, e_low)
            h_syst_pieces[sample + "_up"].SetBinError(ibin + 1, 0)
            h_syst_pieces[sample + "_dn"].SetBinError(ibin + 1, 0)
    h.Write('bkgtotal_unc_sr', rt.TObject.kOverwrite)
    h.Write('bkgtotal_syst_unc_sr', rt.TObject.kOverwrite)
    for sample in all_samples:
        h_pieces[sample].Write(sample + '_unc_sr', rt.TObject.kOverwrite)
        h_syst_pieces[sample + "_up"].Write(sample + '_syst_up',
                                            rt.TObject.kOverwrite)
        h_syst_pieces[sample + "_dn"].Write(sample + '_syst_dn',
                                            rt.TObject.kOverwrite)
    f.Close()
Example #4
0
def normalizeGraph(graph, binwidth):
    xsecSum = 0.
    for pt in range(1, graph.GetN()):
        xsecSum += graph.GetY()[pt] * binwidth[pt]
    normGraph = TGraphAsymmErrors(graph.GetN() - 1)
    for pt in range(0, normGraph.GetN()):
        normGraph.SetPoint(pt,
                           graph.GetX()[pt + 1],
                           graph.GetY()[pt + 1] / xsecSum)
        normGraph.SetPointEYhigh(pt, graph.GetErrorYhigh(pt + 1) / xsecSum)
        normGraph.SetPointEYlow(pt, graph.GetErrorYlow(pt + 1) / xsecSum)
    return normGraph
Example #5
0
    def calculate(self, histo):        
        from ROOT import TGraphAsymmErrors
        frac = self.__getWeightOneHisto(histo, self.__name)
        total = self.__getWeightOneHisto( histo, self.__norm)

        if(frac.GetEntries() > total.GetEntries()):
            raise StandardError," comparing '%s' to '%s' in '%s' makes no sense eff > 1!"%(self.__name, self.__norm, histo.GetName())
        
        eff = TGraphAsymmErrors(1)
        eff.BayesDivide(frac, total)
        if eff.GetN() < 1: 
            raise StandardError,"Efficiency cannot be calculated '%s' in '%s'"%(self.__name, histo.GetName())
        return ( eff.GetY()[0], (eff.GetEYlow()[0],eff.GetEYhigh()[0]) )
    def diffGraph(self, g, h, opt):
        gdiff = TGraphAsymmErrors(g)
        gdiff.SetName(g.GetName() + h.GetName() + '_diff')

        for i in range(0, gdiff.GetN()):
            x = Double(0.)
            y = Double(0.)
            g.GetPoint(i, x, y)
            gdiff.SetPoint(i, x, y - h.GetBinContent(i + 1))

            if opt == 1:  # keep bin errors
                pass
            elif opt == 2:
                gdiff.SetPointEYhigh(
                    i,
                    math.sqrt(g.GetErrorYhigh(i)**2 + h.GetBinError(i + 1)**2))

        return gdiff
    def createTGraphPoisson(self, h, w=1.):
        self.tfile.cd()
        g = TGraphAsymmErrors(h)
        for i in range(0, g.GetN()):
            y = h.GetBinContent(i + 1)
            binWidth = h.GetBinWidth(i + 1)

            # From https://twiki.cern.ch/twiki/bin/view/CMS/PoissonErrorBars
            alpha = 1. - 0.6827
            n = int(
                round(y * binWidth /
                      w))  # Round is necessary due to, well, rounding errors
            l = Math.gamma_quantile(alpha / 2., n, 1.) if n != 0. else 0.
            u = Math.gamma_quantile_c(alpha, n + 1, 1)
            # print y*binWidth/w, n, y, u, l
            g.SetPointEYlow(i, (n - l) / binWidth * w)
            g.SetPointEYhigh(i, (u - n) / binWidth * w)

        return g
Example #8
0
    def totalBkgWithStatErrors( self ):
        
        total_bkg_hist = None
        low, high = None, None

        for p in self.__processes:
            if p.isSignal():
                continue
            nbins = p.nominal().GetXaxis().GetNbins()
            if low is None: low = [0]*nbins
            if high is None: high = [0]*nbins
            
            if total_bkg_hist is None:
                total_bkg_hist = p.nominal().Clone()
            else:
                total_bkg_hist.Add( p.nominal() )
            gr = None
            if p.name() in ['nonpromptDF']: gr = self.__dfGraph
            elif p.name() in ['nonpromptSF']: gr = self.__sfGraph
            if gr:
                for ib in range(nbins):
                    low[ib] += math.pow(gr.GetEYlow()[ib], 2)
                    high[ib] += math.pow(gr.GetEYhigh()[ib], 2)
            else:
                for ib in range(nbins):
                    low[ib] += math.pow(p.nominal().GetBinError(ib), 2)
                    high[ib] += math.pow(p.nominal().GetBinError(ib), 2)
                            
        for ib in range(len(low)):
            low[ib] = math.sqrt(low[ib])
            high[ib] = math.sqrt(high[ib])
                    
        total_bkg_graph = TGraphAsymmErrors(total_bkg_hist)
        for ib in range(total_bkg_graph.GetN()):
            total_bkg_graph.SetPointEYlow(ib, low[ib])
            total_bkg_graph.SetPointEYhigh(ib, high[ib])
                    
        return [total_bkg_hist, total_bkg_graph]
Example #9
0
def readFile(fname, maxenergy=4.8):

    infile = file(fname, 'r')
    inlines = infile.readlines()

    graph = TGraphAsymmErrors()

    for iline in range(0, len(inlines)):
        line = inlines[iline]

        if '*' in line: continue

        lineparts = ' '.join(line.split()).strip().split(' ')

        if not check_number(lineparts[0:5]): continue

        energy = float(lineparts[0])
        R = float(lineparts[3])

        if (energy > maxenergy): continue

        statupp = abs(float(lineparts[4]))
        statlow = abs(float(lineparts[5]))

        (systlow, systupp) = systematics(iline, inlines)

        ipoint = graph.GetN()

        graph.SetPoint(ipoint, energy, R)

        graph.SetPointError(
            ipoint, 0, 0,
            math.sqrt(statlow * statlow + 1e-4 * systlow * systlow * R * R),
            math.sqrt(statupp * statupp + 1e-4 * systupp * systupp * R * R))

    return graph
Example #10
0
def ROC_GEN(load_s, load_b):
    n_scan = 10000000
    n_bins = 300  #100
    bin_i = 0
    bin_f = 1
    draw = 1

    param = {}
    param['n_scan'] = n_scan
    param['n_bins'] = n_bins
    param['bin_i'] = bin_i
    param['bin_f'] = bin_f
    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Loading data...'
    #load_s = joblib.load(pth+'/dumps/s.pkl')
    #load_b = joblib.load(pth+'/dumps/b.pkl')

    print len(load_b)

    # Calculate the bin vector:
    bin_width = float(bin_f - bin_i) / n_bins
    bin_value_dict = {}
    for j in xrange(n_bins):
        bin_value_dict[j] = bin_i + (0.5 + j) * bin_width
    #print bin_value_dict

    # if you want to use the GetCumulative() of a histogram and set its error: do not call the Sumw2() of it
    h_after_selection = TH1F('h_after_selection', 'hist_after_selection',
                             n_bins, bin_i, bin_f)
    #h_after_selection.Sumw2()
    h_before_selection = TH1F('h_before_selection', 'hist_before_selection',
                              n_bins, bin_i, bin_f)
    #h_before_selection.Sumw2()

    h_true_positive = TH1F('h_true_positive', 'True_Positives', n_bins, bin_i,
                           bin_f)
    h_true = TH1F('h_true', 'Trues', n_bins, bin_i, bin_f)
    # see if reversing the bin_min and bin_max will cause the histogram axis to reverse(no)
    #h_true          = TH1F('h_true'          ,'Trues'          , n_bins, bin_f, bin_i)

    h_c_b = TH1F('h_c_b', 'hist_after_selection_cum_rev', n_bins, bin_i, bin_f)
    #h_c_b.Sumw2()
    h_c_s = TH1F('h_c_s', 'hist_true_positives_cum_rev', n_bins, bin_i, bin_f)
    #h_c_s.Sumw2()

    ####################################
    ####################################

    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Filling histogram...'
    zeitA = time()

    df_b = load_b.copy()[:n_scan]
    df_b['bin'] = df_b['signal']
    #df_s        = load_s.copy()
    #df_s['bin'] = df_s['signal']

    df_list_pre_sel = []
    df_list_pos_sel = []

    def Appnd(tupl_in):
        df_list_pre_sel.append(tupl_in[0])
        df_list_pos_sel.append(tupl_in[1])

    def DataFrameExpand(k):
        mask_k_b = (bin_value_dict[k] - 0.5 * bin_width <= df_b['bin']) & (
            bin_value_dict[k] + 0.5 * bin_width > df_b['bin'])
        df_b['bin'][mask_k_b] = k
        #mask_k_s = ( bin_value_dict[k] - 0.5*bin_width <= df_s['bin'] ) & ( bin_value_dict[k] + 0.5*bin_width > df_s['bin'] )
        #df_s['bin'][mask_k_s] = k

        mask_k = df_b.bin == k
        df_b_w_k = df_b.weight[mask_k]

        df_list_k_pre_sel = []
        df_list_k_pos_sel = []
        for kk in xrange(n_bins):
            df_tmp_kk_pre_sel = pd.DataFrame()
            df_tmp_kk_pre_sel['weight'] = df_b_w_k
            df_tmp_kk_pre_sel['bin'] = bin_value_dict[kk]
            df_list_k_pre_sel.append(df_tmp_kk_pre_sel)
            if kk > k: continue
            df_tmp_kk_pos_sel = pd.DataFrame()
            df_tmp_kk_pos_sel['weight'] = df_b_w_k
            df_tmp_kk_pos_sel['bin'] = bin_value_dict[kk]
            df_list_k_pos_sel.append(df_tmp_kk_pos_sel)

        df_tmp_k_pre_sel = pd.concat(df_list_k_pre_sel)
        df_tmp_k_pos_sel = pd.concat(df_list_k_pos_sel)

        return df_tmp_k_pre_sel, df_tmp_k_pos_sel

    # Parallelization:
    ''' 
    pool_dfe = mp.Pool()
    for i in xrange(n_bins):
        pool_dfe.apply_async(DataFrameExpand, args=(i, ), callback=Appnd)
    pool_dfe.close()
    pool_dfe.join()
    '''
    for ii in xrange(n_bins):
        callback = DataFrameExpand(ii)
        Appnd(callback)
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~alternatives:
    #process = mp.Process(target=F, args=(k,))
    #manager = mp.Manager()
    #pool.map(FT,L)

    df_before_selection = pd.concat(df_list_pre_sel)
    df_after_selection = pd.concat(df_list_pos_sel)

    rnp.fill_hist(h_before_selection, df_before_selection.bin,
                  df_before_selection.weight)
    rnp.fill_hist(h_c_b, df_after_selection.bin, df_after_selection.weight)

    zeitB = time()
    print 'Time taken for filling histogram(for #events: ' + str(
        n_scan) + '): ', str(zeitB - zeitA)
    ####################################
    ####################################

    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Filling histogram (for tpr)...'
    zeitA = time()
    for index, row in load_s.iterrows():
        tmp_weight = row['weight']
        tmp_signal = row['signal']
        for k in xrange(n_bins):
            h_true.Fill(bin_value_dict[k], tmp_weight)
            if bin_value_dict[
                    k] - 0.5 * bin_width <= tmp_signal and bin_value_dict[
                        k] + 0.5 * bin_width > tmp_signal:
                for kk in xrange(k):
                    h_c_s.Fill(bin_value_dict[kk], tmp_weight)

    g_fpr = GAE()
    g_tpr = GAE()
    g_fpr.Divide(h_c_b, h_before_selection, "cl=0.683 b(1,1) mode")
    g_tpr.Divide(h_c_s, h_true, "cl=0.683 b(1,1) mode")

    g_size = g_fpr.GetN()

    x = Double()
    y = Double()
    x_s = Double()
    y_s = Double()

    arr_x = np.zeros(g_size)
    arr_y = np.zeros(g_size)
    arr_x_s = np.zeros(g_size)
    arr_y_s = np.zeros(g_size)

    for i in xrange(g_size):
        g_fpr.GetPoint(i, x, y)
        arr_x[i] = x
        arr_y[i] = y

        g_tpr.GetPoint(i, x_s, y_s)
        arr_x_s[i] = x_s
        arr_y_s[i] = y_s

    buffer_l = g_fpr.GetEYlow()
    buffer_l.SetSize(g_size)
    arr_l = np.array(buffer_l, copy=True)

    buffer_h = g_fpr.GetEYhigh()
    buffer_h.SetSize(g_size)
    arr_h = np.array(buffer_h, copy=True)
    #print arr_h
    #print arr_l

    buffer_l_s = g_tpr.GetEYlow()
    buffer_l_s.SetSize(g_size)
    arr_l_s = np.array(buffer_l_s, copy=True)

    buffer_h_s = g_tpr.GetEYhigh()
    buffer_h_s.SetSize(g_size)
    arr_h_s = np.array(buffer_h_s, copy=True)
    print len(arr_h)
    print len(arr_l)

    #######################
    # Calculate AOC       #
    #######################
    '''
    x   = np.array(arr_y_s)
    y   = np.array(arr_y)
    exl = np.array(arr_l_s)
    eyl = np.array(arr_l)
    exh = np.array(arr_h_s)
    eyh = np.array(arr_h)
    '''

    #######################
    # Export ROC Position #
    #######################
    roc_dict = {}
    roc_dict['param'] = param
    roc_dict['tpr'] = np.array(arr_y_s)
    roc_dict['fpr'] = np.array(arr_y)
    roc_dict['e_tpr_l'] = np.array(arr_l_s)
    roc_dict['e_fpr_l'] = np.array(arr_l)
    roc_dict['e_tpr_h'] = np.array(arr_h_s)
    roc_dict['e_fpr_h'] = np.array(arr_h)
    roc_dict['threshold'] = bin_value_dict

    roc_dict['cut_based'] = {}
    #roc_dict['cut_based']['lc'] = LC_dict
    #roc_dict['cut_based']['hc'] = HC_dict
    #roc_dict['aoc']       = aoc
    #roc_dict['aoc_l']       = aoc_l
    #roc_dict['aoc_h']       = aoc_h

    #raw_data           = {}
    #raw_data['load_s'] = load_s
    #raw_data['load_b'] = load_b
    #roc_dict['raw'] = raw_data
    '''
    path_dump = '/beegfs/desy/user/hezhiyua/2bBacked/roc_data/'
    name_dump = 'roc.pkl'
    joblib.dump(roc_dict, path_dump+name_dump)
    '''
    return roc_dict
name = ["300", "400", "600", "1000", "1200", "1400", "1600"]

err_sigeff_M1 = []


xM1 = ROOT.Double(0)
yM1 = ROOT.Double(0)


for i in range(nfile):
    preselect = file.Get("h_preselect_"+str(i))
    med1 = file.Get("h_med1_"+str(i))

    effM1 = TGraphAsymmErrors(med1,preselect,"cl=0.683 b(1,1) mode")
    effM1.SetTitle("Medium 1")
    binM1 = effM1.GetN()
    for j in range(binM1):
        effM1.GetPoint(j, xM1, yM1)
        if (yM1 == 0):
            continue
        else:
            errM1 = effM1.GetErrorY(j)
            err_sigeff_M1.append(errM1)
    #print "errM1_"+str(name[i]), errM1

'''
print "####################################"
print "err_sigeff_M1", err_sigeff_M1
print "####################################"
'''
Example #12
0
        h1.Delete()
        h2.Delete()

    print xl
    print yl
    print hl
    print ll
    exit()

    #g_fpr = GAE()
    g_tpr = GAE()
    #g_fpr.Divide(h_c_b, h_before_selection, "cl=0.683 b(1,1) mode")
    g_tpr.Divide(h1, h2, "cl=0.683 b(1,1) mode")

    g_size = g_tpr.GetN()

    #x        = Double()
    #y        = Double()
    x_s = Double()
    y_s = Double()

    #arr_x    = np.zeros(g_size)
    #arr_y    = np.zeros(g_size)
    arr_x_s = np.zeros(g_size)
    arr_y_s = np.zeros(g_size)

    for i in xrange(g_size):
        #g_fpr.GetPoint(i,x,y)
        #arr_x[i]   = x
        #arr_y[i]   = y
xM1 = ROOT.Double(0)
yM1 = ROOT.Double(0)

xM2 = ROOT.Double(0)
yM2 = ROOT.Double(0)

for i in range(nfile):
    preselect = file.Get("h_preselect_"+str(i))
    loo = file.Get("h_loo_"+str(i))
    med1 = file.Get("h_med1_"+str(i))
    med2 = file.Get("h_med2_"+str(i))

    #gPad.Modified()
    effL = TGraphAsymmErrors(loo,preselect,"cl=0.683 b(1,1) mode")
    effL.SetTitle("Loose")
    binL = effL.GetN()
    for j in range(binL):
        effL.GetPoint(j, xL, yL)
        if (yL == 0):
            continue
        else:
            errL = effL.GetErrorY(j)
            err_sigeff_L.append(errL)
    #print "errL_"+str(name[i]), errL

    effM1 = TGraphAsymmErrors(med1,preselect,"cl=0.683 b(1,1) mode")
    effM1.SetTitle("Medium 1")
    binM1 = effM1.GetN()
    for j in range(binM1):
        effM1.GetPoint(j, xM1, yM1)
        if (yM1 == 0):
Example #14
0
def plotQIcalibration(results, outDir = "results", currentMode = ""):
    gROOT.SetBatch(True)
    calibGraphs = []
    gStyle.SetMarkerColor(kBlue)
    gStyle.SetLineColor(kBlack)
    

    #for ch in xrange(1, len(results)+1):   # Number of channels
    for ch in sorted(results.keys()): 
        gr = TGraphAsymmErrors()
        gr.SetMarkerStyle(22)
        gr.SetMarkerSize(1.2)
        gr.SetName("Channel_%d_Charge_vs_DAC" % ch)
        gr.SetTitle("Channel %d  Charge vs DAC value%s" % (ch, "  %s current mode" % currentMode if currentMode in ["low", "high"] else ""))
        

        res = results[ch]
        for i, dacVal in enumerate(sorted(res.keys())):
            mean = res[dacVal]["mean"] * 25.e6  # Convert to fC
            err = res[dacVal]["std"] * 25.e6
   
            # Index of new point
            np = gr.GetN()
            
            # Set value and error
            gr.SetPoint(np, dacVal, mean)
            gr.SetPointError(np, 0., 0., err, err)
 
        calibGraphs.append((gr,ch))

    if outDir[-1] == "/": outDir = outDir[:-1]
    os.system("mkdir -p %s/calibGraphs" % outDir )

    c1 = TCanvas('c1','c1', 1200, 800)
    c1.SetLeftMargin(0.15);
    c1.SetRightMargin(0.25)
    c1.SetBottomMargin(0.25);
    pad1=TPad('p1','p1',0.,0.,1.0,1.0)
    pad1.Draw()

    outF = TFile.Open(outDir + "/calibration.root", "RECREATE")

    fitParams = {}   # Converted to charge by * 25ns

    for i,(gr,ch) in enumerate(calibGraphs):
        gr.Fit('pol1', "Q")   # Q: Quiet mode
        f = gr.GetFunction("pol1")
        p0 = f.GetParameter(0)
        p0_err = f.GetParError(0)
        p1 = f.GetParameter(1)
        p1_err = f.GetParError(1)
        
        fitline = "offset %g #pm %g   slope %g #pm %g" % (p0, p0_err, p1, p1_err)
        
        # Convert to fC
        fitParams[ch] = {"slope":(p1), "offset":(p0)}
        #fitParams[(i+1)] = {"slope":(p1), "offset":(p0)}
        

        gr.GetXaxis().SetTitle("DAC value")
        gr.GetYaxis().SetTitle("Charge [fC]")
        if currentMode == "low":
            gr.GetYaxis().SetTitleOffset(1.37)

        pad1.cd()
        gr.Draw("AP")
        gr.Write()
        txt=TLatex()
        txt.SetNDC(True)
        txt.SetTextFont(43)
        txt.SetTextSize(20)
        txt.SetTextAlign(12)
        txt.DrawLatex(0.40,0.87, fitline)
        Quiet(c1.SaveAs)(outDir + "/calibGraphs/channel_%d.png" % (i+1))
    
#    for g in adcGraphs:
 #       
  #      g.Write()

   # for g in chargeGraphs:
    #    g.Write()

    #outF.Write()
    outF.Close()
    return fitParams
def limit(method, channel):
    particle = channel[1:2]
    particleP = particle + "'" if channel.startswith('X') else channel[0]
    THEORY = ['A1', 'B3'] if channel.startswith('X') else []

    suffix = ""
    if method == "hvt": suffix = "_HVT"
    if method == "cls": suffix = "_CLs"
    if method == "monoH": suffix = "_monoH"

    filename = "./combine/" + method + "/" + channel + "_M%d.txt"
    mass, val = fillValues(filename)

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()
    Theory = {}

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue
        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0])
        Exp0s.SetPoint(n, m, val[m][3])
        Exp1s.SetPoint(n, m, val[m][3])
        Exp1s.SetPointError(n, 0., 0., val[m][3] - val[m][2],
                            val[m][4] - val[m][3])
        Exp2s.SetPoint(n, m, val[m][3])
        Exp2s.SetPointError(n, 0., 0., val[m][3] - val[m][1],
                            val[m][5] - val[m][3])
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        for m in sorted(HVT[t]['Z']['XS'].keys()):
            if m < mass[0] or m > mass[-1]: continue
            XsW, XsW_Up, XsW_Down, XsZ, XsZ_Up, XsZ_Down = 0., 0., 0., 0., 0., 0.
            XsZ = 1000. * HVT[t]['Z']['XS'][m] * HVT[t]['Z']['BR'][m]
            XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                            HVT[t]['Z']['PDF'][m][0] - 1.))
            XsZ_Down = XsZ * (1. - math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                              1. - HVT[t]['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsW + XsZ)
            Theory[t].SetPointError(n, 0., 0.,
                                    (XsW - XsW_Down) + (XsZ - XsZ_Down),
                                    (XsW_Up - XsW) + (XsZ_Up - XsZ))

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma(" + particleP + ") #bf{#it{#Beta}}(" +
                              particleP + " #rightarrow " + particle +
                              "h) (fb)")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.01, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(
        mass[0], min(mass[-1],
                     MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    drawAnalysis(channel)
    drawRegion(channel, True)
    drawCMS(LUMI, YEAR, "Preliminary")  #Preliminary

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()
    """
    if True and channel.endswith('sl'):
        mass, val = fillValues("./combine/alpha/X"+particle+"Hbonly_M%d.txt")
        Exp, Obs = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass):
            if not m in val: continue
            Exp.SetPoint(Exp.GetN(), m, val[m][3])
            Obs.SetPoint(Obs.GetN(), m, val[m][0])
        Exp.SetLineWidth(3)
        Exp.SetLineColor(602) #602
        Exp.SetLineStyle(5)
        Obs.SetLineWidth(3)
        Obs.SetLineColor(602)
        Exp.Draw("SAME, L")
        Obs.Draw("SAME, L")
        
        mass15, val15 = fillValues("./combine/Vh_2015/X"+particle+"h_M%d.txt")
        Exp15, Obs15 = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass15):
            if not m in val: continue
            Exp15.SetPoint(Exp15.GetN(), m, val15[m][3]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
            Obs15.SetPoint(Obs15.GetN(), m, val15[m][0]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
        Exp15.SetLineWidth(3)
        Exp15.SetLineColor(856) #602
        Exp15.SetLineStyle(6)
        Obs15.SetLineWidth(3)
        Obs15.SetLineColor(856)
        Exp15.Draw("SAME, L")
        #Obs15.Draw("SAME, L")
        
        leg2.AddEntry(Exp, "1+2 b-tag", "l")
    """
    if True and channel == 'AZh':
        massLL, valLL = fillValues("./combine/AZh/AZhll_M%d.txt")
        ExpLL, ObsLL = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massLL):
            if not m in val: continue
            ExpLL.SetPoint(ExpLL.GetN(), m, valLL[m][3] * multF)
            ObsLL.SetPoint(ObsLL.GetN(), m, valLL[m][0] * multF)
        ExpLL.SetLineWidth(3)
        ExpLL.SetLineColor(833)  #602
        ExpLL.SetLineStyle(5)
        ObsLL.SetLineWidth(3)
        ObsLL.SetLineColor(833)
        ExpLL.Draw("SAME, L")
        #ObsLL.Draw("SAME, L")

        massNN, valNN = fillValues("./combine/AZh/AZhnn_M%d.txt")
        ExpNN, ObsNN = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massNN):
            if not m in val: continue
            ExpNN.SetPoint(ExpNN.GetN(), m, valNN[m][3] * multF)
            ObsNN.SetPoint(ObsNN.GetN(), m, valNN[m][0] * multF)
        ExpNN.SetLineWidth(3)
        ExpNN.SetLineColor(855)  #602
        ExpNN.SetLineStyle(6)
        ObsNN.SetLineWidth(3)
        ObsNN.SetLineColor(855)
        ExpNN.Draw("SAME, L")
        #ObsNN.Draw("SAME, L")

        leg2.AddEntry(ExpLL,
                      "Expected, A #rightarrow Zh #rightarrow llb#bar{b}", "l")
        leg2.AddEntry(ExpNN,
                      "Expected, A #rightarrow Zh #rightarrow #nu#nub#bar{b}",
                      "l")

    if method == 'combo':
        massAH, valAH = fillValues("./combine/dijet/X" + particle +
                                   "Hah_M%d.txt")
        ExpAH = TGraphAsymmErrors()
        for i, m in enumerate(massAH):
            if not m in val: continue
            ExpAH.SetPoint(ExpAH.GetN(), m, valAH[m][3] * multF)
        ExpAH.SetLineWidth(2)
        ExpAH.SetLineColor(602)  #602
        ExpAH.SetLineStyle(4)
        ExpAH.Draw("SAME, L")

        massSL, valSL = fillValues("./combine/alpha/X" + particle +
                                   "Hsl_M%d.txt")
        ExpSL = TGraphAsymmErrors()
        for i, m in enumerate(massSL):
            if not m in val: continue
            ExpSL.SetPoint(ExpSL.GetN(), m, valSL[m][3] * multF)
        ExpSL.SetLineWidth(3)
        ExpSL.SetLineColor(860 - 9)  #602
        ExpSL.SetLineStyle(7)
        ExpSL.Draw("SAME, L")

        leg2.AddEntry(ExpAH, "B2G-17-002", "l")
        leg2.AddEntry(ExpSL, "B2G-17-004", "l")

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".png")
    c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".C")
        c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m,
        print ""

    print "p1s[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i] + Exp1s.GetErrorYhigh(i), ",",
    print "],"
    print "m1s[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i] - Exp1s.GetErrorYlow(i), ",",
    print "],"
    print "[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i], ",",
    print "]"

    #if not 'ah' in channel and not 'sl' in channel: return

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c2.Print("plotsLimit/Significance/" + channel + suffix + ".png")
    c2.Print("plotsLimit/Significance/" + channel + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+channel+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".png")
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+channel+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".png")
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+channel+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
def plotDataOverMCEff(hist_mc_tight,
                      hist_mc_loose,
                      hist_data_tight,
                      hist_data_loose,
                      plot_name='fakerate.pdf'):

    g = TGraphAsymmErrors(hist_mc_tight)
    g.Divide(hist_mc_tight, hist_mc_loose)
    g.GetYaxis().SetTitle('Fake rate')
    g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle())
    g.GetYaxis().SetTitleOffset(1.2)
    g.GetYaxis().SetTitleOffset(1.3)

    g.SetLineColor(2)
    g.SetMarkerColor(2)

    g_data = TGraphAsymmErrors(hist_data_tight)
    g_data.Divide(hist_data_tight, hist_data_loose)
    g_data.GetYaxis().SetTitle('Fake rate')
    g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle())
    g_data.GetYaxis().SetTitleOffset(1.2)
    g_data.GetYaxis().SetTitleOffset(1.3)
    g_data.SetMarkerColor(1)

    g_vals = g.GetY()
    g_data_vals = g_data.GetY()

    g_ratio = g_data.Clone('ratio')

    for i in xrange(g_data.GetN()):
        ratio = g_data_vals[i] / g_vals[i] if g_vals[i] else 0.
        g_ratio.SetPoint(i, g.GetX()[i], ratio)

        rel_y_low = math.sqrt((g_data.GetErrorYlow(i) / g_data_vals[i])**2 + (
            g.GetErrorYlow(i) /
            g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

        rel_y_high = math.sqrt(
            (g_data.GetErrorYhigh(i) / g_data_vals[i])**2 +
            (g.GetErrorYhigh(i) /
             g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)

    g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
    g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

    g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() /
                                      xtp_ratio)
    g_ratio.GetXaxis().SetTitleOffset(
        g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

    g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
    g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

    g_data.GetXaxis().SetLabelColor(0)
    g_data.GetXaxis().SetLabelSize(0)
    g.GetXaxis().SetLabelColor(0)
    g.GetXaxis().SetLabelSize(0)

    g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle())

    # maxy = 1.1 * min(g.GetMaximum(), g_data.GetMaximum(), 0.2)
    g.GetYaxis().SetRangeUser(0.001, 0.2)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    g.Draw('AP')
    g_data.Draw('P')

    legend = TLegend(0.23, 0.73, 0.43, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend.AddEntry(g.GetName(), 'MC', 'lep')
    legend.AddEntry(g_data.GetName(), 'Observed', 'lep')

    legend.Draw()

    padr.cd()
    g_ratio.GetYaxis().SetRangeUser(0.51, 1.49)
    g_ratio.GetYaxis().SetTitle('Obs/MC')
    g_ratio.Draw('AP')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)
def makeplot_single(
    h1_sig=None,
    h1_bkg=None,
    h1_data=None,
    sig_legends_=None,
    bkg_legends_=None,
    sig_colors_=None,
    bkg_colors_=None,
    hist_name_=None,
    sig_scale_=1.0,
    dir_name_="plots",
    output_name_=None,
    extraoptions=None
    ):

    if h1_sig ==  None or h1_bkg == None:
        print("nothing to plot...")
        return
    os.system("mkdir -p "+dir_name_)
    os.system("cp index.php "+dir_name_)
    s_color = [632, 617, 839, 800, 1]
    b_color = [920, 2007, 2005, 2003, 2001, 2011]
    if sig_colors_:
        s_color = sig_colors_
    if bkg_colors_:
        b_color = bkg_colors_
    for idx in range(len(h1_sig)):
        h1_sig[idx].SetLineWidth(3)
        h1_sig[idx].SetLineColor(s_color[idx])
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].SetLineWidth(2)
        h1_bkg[idx].SetLineColor(b_color[idx])
        h1_bkg[idx].SetFillColorAlpha(b_color[idx], 1)
    if h1_data:
        h1_data.SetBinErrorOption(1)
        h1_data.SetLineColor(1)
        h1_data.SetLineWidth(2)
        h1_data.SetMarkerColor(1)
        h1_data.SetMarkerStyle(20)

    myC = r.TCanvas("myC","myC", 600, 600)
    myC.SetTicky(1)
    pad1 = r.TPad("pad1","pad1", 0.05, 0.33,0.95, 0.97)
    pad1.SetBottomMargin(0.027)
    pad1.SetRightMargin( rightMargin )
    pad1.SetLeftMargin( leftMargin )
    pad2 = r.TPad("pad2","pad2", 0.05, 0.04, 0.95, 0.31)
    pad2.SetBottomMargin(0.4)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin( rightMargin )
    pad2.SetLeftMargin( leftMargin )

    pad2.Draw()
    pad1.Draw()

    pad1.cd()

    for idx in range(len(h1_sig)):
        print("before signal scaling",h1_sig[idx].Integral())
        h1_sig[idx].Scale(sig_scale_)
        print("after signal scaling",h1_sig[idx].Integral())
        
    stack = r.THStack("stack", "stack")
    nS = np.zeros(h1_bkg[0].GetNbinsX())
    eS = np.zeros(h1_bkg[0].GetNbinsX())
    #hist_all is used to make the data/mc ratio. remove signal for the moment due to signal is scaled right now
    hist_all = h1_sig[0].Clone("hist_all")
    hist_all.Scale(0.0)
    hist_s = h1_sig[0].Clone("hist_s")
    hist_b = h1_bkg[0].Clone("hist_b")
    for idx in range(len(h1_bkg)):
        stack.Add(h1_bkg[idx])
        for ib in range(h1_bkg[0].GetNbinsX()):
            nS[ib] += h1_bkg[idx].GetBinContent(ib+1)
            eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_bkg[idx].GetBinError(ib+1)*h1_bkg[idx].GetBinError(ib+1))
        hist_all.Add(h1_bkg[idx]) 
        if idx > 0:
            hist_b.Add(h1_bkg[idx]) 
            
    for idx in range(len(h1_sig)):
        print("ggH signal yield: ", hist_s.Integral())
        if idx > 0:
            hist_temp = h1_sig[idx].Clone(h1_sig[idx].GetName()+"_temp")
            #hist_all.Add(hist_temp)
            hist_s.Add(h1_sig[idx])
        print("all signal yield: ", hist_s.Integral())

    stack.SetTitle("")
    
    maxY = 0.0
    if "stack_signal" in extraoptions and extraoptions["stack_signal"]:
        for idx in range(len(h1_sig)):
            h1_sig[idx].SetFillColorAlpha(s_color[idx], 1)
            stack.Add(h1_sig[idx])
            for ib in range(h1_bkg[0].GetNbinsX()):
                nS[ib] += h1_sig[idx].GetBinContent(ib+1)
                eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_sig[idx].GetBinError(ib+1)*h1_sig[idx].GetBinError(ib+1))
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        #if "SR" in h.GetTitle(): 
        stack.Draw("hist")
    else:
        stack.Draw("hist")
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        for idx in range(len(h1_sig)):
            if h1_sig[idx].GetMaximum() > maxY:
                maxY = h1_sig[idx].GetMaximum()
            if "SR" in h1_bkg[0].GetTitle():
                #h1_sig[idx].Draw("samehist")
                hist_s.Draw("samehist")

    ##draw  stack total unc on top of total histogram
    box = r.TBox(0,0,1,1,)
    box.SetFillStyle(3002)
    box.SetLineWidth(0)
    box.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        box.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]-eS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]+eS[idx])

    if h1_data:
        if h1_data.GetMaximum() > maxY:
            maxY = h1_data.GetMaximum()+np.sqrt(h1_data.GetMaximum())
        #if not "SR" in h1_data.GetTitle() or "fail" in h1_data.GetTitle():  
        if True:
            #print("debug h1_data.GetName()",h1_data.GetName(), h1_data.GetTitle())           
            TGraph_data = TGraphAsymmErrors(h1_data)
            for i in range(TGraph_data.GetN()):
                #data point
                var_x, var_y = Double(0.), Double(0.)
                TGraph_data.GetPoint(i,var_x,var_y)    
                if np.fabs(var_y) < 1e-5:
                    TGraph_data.SetPoint(i,var_x,-1.0)
                    TGraph_data.SetPointEYlow(i,-1)
                    TGraph_data.SetPointEYhigh(i,-1)
                    #print("zero bins in the data TGraph: bin",i+1)
                else:
                    TGraph_data.SetPoint(i,var_x,var_y)
                    err_low = var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y))
                    TGraph_data.SetPointEYlow(i, var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))
                    TGraph_data.SetPointEYhigh(i, (0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)
        
            TGraph_data.SetMarkerColor(1)
            TGraph_data.SetMarkerSize(1)
            TGraph_data.SetMarkerStyle(20)
            TGraph_data.Draw("same P")

    stack.GetYaxis().SetTitle("Events")
    stack.GetYaxis().SetTitleOffset(1.05)
    stack.GetYaxis().SetTitleSize(0.08)
    stack.GetYaxis().SetLabelSize(0.06)
    #stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetLabelSize(0.)
    #stack.GetXaxis().SetLabelOffset(0.013)
    #if "xaxis_range" in extraoptions:
    #    stack.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    leg = r.TLegend(0.2, 0.60, 0.9, 0.88)
    leg.SetNColumns(3)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)
    for idx in range(len(h1_bkg)):
        leg.AddEntry(h1_bkg[idx], bkg_legends_[idx], "F")
    if "SR" in hist_s.GetTitle():
        leg.AddEntry(hist_s, 'HH #times {:1.2}'.format(sig_scale_), "L")

    leg.AddEntry(box, "Total  unc", "F")
    if h1_data:
        leg.AddEntry(h1_data, "Data", "ep")
    leg.Draw()

    pad2.cd()
    pad2.SetGridy(1)
    
    ratio = None
    ratio_Low  = 0.0
    ratio_High  = 4
    
    if h1_data:      
        ratio = TGraphAsymmErrors(h1_data)
        for i in range(ratio.GetN()):
            
            #bkg prediction
            imc = Double(hist_all.GetBinContent(i+1))
            #data point
            var_x, var_y = Double(0.), Double(0.)
            if not ("SR" in h1_data.GetTitle() and (i>5 and i<9)):
            	ratio.GetPoint(i,var_x,var_y)    
            if var_y == 0.:
                ratio.SetPoint(i,var_x,-1.0)
                ratio.SetPointEYlow(i,-1)
                ratio.SetPointEYhigh(i,-1)
                continue
            ratio.SetPoint(i,var_x,var_y/imc)
            err_low = (var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))/imc
            err_high = ((0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)/imc
            ratio.SetPointEYlow(i, err_low)
            ratio.SetPointEYhigh(i, err_high)
        
        ratio.SetMarkerColor(1)
        ratio.SetMarkerSize(1)
        ratio.SetMarkerStyle(20)
        ratio.GetXaxis().SetTitle("j_{2} regressed mass [GeV]")
        #myC.Update()
        
        if "ratio_range" in extraoptions:
            ratio_Low = extraoptions["ratio_range"][0]
            ratio_High = extraoptions["ratio_range"][1]
        ratio.GetYaxis().SetTitle("data/mc")
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High)
        ratio.GetXaxis().SetRangeUser(50, 220)
        ratio.SetTitle("")
        ratio.Draw("same AP")
        pad2.Update()
        
        print(ratio.GetTitle(),ratio.GetName(),"debug")
    else:
        ratio = h1_sig[0].Clone("ratio")
        ratio_High = 0.0
        for ibin in range(1,ratio.GetNbinsX()+1):
            s = hist_s.GetBinContent(ibin) 
            b = hist_b.GetBinContent(ibin)
            L = 0.0
            if b > 0.0:
                L = s/math.sqrt(b)
                if L > ratio_High:
                    ratio_High = L
            ratio.SetBinContent(ibin, L)
        if ratio_High > 1.0:
            ratio_High = 1.0
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High*1.2)
        ratio.GetYaxis().SetTitle("S/#sqrt{B}")
        ratio.Draw("samehist")
    ratio.SetLineColor(1)
    ratio.SetLineWidth(2)
    ratio.SetMarkerStyle(20)
    ratio.SetMarkerColor(1)
    ratio.SetFillColorAlpha(1, 0)
    ratio.GetXaxis().SetTitleOffset(0.94)
    ratio.GetXaxis().SetTitleSize(0.18)
    ratio.GetXaxis().SetLabelSize(0.12)
    ratio.GetXaxis().SetLabelOffset(0.013)
    ratio.GetYaxis().SetTitleOffset(0.40)
    ratio.GetYaxis().SetTitleSize(0.17)
    ratio.GetYaxis().SetLabelSize(0.13)
    ratio.GetYaxis().SetTickLength(0.01)
    ratio.GetYaxis().SetNdivisions(505)
    #if "xaxis_range" in extraoptions:
    #    ratio.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    #draw  stack total unc on the ratio plot to present the background uncertainty
    box_ratio = r.TBox(0,0,1,1,)
    box_ratio.SetFillStyle(3002)
    box_ratio.SetLineWidth(0)
    box_ratio.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        if np.fabs(nS[idx])> 1e-06: 
            box_ratio.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]-eS[idx])/nS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]+eS[idx])/nS[idx])
        else:
            print("blinded Higgs peak region") 
    
    if "xaxis_label" in extraoptions and extraoptions["xaxis_label"] != None:
        x_title = extraoptions["xaxis_label"]
        ratio.GetXaxis().SetTitle(x_title)
    ratio.GetYaxis().CenterTitle()

    ##########draw CMS preliminary
    pad1.cd()
    tex1 = r.TLatex(leftMargin, 0.91, "CMS")
    tex1.SetNDC()
    tex1.SetTextFont(61)
    tex1.SetTextSize(0.070)
    tex1.SetLineWidth(2)
    tex1.Draw()
    tex2 = r.TLatex(leftMargin+0.12,0.912,"Internal")
    tex2.SetNDC()
    tex2.SetTextFont(52)
    tex2.SetTextSize(0.055)
    tex2.SetLineWidth(2)
    tex2.Draw()

    lumi_value = 137
    if "lumi_value" in extraoptions:
        lumi_value = extraoptions["lumi_value"]
    tex3 = r.TLatex(0.72,0.912,"%d"%lumi_value+" fb^{-1} (13 TeV)")
    tex3.SetNDC()
    tex3.SetTextFont(42)
    tex3.SetTextSize(0.055)
    tex3.SetLineWidth(2)
    tex3.Draw()
    outFile = dir_name_
    if output_name_:
        outFile = outFile + "/" +output_name_
    else:
        outFile = outFile + "/" + hist_name_

    #print("maxY = "+str(maxY))
    stack.SetMaximum(maxY*1.7)

    #print everything into txt file
    text_file = open(outFile+"_linY.txt", "w")
    text_file.write("bin    |   x    ")
    for idx in range(len(h1_bkg)):
        text_file.write(" | %21s"%bkg_legends_[idx])
    text_file.write(" | %21s"%("total B"))
    for idx in range(len(sig_legends_)):
        text_file.write(" | %25s"%sig_legends_[idx])
    if h1_data:
        text_file.write(" | data | data/mc")
    text_file.write("\n-------------")
    for idx in range(24*(len(h1_bkg) + 1)+ 29*len(sig_legends_)):
        text_file.write("-")
    if h1_data:
        text_file.write("-------")
    text_file.write("\n")
    for ibin in range(0,h1_sig[0].GetNbinsX()+1):
        text_file.write("%3d"%ibin+"   ")
        text_file.write(" | %6.3f"%h1_data.GetBinCenter(ibin)+" ")
        for idx in range(len(h1_bkg)):
            text_file.write(" | %7.3f "%h1_bkg[idx].GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%h1_bkg[idx].GetBinError(ibin))
        text_file.write(" | %7.3f "%hist_b.GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%hist_b.GetBinError(ibin))
        for idx in range(len(sig_legends_)):
            text_file.write(" | %9.3f "%h1_sig[idx].GetBinContent(ibin)+"$\\pm$"+ " %9.3f"%h1_sig[idx].GetBinError(ibin))
        if h1_data:
            text_file.write(" | %d"%h1_data.GetBinContent(ibin) +  " | %7.3f "%h1_data.GetBinContent(ibin) +"$\\pm$"+ " %7.3f"%h1_data.GetBinError(ibin))
        text_file.write("\n\n")
        
    #print yield table for AN
    text_file.write("print yield table for AN\n")
    bkg_all = 0
    bkg_all_errsq = 0
    for idx in range(len(h1_bkg)):
        bkg_tmp = h1_bkg[idx].GetBinContent(7)+h1_bkg[idx].GetBinContent(8)+h1_bkg[idx].GetBinContent(9)
        bkg_errsq_tmp = h1_bkg[idx].GetBinError(7)*h1_bkg[idx].GetBinError(7)+h1_bkg[idx].GetBinError(8)*h1_bkg[idx].GetBinError(8)+h1_bkg[idx].GetBinError(9)*h1_bkg[idx].GetBinError(9)
        bkg_all += bkg_tmp
        bkg_all_errsq += bkg_errsq_tmp
        text_file.write("%s"%(bkg_legends_[idx])+"& %7.2f"%(bkg_tmp)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_errsq_tmp)+"\n")
    text_file.write("total background & %7.2f"%(bkg_all)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_all_errsq)+"\n")
    
    text_file.write("\ggHH SM ($\kapl=1$) & %7.2f"%((h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9)))+"\n")
    text_file.write("\VBFHH SM ($\kapl=1$) & %7.2f"%((h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9)))+"\n")
    
    text_file.write("HH bin 8 value %s"%h1_sig[0].GetBinContent(8)+"\n")
    text_file.write("HH bin 9 value %s"%h1_sig[0].GetBinContent(9)+"\n")
    text_file.write("HH bin 7 value %s"%h1_sig[0].GetBinContent(7)+"\n")

    text_file.write("HH bin 8 error %s"%h1_sig[0].GetBinError(8)+"\n")
    text_file.write("HH bin 9 error %s"%h1_sig[0].GetBinError(9)+"\n")
    text_file.write("HH bin 7 error %s"%h1_sig[0].GetBinError(7)+"\n")
    
    text_file.write("total & %7.2f"%(bkg_all+(h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9)+h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.2f"%(np.sqrt((h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9))/(sig_scale_*sig_scale_)+(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9))/(sig_scale_*sig_scale_)+bkg_all_errsq))+"\n")
    
    text_file.close()
    os.system("cp "+outFile+"_linY.txt "+outFile+"_logY.txt")

    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_linY.png")
    myC.SaveAs(outFile+"_linY.pdf")
    myC.SaveAs(outFile+"_linY.C")
    pad1.cd()
    stack.SetMaximum(maxY*100.0)
    stack.SetMinimum(0.5)
    pad1.SetLogy()
    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_logY.png")
    myC.SaveAs(outFile+"_logY.pdf")
    myC.SaveAs(outFile+"_logY.C")
    #save histogram and ratio to root file
    outFile_root = r.TFile(outFile+".root", "recreate")
    outFile_root.cd()
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].Write()
    for idx in range(len(sig_legends_)):
        h1_sig[idx].Write()
    if  h1_data:
        h1_data.Write()
        ratio.Write()
    #outFile_root.Write()
    outFile_root.Close()
Example #18
0
#slp(33)

g_tpr.SetTitle('True Positive Rate')
g_tpr.SetFillColor(5)
g_tpr.SetMarkerStyle(21)
g_tpr.SetMarkerColor(4)
#g_tpr.Draw('ALP')
#g_tpr.Draw('3A')a
#slp(33)
'''



from ROOT import Double

g_size   = g_efficiency.GetN()
g_size_s = g_tpr.GetN()

x        = Double()
y        = Double()

x_s      = Double()
y_s      = Double()

arr_x    = np.zeros(g_size)
arr_y    = np.zeros(g_size)

arr_x_s  = np.zeros(g_size_s)
arr_y_s  = np.zeros(g_size_s)

for i in range( g_size ):
Example #19
0
                    h14.GetBinError(b + 1) * h14.GetBinWidth(b + 1))
        origh14 = h14.Rebin(
            len(chi_binnings[massbin]) - 1,
            h14.GetName() + "rebinorig", chi_binnings[massbin])
        h14 = rebin2(h14,
                     len(chi_binnings[massbin]) - 1, chi_binnings[massbin])

        h14G = TGraphAsymmErrors(h14.Clone(histname + "G"))
        new_hists += [h14G]
        h14G.SetMarkerStyle(21)
        h14G.SetMarkerSize(0.4)
        h14G.SetMarkerColor(1)
        h14G.SetLineColor(1)
        alpha = 1. - 0.6827
        nevents = 0
        for b in range(h14G.GetN()):
            if unfoldedData:
                N = origh14.GetBinContent(b + 1)
            else:
                N = 1. / pow(
                    h14.GetBinError(b + 1) / h14.GetBinContent(b + 1), 2)
            print N
            nevents += N
            L = 0
            if N > 0:
                L = ROOT.Math.gamma_quantile(alpha / 2., N, 1.)
            U = ROOT.Math.gamma_quantile_c(alpha / 2., N + 1, 1.)
            h14G.SetPointEYlow(b, (N - L) / N * h14.GetBinContent(b + 1))
            h14G.SetPointEYhigh(b, (U - N) / N * h14.GetBinContent(b + 1))
        print "data events:", nevents
Example #20
0
def plotDataOverMCEff(hist_mc_tight, hist_mc_loose, hist_data_tight, hist_data_loose, plot_name='fakerate.pdf', mc_leg='MC', obs_leg='Observed', ratio_leg='Obs/MC'):

    g = TGraphAsymmErrors(hist_mc_tight)
    g.Divide(hist_mc_tight, hist_mc_loose)
    g.GetYaxis().SetTitle('Misidentification rate')
    g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle())
    g.GetYaxis().SetTitleOffset(1.2)
    g.GetYaxis().SetTitleOffset(1.3)

    g.SetLineColor(2)
    g.SetMarkerColor(2)

    g_data = TGraphAsymmErrors(hist_data_tight)
    g_data.Divide(hist_data_tight, hist_data_loose)

    # if g_data.GetN() != hist_data_tight.GetNbinsX():
    #     import pdb; pdb.set_trace()

    g_data.GetYaxis().SetTitle('Misidentification rate')
    g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle())
    g_data.GetYaxis().SetTitleOffset(1.2)
    g_data.GetYaxis().SetTitleOffset(1.3)
    g_data.SetMarkerColor(1)

    g_vals = g.GetY()
    g_data_vals = g_data.GetY()

    g_ratio = g_data.Clone('ratio')

    for i in xrange(g_data.GetN()):
        ratio = g_data_vals[i]/g_vals[i] if g_vals[i] else 0.
        g_ratio.SetPoint(i, g.GetX()[i], ratio)

        rel_y_low = math.sqrt((g_data.GetErrorYlow(i)/g_data_vals[i])**2 + (g.GetErrorYlow(i)/g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

        rel_y_high = math.sqrt((g_data.GetErrorYhigh(i)/g_data_vals[i])**2 + (g.GetErrorYhigh(i)/g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)

    g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
    g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

    g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() / xtp_ratio)
    g_ratio.GetXaxis().SetTitleOffset(g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

    g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
    g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

    g_data.GetXaxis().SetLabelColor(0)
    g_data.GetXaxis().SetLabelSize(0)
    g.GetXaxis().SetLabelColor(0)
    g.GetXaxis().SetLabelSize(0)

    g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle())

    maxy = 1.3 * max(g.GetMaximum(), g_data.GetMaximum(), 0.05)
    g.GetYaxis().SetRangeUser(0.0011, maxy)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    g.Draw('AP')
    g_data.Draw('P')

    legend = TLegend(0.23, 0.73, 0.43, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend.AddEntry(g.GetName(), mc_leg, 'lep')
    legend.AddEntry(g_data.GetName(), obs_leg, 'lep')

    legend.Draw()

    padr.cd()
    g_ratio.GetYaxis().SetRangeUser(0.01, 1.99)
    g_ratio.GetYaxis().SetTitle(ratio_leg)
    g_ratio.Draw('AP')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)

    g.GetYaxis().SetRangeUser(0.0001, 1)
    pad.SetLogy(True)
    cv.Print(plot_name.replace('.', '_log.'))
    f = ROOT.TFile(plot_name.replace('.', '_log.').replace('.pdf', '.root'), 'RECREATE')
    g.Write()
    g_data.Write()
    cv.Write()
    f.Close()
Example #21
0
g_fpr.SetMarkerStyle(21)
g_fpr.SetMarkerColor(4)
#g_fpr.Draw('ALP')
#g_fpr.Draw('ALPE1')
#g_fpr.Draw('3A')a
#slp(33)
g_tpr.SetTitle('True Positive Rate')
g_tpr.SetFillColor(5)
g_tpr.SetMarkerStyle(21)
g_tpr.SetMarkerColor(4)
#g_tpr.Draw('ALP')
#g_tpr.Draw('3A')a
#slp(33)
'''

g_size = g_fpr.GetN()

x = Double()
y = Double()
x_s = Double()
y_s = Double()

arr_x = np.zeros(g_size)
arr_y = np.zeros(g_size)
arr_x_s = np.zeros(g_size)
arr_y_s = np.zeros(g_size)

for i in xrange(g_size):
    g_fpr.GetPoint(i, x, y)
    arr_x[i] = x
    arr_y[i] = y
Example #22
0
def limit(channel, signal):
    multF = 1.  # in fb
    filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    if (options.mediator == 'SC'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    elif (options.mediator == 'PS'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_pseudo" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    else:
        print 'WRONG mediator type'
    mass, val = fillValues(filename)

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)
        #Sign.SetPoint(n, m, val[m][6])
        #pVal.SetPoint(n, m, val[m][7])
        #Best.SetPoint(n, m, val[m][8])
        #Best.SetPointError(m, 0., 0., abs(val[m][9]), abs(val[m][10]))

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma/#sigma_{th}")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{#phi} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogx()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #Theory[0].Draw("SAME, L")
    #Theory[1].Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.045)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetTitleSize(0.04)
    Exp2s.GetXaxis().SetLabelSize(0.04)
    Exp2s.GetYaxis().SetLabelSize(0.04)
    Exp2s.GetXaxis().SetTitleOffset(1)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.1, 1000.)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis("tDM")
    drawRegion(channel, True)
    drawCMS(LUMI, "Preliminary")

    if True:
        if (options.mediator == 'SC'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_scalar" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_pseudo" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        ExpT, ObsT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massT):
            if not m in val: continue
            ExpT.SetPoint(ExpT.GetN(), m, valT[m][3] * multF)
            ObsT.SetPoint(ObsT.GetN(), m, valT[m][0] * multF)
        ExpT.SetLineWidth(3)
        ExpT.SetLineColor(602)  #602
        ExpT.SetLineStyle(5)
        ObsT.SetLineWidth(3)
        ObsT.SetLineColor(602)
        ExpT.SetMarkerStyle(21)
        ObsT.SetMarkerStyle(22)
        ExpT.SetMarkerColor(602)
        ObsT.SetMarkerColor(602)
        ExpT.Draw("SAME, PC")
        #if not options.blind: ObsT.Draw("SAME, P")

        if (options.mediator == 'SC'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_scalar" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_pseudo" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")

        ExpTTT, ObsTTT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massTTT):
            if not m in val: continue
            ExpTTT.SetPoint(ExpTTT.GetN(), m, valTTT[m][3] * multF)
            ObsTTT.SetPoint(ObsTTT.GetN(), m, valTTT[m][0] * multF)
        ExpTTT.SetLineWidth(3)
        ExpTTT.SetLineColor(634)  #602
        ExpTTT.SetLineStyle(5)
        ObsTTT.SetLineWidth(3)
        ObsTTT.SetLineColor(634)
        ExpTTT.SetMarkerStyle(21)
        ObsTTT.SetMarkerStyle(22)
        ExpTTT.SetMarkerColor(634)
        ObsTTT.SetMarkerColor(634)
        ExpTTT.Draw("SAME, PC")
        #if not options.blind: ObsTTT.Draw("SAME, P")

    # legend
    top = 0.9
    nitems = 4 + 2

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.95, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected (t+DM, tt+DM)", "l")
    leg.AddEntry(Exp1s, "#pm 1 s. d.", "f")
    leg.AddEntry(Exp2s, "#pm 2 s. d.", "f")
    if True:
        leg.AddEntry(ExpT, "Expected (t+DM)", "p")
        leg.AddEntry(ExpTTT, "Expected (tt+DM)", "p")

    leg.Draw()
    c1.GetPad(0).RedrawAxis()
    c1.GetPad(0).Update()
    if gROOT.IsBatch():
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".png")
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    #    print "p1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]+Exp1s.GetErrorYhigh(i), ",",
    #    print "],"
    #    print "m1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]-Exp1s.GetErrorYlow(i), ",",
    #    print "],"
    #    print "[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i], ",",
    #    print "]"

    return

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".C")

# ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".C")

# --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".png")
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".pdf")


#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Example #23
0
#slp(33)

g_tpr.SetTitle('True Positive Rate')
g_tpr.SetFillColor(5)
g_tpr.SetMarkerStyle(21)
g_tpr.SetMarkerColor(4)
#g_tpr.Draw('ALP')
#g_tpr.Draw('3A')a
#slp(33)
'''



from ROOT import Double

g_size   = g_efficiency.GetN()
#g_size_s = g_tpr.GetN()

#print g_size
#print g_size_s

x        = Double()
y        = Double()

#x_s      = Double()
#y_s      = Double()

arr_x    = np.zeros(g_size)
arr_y    = np.zeros(g_size)

#arr_x_s  = np.zeros(g_size_s)