Ejemplo n.º 1
0
def run_bonly_fit(file_name, out_file, ncpu, get_p, data_prefix="data", data_file_name="data.root", do_minos=False, cut=None):

    high = 300.
    rfile = R.TFile(file_name)

    ws = rfile.Get("combined")

    data = ws.data("obsData")

    model = ws.obj("ModelConfig")

    constr = model.GetNuisanceParameters()
    R.RooStats.RemoveConstantParameters(constr)

    # model.GetParametersOfInterest().first().setVal(0.)
    # model.GetParametersOfInterest().first().setConstant()

    pars = model.GetNuisanceParameters()

    # run the fit
    if cut:
        ws.obj("obs_x_sf").setRange("fit", 10, cut)
    if do_minos:
        res = model.GetPdf().fitTo(data, R.RooFit.Constrain(constr), R.RooFit.Save(), R.RooFit.PrintLevel(0), R.RooFit.Minos(), R.RooFit.Hesse(), R.RooFit.Range("fit"))
    else: 
        res = model.GetPdf().fitTo(data, R.RooFit.Constrain(constr), R.RooFit.Save(), R.RooFit.PrintLevel(0), R.RooFit.Range("fit"))


    fitPars = res.floatParsFinal()

    nPar = fitPars.getSize()

    t = PrettyTable()
    if do_minos:
        t.field_names = ['#', '', "Value", "Parabolic Error", "Minos Down", "Minos Up"]
    else:
        t.field_names = ['#', '', "Value", "Parabolic Error"]
    t.vertical_char = "&"
    for i in xrange(nPar):
        name = fitPars.at(i).GetName()
        val =  fitPars.at(i).getVal()
        err =  fitPars.at(i).getError()
        if do_minos:
            minos_up = fitPars.at(i).getErrorLo()
            minos_down = fitPars.at(i).getErrorHi()
            t.add_row((i, name, "{0:.3g}".format(val), "{0:.3g}".format(err), "{0:.3g}".format(minos_down), "{0:.3g}".format(minos_up)))

        else:
            t.add_row((i, name, "{0:.3g}".format(val), "{0:.3g}".format(err)))

    print t

    r = ROOT.get_results2(ws, res, cut, high)
    data_results = results_to_dict(r)

    f = open(out_file, 'w')

    json.dump(data_results, f, indent=3)

    f.close()

    plot_fitted_sf(ws)

    fullcor = res.correlationMatrix()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')

    # make Hinton-style correlation plot
    for i in xrange(fullcor.GetNrows()):
        for j in xrange(fullcor.GetNcols()):
            # if i<=j: continue
            c = fullcor[i][j]
            if abs(c) < 0.01: continue
            if c > 0: color='white'
            else: color='black'
            size = np.sqrt(np.abs(c))
            rect = Rectangle([i-size/2, j-size/2], size, size, facecolor=color, edgecolor='black', lw=0.1)
            ax.add_patch(rect)
    ax.set_xlim(0, fullcor.GetNrows())
    ax.set_ylim(0, fullcor.GetNrows())
    plt.gca().invert_yaxis()
    plt.tight_layout()

    plt.savefig("plots/correlation_full_sf.pdf")

    model.SetSnapshot(model.GetParametersOfInterest())

    money_take2.build_background_shape(ws, 'sf', money_take2.sf_backgrounds, log=True)
    money_take2.build_background_shape(ws, 'sf', money_take2.sf_backgrounds, log=False)


    R.gROOT.ProcessLineSync(".L KS/AndersonDarlingTestStat.cc+")

    AD = R.RooStats.AndersonDarlingTestStat(model.GetPdf())

    # get the test statistic on data
    ts = AD.Evaluate(data)

    if get_p:

        sampler = R.RooStats.ToyMCSampler(AD, 500)
        sampler.SetPdf(model.GetPdf())
        sampler.SetObservables(model.GetObservables())
        sampler.SetGlobalObservables(model.GetGlobalObservables())
        sampler.SetParametersForTestStat(model.GetParametersOfInterest())

        params = R.RooArgSet()
        params.add(model.GetNuisanceParameters())
        params.add(model.GetParametersOfInterest())

        if ncpu > 1:
            pc = R.RooStats.ProofConfig(ws, ncpu, "")
            sampler.SetProofConfig(pc)

        sampDist = sampler.GetSamplingDistribution(params)

        p = 1-sampDist.CDF(ts)

        print "P value:", p
        print "Test statistic on data: {:.7f}".format(ts)

        plot = R.RooStats.SamplingDistPlot()
        plot.AddSamplingDistribution(sampDist)

        plot.Draw()
        raw_input("...")

    print "Test statistic on data: {:.7f}".format(ts)

    return data_results