コード例 #1
0
def fit(model, hists, fitmethod, eps=1.0e-7):
    """Fit beam shapes to Beam Imaging data.

    model: Beam shape model (derived from BeamShapeCore).
    hists: List of four TH2F with BI data.
    fitmethod: Function(pdf, data) that fits pdf to data.
    eps: Value of convergence criteria.
    """

    RooAbsReal.defaultIntegratorConfig().setEpsAbs(eps)
    RooAbsReal.defaultIntegratorConfig().setEpsRel(eps)
    modfuncs = model.model_functions()

    datahist = [
        RooDataHist('scan{0}Beam{1}RestDataHist'.format(c, i),
                    'scan{0}Beam{1}RestDataHist'.format(c, i),
                    RooArgList(model.xvar(), model.yvar()), hists[j])
        for j, (i, c) in enumerate(ic)
    ]
    sample = RooCategory('sample', 'sample')
    for (i, c) in ic:
        sample.defineType('{0}_ScanData_Beam{1}Rest'.format(c, i))
    combdata = RooDataHist('combdata', 'combined data',
                           RooArgList(model.xvar(), model.yvar()),
                           RooFit.Index(sample),
                           RooFit.Import('X_ScanData_Beam1Rest', datahist[0]),
                           RooFit.Import('Y_ScanData_Beam1Rest', datahist[1]),
                           RooFit.Import('X_ScanData_Beam2Rest', datahist[2]),
                           RooFit.Import('Y_ScanData_Beam2Rest', datahist[3]))
    simpdf = RooSimultaneous('simpdf', 'simultaneous pdf', sample)
    for j, (i, c) in enumerate(ic):
        simpdf.addPdf(modfuncs[j], '{0}_ScanData_Beam{1}Rest'.format(c, i))

    result = fitmethod(simpdf, combdata)
    return result, modfuncs, datahist
コード例 #2
0
def performFitInLeptonAbsEta(data_histogram, signal_histogram, bkg1_histogram,
                             bkg2_histogram):
    N_Data = data_histogram.Integral()
    N_signal = signal_histogram.Integral()
    N_bkg1 = bkg1_histogram.Integral()
    N_bkg2 = bkg2_histogram.Integral()
    leptonAbsEta = RooRealVar("leptonAbsEta", "leptonAbsEta", 0., 3.)
    variables = RooArgList()
    variables.add(leptonAbsEta)
    variable_set = RooArgSet()
    variable_set.add(leptonAbsEta)

    lowerBound = 0
    upperBound = N_Data * 2

    data_RooDataHist = RooDataHist("data", "dataset with leptonAbsEta",
                                   variables, data_histogram)
    signal_RooDataHist = RooDataHist("rh_signal", "signal", variables,
                                     signal_histogram)
    bkg1_RooDataHist = RooDataHist("rh_bkg1", "bkg1", variables,
                                   bkg1_histogram)
    bkg2_RooDataHist = RooDataHist("rh_bkg2", "bkg2", variables,
                                   bkg2_histogram)

    signal_RooHistPdf = RooHistPdf("pdf_signal", "Signal PDF", variable_set,
                                   signal_RooDataHist, 0)
    signal_RooHistPdf = RooHistPdf("pdf_signal", "Signal PDF", variable_set,
                                   signal_RooDataHist, 0)
コード例 #3
0
def get_roofit_model( histograms, fit_boundaries, name = 'model' ):
    data_label = 'data'
    samples = sorted( histograms.keys() )
    samples.remove( data_label )
    roofit_histograms = {}
    roofit_pdfs = {}
    roofit_variables = {}
    variables = RooArgList()
    variable_set = RooArgSet()

    fit_variable = RooRealVar( name , name, fit_boundaries[0], fit_boundaries[1] )
    variables.add( fit_variable )
    variable_set.add( fit_variable )
    
    roofit_histograms[data_label] = RooDataHist( data_label,
                                                     data_label,
                                                     variables,
                                                     histograms[data_label] )
    
    pdf_arglist = RooArgList()
    variable_arglist = RooArgList()
    N_total = histograms[data_label].Integral() * 2
    N_min = 0
    for sample in samples:
        roofit_histogram = RooDataHist( sample, sample, variables, histograms[sample] )
        roofit_histograms[sample] = roofit_histogram
        roofit_pdf = RooHistPdf ( 'pdf' + sample, 'pdf' + sample, variable_set, roofit_histogram, 0 )
        roofit_pdfs[sample] = roofit_pdf
        roofit_variable = RooRealVar( sample, "number of " + sample + " events", histograms[sample].Integral(), N_min, N_total, "event" )
        roofit_variables[sample] = roofit_variable
        pdf_arglist.add( roofit_pdf )
        variable_arglist.add( roofit_variable )
        
    model = RooAddPdf( name, name, pdf_arglist, variable_arglist )
    return model, roofit_histograms, fit_variable
コード例 #4
0
ファイル: fits.py プロジェクト: DryRun/StatisticalTools
	def add_data(self, data_histogram):
		print "[MjFit.add_data] INFO : Adding data histogram"
		# Add a data histogram
		self.data_histogram_ = data_histogram.Clone()
		self.data_histogram_.SetDirectory(0)		
		self.data_roohistogram_ = RooDataHist('data_roohistogram','data_roohistogram',RooArgList(self.mjj_),self.data_histogram_)
		self.data_roohistogram_.Print()
コード例 #5
0
ファイル: helper.py プロジェクト: acappati/2018DataStudy
def DoRooFit(histo, title):
    can = makeCMSCanvas(str(random.random()),"Fit result ",900,700)
    
    #Varible
    if "ele" in title:
      x1 = RooRealVar("x1","m_{e^{+}e^{-}}",80,100)
    if "mu" in title:
      x1 = RooRealVar("x1","m_{#mu^{+}#mu^{-}}",80,100)

    #Define CB function
    m = RooRealVar("mean_{CB}","mean of gaussian",60,120)
    s = RooRealVar("#sigma_{CB}","width of gaussian",0,3)
    a = RooRealVar("#alpha_{CB}","mean of gaussian",0,100)
    n = RooRealVar("n_{CB}","width of gaussian",0,5)
    CB = RooCBShape("CB","CB PDF",x1, m, s, a, n)
    
    m.setConstant(kFALSE)
    s.setConstant(kFALSE)
    a.setConstant(kFALSE)
    n.setConstant(kFALSE)
    
    
    #Define Gaussian function
    mean1 = RooRealVar("mean_{G}","mean of gaussian",-60,60)
    sigma1 = RooRealVar("#sigma_{G}","width of gaussian",0,10)
    gauss1 = RooGaussian("gauss1","gaussian PDF",x1,mean1,sigma1)
    
    mean1.setConstant(kFALSE)
    sigma1.setConstant(kFALSE)
    
    #Starting values of the parameters
    mean1.setVal(1.0)
    sigma1.setVal(1.0)
    m.setVal(90.0)
    s.setVal(1.0)
    a.setVal(10.0)
    n.setVal(2.0)

    # Construct CB (x) gauss
    x1.setBins(10000, "cache")
    CBxG = RooFFTConvPdf("CBxG", "CB (X) gauss", x1, CB, gauss1)
    
    can.cd()
    d = RooDataHist("d","d",RooArgList(x1),RooFit.Import(histo))
    CBxG.fitTo(d, RooLinkedList())
   
    # Plot PDF and toy data overlaid
    xframe2 = x1.frame(RooFit.Name("xframe"),RooFit.Title("")) # RooPlot
    d.plotOn(xframe2, RooLinkedList() )
    CBxG.paramOn(xframe2, RooFit.Layout(0.65,0.99,0.9))
    xframe2.getAttText().SetTextSize(0.03)
    CBxG.plotOn(xframe2)
    xframe2.Draw()
    can.SaveAs("DataVsMC/FitResults/"+title+"_Roofit.pdf")
    can.SaveAs("DataVsMC/FitResults/"+title+"_Roofit.png")
    
    return;
コード例 #6
0
 def Gausintialization(self):
     round_energy = round(float(self.energy),-1)
     if round_energy ==240 : round_energy = 250
             
     self.x = RooRealVar("signal_%s_%dGeV"%(self.crystal,round_energy),"signal_%s_%dGeV"%(self.crystal,round_energy),max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.roohist = RooDataHist("roohist_fit_%s_%s"%(self.crystal,self.energy),"roohist_fit_%s_%s"%(self.crystal,self.energy),RooArgList(self.x),self.hist)
     self.m = RooRealVar("mean_%s_%s"%(self.crystal,self.energy),"mean_%s_%s"%(self.crystal,self.energy),self.peak_position,max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.s = RooRealVar("sigma_%s_%s"%(self.crystal,self.energy),"sigma_%s_%s"%(self.crystal,self.energy),self.s_initial,0.001,1.)
     self.sig = RooGaussian("signal_%s_%s"%(self.crystal,self.energy),"signal_%s_%s"%(self.crystal,self.energy),self.x,self.m,self.s)        
コード例 #7
0
 def CBintialization(self):
     round_energy = round(float(self.energy),-1)
     if round_energy ==240 : round_energy = 250
             
     self.x = RooRealVar("signal_%s_%dGeV"%(self.crystal,round_energy),"signal_%s_%dGeV"%(self.crystal,round_energy),max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.roohist = RooDataHist("roohist_fit_%s_%s"%(self.crystal,self.energy),"roohist_fit_%s_%s"%(self.crystal,self.energy),RooArgList(self.x),self.hist)
     self.m = RooRealVar("mean_%s_%s"%(self.crystal,self.energy),"mean_%s_%s"%(self.crystal,self.energy),self.peak_position,max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.s = RooRealVar("sigma_%s_%s"%(self.crystal,self.energy),"sigma_%s_%s"%(self.crystal,self.energy),self.s_initial,0.001,1.) #500.
     self.a = RooRealVar("alpha_%s_%s"%(self.crystal,self.energy),"alpha_%s_%s"%(self.crystal,self.energy),self.a_initial,-10.,10)
     self.n = RooRealVar("exp_%s_%s"%(self.crystal,self.energy),"exp_%s_%s"%(self.crystal,self.energy),self.n_initial,0.,30)
     self.sig = RooCBShape("signal_%s_%s"%(self.crystal,self.energy),"signal_%s_%s"%(self.crystal,self.energy),self.x,self.m,self.s,self.a,self.n)
コード例 #8
0
 def CB2intialization(self):
     round_energy = round(float(self.energy),-1)
     self.x = RooRealVar("signal_%s_%dGeV"%(self.crystal,round_energy),"signal_%s_%dGeV"%(self.crystal,round_energy),max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.roohist = RooDataHist("roohist_fit_%s_%s"%(self.crystal,self.energy),"roohist_fit_%s_%s"%(self.crystal,self.energy),RooArgList(self.x),self.hist)
     self.m = RooRealVar("mean_%s_%s"%(self.crystal,self.energy),"mean_%s_%s"%(self.crystal,self.energy),self.peak_position,max(0.,self.peak_position*(1-self.xaxis_scale)),self.peak_position*(1+self.xaxis_scale))
     self.s = RooRealVar("sigma_%s_%s"%(self.crystal,self.energy),"sigma_%s_%s"%(self.crystal,self.energy),self.s_initial,10,500)
     self.a = RooRealVar("alpha_%s_%s"%(self.crystal,self.energy),"alpha_%s_%s"%(self.crystal,self.energy),self.a_initial,-10.,10)
     self.a2 = RooRealVar("alpha2_%s_%s"%(self.crystal,self.energy),"alpha2_%s_%s"%(self.crystal,self.energy),self.a2_initial,-10.,10)
     self.n = RooRealVar("exp_%s_%s"%(self.crystal,self.energy),"exp_%s_%s"%(self.crystal,self.energy),self.n_initial,0.,30)
     self.n2 = RooRealVar("exp2_%s_%s"%(self.crystal,self.energy),"exp2_%s_%s"%(self.crystal,self.energy),self.n2_initial,0.,30)
     self.sig = ROOT.My_double_CB("signal_%s_%s"%(self.crystal,self.energy),"signal_%s_%s"%(self.crystal,self.energy),self.x,self.m,self.s,self.a,self.n,self.a2,self.n2)        
コード例 #9
0
def saveLandauHistoAmplitude(histo,
                             outfile,
                             canvas,
                             XaxisTitle="",
                             YaxisTitle="",
                             plotTitle="",
                             stats=0):
    ex = "Null Fit"
    amplitude = RooRealVar("amplitude", "Cluster Amplitude", 0, 5000)
    landau_data = RooDataHist("landau_data", "landau_data",
                              RooArgList(amplitude), histo)

    ml = RooRealVar("ml", "mean landau", 1500., 1000, 2000)
    sl = RooRealVar("sl", "sigma landau", 250, 100, 1000)
    landau = RooLandau("lx", "lx", amplitude, ml, sl)

    mg = RooRealVar("mg", "mg", 0)
    sg = RooRealVar("sg", "sg", 100, 20, 500)
    gauss = RooGaussian("gauss", "gauss", amplitude, mg, sg)

    lxg = RooNumConvPdf("lxg", "lxg", amplitude, landau, gauss)

    result = lxg.fitTo(landau_data)

    frame = amplitude.frame()
    landau_data.plotOn(frame)

    lxg.plotOn(frame)

    frame.Draw("")
    frame.SetTitle(plotTitle)
    frame.GetXaxis().SetTitle(XaxisTitle)
    frame.GetYaxis().SetTitle(YaxisTitle)
    frame.SetStats(stats)
    frame.Write(plotTitle)

    canvas.Print(outfile + ".pdf")

    peak = []

    try:
        mean = RooRealVar(result.floatParsFinal().find("landau_mean"))
        err = RooRealVar(mean.errorVar())
        peak.append(mean.GetVal())
        peak.append(err.GetVal())
    except Exception as ex:
        print(ex)
        peak.append(0)
        peak.append(0)

    return peak
コード例 #10
0
ファイル: fitter.py プロジェクト: patriziaazzi/fcc-ee-higgs
    def _make_underlying_model(self):
        self.pdfs = {}
        self.yields = {}  # yields are plain floats
        self.ryields = {}  # keep track of roofit objects for memory management
        nbins, xmin, xmax = self.plot.histos[0].GetBinning()
        self.xvar = RooRealVar("x", "x", xmin, xmax)
        self.xvar.setBins(nbins)
        self.pdfs = {}
        self.hists = []
        pdfs = RooArgList()
        yields = RooArgList()
        for compname, comp in self.plot.histosDict.iteritems():
            if comp.weighted.Integral() == 0:
                continue
            assert (isinstance(comp, Histogram))
            hist = RooDataHist(compname, compname, RooArgList(self.xvar),
                               comp.weighted)
            SetOwnership(hist, False)
            # self.hists.append(hist)
            pdf = RooHistPdf(compname, compname, RooArgSet(self.xvar), hist)
            self.pdfs[compname] = pdf
            # self.pdfs[compname].Print()
            pdfs.add(pdf)
            nevts = comp.Integral(xmin=xmin, xmax=xmax)
            nmin = min(0, nevts * (1 - comp.uncertainty))
            nmax = nevts * (1 + comp.uncertainty)
            theyield = RooRealVar('n{}'.format(compname),
                                  'n{}'.format(compname), nevts, nmin, nmax)
            self.ryields[compname] = theyield
            self.yields[compname] = nevts
            yields.add(theyield)

        self.underlying_model = RooAddPdf('model', 'model', pdfs, yields)
コード例 #11
0
    def addHistData(self,
                    ws,
                    ds_name,
                    item_title,
                    var_set_name,
                    var_set_type,
                    ds_object,
                    sets=None):
        legend = '[exostConfig::addHistData]:'

        arg_list = RooArgList()
        if (var_set_type == 'set'):
            #arg_list.add(ws.set(var_set_name))
            arg_list.add(sets[var_set_name])
        elif (var_set_type == 'var'):
            arg_list.add(ws.var(var_set_name))
        else:
            print legend, 'error: unknown var_set_type, cannot create dataset', ds_name
            return -1

        #create the hist dataset
        ds = RooDataHist(ds_name, item_title, arg_list, ds_object, 1)

        # import the datahist. Note workaround 'import' being a reserved word
        getattr(ws, 'import')(ds)
コード例 #12
0
def doFit(hist,output,rap="BB",flavour="DATA",trackType="TunePNew",funct="doubleCB"):

	
	sig    = []
	sige   = []
	meanList   = []
	meanListe  = []
	nChi2  = []
	gSystem.Load("./RooCruijff_cxx.so")
	gSystem.Load("./RooDCBShape_cxx.so")
	for i,h in enumerate(hist):
		ws = RooWorkspace("tempWS")

		mass = RooRealVar('mass','mass',91, xLow, xHigh )
		getattr(ws,'import')(mass,RooCmdArg())			
		dataHist = RooDataHist("hist","hist",RooArgList(ws.var("mass")),h)
		getattr(ws,'import')(dataHist,RooCmdArg())

		ws.writeToFile("tmpWorkspace.root")
		
		subprocess.call(["python","fitCapsule.py",output,rap,flavour,trackType,funct,"%d"%xLow,"%d"%xHigh,"%d"%rebinFactor,"%d"%i])
		
		returnFile = TFile("tmpWorkspaceReturn.root","OPEN")
		wsReturn = returnFile.Get("tempWS")
		
		sig.append(wsReturn.var("Sig").getVal())
		sige.append(wsReturn.var("Sige").getVal())
		meanList.append(wsReturn.var("Mean").getVal())
		meanListe.append(wsReturn.var("Meane").getVal())
		nChi2.append(wsReturn.var("chi2").getVal()/wsReturn.var("nDOF").getVal())


	return meanList,meanListe,sig,sige, nChi2	
コード例 #13
0
def makeHistPdf(hist, ws, x):
    theVars = RooArgList(x)
    v = RooArgSet(x)
    dataHist = RooDataHist(hist.GetName() + '_dh', 'dataHist', theVars, hist)
    hpdf = RooHistPdf(hist.GetName() + '_pdf', 'hist pdf', v, dataHist)
    getattr(ws, 'import')(hpdf)
    return hpdf
コード例 #14
0
ファイル: load_data.py プロジェクト: TENorbert/SUSY-TOOLS
 def generate_hist(self, hist, varname, n):
     _var = RooRealVar(varname, varname, hist.GetMean())
     _dh = RooDataHist("dh", "dh", RooArgList(_var), hist)
     _pdf = RooHistPdf("pdf", "pdf", RooArgSet(_var), _dh)
     _ds = _pdf.generateBinned(RooArgSet(_var), n)
     _h = _ds.createHistogram('hist', _var)
     #_h.Draw()
     #raw_input('press <enter> to continue...')
     return copy.deepcopy(_h)
コード例 #15
0
def saveLandauHistoSignalToNoise(histo,outfile,canvas,XaxisTitle="",YaxisTitle="",plotTitle="",stats=0):
	ex = "Null Fit"
	signal_to_noise = RooRealVar("signal_to_noise", "Signal to Noise", 0, 50)
	landau_data = RooDataHist("landau_data", "landau_data", RooArgList(signal_to_noise), histo)

	ml = RooRealVar("ml","mean landau",25, 20, 26)
	sl = RooRealVar("sl","sigma landau", 5, 2, 10)
	landau = RooLandau("lx","lx",signal_to_noise,ml,sl)
  
	mg = RooRealVar("mg","mg",0) ;
	sg = RooRealVar("sg","sg", 2, 1, 8)
	gauss = RooGaussian("gauss","gauss",signal_to_noise,mg,sg)

	lxg = RooNumConvPdf("lxg", "lxg", signal_to_noise, landau, gauss)

	result = lxg.fitTo(landau_data)

	frame = signal_to_noise.frame()
	landau_data.plotOn(frame)

	lxg.plotOn(frame)

	frame.Draw("")
	frame.SetTitle(plotTitle)
	frame.GetXaxis().SetTitle(XaxisTitle)
	frame.GetYaxis().SetTitle(YaxisTitle)
	frame.SetStats(stats)
	frame.Write(plotTitle)

	canvas.Print(outfile+".pdf")

	peak = []
	
	try:
		mean = RooRealVar(result.floatParsFinal().find("landau_mean"))
		err = RooRealVar(mean.errorVar())
		peak.append(mean.GetVal())
		peak.append(err.GetVal())
	except Exception as ex:
		print(ex)
		peak.append(0)
		peak.append(0)

	return peak
コード例 #16
0
def get_num_sig_bkg(hist_DataTemplate, hist_SignalTemplate,
                    hist_BackgdTemplate, fit_range_min, fit_range_max):
    '''Given 3 input histograms (TH1F), and a fit range, this function finds
    the amount of signal and background that sum up to the data histogram.
    It does histogram fits.'''
    # Find range of data template
    data_min = hist_DataTemplate.GetXaxis().GetXmin()
    data_max = hist_DataTemplate.GetXaxis().GetXmax()

    # Create basic variables
    x = RooRealVar("x", "x", data_min, data_max)
    x.setBins(hist_DataTemplate.GetXaxis().GetNbins())  # Binned x values
    nsig = RooRealVar("nsig", "number of signal events", 0,
                      hist_DataTemplate.Integral())
    nbkg = RooRealVar("nbkg", "number of background events", 0,
                      hist_DataTemplate.Integral())

    # Create RooDataHists from input TH1Fs
    dh = RooDataHist("dh", "dh", RooArgList(x), hist_DataTemplate)
    ds = RooDataHist("ds", "ds", RooArgList(x), hist_SignalTemplate)
    db = RooDataHist("db", "db", RooArgList(x), hist_BackgdTemplate)

    # Create Probability Distribution Functions from Monte Carlo
    sigPDF = RooHistPdf("sigPDF", "sigPDF", RooArgSet(x), ds)
    bkgPDF = RooHistPdf("bkgPDF", "bkgPDF", RooArgSet(x), db)

    model = RooAddPdf("model", "(g1+g2)+a", RooArgList(bkgPDF, sigPDF),
                      RooArgList(nbkg, nsig))

    # Find the edges of the bins that contain the fit range min/max
    data_min = hist_DataTemplate.GetXaxis().GetBinLowEdge(
        hist_DataTemplate.GetXaxis().FindFixBin(fit_range_min))
    data_max = hist_DataTemplate.GetXaxis().GetBinUpEdge(
        hist_DataTemplate.GetXaxis().FindFixBin(fit_range_max))

    r = model.fitTo(dh, RooFit.Save(), RooFit.Minos(0),
                    RooFit.PrintEvalErrors(0), RooFit.Extended(),
                    RooFit.Range(data_min, data_max))
    r.Print("v")

    #print nsig.getVal(), nsig.getError(), nbkg.getVal(), nbkg.getError()
    return [nsig.getVal(), nsig.getError(), nbkg.getVal(), nbkg.getError()]
コード例 #17
0
def Fit(h, Lc_M):
    h_LcM = RooDataHist('h_LcM', 'h_LcM', RooArgList(Lc_M), h)

    #Create a workspace named 'w' with the model to fit the Lc_Mass peak
    nsig = RooRealVar("nsig", "N signal evts", 100000, 0, 5000000)
    nbkg = RooRealVar("nbkg", "N bkg evts", 400000, 0, 1E10)

    w = CreateMassFitModel(Lc_M, nsig, nbkg)
    model = w.pdf("model")
    model.fitTo(h_LcM, RF.Extended(True))
    return model, w, h_LcM
コード例 #18
0
def makePlot(s):
    if (type(s) == TH1D):
        s.SetStats(0)
        x = RooRealVar("x", "x", 0, 3)
        l = RooArgList(x)
        dh = RooDataHist("dh", "dh", l, s)
        frame = x.frame()

        dh.plotOn(frame)
        #frame.SetTitle(name)
        #frame.GetXaxis().SetTitle(s.GetXaxis().GetTitle())
        frame.GetYaxis().SetTitle(s.GetYaxis().GetTitle())

        #        frame.GetYaxis().SetTopMargin(0.15)
        #frame.Draw(draw)
        return frame

    elif (type(s) == TH2D):
        s.SetStats(0)
        x = RooRealVar("x", "x", 0, 3)
        y = RooRealVar("y", "y", 0, 3)
        l = RooArgList(x, y)
        dh = RooDataHist("dh", "dh", l, s)
        t = TGraph2D(s)
        s.SetMarkerSize(1.0)
        s.SetMarkerStyle(1)
        #t.GetXaxis().SetTitle(s.GetXaxis().GetTitle())
        return s

    elif (type(s) == TGraph2D):
        s.SetMarkerSize(1.0)
        s.SetMarkerStyle(1)
        return s
コード例 #19
0
def compare_binning(filename):
    scans = ('X1', 'Y1', 'X2', 'Y2')

    with BareRootFile(filename) as f:
        oldres = [f.get('residualHist{0}'.format(scan)) for scan in scans]
        oldchi = [f.get_val('chisq{0}'.format(scan)) for scan in scans]
        olddof = [f.get_val('dof{0}'.format(scan)) for scan in scans]
        name = f.get_val('name')
    bcidpos = name.find('bcid')
    dataname = name[16:name.rfind('_', 0, bcidpos - 1)]
    fitname = name[name.rfind('_', 0, bcidpos - 1) + 1:bcidpos - 1]
    bcid = int(name[bcidpos + 4:])

    model = {
        'SG': SingleGauss,
        'DG': DoubleGaussFit,
        'TG': TripleGaussFit
    }[fitname]()
    model.load_root(filename)
    modfuncs = model.model_functions()

    with open('res/hist/{0}.json'.format(dataname)) as f:
        json = load(f)
    nbins = json['nbins']
    scaling = json['scaling']
    datafile = '{0}/{1}.root'.format(json['datapath'], json['name'])

    hists = []
    with BareRootFile(datafile) as f:
        for histname in [
                'hist_Beam2MoveX_bunch{0}Add', 'hist_Beam2MoveY_bunch{0}Add',
                'hist_Beam1MoveX_bunch{0}Add', 'hist_Beam1MoveY_bunch{0}Add'
        ]:
            hist = f.get(histname.format(bcid))
            hists.append(hist)
    datahist = [
        RooDataHist('scan{0}Beam{1}RestDataHist'.format(c, i),
                    'scan{0}Beam{1}RestDataHist'.format(c, i),
                    RooArgList(model.xvar(), model.yvar()), hists[j])
        for j, (i, c) in enumerate([('1', 'X'), ('1', 'Y'), ('2',
                                                             'X'), ('2', 'Y')])
    ]

    chisq, dof, hdata, hmodel = compute_chisq(model, modfuncs, datahist, nbins)
    scDat, scMod, scRes = residual_hist(hdata, hmodel, scaling)

    for i, scan in enumerate(scans):
        oldval = oldchi[i] / olddof[i]
        newval = chisq[i] / dof[i]
        print '{0}: {1:.4f} {2:.4f}'.format(scan, oldval, newval)

    return scRes, oldres
コード例 #20
0
ファイル: fits.py プロジェクト: DryRun/StatisticalTools
	def add_signal(self, signal_name, signal_histogram):
		print "[MjjFit.add_signal] INFO : Adding signal histogram " + signal_name
		# Add a signal histogram. 
		# Scale to sigma=1 (in whatever units the data luminosity is given in), so the 'r' parameter corresponds to the limit on the cross section.
		if self.luminosity_ == 0:
			print "[MjjFit.add_signal] ERROR : Please set luminosity first (MjjFit.set_luminosity(###))."
			sys.exit(1)
		self.signal_names_.append(signal_name)
		self.signal_histograms_[signal_name] = signal_histogram.Clone()
		self.signal_histograms_[signal_name].SetDirectory(0)
		self.signal_histograms_[signal_name].Scale(1. * self.luminosity_ / self.signal_histograms_[signal_name].Integral())
		self.signal_roohistograms_[signal_name] = RooDataHist(signal_histogram.GetName() + "_rdh", signal_histogram.GetName() + "_rdh", RooArgList(self.mjj_), signal_histograms[signal_name])
		self.signal_roohistograms_[signal_name].Print()
コード例 #21
0
    def loadData(self, weight = False):
        if self.ws.data('data_obs'):
            return self.ws.data('data_obs')

        unbinnedName = 'data_obs'
        if self.pars.binData:
            unbinnedName = 'data_unbinned'
        data = self.utils.File2Dataset(self.pars.DataFile, unbinnedName, 
                                       self.ws, weighted = weight)
        if self.pars.binData:
            data = RooDataHist('data_obs', 'data_obs', self.ws.set('obsSet'), 
                               data)
            getattr(self.ws, 'import')(data)
            data = self.ws.data('data_obs')

        return data
コード例 #22
0
def makePDFs(Files, pdf_list, evntCount):
    for (inputMass, inputFilename) in Files:
        histo = load_histos(inputFilename)
        evntCount.append(histo.Integral())
        # could construct name and title from inputmass
        if 'nom' in inputFilename:
            myString = inputFilename.partition("230_")[2].partition(
                "_result")[0] + str(inputMass)
        else:
            myString = inputFilename.partition("jes_")[2].partition(
                "_result")[0] + str(inputMass)
        # Convert the TH1F Histogram (data_hist) into a RooDataHist object
        data_hist = RooDataHist(myString, myString, RooArgList(x), histo)
        # Turn the RooDataHist object into a RooHistPdf object
        pdf = RooHistPdf(myString, myString, RooArgSet(x), data_hist)
        # both the data_hist and pdf must survive
        pdf_list.append([data_hist, pdf])
コード例 #23
0
def histoToRooHistFunc(ws, cfg, section, histo, name):
    nBins = len(cfg.get(section, 'obsBins').split(',')) - 1
    makeLastBinOverflow(histo, nBins)
    histo.SetName('%s_%s_input' % (section, name))
    getattr(ws, 'import')(histo)

    #make the histogram, using the binning defined by the histogram
    rdh = RooDataHist(
        '%s_%s_yields' % (section, name), '%s_%s_yields' % (section, name),
        RooArgList(ws.var('%s_%s' % (cfg.get(section, 'obsVar'), section))),
        RooFit.Import(ws.obj('%s_%s_input' % (section, name)), False))
    getattr(ws, 'import')(rdh)

    #make the hist func so we can get at the yield
    ws.factory("""
    RooHistFunc::%s_%s_model
    ({%s_%s},%s_%s_yields)
    """ % (section, name, cfg.get(section, 'obsVar'), section, section, name))
コード例 #24
0
    def Hist2Pdf(self, hist, pdfName, ws, order=0):
        if ws.pdf(pdfName):
            return ws.pdf(pdfName)

        try:
            obs = [self.pars.varNames[x] for x in self.pars.var]
        except AttributeError:
            obs = self.pars.var

        varList = RooArgList()
        for v in obs:
            varList.add(ws.var(v))
        newHist = RooDataHist(pdfName + '_hist', pdfName + '_hist', varList,
                              hist)

        thePdf = RooHistPdf(pdfName, pdfName, RooArgSet(varList), newHist,
                            order)
        getattr(ws, 'import')(thePdf)

        return ws.pdf(pdfName)
コード例 #25
0
    def loadDataFromWorkspace(self, other, cut = None):
        #pull unbinned data from other workspace
        unbinnedData = other.data('data_unbinned')
        if not unbinnedData:
            unbinnedData = other.data('data_obs')

        if cut:
            unbinnedData = unbinnedData.reduce(cut)

        unbinnedData.Print()
        if self.pars.binData:
            #bin and import data
            unbinnedData.SetName('data_unbinned')
            getattr(self.ws, 'import')(unbinnedData)
            data = RooDataHist('data_obs', 'data_obs', other.set('obsSet'), 
                               unbinnedData)
            getattr(self.ws, 'import')(data)
        else:
            #just import data
            unbinnedData.SetName('data_obs')
            getattr(self.ws, 'import')(unbinnedData)
コード例 #26
0
    def __init__( self, fit_data ):
        MapStrRootPtr = stl.map( stl.string, "TH1*" )
        StrHist = stl.pair( stl.string, "TH1*" )
        self.fit_data = fit_data
        self.models = {}
        self.sample = RooCategory( 'sample', 'sample' )
        self.roofit_variables = []
        input_hists = MapStrRootPtr()

        # first create observables
        # Since we are looking for normalisation in equivalent regions
        # the number of events in each sample has to be identical
        # Hence, pick one fit_data to create the set of observables
        fit_data_1 = fit_data.itervalues().next()
        samples = fit_data_1.samples
        self.observables = {}
        N_min = 0
        N_max = fit_data_1.n_data() * 2
        for sample in samples:
            self.observables[sample] = Observable( 'n_' + sample,
                                                  'number of ' + sample + " events",
                                                  fit_data_1.normalisation[sample],
                                                  N_min,
                                                  N_max,
                                                  "events" )

        # next create the models
        for variable, fit_input in fit_data.iteritems():
            self.models[variable] = fit_input.get_roofit_model( variable, self.observables )
            self.sample.defineType( variable )
            self.sample.setLabel ( variable )
            data = deepcopy( fit_input.real_data_histogram() )
            input_hists.insert( StrHist( variable, data ) )
            self.roofit_variables.append( fit_input.fit_variable )
        self.comb_data = RooDataHist( "combData",
                                    "combined data",
                                    RooArgList( self.roofit_variables[0] ),
                                    self.sample,
                                    input_hists,
                                    )
コード例 #27
0
def generate(histList, varName, varLow, varHigh, histSig="", weightSig=0.):
    """
    Generate toy data

    @param histList List of histograms
    @param varname Variable name to use
    @param varLow Lower edge of left bin
    @param varHigh Upper edge of right bin
    @param histSig Optional signal histogram
    @param weightSig Optional signal weight
    """

    testHist_pred = TH1D()
    for (iHist, hist) in enumerate(histList):
        if not iHist:
            testHist_pred = hist.Clone("hPRED")
        else:
            testHist_pred.Add(hist)

    testHist_pred_ds = TH1D(
        "hPSDATA", "hPSDATA", testHist_pred.GetNbinsX(),
        testHist_pred.GetXaxis().GetBinLowEdge(1),
        testHist_pred.GetXaxis().GetBinUpEdge(testHist_pred.GetNbinsX()))

    nEvents_pred = int(testHist_pred.Integral())
    print "nEvents_pred = %d" % nEvents_pred

    var = RooRealVar(varName, varName, varLow, varHigh)

    dh_pred = RooDataHist("dhPSDATA", "dhPSDATA", RooArgList(var),
                          RooFit.Import(testHist_pred))

    ph_pred = RooHistPdf("phPSDATA", "phPSDATA", RooArgSet(var), dh_pred)

    ds_pred = ph_pred.generate(RooArgSet(var), nEvents_pred)

    testHist_pred_ds = ds_pred.fillHistogram(testHist_pred_ds, RooArgList(var))

    return testHist_pred_ds
コード例 #28
0
def MakeRooDataHist(phys_process, fullrange_=False):
    MPruned_Merged.Scale(0.0)
    iweight = 0
    for irootfile in Utils.samples[phys_process]['files']:

        file01 = TFile('AnalysisHistograms_V7/' + irootfile, 'READ')
        #file01 = TFile(irootfile, 'READ')

        MPruned_ttbar_sb = file01.Get('histfacFatJet_ZLight/h_Mjj0')
        MPruned_ttbar_sig = file01.Get(
            'MonoHFatJetSelection_JetAndLeptonVeto/h_Mjj0')

        if debug_:
            print "before ", MPruned_ttbar_sb.Integral()
            print "before ", MPruned_ttbar_sig.Integral()

        if phys_process != 'data_obs':
            MPruned_ttbar_sb.Scale(
                Utils.samples[phys_process]['weight'][iweight])
            MPruned_ttbar_sig.Scale(
                Utils.samples[phys_process]['weight'][iweight])

        if debug_:
            print "weight = ", Utils.samples[phys_process]['weight'][iweight]
            print "after ", MPruned_ttbar_sb.Integral()
            print "after ", MPruned_ttbar_sig.Integral()

        MPruned_Merged.Add(MPruned_ttbar_sb)
        if fullrange_ | options.fullrange:
            MPruned_Merged.Add(MPruned_ttbar_sig)
        ## convert Histogram to RooDataHist
        MPruned_ttbar_hist = RooDataHist('MPruned_ttbar_hist',
                                         'MPruned_ttbar_hist',
                                         RooArgList(J_Mass), MPruned_Merged)
        iweight = iweight + 1
    print "final intgral = ", MPruned_Merged.Integral()
    return MPruned_ttbar_hist
コード例 #29
0
ファイル: fitter2.py プロジェクト: patriziaazzi/fcc-ee-higgs
    def _make_underlying_model(self):
        self.pdfs = {}
        self.yields = {}  # yields are plain floats
        self.ryields = {}  # keep track of roofit objects for memory management
        h = self._histos[0]
        nbins = h.GetXaxis().GetNbins()
        xmin = h.GetXaxis().GetXmin()
        xmax = h.GetXaxis().GetXmax()
        self.xvar = RooRealVar("x", "x", xmin, xmax)
        self.xvar.setBins(nbins)
        self.pdfs = {}
        self.hists = []
        pdfs = RooArgList()
        yields = RooArgList()
        for histo in self._histos:
            if histo.Integral() == 0:
                continue
            compname = histo.GetName()
            hist = RooDataHist(compname, compname, RooArgList(self.xvar),
                               histo)
            SetOwnership(hist, False)
            # self.hists.append(hist)
            pdf = RooHistPdf(compname, compname, RooArgSet(self.xvar), hist)
            self.pdfs[compname] = pdf
            # self.pdfs[compname].Print()
            pdfs.add(pdf)
            nevts = histo.Integral()
            uncertainty = self._uncertainty
            nmin = min(0, nevts * (1 - uncertainty))
            nmax = nevts * (1 + uncertainty)
            theyield = RooRealVar('n{}'.format(compname),
                                  'n{}'.format(compname), nevts, nmin, nmax)
            self.ryields[compname] = theyield
            self.yields[compname] = nevts
            yields.add(theyield)

        self.underlying_model = RooAddPdf('model', 'model', pdfs, yields)
コード例 #30
0
def broadenspec(ms, E_0):
    spec = decayspec(ms, E_0)
    smear = core(E_0_center)
    newspec = TH1D("", "", spec.GetNbinsX(), -17.5, 17.5)
    for i in range(1, spec.GetNbinsX() + 1):
        newspec.SetBinContent(i, spec.GetBinContent(i))

    #x = RooRealVar("x","x",-30+E_0_center, 5+E_0_center)
    x = RooRealVar("x", "x", -17.5, 17.5)
    data = RooDataHist("", "", RooArgList(x), newspec)
    specpdf = RooHistPdf("", "", RooArgSet(x), data)
    #y = RooRealVar("y","y",-30, 5)
    x.setBins(10000)
    smearpdf = RooFit.bindPdf(smear, x)
    fft = RooFFTConvPdf("tt", "tt", x, specpdf, smearpdf)
    #fft.setShift(0, -18574)
    #c1 = TCanvas()
    #frame = x.frame()
    #fft.plotOn(frame)
    #frame.Draw()
    tf = fft.asTF(RooArgList(x))
    tf.SetNpx(10000)
    rtf = tf.Clone()
    return rtf
コード例 #31
0
def generate(histList,varName,varLow,varHigh,histSig="",weightSig=0.):
    testHist_pred = TH1D()
    for (iHist,hist) in enumerate(histList):
        if not iHist:
            testHist_pred = hist.Clone("hPRED")
        else:
            testHist_pred.Add(hist)

    testHist_pred_ds = TH1D("hPSDATA","hPSDATA",testHist_pred.GetNbinsX(),testHist_pred.GetXaxis().GetBinLowEdge(1),testHist_pred.GetXaxis().GetBinUpEdge(testHist_pred.GetNbinsX()))

    nEvents_pred = int(testHist_pred.Integral())
    print "nEvents_pred = %d" % nEvents_pred

    var = RooRealVar(varName,varName,varLow,varHigh)

    dh_pred = RooDataHist("dhPSDATA","dhPSDATA",RooArgList(var),RooFit.Import(testHist_pred))

    ph_pred = RooHistPdf("phPSDATA","phPSDATA",RooArgSet(var),dh_pred)

    ds_pred = ph_pred.generate(RooArgSet(var),nEvents_pred)

    testHist_pred_ds = ds_pred.fillHistogram(testHist_pred_ds,RooArgList(var))

    return testHist_pred_ds
コード例 #32
0
ファイル: plotMassRatio.py プロジェクト: scasasso/usercode
def main():

    parser = OptionParser()
    parser.add_option("-d", "--dir", type="string", dest="outDir", metavar="DIR", default="./",
                      help="output directory for .png")
        

    (options, args) = parser.parse_args()

    if os.path.exists(options.outDir) and options.outDir!="./":
        print "Sorry, file ",options.outDir," already exist, choose another name\n"
        exit(1)
    else:
        os.system("mkdir -p "+options.outDir)


    """
    Set the style ...
    """

    myNewStyle = TStyle("myNewStyle","A better style for my plots")
    setStyle(myNewStyle)

    TH1F.SetDefaultSumw2(True)

    # Histogram range
    xlow = 70.
    xup = 110.
    
    # Mass range for fit
    minM_fit = 75.
    maxM_fit = 105.

    # Ratio plot range
    minR = 0.8
    maxR = 1.2

    # TLines for ratio plot
    line = TLine(minM_fit,1,maxM_fit,1)
    line.SetLineWidth(2)
    line.SetLineColor(2)

    # Canvas
    spectrum_height = 0.75
    ratio_correction = 1.4
    ratio_height = (1-spectrum_height)*ratio_correction
    xOffset = 0.08
    yOffset = 0.04

    cTest = TCanvas("cTest","cTest")
    
    c2 = TCanvas("c2","c2")
    c2.SetFillColor(0)
    c2.Divide(1,2)

    
    c3 = TCanvas("c3","c3")
    c3.SetFillColor(0)
    c3.Divide(1,2)

    # Files MuScleFit
    fDataBefore = TFile("h3_Z_data_beforeCorrection.root")
    fDataAfter  = TFile("h3_Z_data_afterCorrection.root")
    fMcBefore = TFile("h3_Z_mc_beforeCorrection.root")
    fMcAfter  = TFile("h3_Z_mc_afterCorrection.root")
    
                
    # Retrieve histograms and fit
    hDataBefore = fDataBefore.Get("h1_Z_data")
    hDataAfter  = fDataAfter.Get("h1_Z_data")
    hMcBefore   = fMcBefore.Get("h1_Z_mc")
    hMcAfter    = fMcAfter.Get("h1_Z_mc")

    # Identifiers
    ids = ["data_before","data_after","mc_before","mc_after"]

    # Create histograms dictionary
    histos = {}
    histos["data_before"] = hDataBefore
    histos["data_after"]  = hDataAfter
    histos["mc_before"]   = hMcBefore
    histos["mc_after"]    = hMcAfter

    histosSubtr = {}

    # Create parameters dictionary
    expPars = {}
    signalPars = {}

    for i in ids:
        # RooFit definitions
        ## RooRealVars
        x = RooRealVar("x","M_{#mu#mu} (GeV)",minM_fit,maxM_fit)
        mean = RooRealVar("mean","mean",91.19,87.,94.)
        meanCB = RooRealVar("meanCB","meanCB",0.,-10.,10.)
        meanCB.setConstant(True)
        width = RooRealVar("width","width",2.4952,2.3,2.6)
        width.setConstant(True)
        sigma = RooRealVar("sigma","sigma",1.3,0.001,3.)
        #    sigma.setConstant(True)
        slope = RooRealVar("slope","slope",-0.1,-1.0,0.)
        #    slope.setConstant(True)
        alpha = RooRealVar("alpha","alpha",1.,0.,30.)
        #    alpha.setConstant(True)
        N = RooRealVar("N","N",2.,0.,100.)
        #    N.setConstant(True)
        fsig = RooRealVar("fsig","fsig",0.9,0.,1.0)
        
        ## PDFs
        relBW = RooGenericPdf("relBW","relBW","@0/(pow(@0*@0-@1*@1,2) + @2*@2*@0*@0*@0*@0/(@1*@1))",RooArgList(x,mean,width))
        CB = RooCBShape("CB","CB",x,meanCB,sigma,alpha,N)
        expo = RooExponential("expo","expo",x,slope)
        relBWTimesCB = RooFFTConvPdf("relBWTimesCB","relBWTimesCB",x,relBW,CB)
        relBWTimesCBPlusExp = RooAddPdf("relBWTimesCBPlusExp","relBWTimesCBPlusExp",relBWTimesCB,expo,fsig)

        # Fit
        frame = x.frame()
        h = histos[i]
        # h.Rebin(10)
        h.Sumw2()
        nbin = h.GetNbinsX()
        dh = RooDataHist("dh","dh",RooArgList(x),h)
        dh.plotOn(frame)
        relBWTimesCBPlusExp.fitTo(dh)
        relBWTimesCBPlusExp.plotOn(frame)
        relBWTimesCBPlusExp.paramOn(frame)

        # Plot
        c = TCanvas("c_"+i,"c_"+i) 
        c.SetFillColor(0)
        c.cd()
        frame.Draw()
        c.SaveAs(options.outDir+"/DimuonWithFit_"+i+".png")
        
        # Extract the result of the fit
        expParams = []
        expCoef = slope.getValV()
        fSig    = fsig.getValV()
        binLow = h.GetXaxis().FindBin(minM_fit)
        binHigh = h.GetXaxis().FindBin(maxM_fit)
        nEntries = h.Integral(binLow,binHigh)
        expParams = [expCoef,fSig,nEntries,binLow,binHigh]
        expPars[i] = expParams

        signalParams = [mean.getVal(),width.getVal(),meanCB.getVal(),sigma.getVal(),alpha.getVal(),N.getVal()]
        signalPars[i] = signalParams

        # Subtract the bkg from the histograms
        h_woBkg = h.Clone()
        h_bkg = TH1F("h_bkg_"+i,"Histogram of bkg events",nbin,xlow,xup)
        
        h_bkg.Sumw2()
        expNorm = (math.fabs(expCoef)*(1-fSig)*nEntries)/(math.exp(expCoef*minM_fit)-math.exp(expCoef*maxM_fit))
        for ibin in range(binLow,binHigh):
            w = integrateExp(expNorm,expCoef,h_bkg.GetBinLowEdge(ibin),h_bkg.GetBinLowEdge(ibin+1))
            h_bkg.SetBinContent(ibin,w)

        h_woBkg.Add(h_bkg,-1)
        nEvts_woBkg = h_woBkg.Integral(binLow,binHigh)
        h_woBkg.Scale(1/nEvts_woBkg)
        histosSubtr[i] = h_woBkg


        del expParams, c
        del relBWTimesCBPlusExp, relBW, CB, relBWTimesCB, expo
        del x, mean, width, sigma, fsig, N, alpha, slope, meanCB
        del frame, dh, h, h_woBkg, h_bkg



    # BEFORE CORRECTIONS
    
#     # RooFit definitions (again, sorry)
#     ## RooRealVars
#     x = RooRealVar("x","M_{#mu#mu} (GeV)",minM_fit,maxM_fit)
#     mean = RooRealVar("mean","mean",91.19)
#     meanCB = RooRealVar("meanCB","meanCB",0.)
#     width = RooRealVar("width","width",2.4952)
#     sigma = RooRealVar("sigma","sigma",1.3)
#     alpha = RooRealVar("alpha","alpha",1.)
#     N = RooRealVar("N","N",2.)

#     ## PDFs (again, sorry)
#     relBW = RooGenericPdf("relBW","relBW","@0/(pow(@0*@0-@1*@1,2) + @2*@2*@0*@0*@0*@0/(@1*@1))",RooArgList(x,mean,width))
#     CB = RooCBShape("CB","CB",x,meanCB,sigma,alpha,N)
#     relBWTimesCB = RooFFTConvPdf("relBWTimesCB","relBWTimesCB",x,relBW,CB)

    
    # Ratio plot after background subtraction
    histosSubtr["data_before"].GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    histosSubtr["data_before"].GetYaxis().SetRangeUser(0.,histosSubtr["data_before"].GetMaximum()+0.1*histosSubtr["data_before"].GetMaximum())
    histosSubtr["data_before"].SetLineColor(1)

    histosSubtr["mc_before"].GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    if histosSubtr["mc_before"].GetMaximum()>histosSubtr["data_before"].GetMaximum():
        histosSubtr["data_before"].GetYaxis().SetRangeUser(0.,histosSubtr["mc_before"].GetMaximum()+0.1*histosSubtr["mc_before"].GetMaximum())
    histosSubtr["mc_before"].SetLineColor(2)

    ## This is the simple overlay of the normalized spectra
    # c2.cd(1)
    r.SetOwnership(c2, False)
    c2_spectrum = c2.GetListOfPrimitives().FindObject("c2_1")
    c2_ratio    = c2.GetListOfPrimitives().FindObject("c2_2")
    c2_spectrum.SetPad(0.+xOffset, (1 - spectrum_height)+yOffset, 1.+xOffset, 1.+yOffset)
    c2_ratio.SetPad(0.+xOffset, 0.+yOffset, 1.+xOffset, ratio_height+yOffset)
    c2_ratio.SetTopMargin(0)   
    c2_ratio.SetBottomMargin(0.2)
    c2_spectrum.SetLeftMargin(0.12)
    c2_spectrum.SetRightMargin(0.15)
    c2_ratio.SetLeftMargin(0.12)
    c2_ratio.SetRightMargin(0.15)

    leg=0
    leg = TLegend(0.10,0.75,0.40,0.90)
    leg.SetHeader("Before corrections")
    leg.SetFillColor(0)
    leg.SetTextSize(0.06)
    leg.AddEntry(histosSubtr["data_before"],"DATA")
    leg.AddEntry(histosSubtr["mc_before"],"MC")
    setHistoStyle(histosSubtr["data_before"])
    setHistoStyle(histosSubtr["mc_before"])
    histosSubtr["data_before"].SetTitle("Dimuon mass spectrum (after background subtraction) data vs. MC")
    histosSubtr["data_before"].GetXaxis().SetTitle("M_{#mu#mu} (GeV)")
    histosSubtr["data_before"].GetYaxis().SetTitle("Arbitrary units")
    histosSubtr["mc_before"].GetXaxis().SetTitle("M_{#mu#mu} (GeV)")
    histosSubtr["mc_before"].GetYaxis().SetTitle("Arbitrary units")
    
    c2_spectrum.cd()
#     c2_spectrum.SetLogy()
    histosSubtr["data_before"].Draw("HIST")
    histosSubtr["mc_before"].Draw("HISTsame")
    tpt_pars_data = TPaveText(0.13, 0.45, 0.4, 0.59, "NDC")
    tpt_pars_data.SetTextSize(0.045)
    tpt_pars_data.SetTextFont(42)
    tpt_pars_data.SetFillColor(0)
    tpt_pars_data.SetBorderSize(0)
    tpt_pars_data.SetMargin(0.01)
    tpt_pars_data.SetTextAlign(12)
    tpt_pars_data.AddText(0.0,0.9,"M^{fit}_{Z,data} = "+str(round(signalPars["data_before"][0],2))+" GeV")
    tpt_pars_data.AddText(0.0,0.4,"#sigma_{CB,data} = "+str(round(signalPars["data_before"][3],2))+" GeV")
    tpt_pars_data.Draw("same")
    
    tpt_pars_mc = TPaveText(0.13, 0.30, 0.4, 0.44, "NDC")
    tpt_pars_mc.SetTextSize(0.045)
    tpt_pars_mc.SetTextFont(42)
    tpt_pars_mc.SetFillColor(0)
    tpt_pars_mc.SetBorderSize(0)
    tpt_pars_mc.SetMargin(0.01)
    tpt_pars_mc.SetTextAlign(12)
    tpt_pars_mc.SetTextColor(2)
    tpt_pars_mc.AddText(0.0,0.9,"M^{fit}_{Z,MC} = "+str(round(signalPars["mc_before"][0],2))+" GeV")
    tpt_pars_mc.AddText(0.0,0.4,"#sigma_{CB,MC} = "+str(round(signalPars["mc_before"][3],2))+" GeV")
    tpt_pars_mc.Draw("same")
    leg.Draw("same")
    
#     mean.setVal(signalPars["data_before"][0])
#     sigma.setVal(signalPars["data_before"][3])
#     alpha.setVal(signalPars["data_before"][4])
#     N.setVal(signalPars["data_before"][5])
#     dh_data = RooDataHist("dh_data","dh_data",RooArgList(x),histosSubtr["data_before"])
#     frame_data = x.frame()
#     dh_data.plotOn(frame_data,RooFit.LineColor(1),RooFit.DrawOption("B"))
#     # relBWTimesCB.plotOn(frame_data,RooFit.LineColor(1))
#     frame_data.Draw()

#     mean.setVal(signalPars["mc_before"][0])
#     # mean.setVal(97)
#     sigma.setVal(signalPars["mc_before"][3])
#     alpha.setVal(signalPars["mc_before"][4])
#     N.setVal(signalPars["mc_before"][5])
#     dh_mc = RooDataHist("dh_mc","dh_mc",RooArgList(x),histosSubtr["mc_before"])
#     frame_mc = x.frame()
#     # dh_mc.plotOn(frame_mc,RooFit.LineColor(2),RooFit.MarkerColor(2),RooFit.MarkerSize(0.4),RooFit.DrawOption("HIST"))
#     # relBWTimesCB.plotOn(frame_mc,RooFit.LineColor(2))
#     # frame_mc.Draw("same")


    ## Ratio histogram
    h_Num_woBkg = histosSubtr["data_before"].Clone()
    h_Den_woBkg = histosSubtr["mc_before"].Clone()
    # h_Num_woBkg.Rebin(10)
    # h_Den_woBkg.Rebin(10)
    h_Num_woBkg.Divide(h_Den_woBkg)
    h_Num_woBkg.GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    h_Num_woBkg.GetYaxis().SetRangeUser(minR,maxR)
    h_Num_woBkg.GetXaxis().SetTitleSize(0.09)
    h_Num_woBkg.GetYaxis().SetTitleSize(0.09)
    h_Num_woBkg.GetXaxis().SetLabelSize(0.08)
    h_Num_woBkg.GetYaxis().SetLabelSize(0.08)
    h_Num_woBkg.GetYaxis().SetTitleOffset(0.45)

    ## This is the DATA/MC ratio
    c2_ratio.cd()
    h_Num_woBkg.GetYaxis().SetTitle("DATA/MC Ratio")
    h_Num_woBkg.SetTitle("")
    # setHistoStyle(h_Num_woBkg)
    h_Num_woBkg.SetMarkerStyle(20)
    h_Num_woBkg.SetMarkerSize(0.85)
    h_Num_woBkg.Draw("E")
    line.Draw("same")
    c2.SaveAs(options.outDir+"/DimuonAfterBkgSub_beforeCorrections.png")
    c2.SaveAs(options.outDir+"/DimuonAfterBkgSub_beforeCorrections.pdf")
    c2.SaveAs(options.outDir+"/DimuonAfterBkgSub_beforeCorrections.eps")

    del tpt_pars_data, tpt_pars_mc, h_Num_woBkg


    # AFTER CORRECTIONS
    
#     # RooFit definitions (again, sorry)
#     ## RooRealVars
#     x = RooRealVar("x","M_{#mu#mu} (GeV)",minM_fit,maxM_fit)
#     mean = RooRealVar("mean","mean",91.19)
#     meanCB = RooRealVar("meanCB","meanCB",0.)
#     width = RooRealVar("width","width",2.4952)
#     sigma = RooRealVar("sigma","sigma",1.3)
#     alpha = RooRealVar("alpha","alpha",1.)
#     N = RooRealVar("N","N",2.)

#     ## PDFs (again, sorry)
#     relBW = RooGenericPdf("relBW","relBW","@0/(pow(@0*@0-@1*@1,2) + @2*@2*@0*@0*@0*@0/(@1*@1))",RooArgList(x,mean,width))
#     CB = RooCBShape("CB","CB",x,meanCB,sigma,alpha,N)
#     relBWTimesCB = RooFFTConvPdf("relBWTimesCB","relBWTimesCB",x,relBW,CB)

    
    # Ratio plot after background subtraction
    histosSubtr["data_after"].GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    histosSubtr["data_after"].GetYaxis().SetRangeUser(0.,histosSubtr["data_after"].GetMaximum()+0.1*histosSubtr["data_after"].GetMaximum())
    histosSubtr["data_after"].SetLineColor(1)

    histosSubtr["mc_after"].GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    if histosSubtr["mc_after"].GetMaximum()>histosSubtr["data_after"].GetMaximum():
        histosSubtr["data_after"].GetYaxis().SetRangeUser(0.,histosSubtr["mc_after"].GetMaximum()+0.1*histosSubtr["mc_after"].GetMaximum())
    histosSubtr["mc_after"].SetLineColor(2)

    ## This is the simple overlay of the normalized spectra
    # c3.cd(1)
    r.SetOwnership(c3, False)
    c3_spectrum = c3.GetListOfPrimitives().FindObject("c3_1")
    c3_ratio    = c3.GetListOfPrimitives().FindObject("c3_2")
    c3_spectrum.SetPad(0.+xOffset, (1 - spectrum_height)+yOffset, 1.+xOffset, 1.+yOffset)
    c3_ratio.SetPad(0.+xOffset, 0.+yOffset, 1.+xOffset, ratio_height+yOffset)
    c3_ratio.SetTopMargin(0)   
    c3_ratio.SetBottomMargin(0.2)
    c3_spectrum.SetLeftMargin(0.12)
    c3_spectrum.SetRightMargin(0.15)
    c3_ratio.SetLeftMargin(0.12)
    c3_ratio.SetRightMargin(0.15)

    leg=0
    leg = TLegend(0.10,0.75,0.40,0.90)
    leg.SetHeader("After corrections")
    leg.SetFillColor(0)
    leg.SetTextSize(0.06)
    leg.AddEntry(histosSubtr["data_after"],"DATA")
    leg.AddEntry(histosSubtr["mc_after"],"MC")
    setHistoStyle(histosSubtr["data_after"])
    setHistoStyle(histosSubtr["mc_after"])
    histosSubtr["data_after"].SetTitle("Dimuon mass spectrum (after background subtraction) data vs. MC")
    histosSubtr["data_after"].GetXaxis().SetTitle("M_{#mu#mu} (GeV)")
    histosSubtr["data_after"].GetYaxis().SetTitle("Arbitrary units")
    histosSubtr["mc_after"].GetXaxis().SetTitle("M_{#mu#mu} (GeV)")
    histosSubtr["mc_after"].GetYaxis().SetTitle("Arbitrary units")
    
    c3_spectrum.cd()
#     c3_spectrum.SetLogy()
    histosSubtr["data_after"].Draw("HIST")
    histosSubtr["mc_after"].Draw("HISTsame")
    tpt_pars_data = 0
    tpt_pars_data = TPaveText(0.13, 0.45, 0.4, 0.59, "NDC")
    tpt_pars_data.SetTextSize(0.045)
    tpt_pars_data.SetTextFont(42)
    tpt_pars_data.SetFillColor(0)
    tpt_pars_data.SetBorderSize(0)
    tpt_pars_data.SetMargin(0.01)
    tpt_pars_data.SetTextAlign(12)
    tpt_pars_data.AddText(0.0,0.9,"M^{fit}_{Z,data} = "+str(round(signalPars["data_after"][0],2))+" GeV")
    tpt_pars_data.AddText(0.0,0.4,"#sigma_{CB,data} = "+str(round(signalPars["data_after"][3],2))+" GeV")
    tpt_pars_data.Draw("same")

    tpt_pars_mc = 0
    tpt_pars_mc = TPaveText(0.13, 0.30, 0.4, 0.44, "NDC")
    tpt_pars_mc.SetTextSize(0.045)
    tpt_pars_mc.SetTextFont(42)
    tpt_pars_mc.SetFillColor(0)
    tpt_pars_mc.SetBorderSize(0)
    tpt_pars_mc.SetMargin(0.01)
    tpt_pars_mc.SetTextAlign(12)
    tpt_pars_mc.SetTextColor(2)
    tpt_pars_mc.AddText(0.0,0.9,"M^{fit}_{Z,MC} = "+str(round(signalPars["mc_after"][0],2))+" GeV")
    tpt_pars_mc.AddText(0.0,0.4,"#sigma_{CB,MC} = "+str(round(signalPars["mc_after"][3],2))+" GeV")
    tpt_pars_mc.Draw("same")
    leg.Draw("same")
    
#     mean.setVal(signalPars["data_after"][0])
#     sigma.setVal(signalPars["data_after"][3])
#     alpha.setVal(signalPars["data_after"][4])
#     N.setVal(signalPars["data_after"][5])
#     dh_data = RooDataHist("dh_data","dh_data",RooArgList(x),histosSubtr["data_after"])
#     frame_data = x.frame()
#     dh_data.plotOn(frame_data,RooFit.LineColor(1),RooFit.DrawOption("B"))
#     # relBWTimesCB.plotOn(frame_data,RooFit.LineColor(1))
#     frame_data.Draw()

#     mean.setVal(signalPars["mc_after"][0])
#     # mean.setVal(97)
#     sigma.setVal(signalPars["mc_after"][3])
#     alpha.setVal(signalPars["mc_after"][4])
#     N.setVal(signalPars["mc_after"][5])
#     dh_mc = RooDataHist("dh_mc","dh_mc",RooArgList(x),histosSubtr["mc_after"])
#     frame_mc = x.frame()
#     # dh_mc.plotOn(frame_mc,RooFit.LineColor(2),RooFit.MarkerColor(2),RooFit.MarkerSize(0.4),RooFit.DrawOption("HIST"))
#     # relBWTimesCB.plotOn(frame_mc,RooFit.LineColor(2))
#     # frame_mc.Draw("same")


    ## Ratio histogram
    h_Num_woBkg = histosSubtr["data_after"].Clone()
    h_Den_woBkg = histosSubtr["mc_after"].Clone()
    # h_Num_woBkg.Rebin(10)
    # h_Den_woBkg.Rebin(10)
    h_Num_woBkg.Divide(h_Den_woBkg)
    h_Num_woBkg.GetXaxis().SetRangeUser(minM_fit,maxM_fit)
    h_Num_woBkg.GetYaxis().SetRangeUser(minR,maxR)
    h_Num_woBkg.GetXaxis().SetTitleSize(0.09)
    h_Num_woBkg.GetYaxis().SetTitleSize(0.09)
    h_Num_woBkg.GetXaxis().SetLabelSize(0.08)
    h_Num_woBkg.GetYaxis().SetLabelSize(0.08)
    h_Num_woBkg.GetYaxis().SetTitleOffset(0.45)

    ## This is the DATA/MC ratio
    c3_ratio.cd()
    h_Num_woBkg.GetYaxis().SetTitle("DATA/MC Ratio")
    h_Num_woBkg.SetTitle("")
    # setHistoStyle(h_Num_woBkg)
    h_Num_woBkg.SetMarkerStyle(20)
    h_Num_woBkg.SetMarkerSize(0.85)
    h_Num_woBkg.Draw("E")
    line.Draw("same")
    c3.SaveAs(options.outDir+"/DimuonAfterBkgSub_afterCorrections.png")
    c3.SaveAs(options.outDir+"/DimuonAfterBkgSub_afterCorrections.pdf")
    c3.SaveAs(options.outDir+"/DimuonAfterBkgSub_afterCorrections.eps")
コード例 #33
0
ファイル: ngZmmToZbbFit.py プロジェクト: degrutto/VHbbUF
latex.SetTextAlign(12)
latex.SetTextFont(42)
latex.SetTextSize(0.035)

ws = RooWorkspace("ws")
x = RooRealVar("x", "p_{T}^{reco}/p_{T}^{parton}", xlow,xup)
obs = RooArgList(x)
c1 = TCanvas("c1", "c1",600,600) ;
if logy:  c1.SetLogy()


# Loop over input files (currently disabled)
infile = TFile.Open(infilename)
for ih in xrange(ih_,ih_+1):
    h = getattr(infile, "hh1_%i" % ih)
    data = RooDataHist("data_%i" %ih, "", obs, h)
    getattr(ws, 'import')(data)

    hl = getattr(infile, "hl_%i" % ih)
    
    frame = x.frame()
    
    if h.Integral() < 150:
        h.Draw()
        latex.DrawLatex(0.19, 0.90, "%.0f<p_{T}^{Z}<%.0f, %.0f<p_{T}^{j}<%.0f, %.1f<|#eta^{j}|<%.1f" % tuple([hl.GetBinContent(l) for l in xrange(1,7)]))
        latex.DrawLatex(0.19, 0.85, "#color[1]{FullSim}")
        latex.DrawLatex(0.42, 0.85, "#color[1]{#mu=%.3f, #sigma=%.3f}" % (h.GetMean(), h.GetRMS()))
        gPad.Print("plots/zmmtozbb_fit%i_%s.png" % (ifunc,h.GetName() if logy else h.GetName()+"_lin"))
        #gPad.Print("plots/zmmtozbb_fit%i_%s.pdf" % (ifunc,h.GetName() if logy else h.GetName()+"_lin"))
        
        continue
コード例 #34
0
def fitHistogram( histToFit, channel, variable='', bin='', treeSuffix ='' ) :
	# Declare variables x,mean,sigma with associated name, title, initial value and allowed range
	x = RooRealVar("M(jj)","M(jj)",40,500)

	title = channel
	if variable != '' and bin != '' :
		title = '%s_%s_%s' % (channel, variable, bin)

	histToFit = RooDataHist('histToFit', 'histToFit', RooArgList( x ), RooFit.Import( histToFit ) )
	frame = x.frame(RooFit.Title( title )) 
	histToFit.plotOn( frame )

	# Setup fit function
	fitFunction = None

	# Stuff for gauss
	mg = RooRealVar("mean","mean of gaussian",86,50,120) 
	sg = RooRealVar("sigma","width of gaussian",10,2,50) 
	gauss = RooGaussian("gauss","gaussian PDF",x,mg,sg)   

	CBmean = RooRealVar("CBmean", "CBmean",110, 5, 500)
	CBsigma = RooRealVar("CBsigma", "CBsigma",40, 20, 150)
	CBalpha = RooRealVar("CBalpha", "CBalpha", -0.5, -20., 0.)
	# CBalpha = RooRealVar("CBalpha", "CBalpha", 10, 0., 20.)
	CBn = RooRealVar("CBn", "CBn", 1., 0., 20.)
	crystalBall = RooCBShape("crystalBall","Crystal Ball resolution model", x, CBmean, CBsigma, CBalpha, CBn)

	fracGauss = RooRealVar("fracGauss", "fracGauss", 0.4, 0, 1)
	gaussPlusCrystalBall = RooAddPdf("gaussPlusCrystalBall", "Gauss plus Crystal Ball", RooArgList(gauss, crystalBall), RooArgList( fracGauss ) )
	fitFunction = gaussPlusCrystalBall

	# # Fit pdf to data
	fitFunction.fitTo(histToFit, RooFit.PrintLevel(-1))

	# Plot histogram being fitted
	histToFit.plotOn(frame)

	# Plot fit functions and components
	fitFunction.plotOn(frame, RooFit.LineColor(kRed))

	toPlot = RooArgSet(crystalBall)
	fitFunction.plotOn(frame, RooFit.Components(toPlot), RooFit.LineStyle(kDashed), RooFit.LineColor(kRed))

	toPlot = RooArgSet(gauss)
	fitFunction.plotOn(frame, RooFit.Components(toPlot), RooFit.LineStyle(kDashed), RooFit.LineColor(kBlue))

	fitFunction.paramOn(frame,RooFit.Layout(0.55, 0.9, 0.9)) ;

	# # Draw frame on a canvas
	c = TCanvas("WMass","WMass",800,400) 
	gPad.SetLeftMargin(0.15)
	frame.GetYaxis().SetTitleOffset(1.6)
	frame.Draw() 
	gPad.Update()

	if variable == '' and bin == '':
		c.Print( 'plots/WStudies/%s%s.pdf' % ( channel, treeSuffix ) )
	elif variable != '' and bin != '':
		outputDir = 'plots/WStudies/%s%s/%s' % (channel, treeSuffix, variable)
		if not os.path.exists( outputDir ):
			os.makedirs( outputDir )
		c.Print( '%s/%s.pdf' % (outputDir, bin) )
	# raw_input('Carry on')
	# mg.Print()
	return mg
コード例 #35
0
ファイル: plotSignalModel.py プロジェクト: ETHZ/h2gglobe
def main(options,args):

    from ROOT import gSystem, gROOT, gStyle
    gROOT.SetBatch()
    gSystem.Load("libRooFitCore")

    if options.doWebPage:
        from lip.Tools.rootutils import loadToolsLib, apply_modifs
        loadToolsLib()
    
    from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList
    from ROOT import kWhite, kBlue, kOpenSquare
    if options.doWebPage:
        from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot

    rootglobestyle.setTDRStyle()
    gStyle.SetMarkerSize(1.5)
    gStyle.SetTitleYOffset(1.5)
    
    gStyle.SetPadLeftMargin(0.16)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.13)
    
    gStyle.SetLabelFont(42,"XYZ")
    gStyle.SetLabelOffset(0.007, "XYZ")
    gStyle.SetLabelSize(0.05,"XYZ")
    
    gStyle.SetTitleSize(0.06,"XYZ")
    gStyle.SetTitleXOffset(0.9)
    gStyle.SetTitleYOffset(1.24)
    gStyle.SetTitleFont(42,"XYZ")
    
    ##
    ## Read files
    ##
    options.outdir = "%s_m%1.0f" % ( options.outdir, options.mH  )
    if options.fp:
        options.outdir += "_fp"

    ncat=options.ncat
    cats=options.cats
    if cats is "":
        categories =[  "_cat%d" % i for i in range(0,ncat) ]
    else:
        categories =[  "_cat%s" % i for i in cats.split(",") ]
    
    if options.mva:
        clables = { "_cat0" : ("MVA > 0.89",""),
                    "_cat1" : ("0.74 #leq MVA","MVA < 0.89"),
                    "_cat2" : ("0.545 #leq MVA","MVA < 0.74"),
                    "_cat3" : ("0.05 #leq MVA","MVA < 0.545"),
                    "_cat4" : ("Di-jet","Tagged"),
                    "_cat5" : ("Di-jet","Tagged"),
                    "_combcat" : ("All Classes","Combined")
                    }
    else:
        clables = { "_cat0" : ("max(|#eta|<1.5","min(R_{9})>0.94"),
                    "_cat1" : ("max(|#eta|<1.5","min(R_{9})<0.94"),
                    "_cat2" : ("max(|#eta|>1.5","min(R_{9})>0.94"),
                    "_cat3" : ("max(|#eta|>1.5","min(R_{9})<0.94"),
                    "_cat4" : ("Di-jet","Tagged"),
                    "_cat5" : ("Di-jet","Tagged"),
                    "_combcat" : ("All Classes","Combined")
                    }
    helper = Helper()

    fin = TFile.Open(options.infile)
    helper.files.append(fin)
    ws = fin.Get("cms_hgg_workspace")
    mass = ws.var("CMS_hgg_mass")
    mass.SetTitle("m_{#gamma#gamma}");
    mass.setUnit("GeV");
    mass.setRange(100.,150.)
    mass.setBins(100,"plot")
    mass.setBins(5000)

    print ws
    
    aset = RooArgSet(mass)

    helper.objs.append( mass )
    helper.objs.append( aset )

    fitopt = ( RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8) )
        
    if not options.binned and not options.refit:
        finpdf =  TFile.Open(options.infilepdf)
        helper.files.append(finpdf)
        wspdf = finpdf.Get("wsig")
    else:
        wspdf = ws
    
    for c in categories:
        processes = [ "ggh", "vbf", "wzh" ]
        if options.fp:
            processes = [ "vbf", "wzh" ]
        ### elif clables[c][0] == "Di-jet":
        ###     processes = [ "vbf", "ggh" ]
        
        dsname = "sig_mass_m%1.0f%s" % (options.mH,c)
        print dsname
        print ws
        ds = ws.data( "sig_%s_mass_m%1.0f%s" % (processes[0],options.mH,c)  ).Clone(dsname)
        for proc in processes[1:]:
            ds.append( ws.data( "sig_%s_mass_m%1.0f%s" % (proc,options.mH,c)  ) )
        helper.dsets.append( ds )


        if options.binned:
            binned_ds = RooDataHist( "binned_%s" % dsname,"binned_%s" % dsname,aset, ds)
            pdf = RooKeysPdf( "pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass,  ds )
            plot_pdf = RooHistPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, aset,  plot_ds )
            helper.add( binned_ds,    binned_ds.GetName()  )
        else:
            if options.refit:
                if options.refitall and clables[c][0] != "Di-jet":
                    rpdfs = []
                    for proc in processes:
                        for ngaus in range(1,4):
                            pp = build_pdf(ws,"%s_%s" % (c,proc),ngaus,ngaus==3 )
                            pp.fitTo( ws.data( "sig_%s_mass_m%1.0f%s" % (proc,options.mH,c)), RooFit.Strategy(0), *fitopt )
                        rpdfs.append(pp)
                    pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs) ))
                else:
                    if options.refitall and clables[c][0] == "Di-jet":
                        for ngaus in range(1,5):
                            pdf = build_pdf(ws,c,ngaus,ngaus==5)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt )
                    else:
                        for ngaus in range(1,4):
                            pdf = build_pdf(ws,c,ngaus,ngaus==3)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt )
            else:
                pdfs = (wspdf.pdf( "hggpdfrel%s_%s" % (c, p)) for p in processes )
                pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs ))
            helper.add(pdf,pdf.GetName())
            plot_pdf = pdf.Clone("pdf_%s" % dsname)

        plot_ds = RooDataHist( "plot_%s" % dsname,"plot_%s" % dsname, aset, "plot")
        plot_ds.add( ds )

        cdf = pdf.createCdf(aset)
        hmin, hmax, hm = get_FWHM( mass, pdf, cdf, options.mH-10., options.mH+10. )
        wmin, wmax = get_eff_sigma( mass, pdf, cdf, options.mH-10., options.mH+10. )
        ### hmin, hmax, hm = get_FWHM( points )
        
        helper.add( plot_ds,      plot_ds.GetName()    )
        helper.add( plot_pdf,     plot_pdf.GetName()   )
        helper.add( (wmin,wmax),  "eff_sigma%s" % c    )
        helper.add( (hmin, hmax, hm),  "FWHM%s" % c    )
        helper.add( ds.sumEntries(), "sumEntries%s" %c ) # signal model integral

        # data integral for PAS tables
        data = ws.data( "data_mass%s"%c)
        helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f"%(options.mH-10.,options.mH+10.)),"data_sumEntries%s"%c)

        
        del cdf
        del pdf
    

    dsname = "sig_mass_m%1.0f_combcat" % options.mH
    print dsname
    combined_ds = helper.dsets[0].Clone(dsname)
    for d in helper.dsets[1:]:
        combined_ds.append(d)
    
    if options.binned:
        binned_ds = RooDataHist( "binned_%s" % dsname,"binned_%s" % dsname,aset, combined_ds)
        pdf = RooKeysPdf( "pdf_%s" % (dsname), "pdf_%s" % dsname, mass,  combined_ds )
        plot_pdf = RooHistPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, aset,  plot_ds )
        helper.add( binned_ds, binned_ds.GetName()  )
    else:
        #### pdf = build_pdf(ws,"_combcat")
        #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt )
        #### plot_pdf = pdf.Clone( "pdf_%s" % dsname )
        pdf = RooAddPdf(  "pdf_%s" % dsname,  "pdf_%s" % dsname, RooArgList( *(helper.histos["hggpdfrel%s" % c] for c in categories) ) )
        plot_pdf = pdf
        
    cdf = pdf.createCdf(aset)
    
    plot_ds = RooDataHist( "plot_%s" % dsname,"plot_%s" % dsname, aset, "plot")
    plot_ds.add( combined_ds )
      
    wmin, wmax = get_eff_sigma( mass, pdf, cdf, options.mH-10., options.mH+10. )
    hmin, hmax, hm = get_FWHM( mass, pdf, cdf, options.mH-10., options.mH+10. )
    
    helper.add( plot_ds, plot_ds.GetName()  )
    helper.add( plot_pdf, plot_pdf.GetName()  )
    helper.add( (wmin,wmax), "eff_sigma_combcat"  )
    helper.add( (hmin, hmax, hm),  "FWHM_combcat"  )
    helper.add( plot_ds.sumEntries(), "sumEntries_combcat"  )
    
    mass.setRange("higgsrange",options.mH-25.,options.mH+15.);
    
    del cdf
    del pdf
    del helper.dsets
    
    ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}")
    label = TLatex(0.7,0.86,"#scale[0.65]{#splitline{CMS preliminary}{Simulation}}")
    label.SetNDC(1)
    
    ## 
    ## Make web page with plots
    ##
    if options.doWebPage:
        hth = HtmlHelper(options.outdir)
        hth.navbar().cell( HtmlTag("a") ).firstChild().txt("..").set("href","../?C=M;O=D")
        hth.navbar().cell( HtmlTag("a") ).firstChild().txt("home").set("href","./")
    
        tab = hth.body().add( HtmlTable() )
    
    ip = 0
    for c in ["_combcat"]+categories:
    ### for c in categories:
        if options.doWebPage and ip % 4 == 0:
            row = tab.row()
        ip = ip + 1

        dsname = "sig_mass_m%1.0f%s" % (options.mH,c)
        canv = TCanvas(dsname,dsname,600,600)
        helper.objs.append(canv)
        
        ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322)
        leg = TLegend(0.2,0.96,0.5,0.55)
        #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] )
        
        hplotcompint = mass.frame(RooFit.Bins(250),RooFit.Range("higgsrange"))
        helper.objs.append(hplotcompint)
        helper.objs.append(leg)
        
        plot_ds  =helper.histos["plot_%s" % dsname ]  
        plot_pdf =helper.histos["pdf_%s" % dsname ]  
        wmin,wmax = helper.histos["eff_sigma%s" % c ]
        hmin, hmax, hm = helper.histos["FWHM%s" % c ]
        print hmin, hmax, hm
        
        style = ( RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0) )
        style_seff = (  RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), )
        style_ds = ( RooFit.MarkerStyle(kOpenSquare), )
                  
        plot_ds.plotOn(hplotcompint,RooFit.Invisible())
        
        plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range(wmin,wmax), RooFit.FillColor(19),
                        RooFit.DrawOption("F"), *style_seff)
        seffleg = hplotcompint.getObject(int(hplotcompint.numItems()-1))
        plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range(wmin,wmax), RooFit.LineColor(15), *style_seff)

        plot_pdf.plotOn(hplotcompint,RooFit.NormRange("higgsrange"),RooFit.Range("higgsrange"),*style)
        pdfleg = hplotcompint.getObject(int(hplotcompint.numItems()-1))

        plot_ds.plotOn(hplotcompint,*style_ds)
        pointsleg = hplotcompint.getObject(int(hplotcompint.numItems()-1))
        
        iob = int( hplotcompint.numItems() - 1 )
        leg.AddEntry( pointsleg,  "Simulation", "pe" )  
        leg.AddEntry( pdfleg,  "Parametric model", "l" )  
        leg.AddEntry( seffleg, "#sigma_{eff} = %1.2f GeV " % ( 0.5*(wmax-wmin) ), "fl" )  

        clabel = TLatex(0.74,0.65,"#scale[0.65]{#splitline{%s}{%s}}" % clables[c])
        clabel.SetNDC(1)
        helper.objs.append(clabel)

        hm = hplotcompint.GetMaximum()*0.5*0.9
        ### hm = pdfleg.GetMaximum()*0.5
        fwhmarrow = TArrow(hmin,hm,hmax,hm)
        fwhmarrow.SetArrowSize(0.03)
        helper.objs.append(fwhmarrow)
        fwhmlabel = TPaveText(0.20,0.58,0.56,0.48,"brNDC")
        fwhmlabel.SetFillStyle(0)
        fwhmlabel.SetLineColor(kWhite)
        reducedFWHM = (hmax-hmin)/2.3548200
        fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM)
        helper.objs.append(fwhmlabel)

        hplotcompint.SetTitle("");
        hplotcompint.GetXaxis().SetNoExponent(True);
        hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)");
        hplotcompint.GetXaxis().SetNdivisions(509);
        ## hplotcompint.GetYaxis().SetTitle("A.U.");
        ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4);
        hplotcompint.Draw();    
        leg.Draw("same")
        label.Draw("same")
        clabel.Draw("same")
        fwhmarrow.Draw("<>")
        fwhmlabel.Draw("same")
        
        plot_ds.sumEntries()

        
        if options.doWebPage:
            hpl = HtmlPlot(canv,False,"",True,True,True)
            hpl.caption("<i>%s</i>" % canv.GetTitle())
            row.cell( hpl )
        else:
            if os.path.isdir(options.outdir) is False:
                os.mkdir(options.outdir)
            for ext in "C","png","pdf":
                canv.SaveAs( os.path.join(options.outdir,"%s.%s" % (canv.GetName(), ext)) )
        
        if "comb" in c:
            ip = 0
            
    if options.doWebPage:
        print "Creating pages..."
        hth.dump()
        
    for f in helper.files:
        f.Close()
    gROOT.Reset()

    from pprint import pprint
    pprint(helper)
 
    print 'Summary statistics per event class'
    print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35'%options.mH
    sigTotal=0.
    dataTotal=0.
    for c in categories:
      sigVal = helper.histos["sumEntries%s"%c]
      datVal = helper.histos["data_sumEntries%s"%c]
      sigTotal+=sigVal
      dataTotal+=datVal
    for c in categories:
      sigVal = helper.histos["sumEntries%s"%c]
      datVal = helper.histos["data_sumEntries%s"%c]
      effSig = 0.5*(helper.histos["eff_sigma%s"%c][1]-helper.histos["eff_sigma%s"%c][0])
      fwhm = (helper.histos["FWHM%s"%c][1]-helper.histos["FWHM%s"%c][0]) / 2.3548200
      print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f'%(sigVal,100.*sigVal/sigTotal,datVal/(10.+10.),100.*datVal/dataTotal,effSig,fwhm)

    print "Done."
コード例 #36
0
ファイル: fit_routines.py プロジェクト: e-gillies-ix/g4sim
def fit2GausPol1(Elo, Ehi, Emid, hist, name_prefix = None,
                 area1_lo = None, area1_hi = None,
                 area2_lo = None, area2_hi = None,
                 offset_lo = None, offset_hi = None,
                 slope_lo = None, slope_hi = None,
                 nbkg_lo = None, nbkg_hi = None,
                 verbose = None):
    """ Fitting two gaussian peaks on top of a first order polynomial
    background. Some parameters are hardcoded.
    A name can be provided to make the fit parameters unique.
    """
    if area1_lo is None:
        area1_lo = 1.
    if area1_hi is None:
        area1_hi = 1.E4
    if area2_lo is None:
        area2_lo = 1.
    if area2_hi is None:
        area2_hi = 1.E4        
    if nbkg_lo is None:
        nbkg_lo = 0.
    if nbkg_hi is None:
        nbkg_hi = 1.E4
    if offset_lo is None:
        offset_lo = -10.
    if offset_hi is None:
        offset_hi = 100.
    if slope_lo is None:
        slope_lo = -0.1
    if slope_hi is None:
        slope_hi = 0.1

    if verbose is not None: 
        print "Fitting two Gaussian peaks on top of a 1st order polynomial\
        background to the", hist.GetName(), "in range:", Elo, "--", Ehi, "keV"
    
    ws = ROOT.RooWorkspace()
    
    bookstr = "Polynomial::pol1_bkg(" +\
    "edep[" + Elo.__str__() + ", " + Ehi.__str__() +"]" +\
    ", {bkg_offset[" + offset_lo.__str__() + "," +offset_hi.__str__()+ "]" +\
    ", bkg_slope[" + slope_lo.__str__() +"," + slope_hi.__str__() +"]"+\
    "} )"
    if verbose is not None:
        print bookstr
    ws.factory(bookstr)

    bookstr = "Gaussian::peak1_pdf(" +\
    "edep[" + Elo.__str__() + ", " + Ehi.__str__() +"]" +\
    ", centroid1[" + Elo.__str__() + ", " + (Emid+2).__str__() +"]" +\
    ", sigma1[0.3, 10.])"
    if verbose is not None:
        print bookstr
    ws.factory(bookstr)
    
    bookstr = "Gaussian::peak2_pdf(" +\
    "edep[" + Elo.__str__() + ", " + Ehi.__str__() +"]" +\
    ", centroid2[" + (Emid-2).__str__() + ", " + Ehi.__str__() +"]" +\
    ", sigma2[0.3, 10.])"
    if verbose is not None:
        print bookstr
    ws.factory(bookstr)
    
    bookstr = "SUM:sum_pdf(area1[" + area1_lo.__str__() + "," + area1_hi.__str__() + "]*peak1_pdf"+\
    ", area2[" + area2_lo.__str__() + "," + area2_hi.__str__() + "]*peak2_pdf"+\
    ", nbkg[" + nbkg_lo.__str__()+ "," + nbkg_hi.__str__() + "]*pol1_bkg)"
    if verbose is not None:
        print bookstr

    ws.factory(bookstr)
    #ws.factory("SUM:sum_pdf(area1[0,10000]*peak1_pdf, area2[0,1E5]*peak2_pdf, nbkg[0,100000]*pol1_bkg)")

    edep = ws.var("edep")
    pdf = ws.pdf("sum_pdf")
    centroid1 = ws.var("centroid1")
    centroid2 = ws.var("centroid2")
    
    datahist = RooDataHist("tmp_datahist","tmp_datahist", RooArgList(edep), hist)
    
    model_config = RooStats.ModelConfig("model_config", ws)
    model_config.SetPdf(pdf)
    model_config.SetParametersOfInterest(RooArgSet(ws.var("area1"),
                                                   ws.var("area2")))
    model_config.SetObservables(RooArgSet(ws.var("edep")))

    model_config.SetNuisanceParameters(RooArgSet(ws.var("nbkg")))
    
    pllCal = RooStats.ProfileLikelihoodCalculator(datahist, model_config)
    fit_result = pllCal.fFitResult
    pllCal.SetConfidenceLevel(0.683)
    interval = pllCal.GetInterval()
    POIs = model_config.GetParametersOfInterest()

    #lowerlimit = interval.LowerLimit(firstPOI)
    #upperlimit = interval.UpperLimit(firstPOI)
    
    if verbose is not None: 
        print "Fit status:",fit_result.status()

    frame = edep.frame()
    datahist.plotOn(frame,
                    RooFit.MarkerSize(0.3),
                    RooFit.MarkerColor(ROOT.kAzure))
    pdf.plotOn(frame,
               RooFit.Components("peak1_pdf"),
               RooFit.LineColor(ROOT.kOrange))
    pdf.plotOn(frame,
               RooFit.Components("peak2_pdf"),
               RooFit.LineColor(ROOT.kOrange+2))
    pdf.plotOn(frame,
               RooFit.Components("pol1_bkg"),
               RooFit.LineStyle(ROOT.kDotted),
               RooFit.LineColor(ROOT.kMagenta))
    pdf.plotOn(frame,
               RooFit.LineColor(ROOT.kRed))
    c = TCanvas()
    c.SetWindowSize(400,250)
    frame.Draw()    
    
    output = {}
    output["fit_status"] = fit_result.status()
    output["area1"] = POIs["area1"]
    output["area2"] = POIs["area2"]
    output["nbkg"] = ws.var("nbkg")
    output["centroid1"] = ws.var("centroid1")
    output["centroid2"] = ws.var("centroid2")
    output["sigma1"] = ws.var("sigma1")
    output["sigma2"] = ws.var("sigma2")
    output["bkg_slope"] = ws.var("bkg_slope")
    output["bkg_offset"] = ws.var("bkg_offset")
    output["canvas"] = c
    
    for param in output:
        if hasattr(output[param], 'GetName'):
            oldname = output[param].GetName()
            if name_prefix is None:
                newname = hist.GetName() + "_" + Elo.__str__()\
                + "_" + Ehi.__str__() + "_" + oldname
            else:
                newname = oldname
            output[param].SetName(newname)
    del ws        
    return output
コード例 #37
0
    p  = RooRealVar('p','p',1,0,5)
    x0 = RooRealVar('x0','x0',1000,100,5000)

    bkg = RooGenericPdf('bkg','1/(exp(pow(@0/@1,@2))+1)',RooArgList(x,x0,p))

    fsig= RooRealVar('fsig','fsig',0.5,0.,1.)
    signal = RooAddPdf('signal','signal',sig,bkg,fsig)

    # -----------------------------------------
    # fit signal
    canSname = 'can_Mjj'+str(mass)

    canS = TCanvas(canSname,canSname,900,600)
    #gPad.SetLogy() 

    roohistSig = RooDataHist('roohist','roohist',RooArgList(x),hSig)

    signal.fitTo(roohistSig)
    frame = x.frame()
    roohistSig.plotOn(frame)
    signal.plotOn(frame)
    signal.plotOn(frame,RooFit.Components('bkg'),RooFit.LineColor(ROOT.kRed),RooFit.LineWidth(2),RooFit.LineStyle(ROOT.kDashed))
    frame.GetXaxis().SetRangeUser(900,4500)
    frame.GetXaxis().SetTitle('m_{jj} (GeV)')
    frame.Draw()

    parsSig = signal.getParameters(roohistSig)
    parsSig.setAttribAll('Constant', True)

if fitDat: 
コード例 #38
0
    sbhist.Add(hvv,signalweight)
    sbhist.Scale(hqcd.Integral()/sbhist.Integral())
    mchist=sbhist.Clone("mchist")
    if cuts.index(cut)==1:
      summchist=sbhist.Clone("mchist")
    else:
      summchist.Add(sbhist)
    sighist=hvv.Clone("sighist")
    if cuts.index(cut)==1:
   	sumsighist=hvv.Clone("sighist")
    else:
   	sumsighist.Add(hvv)
 
  if fit=="data":
    if cut>1:
      data=RooDataHist("data"+str(cut),"data",RooArgList(mass),sumdatahist)
    else:
      data=RooDataHist("data"+str(cut),"data",RooArgList(mass),datahist)
  elif fit=="b":
    if cut>1:
      data=RooDataHist("data"+str(cut),"QCD",RooArgList(mass),sumqcdhist)
    else:
      data=RooDataHist("data"+str(cut),"QCD",RooArgList(mass),qcdhist)
  elif fit=="sb":
    if cut>1:
      data=RooDataHist("data"+str(cut),"QCD + V+jets",RooArgList(mass),summchist)
    else:
      data=RooDataHist("data"+str(cut),"QCD + V+jets",RooArgList(mass),mchist)
  if cut>1:
    signal=RooDataHist("signal"+str(cut),"signal",RooArgList(mass),sumsighist)
  else:
コード例 #39
0
def fitWPeak():

	# Get histograms from file
	mcHist = 0
	with root_open( inputFile, 'read' ) as file:
		gROOT.cd()
		mcHist = file.Get(inputHistogram).Clone('histToFit')
		# mcHist = file.Get(inputHistogram).GetStack().Last().Clone('histToFit')

	# Data hist gone out of scope?
	print mcHist

	# Import the data to fit

	# Declare variables x,mean,sigma with associated name, title, initial value and allowed range
	x = RooRealVar("M(jj)","M(jj)",40,180)

	histToFit = RooDataHist('histToFit', 'histToFit', RooArgList( x ), RooFit.Import( mcHist ) )
	frame = x.frame(RooFit.Title("E Plus Jets")) 
	histToFit.plotOn( frame )

	# Setup fit function
	fitFunction = None
	print fitFunction
	if whatToFit == 'realLife':
		# Stuff for gauss
		mg = RooRealVar("mean","mean of gaussian",86,50,120) 
		sg = RooRealVar("sigma","width of gaussian",10,0,50) 
		gauss = RooGaussian("gauss","gaussian PDF",x,mg,sg)   

		CBmean = RooRealVar("CBmean", "CBmean",110, 60, 200)
		CBsigma = RooRealVar("CBsigma", "CBsigma",40, 20, 100)
		CBalpha = RooRealVar("CBalpha", "CBalpha", -0.5, -20., 0.)
		# CBalpha = RooRealVar("CBalpha", "CBalpha", 10, 0., 20.)
		CBn = RooRealVar("CBn", "CBn", 1., 0., 20.)
		crystalBall = RooCBShape("crystalBall","Crystal Ball resolution model", x, CBmean, CBsigma, CBalpha, CBn)

		fracGauss = RooRealVar("fracGauss", "fracGauss", 0.4, 0, 1)
		gaussPlusCrystalBall = RooAddPdf("gaussPlusCrystalBall", "Gauss plus Crystal Ball", RooArgList(gauss, crystalBall), RooArgList( fracGauss ) )
		fitFunction = gaussPlusCrystalBall
	elif whatToFit == 'partons':
		mg = RooRealVar("mean","mean of gaussian",86,50,120) 
		sg = RooRealVar("sigma","width of gaussian",10,0,50) 
		breitWigner = RooBreitWigner('bw', 'bw', x, mg, sg)
		fitFunction = breitWigner
	elif whatToFit == 'genJetsFromPartons':
		# mg = RooRealVar("mean","mean of gaussian",86,50,120) 
		# sg = RooRealVar("sigma","width of gaussian",10,0,50) 
		# breitWigner = RooBreitWigner('bw', 'bw', x, mg, sg)
		# fitFunction = breitWigner
		# mg = RooRealVar("mean","mean of gaussian",86,50,120)
		# sg = RooRealVar("sigma","width of gaussian",1,0,20)
		# width = RooRealVar("width","width of gaussian",5,0,50)
		# voigtian = RooVoigtian("voigt","voigt",x,mg,sg,width);
		# fitFunction = voigtian
		mg = RooRealVar("mean","mean of gaussian",86,50,120) 
		sg = RooRealVar("sigma","width of gaussian",10,0,50) 
		gauss = RooGaussian("gauss","gaussian PDF",x,mg,sg)
		fitFunction = gauss


	print fitFunction
	
	# # Fit pdf to data
	fitFunction.fitTo(histToFit)

	# Plot histogram being fitted
	histToFit.plotOn(frame)

	# Plot fit functions and components
	fitFunction.plotOn(frame, RooFit.LineColor(kRed))
	print 'Chi square with 7 : ',frame.chiSquare(7)
	print frame.chiSquare()
	print fitFunction.getParameters(histToFit).selectByAttrib('Constant', kFALSE).getSize()

	toPlot = RooArgSet(crystalBall)
	fitFunction.plotOn(frame, RooFit.Components(toPlot), RooFit.LineStyle(kDashed), RooFit.LineColor(kRed))

	toPlot = RooArgSet(gauss)
	fitFunction.plotOn(frame, RooFit.Components(toPlot), RooFit.LineStyle(kDashed), RooFit.LineColor(kBlue))

	fitFunction.paramOn(frame,RooFit.Layout(0.55, 0.9, 0.9)) ;


	# Print values of mean and sigma (that now reflect fitted values and errors)
	mg.Print()
	sg.Print()
	# CBmean.Print() 
	# CBsigma.Print() 
	# CBalpha.Print() 
	# CBn.Print()
	# fracGauss.Print()

	# # Draw frame on a canvas
	c = TCanvas("WMass","WMass",800,400) 
	gPad.SetLeftMargin(0.15)
	frame.GetYaxis().SetTitleOffset(1.6)
	frame.Draw() 
	gPad.Update()
	c.Print('EPlusJets_mjj_fit.pdf')
	raw_input()
コード例 #40
0
ファイル: simpleltFit.py プロジェクト: lbel/Bs2DsKTools
elif accfn == 'arctan':
    acc_cond = '(@0<0.0002)'
    expr = '(atan(@0*exp(@1*@0-@2)))'
    PDF = RooGenericPdf('PDF', '%s ? 0 : %s' % (acc_cond, expr),
                               RooArgList(time, turnon, offset))
elif accfn == 'erf':
    acc_cond = '(@1<0.0002)'
    expr = '(0.5*(TMath::Erf((@1-@2)/@0)+1))'
    PDF = RooGenericPdf('PDF', '%s ? 0 : %s' % (acc_cond, expr),
                               RooArgList(turnon, time, offset))
else:
    print 'Unknown acceptance type. Aborting'
    assert(False)

# Dataset to fit to
datahist = RooDataHist('datahist', 'Dataset from a histogram',
                       RooArgList(time), RooFit.Import(timehist2, False))
# Debug
datahist.Print('v')

# Fit
PDF.fitTo(datahist, RooFit.SumW2Error(True), RooFit.NumCPU(1),
          RooFit.Range(epsilon, 0.005),
          RooFit.Optimize(False), RooFit.Verbose(True), RooFit.Strategy(2))

# Plot
tframe1 = time.frame(RooFit.Name('ptime'),
                     RooFit.Title('Lifetime acceptance fitted to %s' % accfn))
datahist.plotOn(tframe1, RooFit.MarkerStyle(kFullTriangleUp))
PDF.plotOn(tframe1, RooFit.LineColor(kGreen))

# canvas2 = TCanvas('canvas2', 'Acceptance', 800, 600)
コード例 #41
0
def main():
    # usage description
    usage = "Example: ./scripts/createDatacards.py --inputData inputs/rawhistV7_Run2015D_scoutingPFHT_UNBLINDED_649_838_JEC_HLTplusV7_Mjj_cor_smooth.root --dataHistname mjj_mjjcor_gev --inputSig inputs/ResonanceShapes_gg_13TeV_Scouting_Spring15.root -f gg -o datacards -l 1866 --lumiUnc 0.027 --massrange 1000 1500 50 --runFit --p1 5 --p2 7 --p3 0.4 --massMin 838 --massMax 2037 --fitStrategy 2"

    # input parameters
    parser = ArgumentParser(description='Script that creates combine datacards and corresponding RooFit workspaces',epilog=usage)
    parser.add_argument("analysis", type=str, help="Analysis name")
    parser.add_argument("model", type=str, help="Model (Hbb, RSG)")

    #parser.add_argument("--inputData", dest="inputData", required=True,
    #                    help="Input data spectrum",
    #                    metavar="INPUT_DATA")

    parser.add_argument("--dataHistname", dest="dataHistname", type=str, default="h_data",
                        help="Data histogram name",
                        metavar="DATA_HISTNAME")

    #parser.add_argument("--inputSig", dest="inputSig", required=True,
    #                    help="Input signal shapes",
    #                    metavar="INPUT_SIGNAL")

    parser.add_argument("-f", "--final_state", dest="final_state", default="qq",
                        help="Final state (e.g. qq, qg, gg)",
                        metavar="FINAL_STATE")
    parser.add_argument("--fit_functions", dest="fit_functions", default="f1,f2,f3,f4,f5", help="List of fit functions")

    #parser.add_argument("-f2", "--type", dest="atype", required=True, help="Type (e.g. hG, lG, hR, lR)")

    parser.add_argument("-o", "--output_path", dest="output_path",
                        help="Output path where datacards and workspaces will be stored. If not specified, this is derived from limit_configuration.",
                        metavar="OUTPUT_PATH")

    parser.add_argument("--correctTrigger", dest="correctTrigger",
                        action='store_true',
                        help="Include trigger correction in PDF")

    parser.add_argument("-l", "--lumi", dest="lumi",
                        default=19700., type=float,
                        help="Integrated luminosity in pb-1 (default: %(default).1f)",
                        metavar="LUMI")

    parser.add_argument("--massMin", dest="massMin",
                        default=500, type=int,
                        help="Lower bound of the mass range used for fitting (default: %(default)s)",
                        metavar="MASS_MIN")

    parser.add_argument("--massMax", dest="massMax",
                        default=1200, type=int,
                        help="Upper bound of the mass range used for fitting (default: %(default)s)",
                        metavar="MASS_MAX")
    parser.add_argument("--fitSignal", action="store_true", help="Use signal fitted shapes (CB+Voigtian) instead of histogram templates")
    #parser.add_argument("--lumiUnc", dest="lumiUnc",
    #                    required=True, type=float,
    #                    help="Relative uncertainty in the integrated luminosity",
    #                    metavar="LUMI_UNC")

    #parser.add_argument("--jesUnc", dest="jesUnc",
    #                    type=float,
    #                    help="Relative uncertainty in the jet energy scale",
    #                    metavar="JES_UNC")

    #parser.add_argument("--jerUnc", dest="jerUnc",
    #                    type=float,
    #                    help="Relative uncertainty in the jet energy resolution",
    #                    metavar="JER_UNC")

    parser.add_argument("--sqrtS", dest="sqrtS",
                        default=8000., type=float,
                        help="Collision center-of-mass energy (default: %(default).1f)",
                        metavar="SQRTS")

    parser.add_argument("--fixP3", dest="fixP3", default=False, action="store_true", help="Fix the fit function p3 parameter")

    parser.add_argument("--runFit", dest="runFit", default=False, action="store_true", help="Run the fit")

    parser.add_argument("--fitBonly", dest="fitBonly", default=False, action="store_true", help="Run B-only fit")

    parser.add_argument("--fixBkg", dest="fixBkg", default=False, action="store_true", help="Fix all background parameters")

    parser.add_argument("--decoBkg", dest="decoBkg", default=False, action="store_true", help="Decorrelate background parameters")

    parser.add_argument("--fitStrategy", dest="fitStrategy", type=int, default=1, help="Fit strategy (default: %(default).1f)")

    parser.add_argument("--debug", dest="debug", default=False, action="store_true", help="Debug printout")

    parser.add_argument("--postfix", dest="postfix", default='', help="Postfix for the output file names (default: %(default)s)")

    parser.add_argument("--pyes", dest="pyes", default=False, action="store_true", help="Make files for plots")

    parser.add_argument("--jyes", dest="jyes", default=False, action="store_true", help="Make files for JES/JER plots")

    parser.add_argument("--pdir", dest="pdir", default='testarea', help="Name a directory for the plots (default: %(default)s)")

    parser.add_argument("--chi2", dest="chi2", default=False, action="store_true", help="Compute chi squared")

    parser.add_argument("--widefit", dest="widefit", default=False, action="store_true", help="Fit with wide bin hist")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument("--mass",
                            type=int,
                            nargs = '*',
                            default = 1000,
                            help="Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
                            )
    mass_group.add_argument("--massrange",
                            type=int,
                            nargs = 3,
                            help="Define a range of masses to be produced. Format: min max step",
                            metavar = ('MIN', 'MAX', 'STEP')
                            )
    mass_group.add_argument("--masslist",
                            help = "List containing mass information"
                            )

    args = parser.parse_args()

    fit_functions = args.fit_functions.split(",")

    # mass points for which resonance shapes will be produced
    masses = []

    if args.fitBonly:
        masses.append(750)
    else:
        if args.massrange != None:
            MIN, MAX, STEP = args.massrange
            masses = range(MIN, MAX+STEP, STEP)
        elif args.masslist != None:
            # A mass list was provided
            print  "Will create mass list according to", args.masslist
            masslist = __import__(args.masslist.replace(".py",""))
            masses = masslist.masses
        else:
            masses = args.mass

    # sort masses
    masses.sort()

    # import ROOT stuff
    from ROOT import gStyle, TFile, TH1F, TH1D, TGraph, kTRUE, kFALSE, TCanvas, TLegend, TPad, TLine
    from ROOT import RooHist, RooRealVar, RooDataHist, RooArgList, RooArgSet, RooAddPdf, RooProdPdf, RooEffProd, RooFit, RooGenericPdf, RooWorkspace, RooMsgService, RooHistPdf, RooExtendPdf

    if not args.debug:
        RooMsgService.instance().setSilentMode(kTRUE)
        RooMsgService.instance().setStreamStatus(0,kFALSE)
        RooMsgService.instance().setStreamStatus(1,kFALSE)

    # input data file
    #inputData = TFile(limit_config.get_data_input(args.analysis))
    # input data histogram
    #hData = inputData.Get(args.dataHistname)
    #hData.SetDirectory(0)
    data_file = TFile(analysis_config.get_b_histogram_filename(args.analysis, "BJetPlusX_2012"))
    hData = data_file.Get("BHistograms/h_pfjet_mjj")
    hData.SetDirectory(0)

    # input sig file
    if not args.fitSignal:
        print "[create_datacards] INFO : Opening resonance shapes file at " + limit_config.get_resonance_shapes(args.analysis, args.model)
        inputSig = TFile(limit_config.get_resonance_shapes(args.analysis, args.model), "READ")

    sqrtS = args.sqrtS

    # mass variable
    mjj = RooRealVar('mjj','mjj',float(args.massMin),float(args.massMax))

    # integrated luminosity and signal cross section
    lumi = args.lumi
    signalCrossSection = 1. # set to 1. so that the limit on r can be interpreted as a limit on the signal cross section

    if args.correctTrigger:
        trigger_efficiency_pdf = trigger_efficiency.get_pdf(args.analysis, mjj)
        trigger_efficiency_formula = trigger_efficiency.get_formula(args.analysis, mjj)
    else:
        trigger_efficiency_pdf = trigger_efficiency.get_trivial_pdf(mjj)
        trigger_efficiency_formula = trigger_efficiency.get_trivial_formula(mjj)

    for mass in masses:

        print ">> Creating datacard and workspace for %s resonance with m = %i GeV..."%(args.final_state, int(mass))
        
        rooDataHist = RooDataHist('rooDatahist','rooDathist',RooArgList(mjj),hData)

        if not args.fitSignal:
            hSig = inputSig.Get( "h_" + args.final_state + "_" + str(int(mass)) )
            if not hSig:
                raise Exception("Couldn't find histogram " + "h_" + args.final_state + "_" + str(int(mass)) + " in file " + limit_config.get_resonance_shapes(args.analysis, args.model))
            # normalize signal shape to the expected event yield (works even if input shapes are not normalized to unity)
            hSig.Scale(signalCrossSection*lumi/hSig.Integral()) # divide by a number that provides roughly an r value of 1-10
            rooSigHist = RooDataHist('rooSigHist','rooSigHist',RooArgList(mjj),hSig)
            print 'Signal acceptance:', (rooSigHist.sumEntries()/hSig.Integral())

        # If using fitted signal shapes, load the signal PDF
        if args.fitSignal:
            print "[create_datacards] Loading fitted signal PDFs from " + analysis_config.get_signal_fit_file(args.analysis, args.model, mass, "bukin", interpolated=(not mass in analysis_config.simulation.simulated_masses))
            f_signal_pdfs = TFile(analysis_config.get_signal_fit_file(args.analysis, args.model, mass, "bukin", interpolated=(not mass in analysis_config.simulation.simulated_masses)), "READ")
            w_signal = f_signal_pdfs.Get("w_signal")
            input_parameters = signal_fits.get_parameters(w_signal.pdf("signal"))

            # Make a new PDF with nuisance parameters
            signal_pdf_notrig, signal_vars = signal_fits.make_signal_pdf_systematic("bukin", mjj, mass=mass)
            signal_pdf_name = signal_pdf_notrig.GetName()
            signal_pdf_notrig.SetName(signal_pdf_name + "_notrig")
            #signal_pdf = RooProdPdf(signal_pdf_name, signal_pdf_name, signal_pdf_notrig, trigger_efficiency_pdf) 
            signal_pdf = RooEffProd(signal_pdf_name, signal_pdf_name, signal_pdf_notrig, trigger_efficiency_formula)

            # Copy input parameter values
            signal_vars["xp_0"].setVal(input_parameters["xp"][0])
            signal_vars["xp_0"].setError(input_parameters["xp"][1])
            signal_vars["xp_0"].setConstant()
            signal_vars["sigp_0"].setVal(input_parameters["sigp"][0])
            signal_vars["sigp_0"].setError(input_parameters["sigp"][1])
            signal_vars["sigp_0"].setConstant()
            signal_vars["xi_0"].setVal(input_parameters["xi"][0])
            signal_vars["xi_0"].setError(input_parameters["xi"][1])
            signal_vars["xi_0"].setConstant()
            signal_vars["rho1_0"].setVal(input_parameters["rho1"][0])
            signal_vars["rho1_0"].setError(input_parameters["rho1"][1])
            signal_vars["rho1_0"].setConstant()
            signal_vars["rho2_0"].setVal(input_parameters["rho2"][0])
            signal_vars["rho2_0"].setError(input_parameters["rho2"][1])
            signal_vars["rho2_0"].setConstant()
            f_signal_pdfs.Close()

        signal_parameters = {}
        signal_pdfs_notrig = {}
        signal_pdfs = {}
        signal_norms = {}
        background_pdfs = {}
        background_pdfs_notrig = {}
        background_parameters = {}
        background_norms = {}
        signal_epdfs = {}
        background_epdfs = {}
        models = {}
        fit_results = {}

        for fit_function in fit_functions:
            print "[create_datacards] INFO : On fit function {}".format(fit_function)

            if args.fitSignal:
                # Make a copy of the signal PDF, so that each fitTo call uses its own copy.
                # The copy should have all variables set constant.  
                #signal_pdfs[fit_function], signal_parameters[fit_function] = signal_fits.copy_signal_pdf("bukin", signal_pdf, mjj, tag=fit_function, include_systematics=True)
                signal_pdfs_notrig[fit_function] = ROOT.RooBukinPdf(signal_pdf_notrig, signal_pdf_notrig.GetName() + "_" + fit_function)
                signal_pdfs[fit_function] = RooEffProd(signal_pdf.GetName() + "_" + fit_function, signal_pdf.GetName() + "_" + fit_function, signal_pdfs_notrig[fit_function], trigger_efficiency_formula) 
                #signal_pdfs[fit_function] = RooProdPdf(signal_pdf.GetName() + "_" + fit_function, signal_pdf.GetName() + "_" + fit_function, signal_pdfs_notrig[fit_function], trigger_efficiency_pdf) 
                iterator = signal_pdfs_notrig[fit_function].getVariables().createIterator()
                this_parameter = iterator.Next()
                while this_parameter:
                    this_parameter.setConstant()
                    this_parameter = iterator.Next()
            else:
                signal_pdfs[fit_function] = RooHistPdf('signal_' + fit_function,'signal_' + fit_function, RooArgSet(mjj), rooSigHist)
            signal_norms[fit_function] = RooRealVar('signal_norm_' + fit_function, 'signal_norm_' + fit_function, 0., 0., 1e+05)
            if args.fitBonly: 
                signal_norms[fit_function].setConstant()
            background_pdfs_notrig[fit_function], background_parameters[fit_function] = make_background_pdf(fit_function, mjj, collision_energy=8000.)
            background_pdf_name = background_pdfs_notrig[fit_function].GetName()
            background_pdfs_notrig[fit_function].SetName(background_pdf_name + "_notrig")
            background_pdfs[fit_function] = RooEffProd(background_pdf_name, background_pdf_name, background_pdfs_notrig[fit_function], trigger_efficiency_formula)
            #background_pdfs[fit_function] = RooProdPdf(background_pdf_name, background_pdf_name, background_pdfs_notrig[fit_function], trigger_efficiency_pdf)
            #background_pdfs[fit_function] = background_pdfs_notrig[fit_function]
            #background_pdfs[fit_function].SetName(background_pdf_name)
            
            # Initial values
            if "trigbbh" in args.analysis:
                if fit_function == "f3":
                    background_parameters[fit_function]["p1"].setVal(55.)
                    background_parameters[fit_function]["p1"].setMin(20.)
                    background_parameters[fit_function]["p2"].setVal(8.)
                elif fit_function == "f4":
                    background_parameters[fit_function]["p1"].setVal(28.)
                    background_parameters[fit_function]["p2"].setVal(-22.)
                    background_parameters[fit_function]["p3"].setVal(10.)
            elif "trigbbl" in args.analysis:
                if fit_function == "f3":
                    background_parameters[fit_function]["p1"].setVal(82.)
                    background_parameters[fit_function]["p1"].setMin(60.)
                    background_parameters[fit_function]["p2"].setVal(8.)
                elif fit_function == "f4":
                    background_parameters[fit_function]["p1"].setVal(41.)
                    background_parameters[fit_function]["p2"].setVal(-45.)
                    background_parameters[fit_function]["p3"].setVal(10.)

            data_integral = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
            background_norms[fit_function] = RooRealVar('background_' + fit_function + '_norm', 'background_' + fit_function + '_norm', data_integral, 0., 1.e8)

            signal_epdfs[fit_function] = RooExtendPdf('esignal_' + fit_function, 'esignal_' + fit_function, signal_pdfs[fit_function], signal_norms[fit_function])
            background_epdfs[fit_function] = RooExtendPdf('ebackground_' + fit_function, 'ebackground_' + fit_function, background_pdfs[fit_function], background_norms[fit_function])

            models[fit_function] = RooAddPdf('model_' + fit_function, 's+b', RooArgList(background_epdfs[fit_function], signal_epdfs[fit_function]))

            if args.runFit:
                print "[create_datacards] INFO : Starting fit with function {}".format(fit_function)
                fit_results[fit_function] = models[fit_function].fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Extended(kTRUE), RooFit.Strategy(args.fitStrategy), RooFit.Verbose(0))
                print "[create_datacards] INFO : Done with fit {}. Printing results.".format(fit_function)
                fit_results[fit_function].Print()
                print "[create_datacards] DEBUG : End args.runFit if block."

            # needed if want to evaluate limits without background systematics
            if args.fixBkg:
                background_norms[fit_function].setConstant()
                for par_name, par in background_parameters[fit_function].iteritems():
                    par.setConstant()

        # -----------------------------------------
        #signal_pdfs_syst = {}
        # JES and JER uncertainties
        if args.fitSignal:
            print "[create_datacards] INFO : Getting signal PDFs from " + analysis_config.get_signal_fit_file(args.analysis, args.model, mass, "bukin", interpolated=(not mass in analysis_config.simulation.simulated_masses))
            f_signal_pdfs = TFile(analysis_config.get_signal_fit_file(args.analysis, args.model, mass, "bukin", interpolated=(not mass in analysis_config.simulation.simulated_masses)))
            w_signal = f_signal_pdfs.Get("w_signal")
            if "jes" in systematics:
                xp_central = signal_vars["xp_0"].getVal()
                #print w_signal.pdf("signal__JESUp")
                #print signal_fits.get_parameters(w_signal.pdf("signal__JESUp"))
                xp_up = signal_fits.get_parameters(w_signal.pdf("signal__JESUp"))["xpJESUp"][0]
                xp_down = signal_fits.get_parameters(w_signal.pdf("signal__JESDown"))["xpJESDown"][0]
                signal_vars["dxp"].setVal(max(abs(xp_up - xp_central), abs(xp_down - xp_central)))
                if signal_vars["dxp"].getVal() > 2 * mass * 0.1:
                    print "[create_datacards] WARNING : Large dxp value. dxp = {}, xp_down = {}, xp_central = {}, xp_up = {}".format(signal_vars["dxp"].getVal(), xp_down, xp_central, xp_up)
                signal_vars["alpha_jes"].setVal(0.)
                signal_vars["alpha_jes"].setConstant(False)
            else:
                signal_vars["dxp"].setVal(0.)
                signal_vars["alpha_jes"].setVal(0.)
                signal_vars["alpha_jes"].setConstant()
            signal_vars["dxp"].setError(0.)
            signal_vars["dxp"].setConstant()

            if "jer" in systematics:
                sigp_central = signal_vars["sigp_0"].getVal()
                sigp_up = signal_fits.get_parameters(w_signal.pdf("signal__JERUp"))["sigpJERUp"][0]
                sigp_down = signal_fits.get_parameters(w_signal.pdf("signal__JERDown"))["sigpJERDown"][0]
                signal_vars["dsigp"].setVal(max(abs(sigp_up - sigp_central), abs(sigp_down - sigp_central)))
                signal_vars["alpha_jer"].setVal(0.)
                signal_vars["alpha_jer"].setConstant(False)
            else:
                signal_vars["dsigp"].setVal(0.)
                signal_vars["alpha_jer"].setVal(0.)
                signal_vars["alpha_jer"].setConstant()
            signal_vars["dsigp"].setError(0.)
            signal_vars["dsigp"].setConstant()
                #for variation in ["JERUp", "JERDown"]:
                #    signal_pdfs_syst[variation] = w_signal.pdf("signal__" + variation)
            #for variation, pdf in signal_pdfs_syst.iteritems():
            #    signal_parameters = pdf.getVariables()
            #    iter = signal_parameters.createIterator()
            #    var = iter.Next()
            #    while var:
            #        var.setConstant()
            #        var = iter.Next()
            f_signal_pdfs.Close()
        else:
            # dictionaries holding systematic variations of the signal shape
            hSig_Syst = {}
            hSig_Syst_DataHist = {}
            sigCDF = TGraph(hSig.GetNbinsX()+1)

            if "jes" in systematics or "jer" in systematics:

                sigCDF.SetPoint(0,0.,0.)
                integral = 0.
                for i in range(1, hSig.GetNbinsX()+1):
                    x = hSig.GetXaxis().GetBinLowEdge(i+1)
                    integral = integral + hSig.GetBinContent(i)
                    sigCDF.SetPoint(i,x,integral)

            if "jes" in systematics:
                hSig_Syst['JESUp'] = copy.deepcopy(hSig)
                hSig_Syst['JESDown'] = copy.deepcopy(hSig)

            if "jer" in systematics:
                hSig_Syst['JERUp'] = copy.deepcopy(hSig)
                hSig_Syst['JERDown'] = copy.deepcopy(hSig)

            # reset signal histograms
            for key in hSig_Syst.keys():
                hSig_Syst[key].Reset()
                hSig_Syst[key].SetName(hSig_Syst[key].GetName() + '_' + key)

            # produce JES signal shapes
            if "jes" in systematics:
                for i in range(1, hSig.GetNbinsX()+1):
                    xLow = hSig.GetXaxis().GetBinLowEdge(i)
                    xUp = hSig.GetXaxis().GetBinLowEdge(i+1)
                    jes = 1. - systematics["jes"]
                    xLowPrime = jes*xLow
                    xUpPrime = jes*xUp
                    hSig_Syst['JESUp'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                    jes = 1. + systematics["jes"]
                    xLowPrime = jes*xLow
                    xUpPrime = jes*xUp
                    hSig_Syst['JESDown'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                hSig_Syst_DataHist['JESUp'] = RooDataHist('hSig_JESUp','hSig_JESUp',RooArgList(mjj),hSig_Syst['JESUp'])
                hSig_Syst_DataHist['JESDown'] = RooDataHist('hSig_JESDown','hSig_JESDown',RooArgList(mjj),hSig_Syst['JESDown'])
            
            # produce JER signal shapes
            if "jer" in systematics:
                for i in range(1, hSig.GetNbinsX()+1):
                    xLow = hSig.GetXaxis().GetBinLowEdge(i)
                    xUp = hSig.GetXaxis().GetBinLowEdge(i+1)
                    jer = 1. - systematics["jer"]
                    xLowPrime = jer*(xLow-float(mass))+float(mass)
                    xUpPrime = jer*(xUp-float(mass))+float(mass)
                    hSig_Syst['JERUp'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                    jer = 1. + systematics["jer"]
                    xLowPrime = jer*(xLow-float(mass))+float(mass)
                    xUpPrime = jer*(xUp-float(mass))+float(mass)
                    hSig_Syst['JERDown'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                hSig_Syst_DataHist['JERUp'] = RooDataHist('hSig_JERUp','hSig_JERUp',RooArgList(mjj),hSig_Syst['JERUp'])
                hSig_Syst_DataHist['JERDown'] = RooDataHist('hSig_JERDown','hSig_JERDown',RooArgList(mjj),hSig_Syst['JERDown'])


        # -----------------------------------------
        # create a datacard and corresponding workspace
        postfix = (('_' + args.postfix) if args.postfix != '' else '')
        wsName = 'workspace_' + args.final_state + '_m' + str(mass) + postfix + '.root'

        w = RooWorkspace('w','workspace')
        if args.fitSignal:
            signal_pdf.SetName("signal")
            getattr(w,'import')(signal_pdf,RooFit.Rename("signal"))
            # Create a norm variable "signal_norm" which normalizes the PDF to unity.
            norm = args.lumi
            #signal_norm = ROOT.RooRealVar("signal_norm", "signal_norm", 1. / norm, 0.1 / norm, 10. / norm)
            #if args.analysis == "trigbbh_CSVTM" and mass >= 1100:
            signal_norm = ROOT.RooRealVar("signal_norm", "signal_norm", norm/100., norm/100. / 10., norm * 10.)
            #else:
            #    signal_norm = ROOT.RooRealVar("signal_norm", "signal_norm", norm, norm / 10., norm * 10.)
            print "[create_datacards] INFO : Set signal norm to {}".format(signal_norm.getVal())
            signal_norm.setConstant()
            getattr(w,'import')(signal_norm,ROOT.RooCmdArg())
            #if "jes" in systematics:
            #    getattr(w,'import')(signal_pdfs_syst['JESUp'],RooFit.Rename("signal__JESUp"))
            #    getattr(w,'import')(signal_pdfs_syst['JESDown'],RooFit.Rename("signal__JESDown"))
            #if "jer" in systematics:
            #    getattr(w,'import')(signal_pdfs_syst['JERUp'],RooFit.Rename("signal__JERUp"))
            #    getattr(w,'import')(signal_pdfs_syst['JERDown'],RooFit.Rename("signal__JERDown"))
        else:
            getattr(w,'import')(rooSigHist,RooFit.Rename("signal"))
            if "jes" in systematics:
                getattr(w,'import')(hSig_Syst_DataHist['JESUp'],RooFit.Rename("signal__JESUp"))
                getattr(w,'import')(hSig_Syst_DataHist['JESDown'],RooFit.Rename("signal__JESDown"))
            if "jer" in systematics:
                getattr(w,'import')(hSig_Syst_DataHist['JERUp'],RooFit.Rename("signal__JERUp"))
                getattr(w,'import')(hSig_Syst_DataHist['JERDown'],RooFit.Rename("signal__JERDown"))
        if args.decoBkg:
            getattr(w,'import')(background_deco,ROOT.RooCmdArg())
        else:
            for fit_function in fit_functions:
                print "Importing background PDF"
                print background_pdfs[fit_function]
                background_pdfs[fit_function].Print()
                getattr(w,'import')(background_pdfs[fit_function],ROOT.RooCmdArg(),RooFit.Rename("background_" + fit_function), RooFit.RecycleConflictNodes())
                w.pdf("background_" + fit_function).Print()
                getattr(w,'import')(background_norms[fit_function],ROOT.RooCmdArg(),RooFit.Rename("background_" + fit_function + "_norm"))
                getattr(w,'import')(fit_results[fit_function])
                getattr(w,'import')(signal_norms[fit_function],ROOT.RooCmdArg())
                if args.fitBonly:
                    getattr(w,'import')(models[fit_function],ROOT.RooCmdArg(),RooFit.RecycleConflictNodes())
        getattr(w,'import')(rooDataHist,RooFit.Rename("data_obs"))

        w.Print()
        print "Starting save"
        if args.output_path:
            if not os.path.isdir( os.path.join(os.getcwd(),args.output_path) ):
                os.mkdir( os.path.join(os.getcwd(),args.output_path) )
            print "[create_datacards] INFO : Writing workspace to file {}".format(os.path.join(args.output_path,wsName))
            w.writeToFile(os.path.join(args.output_path,wsName))
        else:
            print "[create_datacards] INFO : Writing workspace to file {}".format(limit_config.get_workspace_filename(args.analysis, args.model, mass, fitBonly=args.fitBonly, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger))
            w.writeToFile(limit_config.get_workspace_filename(args.analysis, args.model, mass, fitBonly=args.fitBonly, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger))

        # Clean up
        for name, obj in signal_norms.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in background_pdfs.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in background_pdfs_notrig.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in background_norms.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in signal_pdfs.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in signal_pdfs_notrig.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in signal_epdfs.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in background_epdfs.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, obj in fit_results.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        for name, dict_l2 in background_parameters.iteritems():
            for name2, obj in dict_l2.iteritems():
                if obj:
                    obj.IsA().Destructor(obj)
        for name, obj in models.iteritems():
            if obj:
                obj.IsA().Destructor(obj)
        rooDataHist.IsA().Destructor(rooDataHist)
        w.IsA().Destructor(w)

        # Make datacards only if S+B fitted
        if not args.fitBonly:
            beffUnc = 0.3
            boffUnc = 0.06
            for fit_function in fit_functions:
                if args.output_path:
                    dcName = 'datacard_' + args.final_state + '_m' + str(mass) + postfix + '_' + fit_function + '.txt'
                    print "[create_datacards] INFO : Writing datacard to file {}".format(os.path.join(args.output_path,dcName)) 
                    datacard = open(os.path.join(args.output_path,dcName),'w')
                else:
                    print "[create_datacards] INFO : Writing datacard to file {}".format(limit_config.get_datacard_filename(args.analysis, args.model, mass, fit_function, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger)) 
                    datacard = open(limit_config.get_datacard_filename(args.analysis, args.model, mass, fit_function, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger), 'w')
                datacard.write('imax 1\n')
                datacard.write('jmax 1\n')
                datacard.write('kmax *\n')
                datacard.write('---------------\n')
                if ("jes" in systematics or "jer" in systematics) and not args.fitSignal:
                    if args.output_path:
                        datacard.write('shapes * * '+wsName+' w:$PROCESS w:$PROCESS__$SYSTEMATIC\n')
                    else:
                        datacard.write('shapes * * '+os.path.basename(limit_config.get_workspace_filename(args.analysis, args.model, mass, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger))+' w:$PROCESS w:$PROCESS__$SYSTEMATIC\n')
                else:
                    if args.output_path:
                        datacard.write('shapes * * '+wsName+' w:$PROCESS\n')
                    else:
                        datacard.write('shapes * * '+os.path.basename(limit_config.get_workspace_filename(args.analysis, args.model, mass, fitSignal=args.fitSignal, correctTrigger=args.correctTrigger))+' w:$PROCESS\n')
                datacard.write('---------------\n')
                datacard.write('bin 1\n')
                datacard.write('observation -1\n')
                datacard.write('------------------------------\n')
                datacard.write('bin          1          1\n')
                datacard.write('process      signal     background_' + fit_function + '\n')
                datacard.write('process      0          1\n')
                if args.fitSignal:
                    datacard.write('rate         1         1\n')
                else:
                    datacard.write('rate         -1         1\n')
                datacard.write('------------------------------\n')
                datacard.write('lumi  lnN    %f         -\n'%(1.+systematics["luminosity"]))
                datacard.write('beff  lnN    %f         -\n'%(1.+beffUnc))
                datacard.write('boff  lnN    %f         -\n'%(1.+boffUnc))
                #datacard.write('bkg   lnN     -         1.03\n')
                if args.fitSignal:
                    if "jes" in systematics:
                        datacard.write("alpha_jes  param  0.0  1.0\n")
                    if "jer" in systematics:
                        datacard.write("alpha_jer  param  0.0  1.0\n")
                else:
                    if "jes" in systematics:
                        datacard.write('JES  shape   1          -\n')
                    if "jer" in systematics:
                        datacard.write('JER  shape   1          -\n')
                # flat parameters --- flat prior
                datacard.write('background_' + fit_function + '_norm  flatParam\n')
                if args.decoBkg:
                    datacard.write('deco_eig1  flatParam\n')
                    datacard.write('deco_eig2  flatParam\n')
                else:
                    for par_name, par in background_parameters[fit_function].iteritems():
                        datacard.write(fit_function + "_" + par_name + '  flatParam\n')
                datacard.close()
                print "[create_datacards] INFO : Done with this datacard"

    #print '>> Datacards and workspaces created and stored in %s/'%( os.path.join(os.getcwd(),args.output_path) )
    print "All done."
コード例 #42
0
def rf501_simultaneouspdf():
    signal_1, bkg_1, signal_2, bkg_2 = get_templates()
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar( "x", "x", 0, 200 ) 
    x.setBins(n_bins)
    nsig = RooRealVar( "nsig", "#signal events", N_signal_obs, 0., 2*N_data )
    nbkg = RooRealVar( "nbkg", "#background events", N_bkg1_obs, 0., 2*N_data )

    # Construct signal pdf
#     mean = RooRealVar( "mean", "mean", mu4, 40, 200 ) 
#     sigma = RooRealVar( "sigma", "sigma", sigma4, 0.1, 20 )
#     gx = RooGaussian( "gx", "gx", x, mean, sigma ) 
    roofit_signal_1 = RooDataHist( 'signal_1', 'signal_1', RooArgList(x), signal_1 )
    signal_1_pdf = RooHistPdf ( 'signal_1_pdf' , 'signal_1_pdf', RooArgSet(x), roofit_signal_1) 

    # Construct background pdf
#     mean_bkg = RooRealVar( "mean_bkg", "mean_bkg", mu3, 40, 200 ) 
#     sigma_bkg = RooRealVar( "sigma_bkg", "sigma_bkg", sigma3, 0.1, 20 ) 
#     px = RooGaussian( "px", "px", x, mean_bkg, sigma_bkg ) 
    roofit_bkg_1 = RooDataHist( 'bkg_1', 'bkg_1', RooArgList(x), bkg_1 )
    bkg_1_pdf = RooHistPdf ( 'bkg_1_pdf' , 'bkg_1_pdf', RooArgSet(x), roofit_bkg_1) 

    # Construct composite pdf
    model = RooAddPdf( "model", "model", RooArgList( signal_1_pdf, bkg_1_pdf ), RooArgList( nsig, nbkg ) ) 



    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf. 
    # NOTE that sigma is shared with the signal sample model
    y = RooRealVar( "y", "y", 0, 200 )
    y.setBins(n_bins)
    mean_ctl = RooRealVar( "mean_ctl", "mean_ctl", mu2, 0, 200 ) 
    sigma_ctl = RooRealVar( "sigma", "sigma", sigma2, 0.1, 10 ) 
    gx_ctl = RooGaussian( "gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl ) 

    # Construct the background pdf
    mean_bkg_ctl = RooRealVar( "mean_bkg_ctl", "mean_bkg_ctl", mu1, 0, 200 ) 
    sigma_bkg_ctl = RooRealVar( "sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20 ) 
    px_ctl = RooGaussian( "px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl ) 

    # Construct the composite model
#     f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. ) 
    model_ctl = RooAddPdf( "model_ctl", "model_ctl", RooArgList( gx_ctl, px_ctl ),
                           RooArgList( nsig, nbkg ) ) 
    


    # G e t   e v e n t s   f o r   b o t h   s a m p l e s 
    # ---------------------------------------------------------------
    real_data, real_data_ctl = get_data()
    real_data_hist = RooDataHist( 'real_data_hist',
                                 'real_data_hist',
                                 RooArgList( x ),
                                 real_data )
    real_data_ctl_hist = RooDataHist( 'real_data_ctl_hist',
                                     'real_data_ctl_hist',
                                     RooArgList( y ),
                                     real_data_ctl )
    input_hists = MapStrRootPtr()
    input_hists.insert( StrHist( "physics", real_data ) )
    input_hists.insert( StrHist( "control", real_data_ctl ) )

    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s 
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory( "sample", "sample" ) 
    sample.defineType( "physics" ) 
    sample.defineType( "control" ) 

    # Construct combined dataset in (x,sample)
    combData = RooDataHist( "combData", "combined data", RooArgList( x), sample ,
                           input_hists )


    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous( "simPdf", "simultaneous pdf", sample ) 

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf( model, "physics" ) 
    simPdf.addPdf( model_ctl, "control" ) 

#60093.048127    173.205689173    44.7112503776

    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------
    model.fitTo( real_data_hist,
                RooFit.Minimizer( "Minuit2", "Migrad" ),
                        RooFit.NumCPU( 1 ),
#                         RooFit.Extended(),
#                         RooFit.Save(), 
                        )
    summary = 'fit in signal region\n'
    summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
    summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n'
#     
#     model_ctl.fitTo( real_data_ctl_hist )
#     summary += 'fit in control region\n'
#     summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
#     summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' 
# 
#     # Perform simultaneous fit of model to data and model_ctl to data_ctl
#     simPdf.fitTo( combData ) 
#     summary += 'Combined fit\n'
#     summary += 'nsig: ' + str( nsig.getValV() ) + ' +- ' + str( nsig.getError() ) + '\n' 
#     summary += 'nbkg: ' + str( nbkg.getValV() ) + ' +- ' + str( nbkg.getError() ) + '\n' 


    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s 
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame( RooFit.Bins( 30 ), RooFit.Title( "Physics sample" ) ) 

    # Plot all data tagged as physics sample
    combData.plotOn( frame1, RooFit.Cut( "sample==sample::physics" ) ) 

    # Plot "physics" slice of simultaneous pdf. 
    # NBL You _must_ project the sample index category with data using ProjWData 
    # as a RooSimultaneous makes no prediction on the shape in the index category 
    # and can thus not be integrated
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ), ) 
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.Components( "signal_1_pdf" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ),
                   RooFit.LineStyle( kDashed ),
                   ) 
    simPdf.plotOn( frame1, RooFit.Slice( sample, "physics" ),
                   RooFit.Components( "bkg_1_pdf" ),
                   RooFit.ProjWData( RooArgSet( sample ), combData ),
                   RooFit.LineStyle( kDashed ),
                   RooFit.LineColor( kRed ) ) 

    # The same plot for the control sample slice
    frame2 = y.frame( RooFit.Bins( 30 ), RooFit.Title( "Control sample" ) ) 
    combData.plotOn( frame2, RooFit.Cut( "sample==sample::control" ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.ProjWData( RooArgSet( sample ), combData ) ) 
    simPdf.plotOn( frame2, RooFit.Slice( sample, "control" ),
                  RooFit.Components( "px_ctl" ),
                  RooFit.ProjWData( RooArgSet( sample ), combData ),
                  RooFit.LineStyle( kDashed ) ) 



    c = TCanvas( "rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400 ) 
    c.Divide( 2 ) 
    c.cd( 1 )
    gPad.SetLeftMargin( 0.15 )
    frame1.GetYaxis().SetTitleOffset( 1.4 )
    frame1.Draw() 
    c.cd( 2 )
    gPad.SetLeftMargin( 0.15 )
    frame2.GetYaxis().SetTitleOffset( 1.4 )
    frame2.Draw() 
    
    print summary
    print real_data.Integral()
    raw_input()
コード例 #43
0
ファイル: taggingutils.py プロジェクト: suvayu/B2DXFitters
def getMistagBinBounds(config, mistag, mistagdistrib):
    """
    suggest a binning for turning per-event mistag into mistag categories

    This routine takes a mistag observable and a PDF or data set, and suggests
    a number of mistag category boundaries which have approximately equal
    statistics in each category.

    config          -- config dictionary
    mistag          -- mistag observable (eta)
    mistagdistrib   -- a PDF or a RooDataSet

    returns a (python) list of mistag category bin bounds

    relevant configuration dictionary keys:
    'NMistagCategories':
        number of mistag categories for which to suggest a set of bin bounds
    """
    mistag.setBins(1000, 'MistagBinBounds')
    from ROOT import RooArgSet, RooHistPdf, RooDataHist
    if (mistagdistrib.InheritsFrom('RooAbsData') and not
            mistagdistrib.InheritsFrom('RooDataHist')):
        # ok, unbinned data set, get only tagged events, and form a binned clone
        argset = RooArgSet(mistag)
        mistagdistrib = mistagdistrib.reduce(
                RooFit.SelectVars(argset), RooFit.cut('0 != qt'))
        ROOT.SetOwnership(mistagdistrib, True)
        dhist = RooDataHist(
                '%s_binned' % mistagdistrib.GetName(),
                '%s_binned' % mistagdistrib.GetName(),
                mistagdistrib.get(), 'MistagBinBounds')
        dhist.add(mistagdistrib)
        mistagdistrib = dhist
    if mistagdistrib.InheritsFrom('RooAbsData'):
        # convert a binned dataset to a RooHistPdf
        dhist = mistagdistrib
        mistagdistrib = RooHistPdf('%s_pdf' % dhist.GetName(),
                '%s_pdf' % dhist.GetName(), RooArgSet(mistag), dhist)
    if (mistagdistrib.InheritsFrom('RooAbsPdf')):
        # use createCdf to obtain the CDF
        cdfroofit = mistagdistrib.createCdf(
                RooArgSet(mistag), RooArgSet(mistag))
        ROOT.SetOwnership(cdfroofit, True)
        def cdf(x):
            oldval = mistag.getVal()
            mistag.setVal(x)
            retVal = cdfroofit.getVal()
            mistag.setVal(oldval)
            return retVal
    if (mistagdistrib.InheritsFrom('RooHistPdf') and
            (abs(cdf(mistag.getMin())) > 1e-9 or
                abs(cdf(mistag.getMax()) - 1.) > 1e-9)):
        # createCdf does not work properly for RooHistPdf in older ROOT
        # versions because RooHistPdf does not support integrals over
        # subranges, so we have to fake this functionality until it's
        # supported by RooFit upstream
        #
        # capture histogram bin boundaries and contents
        print 'WARNING: Your version of RooFit still has buggy analytical ' \
                'integrals for RooHistPdf - activating workaround.'
        binboundlist = mistagdistrib.binBoundaries(
                mistag, mistag.getMin(), mistag.getMax())
        ROOT.SetOwnership(binboundlist, True)
        binbounds = [ v for v in binboundlist ]
        del binboundlist
        bincontents = [ ]
        oldval = mistag.getVal()
        for i in xrange(0, len(binbounds) - 1):
            mistag.setVal(0.5 * (binbounds[i] + binbounds[i + 1]))
            bincontents.append(mistagdistrib.getValV(RooArgSet(mistag)))
        mistag.setVal(oldval)
        # build CDF from histogram
        def cdf(x):
            s = 0.
            for i in xrange(0, len(binbounds) - 1):
                if x < binbounds[i]:
                    break
                elif x >= binbounds[i + 1]:
                    s += bincontents[i]
                else:
                    s += (bincontents[i] * (x - binbounds[i]) /
                                (binbounds[i + 1] - binbounds[i]))
                    break
            return s
    # find x for which f(x) = y by bisection
    def mybisect(y, f, lo, hi):
        initdx = abs(hi - lo)
        flo, fhi = f(lo) - y, f(hi) - y
        if 0. == flo: return lo
        elif 0. == fhi: return hi
        mid = .5 * (lo + hi)
        while (abs(hi - lo) > 1e-15 and abs(hi - lo) / initdx > 1e-15):
            fmid = f(mid) - y
            if 0. == fmid: break
            elif flo * fmid < 0.: hi, fhi = mid, fmid
            elif fmid * fhi < 0.: lo, flo = mid, fmid
            else: raise ValueError('no sign change in f(x) between %g and %g'
                    % (lo, hi))
            mid = .5 * (lo + hi)
        return mid
    # find binning with roughly same stats by inverting the CDF by bisection
    lo, hi, binsum = mistag.getMin(), mistag.getMax(), cdf(mistag.getMax())
    retVal = [ lo ]
    for i in xrange(1, config['NMistagCategories']):
        retVal.append(mybisect(binsum *
            float(i) / float(config['NMistagCategories']), cdf, lo, hi))
    retVal.append(hi)
    print 'INFO: suggested mistag category bounds: %s' % str(retVal)
    return retVal
コード例 #44
0
dspihist = dspi_data.fillHistogram(dspihist, RooArgList(time))
dskhist = dsk_data.fillHistogram(dskhist, RooArgList(time))
ratiohist.Divide(dskhist, dspihist)

# relative normalisation
fintegral = ratio.createIntegral(RooArgSet(time), 'fullrange').getVal()
hintegral = ratiohist.Integral('width') # has weights, use width
norm = fintegral / hintegral
print '=' * 5, ' Integrals ', '=' * 5
print 'Function integral / histogram integral = %g / %g = %g' % (
    fintegral, hintegral, norm)
ratiohist.Scale(norm)

# make dataset from histogram
ratiodset = RooDataHist('ratiodset', '', RooArgList(time), ratiohist)
ratiodset.Print('v')


## Plot
tframe = time.frame(RooFit.Title('Time acceptance ratio'))
paramset = RooArgSet(rturnon, roffset, rbeta)
ratio.plotOn(tframe, RooFit.VisualizeError(fitresult, paramset, 1, False))
ratio.plotOn(tframe)
ratiodset.plotOn(tframe, RooFit.MarkerStyle(kFullDotMedium))

tframe.Draw()

# Print
if doPrint:
    print 'Plotting to file: plots/DsK_ratio_%s.{png,pdf}' % timestamp
コード例 #45
0
def makePlots():
    
    histoFile = TFile('histos_'+sample+'.root')
    histos = {}
    for key in histoFile.GetListOfKeys():
        histos[key.GetName()] = histoFile.Get(key.GetName())

    outFile_name = 'plots_'+sample+'.pdf'
    c1 = TCanvas('c1', 'c1')
    c1.Print(outFile_name+'[')

    
    # Plot comparing m_Phi various method
    drawMultiPlot(outFile_name,';m_{KK [MeV]};', 'm_phi',
                  **{'m_{KK}' : histos['m_KK'],
                   'm_{#Phi}' : histos['m_Phi'],
                   'm_{#Phi} DTF #tau' : histos['m_DTFTau_Phi'],
                   'm_{#Phi} DTF #Phi' : histos['m_DTF_Phi']})

        

    # Plot comparing m_Tau various method
    drawMultiPlot(outFile_name, ';m_{KK#mu [MeV]};', 'm_tau',
                  **{'m_{KK#mu}' : histos['m_KKMu'],
                     'm_{#Phi#mu}' : histos['m_PhiMu'],
                     'm_{#tau} DTF #Phi' : histos['m_DTF_Tau']})
    
 
    # m_KPi and m_PiK
    drawMultiPlot(outFile_name, ';m_{K#pi} [MeV];', 'm_KPi',
                  **{'m_{K#pi}' : histos['m_KPi'],
                     'm_{#piK}' : histos['m_PiK']})
    
   
    # m_KKpi and m_PhiPi
    drawMultiPlot(outFile_name, ';m_{KK#pi} [MeV];', 'm_KKPi',
                  **{'m_{KK#pi}' : histos['m_KKPi'],
                     'm_{#Phi#pi}' : histos['m_PhiPi']})

    # m_KPiPi_SS and KPiPi_OS
    drawMultiPlot(outFile_name, ';m_{K#pi#pi} [MeV];', 'm_KPiPi',
                  **{'m_{K^{+}#pi^{-}#pi^{-}}' : histos['m_KPiPi_SS'],
                     'm_{K^{-}#pi^{+}#pi^{-}}' : histos['m_KPiPi_OS']})
    drawMultiPlot(outFile_name, 'not in D peak;m_{K#pi#pi} [MeV];', 'm_KPiPi_noD',
                  **{'m_{K^{+}#pi^{-}#pi^{-}}' : histos['m_KPiPi_SS_noD'],
                     'm_{K^{-}#pi^{+}#pi^{-}}' : histos['m_KPiPi_OS_noD']})
    
 
    #Plot various histos
    for key in ('m_PiPi', 'm_PiPi_noD', 'm_KPi_fromMu','m_KPi_fromMu_noD' , 'm_KKPi_D' ,'Tau_DTF_PROB', 'Tau_DTFTau_PROB'):
        histos[key].Draw()
        c1.Update()  
        c1.Print(outFile_name)
        c1.Print('plots/'+sample+'/'+key+'.pdf')

    from ROOT import RooFit, RooRealVar, RooDataHist, RooArgList

    # Fit m_DTF_Phi
    gStyle.SetOptFit(1111)
    histo = histos['m_DTF_Phi']

    x = RooRealVar('x', 'm_{#Phi}', 1008,1032,'MeV')
    ral = RooArgList(x)
    dh = RooDataHist ("dh","dh",ral,RooFit.Import(histo))
    frame = x.frame(RooFit.Title('Mass Decay Tree Fitter m_{#Phi} constrained'))
    dh.plotOn(frame)

    mean = RooRealVar("mean","mean",1020,1010,1025) 
    sigma = RooRealVar("sigma","sigma",3,0.1,10)
    alpha = RooRealVar('alpha', 'alpha', 1, 0.1, 10)
    param_n = RooRealVar('param_n','param_n', 2, 0.1, 10)
    #pdf = ROOT.RooGaussian("gauss","gauss",x,mean,sigma)
    pdf = ROOT.RooBreitWigner('BW','BW',x,mean, sigma)
    #pdf = ROOT.RooVoigtian('voit','voit', x, mean, sigma)
    #pdf = ROOT.RooCBShape('CB','CB', x, mean, sigma, alpha, param_n)

    fit_region = x.setRange("fit_region",1015,1025)
    pdf.fitTo(dh, RooFit.Range("fit_region"))
    pdf.paramOn(frame, RooFit.Layout(0.1,0.44,0.9))
    pdf.plotOn(frame)
    chi2 = round(frame.chiSquare(),2)
    leg = TLegend(0.3,0,.10,.10)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.AddEntry(0,'#chi^{2} ='+str(chi2),'')
    frame.addObject(leg)
    
    frame.Draw()
    c1.Update()  
    c1.Print(outFile_name)

    # Fit m_Kpipi
    histo = histos['m_KPiPi_SS_noD']
    x = RooRealVar('x', 'm_{K#pi#pi}', 1100,1900,'MeV')
    ral = RooArgList(x)
    dh = RooDataHist ("dh","dh",ral,RooFit.Import(histo))
    frame = x.frame(RooFit.Title('Combinatorial mass not in D- region'))
    dh.plotOn(frame)
    
    mean = RooRealVar("mean","mean",1510,1100,1900) 
    sigma = RooRealVar("sigma","sigma",107,0.1,300)
    alpha = RooRealVar('alpha', 'alpha', 1, 0.1, 10)
    param_n = RooRealVar('param_n','param_n', 2, 0.1, 10)
    #pdf = ROOT.RooGaussian("gauss","gauss",x,mean,sigma)
    pdf = ROOT.RooCBShape('CB','CB', x, mean, sigma, alpha, param_n)
   

    fit_region = x.setRange("fit_region",1100,1900)
    pdf.fitTo(dh, RooFit.Range("fit_region"))
    pdf.paramOn(frame, RooFit.Layout(0.1,0.44,0.9))
    pdf.plotOn(frame)
    chi2 = round(frame.chiSquare(),2)
    leg = TLegend(0.3,0,.10,.10)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.AddEntry(0,'#chi^{2} ='+str(chi2),'')
    frame.addObject(leg)
    frame.Draw()
    c1.Update()
    c1.Print(outFile_name)

    histo.Fit('gaus')
    histo.Draw()
    c1.Update()
    c1.Print(outFile_name)


   #  # Traditional Root way to fit
#     func = TF1('myBW', '[0]*TMath::BreitWigner(x,[1],[2])', 1010,1025)
# #    func = TF1('myfunc', '[0]*TMath::Gaus(x,[1],[2])', 1010,1025)
#     func = TF1('myfunc', '[0]*TMath::Voigt(x-[1],[2],[3])', 1010,1025)
#     func.SetParameter(0,1048)
#     func.SetParName(0,'Norm')
#     func.SetParameter(1,1020)
#     func.SetParName(1,'mean')
#     func.SetParameter(2,4)
#     func.SetParName(2,'gamma')

#     func = TF1('myfunc', '[0]*TMath::Voigt(x-[1],[2],[3])', 1010,1025)
#     func.SetParameter(0,1048)
#     func.SetParName(0,'Norm')
#     func.SetParameter(1,1020)
#     func.SetParName(1,'mean')
#     func.SetParameter(2,4)
#     func.SetParName(2,'sigma')
#     func.SetParameter(3,4)
#     func.SetParName(2,'gamma')
    
#     histo.Fit('myfunc')
#     #histo.Fit('gaus')
#     histo.Draw()
#     c1.Update()  
#     c1.Print(outFile_name)
 

    c1.Print(outFile_name+']')
コード例 #46
0
ファイル: sidebands.py プロジェクト: AdrianoDee/X4140

# In[8]:


cheb = RooChebychev("cheb","Background",mass,aset)
gauss = RooGaussian("gauss","gaussian PDF ",mass,mean,sigma)

tot = RooAddPdf("tot","g+cheb",gauss,cheb,sFrac)


# In[9]:


masslist = RooArgList(mass)
dh = RooDataHist("dh","dh",masslist,hist)
numEvts = dh.sum(False)
print numEvts


# In[10]:


tot.fitTo(dh)


# In[11]:


massFrame = mass.frame()
massFrame.SetTitle("Phi signal")
コード例 #47
0
ファイル: makePlot3.py プロジェクト: YoungKwonJo/CMSDAS
k2=RooRealVar("k2","normalization factor", 1.0, 0.5, 1.5) 
k1 =RooRealVar("k1","k1",rttbar,0.,0.5);
#k2 =RooRealVar("k2","k2",rQCD,0.0,0.2);

nttbar =RooRealVar("nttbar","number of ttbar events", n_ttbar , n_ttbar, n_ttbar)
k1nttbar=RooFormulaVar("k1nttbar","number of ttbar events after fitting","k*nttbar",RooArgList(k1,nttbar) )

n_mc = n_ttbar+n_background
nmc = RooRealVar("nmc","number of mc events", n_mc , n_mc, n_mc)
k2nmc = RooFormulaVar("k2nmc","number of mc events"," ",RooArgList(k2,nmc))
#RooRealVar    nbackground("nbackground","number of background events", n_background , n_background, n_background);
#RooFormulaVar k2background("k2background","number of background events after fitting","k2*nbackground",RooArgList(k2,nbackground) );
nqcd = RooRealVar("nqcd","number of qcd events", n_qcd , n_qcd, n_qcd)
#k2nqcd = RooFormulaVar("k2nqcd","number of qcd events"," ",RooArgList(k2,nqcd))

data       = RooDataHist("data",      "data set with (x)", RooArgList(x), h_data_m3HistS)
ttbar      = RooDataHist("ttbar",     "data set with (x)", RooArgList(x), h_ttbar_m3HistS)
background = RooDataHist("background","data set with (x)", RooArgList(x), h_background_m3Hist)

qcd        = RooDataHist("qcd",      "data set with (x)", RooArgList(x), h_qcd_data_m3HistS)
# RooHistPdf::RooHistPdf(const char* name, const char* title, const RooArgSet& vars, const RooDataHist& dhist, int intOrder = 0) =>
#print "ttbar type: "+str(type(ttbar))
#print "rooArglist(x):"+str(type(RooArgList(x)))

ttbarpdf      = RooHistPdf("ttbarpdf",     "ttbarpdf",      RooArgList(x), RooArgList(x), ttbar)
backgroundpdf = RooHistPdf("backgroundpdf","backgroundpdf", RooArgList(x), RooArgList(x), background)
qcdpdf        = RooHistPdf("qcdpdf",       "qcdpdf",        RooArgList(x), RooArgList(x), qcd)

#ttbarpdf      = RooHistPdf(ttbar,"ttbarpdf")
#backgroundpdf = RooHistPdf(background,"backgroundpdf")
コード例 #48
0
def main():
    # usage description
    usage = "Example: ./scripts/createDatacards.py --inputData inputs/rawhistV7_Run2015D_scoutingPFHT_UNBLINDED_649_838_JEC_HLTplusV7_Mjj_cor_smooth.root --dataHistname mjj_mjjcor_gev --inputSig inputs/ResonanceShapes_gg_13TeV_Scouting_Spring15.root -f gg -o datacards -l 1866 --lumiUnc 0.027 --massrange 1000 1500 50 --runFit --p1 5 --p2 7 --p3 0.4 --massMin 838 --massMax 2037 --fitStrategy 2"

    # input parameters
    parser = ArgumentParser(description='Script that creates combine datacards and corresponding RooFit workspaces',epilog=usage)

    parser.add_argument("--inputData", dest="inputData", required=True,
                        help="Input data spectrum",
                        metavar="INPUT_DATA")

    parser.add_argument("--dataHistname", dest="dataHistname", required=True,
                        help="Data histogram name",
                        metavar="DATA_HISTNAME")

    parser.add_argument("--inputSig", dest="inputSig", required=True,
                        help="Input signal shapes",
                        metavar="INPUT_SIGNAL")

    parser.add_argument("-f", "--final_state", dest="final_state", required=True,
                        help="Final state (e.g. qq, qg, gg)",
                        metavar="FINAL_STATE")

    parser.add_argument("-f2", "--type", dest="atype", required=True, help="Type (e.g. hG, lG, hR, lR)")

    parser.add_argument("-o", "--output_path", dest="output_path", required=True,
                        help="Output path where datacards and workspaces will be stored",
                        metavar="OUTPUT_PATH")

    parser.add_argument("-l", "--lumi", dest="lumi", required=True,
                        default=1000., type=float,
                        help="Integrated luminosity in pb-1 (default: %(default).1f)",
                        metavar="LUMI")

    parser.add_argument("--massMin", dest="massMin",
                        default=500, type=int,
                        help="Lower bound of the mass range used for fitting (default: %(default)s)",
                        metavar="MASS_MIN")

    parser.add_argument("--massMax", dest="massMax",
                        default=1200, type=int,
                        help="Upper bound of the mass range used for fitting (default: %(default)s)",
                        metavar="MASS_MAX")

    parser.add_argument("--p1", dest="p1",
                        default=5.0000e-03, type=float,
                        help="Fit function p1 parameter (default: %(default)e)",
                        metavar="P1")

    parser.add_argument("--p2", dest="p2",
                        default=9.1000e+00, type=float,
                        help="Fit function p2 parameter (default: %(default)e)",
                        metavar="P2")

    parser.add_argument("--p3", dest="p3",
                        default=5.0000e-01, type=float,
                        help="Fit function p3 parameter (default: %(default)e)",
                        metavar="P3")

    parser.add_argument("--lumiUnc", dest="lumiUnc",
                        required=True, type=float,
                        help="Relative uncertainty in the integrated luminosity",
                        metavar="LUMI_UNC")

    parser.add_argument("--jesUnc", dest="jesUnc",
                        type=float,
                        help="Relative uncertainty in the jet energy scale",
                        metavar="JES_UNC")

    parser.add_argument("--jerUnc", dest="jerUnc",
                        type=float,
                        help="Relative uncertainty in the jet energy resolution",
                        metavar="JER_UNC")

    parser.add_argument("--sqrtS", dest="sqrtS",
                        default=13000., type=float,
                        help="Collision center-of-mass energy (default: %(default).1f)",
                        metavar="SQRTS")

    parser.add_argument("--fixP3", dest="fixP3", default=False, action="store_true", help="Fix the fit function p3 parameter")

    parser.add_argument("--runFit", dest="runFit", default=False, action="store_true", help="Run the fit")

    parser.add_argument("--fitBonly", dest="fitBonly", default=False, action="store_true", help="Run B-only fit")

    parser.add_argument("--fixBkg", dest="fixBkg", default=False, action="store_true", help="Fix all background parameters")

    parser.add_argument("--decoBkg", dest="decoBkg", default=False, action="store_true", help="Decorrelate background parameters")

    parser.add_argument("--fitStrategy", dest="fitStrategy", type=int, default=1, help="Fit strategy (default: %(default).1f)")

    parser.add_argument("--debug", dest="debug", default=False, action="store_true", help="Debug printout")

    parser.add_argument("--postfix", dest="postfix", default='', help="Postfix for the output file names (default: %(default)s)")

    parser.add_argument("--pyes", dest="pyes", default=False, action="store_true", help="Make files for plots")

    parser.add_argument("--jyes", dest="jyes", default=False, action="store_true", help="Make files for JES/JER plots")

    parser.add_argument("--pdir", dest="pdir", default='testarea', help="Name a directory for the plots (default: %(default)s)")

    parser.add_argument("--chi2", dest="chi2", default=False, action="store_true", help="Compute chi squared")

    parser.add_argument("--widefit", dest="widefit", default=False, action="store_true", help="Fit with wide bin hist")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument("--mass",
                            type=int,
                            nargs = '*',
                            default = 1000,
                            help="Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
                            )
    mass_group.add_argument("--massrange",
                            type=int,
                            nargs = 3,
                            help="Define a range of masses to be produced. Format: min max step",
                            metavar = ('MIN', 'MAX', 'STEP')
                            )
    mass_group.add_argument("--masslist",
                            help = "List containing mass information"
                            )

    args = parser.parse_args()

    if args.atype == 'hG':
	fstr = "bbhGGBB"
	in2 = 'bcorrbin/binmodh.root'
    elif args.atype == 'hR':
	fstr = "bbhRS"
	in2 = 'bcorrbin/binmodh.root'
    elif args.atype == 'lG':
	fstr = "bblGGBB"
	in2 = 'bcorrbin/binmodl.root'
    else:
	fstr = "bblRS"
	in2 = 'bcorrbin/binmodl.root'

    # check if the output directory exists
    if not os.path.isdir( os.path.join(os.getcwd(),args.output_path) ):
        os.mkdir( os.path.join(os.getcwd(),args.output_path) )

    # mass points for which resonance shapes will be produced
    masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        masses = range(MIN, MAX+STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print  "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py",""))
        masses = masslist.masses
    else:
        masses = args.mass

    # sort masses
    masses.sort()

    # import ROOT stuff
    from ROOT import gStyle, TFile, TH1F, TH1D, TGraph, kTRUE, kFALSE, TCanvas, TLegend, TPad, TLine
    from ROOT import RooHist, RooRealVar, RooDataHist, RooArgList, RooArgSet, RooAddPdf, RooFit, RooGenericPdf, RooWorkspace, RooMsgService, RooHistPdf

    if not args.debug:
        RooMsgService.instance().setSilentMode(kTRUE)
        RooMsgService.instance().setStreamStatus(0,kFALSE)
        RooMsgService.instance().setStreamStatus(1,kFALSE)

    # input data file
    inputData = TFile(args.inputData)
    # input data histogram
    hData = inputData.Get(args.dataHistname)

    inData2 = TFile(in2)
    hData2 = inData2.Get('h_data')

    # input sig file
    inputSig = TFile(args.inputSig)

    sqrtS = args.sqrtS

    # mass variable
    mjj = RooRealVar('mjj','mjj',float(args.massMin),float(args.massMax))

    # integrated luminosity and signal cross section
    lumi = args.lumi
    signalCrossSection = 1. # set to 1. so that the limit on r can be interpreted as a limit on the signal cross section

    for mass in masses:

        print ">> Creating datacard and workspace for %s resonance with m = %i GeV..."%(args.final_state, int(mass))

        # get signal shape
        hSig = inputSig.Get( "h_" + args.final_state + "_" + str(int(mass)) )
        # normalize signal shape to the expected event yield (works even if input shapes are not normalized to unity)
        hSig.Scale(signalCrossSection*lumi/hSig.Integral()) # divide by a number that provides roughly an r value of 1-10
        rooSigHist = RooDataHist('rooSigHist','rooSigHist',RooArgList(mjj),hSig)
        print 'Signal acceptance:', (rooSigHist.sumEntries()/hSig.Integral())
        signal = RooHistPdf('signal','signal',RooArgSet(mjj),rooSigHist)
        signal_norm = RooRealVar('signal_norm','signal_norm',0,-1e+05,1e+05)
        if args.fitBonly: signal_norm.setConstant()

        p1 = RooRealVar('p1','p1',args.p1,0.,100.)
        p2 = RooRealVar('p2','p2',args.p2,0.,60.)
        p3 = RooRealVar('p3','p3',args.p3,-10.,10.)
	p4 = RooRealVar('p4','p4',5.6,-50.,50.)
	p5 = RooRealVar('p5','p5',10.,-50.,50.)
	p6 = RooRealVar('p6','p6',.016,-50.,50.)
	p7 = RooRealVar('p7','p7',8.,-50.,50.)
	p8 = RooRealVar('p8','p8',.22,-50.,50.)
	p9 = RooRealVar('p9','p9',14.1,-50.,50.)
	p10 = RooRealVar('p10','p10',8.,-50.,50.)
	p11 = RooRealVar('p11','p11',4.8,-50.,50.)
	p12 = RooRealVar('p12','p12',7.,-50.,50.)
	p13 = RooRealVar('p13','p13',7.,-50.,50.)
	p14 = RooRealVar('p14','p14',7.,-50.,50.)
	p15 = RooRealVar('p15','p15',1.,-50.,50.)
	p16 = RooRealVar('p16','p16',9.,-50.,50.)
	p17 = RooRealVar('p17','p17',0.6,-50.,50.)

        if args.fixP3: p3.setConstant()

        background = RooGenericPdf('background','(pow(1-@0/%.1f,@1)/pow(@0/%.1f,@2+@3*log(@0/%.1f)))'%(sqrtS,sqrtS,sqrtS),RooArgList(mjj,p1,p2,p3))
        dataInt = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm = RooRealVar('background_norm','background_norm',dataInt,0.,1e+08)

	background2 = RooGenericPdf('background2','(pow(@0/%.1f,-@1)*pow(1-@0/%.1f,@2))'%(sqrtS,sqrtS),RooArgList(mjj,p4,p5))
        dataInt2 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm2 = RooRealVar('background_norm2','background_norm2',dataInt2,0.,1e+08)

	background3 = RooGenericPdf('background3','(1/pow(@1+@0/%.1f,@2))'%(sqrtS),RooArgList(mjj,p6,p7))
        dataInt3 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm3 = RooRealVar('background_norm3','background_norm3',dataInt3,0.,1e+08)

	background4 = RooGenericPdf('background4','(1/pow(@1+@2*@0/%.1f+pow(@0/%.1f,2),@3))'%(sqrtS,sqrtS),RooArgList(mjj,p8,p9,p10))
        dataInt4 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm4 = RooRealVar('background_norm4','background_norm4',dataInt4,0.,1e+08)

	background5 = RooGenericPdf('background5','(pow(@0/%.1f,-@1)*pow(1-pow(@0/%.1f,1/3),@2))'%(sqrtS,sqrtS),RooArgList(mjj,p11,p12))
        dataInt5 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm5 = RooRealVar('background_norm5','background_norm5',dataInt5,0.,1e+08)

	background6 = RooGenericPdf('background6','(pow(@0/%.1f,2)+@1*@0/%.1f+@2)'%(sqrtS,sqrtS),RooArgList(mjj,p13,p14))
        dataInt6 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm6 = RooRealVar('background_norm6','background_norm6',dataInt6,0.,1e+08)

	background7 = RooGenericPdf('background7','((-1+@1*@0/%.1f)*pow(@0/%.1f,@2+@3*log(@0/%.1f)))'%(sqrtS,sqrtS,sqrtS),RooArgList(mjj,p15,p16,p17))
        dataInt7 = hData.Integral(hData.GetXaxis().FindBin(float(args.massMin)),hData.GetXaxis().FindBin(float(args.massMax)))
        background_norm7 = RooRealVar('background_norm7','background_norm7',dataInt7,0.,1e+08)

        # S+B model
        model = RooAddPdf("model","s+b",RooArgList(background,signal),RooArgList(background_norm,signal_norm))
	model2 = RooAddPdf("model2","s+b2",RooArgList(background2,signal),RooArgList(background_norm2,signal_norm))
	model3 = RooAddPdf("model3","s+b3",RooArgList(background3,signal),RooArgList(background_norm3,signal_norm))
	model4 = RooAddPdf("model4","s+b4",RooArgList(background4,signal),RooArgList(background_norm4,signal_norm))
	model5 = RooAddPdf("model5","s+b5",RooArgList(background5,signal),RooArgList(background_norm5,signal_norm))
	model6 = RooAddPdf("model6","s+b6",RooArgList(background6,signal),RooArgList(background_norm6,signal_norm))
	model7 = RooAddPdf("model7","s+b7",RooArgList(background7,signal),RooArgList(background_norm7,signal_norm))

        rooDataHist = RooDataHist('rooDatahist','rooDathist',RooArgList(mjj),hData)


        if args.runFit:
	    mframe = mjj.frame()
	    rooDataHist.plotOn(mframe, ROOT.RooFit.Name("setonedata"), ROOT.RooFit.Invisible())
	    res = model.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
	    model.plotOn(mframe, ROOT.RooFit.Name("model1"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kRed)) 
	    res2 = model2.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            model2.plotOn(mframe, ROOT.RooFit.Name("model2"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kOrange))
	    res3 = model3.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            model3.plotOn(mframe, ROOT.RooFit.Name("model3"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kGreen))
	    res4 = model4.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            model4.plotOn(mframe, ROOT.RooFit.Name("model4"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kBlue))
	    res5 = model5.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            model5.plotOn(mframe, ROOT.RooFit.Name("model5"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kViolet))
	    res6 = model6.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
#           model6.plotOn(mframe, ROOT.RooFit.Name("model6"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kPink))
	    res7 = model7.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
#           model7.plotOn(mframe, ROOT.RooFit.Name("model7"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kAzure))

	    rooDataHist2 = RooDataHist('rooDatahist2','rooDathist2',RooArgList(mjj),hData2)
	    rooDataHist2.plotOn(mframe, ROOT.RooFit.Name("data"))

	    canvas = TCanvas("cdouble", "cdouble", 800, 1000)

	    gStyle.SetOptStat(0);
            gStyle.SetOptTitle(0);
	    top = TPad("top", "top", 0., 0.5, 1., 1.)
	    top.SetBottomMargin(0.03)
	    top.Draw()
	    top.SetLogy()
            bottom = TPad("bottom", "bottom", 0., 0., 1., 0.5)
	    bottom.SetTopMargin(0.02)
	    bottom.SetBottomMargin(0.2)
	    bottom.Draw()

	    top.cd()
	    frame_top = TH1D("frame_top", "frame_top", 100, 526, 1500)
	    frame_top.GetXaxis().SetTitleSize(0)
	    frame_top.GetXaxis().SetLabelSize(0)
	    frame_top.GetYaxis().SetLabelSize(0.04)
            frame_top.GetYaxis().SetTitleSize(0.04)
            frame_top.GetYaxis().SetTitle("Events")
	    frame_top.SetMaximum(1000.)
	    frame_top.SetMinimum(0.1)
	    frame_top.Draw("axis")
            mframe.Draw("p e1 same")

            bottom.cd()
	    frame_bottom = TH1D("frame_bottom", "frame_bottom", 100, 526, 1500)
            frame_bottom.GetXaxis().SetTitle("m_{jj} [GeV]")
	    frame_bottom.GetYaxis().SetTitle("Pull")

  	    frame_bottom.GetXaxis().SetLabelSize(0.04)
	    frame_bottom.GetXaxis().SetTitleSize(0.06)
	    frame_bottom.GetXaxis().SetLabelOffset(0.01)
	    frame_bottom.GetXaxis().SetTitleOffset(1.1)

	    frame_bottom.GetYaxis().SetLabelSize(0.04)
	    frame_bottom.GetYaxis().SetTitleSize(0.04)
	    frame_bottom.GetYaxis().SetTitleOffset(0.85)

	    frame_bottom.SetMaximum(4.)
            frame_bottom.SetMinimum(-3.)

	    frame_bottom.Draw("axis")

	    zero = TLine(526., 0., 1500., 0.)
	    zero.SetLineColor(ROOT.EColor.kBlack)
	    zero.SetLineStyle(1)
	    zero.SetLineWidth(2)
	    zero.Draw("same")

	    # Ratio histogram with no errors (not so well defined, since this isn't a well-defined efficiency)
	    newHist = mframe.getHist("data")
	    curve = mframe.getObject(1)
	    hresid = newHist.makePullHist(curve,kTRUE)
	    resframe = mjj.frame()
	    mframe.SetAxisRange(526.,1500.)
	    resframe.addPlotable(hresid,"B X")
	    resframe.Draw("same")
	    canvas.cd()
	    canvas.SaveAs("testdouble.pdf")
		

	    if args.pyes:
	    	c = TCanvas("c","c",800,800)
		mframe.SetAxisRange(300.,1300.)
	    	c.SetLogy()
#	    	mframe.SetMaximum(10)
#	    	mframe.SetMinimum(1)
	    	mframe.Draw()
	    	fitname = args.pdir+'/5funcfit_m'+str(mass)+fstr+'.pdf'
	    	c.SaveAs(fitname)

	        cpull = TCanvas("cpull","cpull",800,800)
	    	pulls = mframe.pullHist("data","model3")
	    	pulls.Draw("ABX")
	   	pullname = args.pdir+'/pull_m'+str(mass)+fstr+'.pdf'
	    	cpull.SaveAs(pullname)

		cpull2 = TCanvas("cpull2","cpull2",800,800)
                pulls2 = mframe.pullHist("setonedata","model1")
                pulls2.Draw("ABX")
                pull2name = args.pdir+'/pull2_m'+str(mass)+fstr+'.pdf'
                cpull2.SaveAs(pull2name)

	    if args.widefit:	
		mframew = mjj.frame()
    	        rooDataHist2.plotOn(mframew, ROOT.RooFit.Name("data"))
                res6 = model.fitTo(rooDataHist2, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            	model.plotOn(mframew, ROOT.RooFit.Name("model1"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kRed))
            	res7 = model2.fitTo(rooDataHist2, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            	model2.plotOn(mframew, ROOT.RooFit.Name("model2"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kOrange))
            	res8 = model3.fitTo(rooDataHist2, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            	model3.plotOn(mframew, ROOT.RooFit.Name("model3"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kGreen))
            	res9 = model4.fitTo(rooDataHist2, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            	model4.plotOn(mframew, ROOT.RooFit.Name("model4"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kBlue))
            	res10 = model5.fitTo(rooDataHist2, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
            	model5.plotOn(mframew, ROOT.RooFit.Name("model5"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.LineWidth(1), ROOT.RooFit.LineColor(ROOT.EColor.kViolet))

                if args.pyes:
                    c = TCanvas("c","c",800,800)
                    mframew.SetAxisRange(300.,1300.)
                    c.SetLogy()
#                   mframew.SetMaximum(10)
#                   mframew.SetMinimum(1)
                    mframew.Draw()
                    fitname = args.pdir+'/5funcfittowide_m'+str(mass)+fstr+'.pdf'
		    c.SaveAs(fitname)

                    cpull = TCanvas("cpull","cpull",800,800)
                    pulls = mframew.pullHist("data","model1")
                    pulls.Draw("ABX")
                    pullname = args.pdir+'/pullwidefit_m'+str(mass)+fstr+'.pdf'
                    cpull.SaveAs(pullname)


	    if args.chi2:
		    fullInt = model.createIntegral(RooArgSet(mjj))
		    norm = dataInt/fullInt.getVal()
		    chi1 = 0.
		    fullInt2 = model2.createIntegral(RooArgSet(mjj))
        	    norm2 = dataInt2/fullInt2.getVal()
	      	    chi2 = 0.
		    fullInt3 = model3.createIntegral(RooArgSet(mjj))
       		    norm3 = dataInt3/fullInt3.getVal()
	            chi3 = 0.
		    fullInt4 = model4.createIntegral(RooArgSet(mjj))
       		    norm4 = dataInt4/fullInt4.getVal()
         	    chi4 = 0.
		    fullInt5 = model5.createIntegral(RooArgSet(mjj))
	            norm5 = dataInt5/fullInt5.getVal()
     	            chi5 = 0.
		    for i in range(args.massMin, args.massMax):
        	        new = 0
			new2 = 0
			new3 = 0
			new4 = 0
			new5 = 0
			height = hData.GetBinContent(i)
	        	xLow = hData.GetXaxis().GetBinLowEdge(i)
			xUp = hData.GetXaxis().GetBinLowEdge(i+1)
			obs = height*(xUp-xLow)
			mjj.setRange("intrange",xLow,xUp)
			integ = model.createIntegral(RooArgSet(mjj),ROOT.RooFit.NormSet(RooArgSet(mjj)),ROOT.RooFit.Range("intrange"))
			exp = integ.getVal()*norm
			new = pow(exp-obs,2)/exp
                	chi1 = chi1 + new
			integ2 = model2.createIntegral(RooArgSet(mjj),ROOT.RooFit.NormSet(RooArgSet(mjj)),ROOT.RooFit.Range("intrange"))
                	exp2 = integ2.getVal()*norm2
                	new2 = pow(exp2-obs,2)/exp2
                	chi2 = chi2 + new2
			integ3 = model3.createIntegral(RooArgSet(mjj),ROOT.RooFit.NormSet(RooArgSet(mjj)),ROOT.RooFit.Range("intrange"))
                	exp3 = integ3.getVal()*norm3
                	new3 = pow(exp3-obs,2)/exp3
                	chi3 = chi3 + new3
			integ4 = model4.createIntegral(RooArgSet(mjj),ROOT.RooFit.NormSet(RooArgSet(mjj)),ROOT.RooFit.Range("intrange"))
                	exp4 = integ4.getVal()*norm4
			if exp4 != 0:
                	    new4 = pow(exp4-obs,2)/exp4
                	else:
			    new4 = 0
			chi4 = chi4 + new4
			integ5 = model5.createIntegral(RooArgSet(mjj),ROOT.RooFit.NormSet(RooArgSet(mjj)),ROOT.RooFit.Range("intrange"))
                	exp5 = integ5.getVal()*norm5
                	new5 = pow(exp5-obs,2)/exp5
                	chi5 = chi5 + new5
	    	    print "chi1 %d "%(chi1)
	    	    print "chi2 %d "%(chi2)
	    	    print "chi3 %d "%(chi3)
	    	    print "chi4 %d "%(chi4)
	    	    print "chi5 %d "%(chi5)

	    if not args.decoBkg: 
		print " "
		res.Print()
#	        res2.Print()
#		res3.Print()
#		res4.Print()
#		res5.Print()
#		res6.Print()
#		res7.Print()

            # decorrelated background parameters for Bayesian limits
            if args.decoBkg:
                signal_norm.setConstant()
                res = model.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy))
                res.Print()
                ## temp workspace for the PDF diagonalizer
                w_tmp = RooWorkspace("w_tmp")
                deco = PdfDiagonalizer("deco",w_tmp,res)
                # here diagonalizing only the shape parameters since the overall normalization is already decorrelated
                background_deco = deco.diagonalize(background)
                print "##################### workspace for decorrelation"
                w_tmp.Print("v")
                print "##################### original parameters"
                background.getParameters(rooDataHist).Print("v")
                print "##################### decorrelated parameters"
                # needed if want to evaluate limits without background systematics
                if args.fixBkg:
                    w_tmp.var("deco_eig1").setConstant()
                    w_tmp.var("deco_eig2").setConstant()
                    if not args.fixP3: w_tmp.var("deco_eig3").setConstant()
                background_deco.getParameters(rooDataHist).Print("v")
                print "##################### original pdf"
                background.Print()
                print "##################### decorrelated pdf"
                background_deco.Print()
                # release signal normalization
                signal_norm.setConstant(kFALSE)
                # set the background normalization range to +/- 5 sigma
                bkg_val = background_norm.getVal()
                bkg_error = background_norm.getError()
                background_norm.setMin(bkg_val-5*bkg_error)
                background_norm.setMax(bkg_val+5*bkg_error)
                background_norm.Print()
                # change background PDF names
                background.SetName("background_old")
                background_deco.SetName("background")

        # needed if want to evaluate limits without background systematics
        if args.fixBkg:
            background_norm.setConstant()
            p1.setConstant()
            p2.setConstant()
            p3.setConstant()

        # -----------------------------------------
        # dictionaries holding systematic variations of the signal shape
        hSig_Syst = {}
        hSig_Syst_DataHist = {}
        sigCDF = TGraph(hSig.GetNbinsX()+1)

        # JES and JER uncertainties
        if args.jesUnc != None or args.jerUnc != None:

            sigCDF.SetPoint(0,0.,0.)
            integral = 0.
            for i in range(1, hSig.GetNbinsX()+1):
                x = hSig.GetXaxis().GetBinLowEdge(i+1)
                integral = integral + hSig.GetBinContent(i)
                sigCDF.SetPoint(i,x,integral)

        if args.jesUnc != None:
            hSig_Syst['JESUp'] = copy.deepcopy(hSig)
            hSig_Syst['JESDown'] = copy.deepcopy(hSig)

        if args.jerUnc != None:
            hSig_Syst['JERUp'] = copy.deepcopy(hSig)
            hSig_Syst['JERDown'] = copy.deepcopy(hSig)

        # reset signal histograms
        for key in hSig_Syst.keys():
            hSig_Syst[key].Reset()
            hSig_Syst[key].SetName(hSig_Syst[key].GetName() + '_' + key)

        # produce JES signal shapes
        if args.jesUnc != None:
            for i in range(1, hSig.GetNbinsX()+1):
                xLow = hSig.GetXaxis().GetBinLowEdge(i)
                xUp = hSig.GetXaxis().GetBinLowEdge(i+1)
                jes = 1. - args.jesUnc
                xLowPrime = jes*xLow
                xUpPrime = jes*xUp
                hSig_Syst['JESUp'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                jes = 1. + args.jesUnc
                xLowPrime = jes*xLow
                xUpPrime = jes*xUp
                hSig_Syst['JESDown'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
            hSig_Syst_DataHist['JESUp'] = RooDataHist('hSig_JESUp','hSig_JESUp',RooArgList(mjj),hSig_Syst['JESUp'])
            hSig_Syst_DataHist['JESDown'] = RooDataHist('hSig_JESDown','hSig_JESDown',RooArgList(mjj),hSig_Syst['JESDown'])
	    
	    if args.jyes:
		c2 = TCanvas("c2","c2",800,800)
	    	mframe2 = mjj.frame(ROOT.RooFit.Title("JES One Sigma Shifts"))
	    	mframe2.SetAxisRange(525.,1200.)
		hSig_Syst_DataHist['JESUp'].plotOn(mframe2, ROOT.RooFit.Name("JESUP"),ROOT.RooFit.DrawOption("L"), ROOT.RooFit.DataError(2), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kRed), ROOT.RooFit.LineColor(ROOT.EColor.kRed))
	    	hSig_Syst_DataHist['JESDown'].plotOn(mframe2,ROOT.RooFit.Name("JESDOWN"),ROOT.RooFit.DrawOption("L"), ROOT.RooFit.DataError(2), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kBlue), ROOT.RooFit.LineColor(ROOT.EColor.kBlue))
	    	rooSigHist.plotOn(mframe2, ROOT.RooFit.DataError(2),ROOT.RooFit.Name("SIG"),ROOT.RooFit.DrawOption("L"), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kGreen), ROOT.RooFit.LineColor(ROOT.EColor.kGreen))
	    	mframe2.Draw()
		mframe2.GetXaxis().SetTitle("Dijet Mass (GeV)")
		leg = TLegend(0.7,0.8,0.9,0.9)
		leg.AddEntry(mframe2.findObject("SIG"),"Signal Model","l")
		leg.AddEntry(mframe2.findObject("JESUP"),"+1 Sigma","l")
		leg.AddEntry(mframe2.findObject("JESDOWN"),"-1 Sigma","l")
		leg.Draw()
	    	jesname = args.pdir+'/jes_m'+str(mass)+fstr+'.pdf'
	    	c2.SaveAs(jesname)

        # produce JER signal shapes
        if args.jesUnc != None:
            for i in range(1, hSig.GetNbinsX()+1):
                xLow = hSig.GetXaxis().GetBinLowEdge(i)
                xUp = hSig.GetXaxis().GetBinLowEdge(i+1)
                jer = 1. - args.jerUnc
                xLowPrime = jer*(xLow-float(mass))+float(mass)
                xUpPrime = jer*(xUp-float(mass))+float(mass)
                hSig_Syst['JERUp'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
                jer = 1. + args.jerUnc
                xLowPrime = jer*(xLow-float(mass))+float(mass)
                xUpPrime = jer*(xUp-float(mass))+float(mass)
                hSig_Syst['JERDown'].SetBinContent(i, sigCDF.Eval(xUpPrime) - sigCDF.Eval(xLowPrime))
            hSig_Syst_DataHist['JERUp'] = RooDataHist('hSig_JERUp','hSig_JERUp',RooArgList(mjj),hSig_Syst['JERUp'])
            hSig_Syst_DataHist['JERDown'] = RooDataHist('hSig_JERDown','hSig_JERDown',RooArgList(mjj),hSig_Syst['JERDown'])

	    if args.jyes:
	    	c3 = TCanvas("c3","c3",800,800)
            	mframe3 = mjj.frame(ROOT.RooFit.Title("JER One Sigma Shifts"))
	    	mframe3.SetAxisRange(525.,1200.)
		hSig_Syst_DataHist['JERUp'].plotOn(mframe3,ROOT.RooFit.Name("JERUP"),ROOT.RooFit.DrawOption("L"), ROOT.RooFit.DataError(2), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kRed), ROOT.RooFit.LineColor(ROOT.EColor.kRed))
            	hSig_Syst_DataHist['JERDown'].plotOn(mframe3,ROOT.RooFit.Name("JERDOWN"),ROOT.RooFit.DrawOption("L"), ROOT.RooFit.DataError(2), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kBlue), ROOT.RooFit.LineColor(ROOT.EColor.kBlue))
            	rooSigHist.plotOn(mframe3,ROOT.RooFit.DrawOption("L"),ROOT.RooFit.Name("SIG"), ROOT.RooFit.DataError(2), ROOT.RooFit.LineStyle(1), ROOT.RooFit.MarkerColor(ROOT.EColor.kGreen), ROOT.RooFit.LineColor(ROOT.EColor.kGreen))
            	mframe3.Draw()
	    	mframe3.GetXaxis().SetTitle("Dijet Mass (GeV)")
		leg = TLegend(0.7,0.8,0.9,0.9)
                leg.AddEntry(mframe3.findObject("SIG"),"Signal Model","l")
                leg.AddEntry(mframe3.findObject("JERUP"),"+1 Sigma","l")
                leg.AddEntry(mframe3.findObject("JERDOWN"),"-1 Sigma","l")
                leg.Draw()	
		jername = args.pdir+'/jer_m'+str(mass)+fstr+'.pdf'
           	c3.SaveAs(jername)


        # -----------------------------------------
        # create a datacard and corresponding workspace
        postfix = (('_' + args.postfix) if args.postfix != '' else '')
        dcName = 'datacard_' + args.final_state + '_m' + str(mass) + postfix + '.txt'
        wsName = 'workspace_' + args.final_state + '_m' + str(mass) + postfix + '.root'

        w = RooWorkspace('w','workspace')
        getattr(w,'import')(rooSigHist,RooFit.Rename("signal"))
        if args.jesUnc != None:
            getattr(w,'import')(hSig_Syst_DataHist['JESUp'],RooFit.Rename("signal__JESUp"))
            getattr(w,'import')(hSig_Syst_DataHist['JESDown'],RooFit.Rename("signal__JESDown"))
        if args.jerUnc != None:
            getattr(w,'import')(hSig_Syst_DataHist['JERUp'],RooFit.Rename("signal__JERUp"))
            getattr(w,'import')(hSig_Syst_DataHist['JERDown'],RooFit.Rename("signal__JERDown"))
        if args.decoBkg:
            getattr(w,'import')(background_deco,ROOT.RooCmdArg())
        else:
            getattr(w,'import')(background,ROOT.RooCmdArg(),RooFit.Rename("background"))

	#if use different fits for shape uncertainties
	#getattr(w,'import')(,ROOT.RooCmdArg(),RooFit.Rename("background__bkgUp"))
	#getattr(w,'import')(,ROOT.RooCmdArg(),RooFit.Rename("background__bkgDown"))
	
	getattr(w,'import')(background_norm,ROOT.RooCmdArg())
        getattr(w,'import')(rooDataHist,RooFit.Rename("data_obs"))
        w.Print()
        w.writeToFile(os.path.join(args.output_path,wsName))

	beffUnc = 0.3
	boffUnc = 0.06

        datacard = open(os.path.join(args.output_path,dcName),'w')
        datacard.write('imax 1\n')
        datacard.write('jmax 1\n')
        datacard.write('kmax *\n')
        datacard.write('---------------\n')
        if args.jesUnc != None or args.jerUnc != None:
            datacard.write('shapes * * '+wsName+' w:$PROCESS w:$PROCESS__$SYSTEMATIC\n')
        else:
            datacard.write('shapes * * '+wsName+' w:$PROCESS\n')
        datacard.write('---------------\n')
        datacard.write('bin 1\n')
        datacard.write('observation -1\n')
        datacard.write('------------------------------\n')
        datacard.write('bin          1          1\n')
        datacard.write('process      signal     background\n')
        datacard.write('process      0          1\n')
        datacard.write('rate         -1         1\n')
        datacard.write('------------------------------\n')
        datacard.write('lumi  lnN    %f         -\n'%(1.+args.lumiUnc))
	datacard.write('beff  lnN    %f         -\n'%(1.+beffUnc))
	datacard.write('boff  lnN    %f         -\n'%(1.+boffUnc))
	datacard.write('bkg   lnN     -         1.03\n')
        if args.jesUnc != None:
            datacard.write('JES  shape   1          -\n')
        if args.jerUnc != None:
            datacard.write('JER  shape   1          -\n')
        # flat parameters --- flat prior
        datacard.write('background_norm  flatParam\n')
        if args.decoBkg:
            datacard.write('deco_eig1  flatParam\n')
            datacard.write('deco_eig2  flatParam\n')
            if not args.fixP3: datacard.write('deco_eig3  flatParam\n')
        else:
            datacard.write('p1  flatParam\n')
            datacard.write('p2  flatParam\n')
            if not args.fixP3: datacard.write('p3  flatParam\n')
        datacard.close()


    print '>> Datacards and workspaces created and stored in %s/'%( os.path.join(os.getcwd(),args.output_path) )
コード例 #49
0
    genFitter.expectedFromPars()
    genFitter.resetYields()
    
    genstartpars = genPdf.getParameters(fitter.ws.set('obsSet'))
    genFitter.ws.defineSet("params", genstartpars)
    genFitter.ws.saveSnapshot("genInitPars", genstartpars)
    print "genPars:"
    genFitter.ws.set('params').Print('v')

    if opts.extendedGen:
        data = genPdf.generate(genFitter.ws.set('obsSet'), RooFit.Name('data_obs'),RooFit.Extended())
    else:
        data = genPdf.generate(genFitter.ws.set('obsSet'), RooFit.Name('data_obs'))
    
    if fitter.pars.binData:
        data = RooDataHist('data_obs', 'data_obs', genFitter.ws.set('obsSet'), data)
        data.Print('v')
    getattr(fitter.ws, 'import')(data)
    
    print 'Generated Data Events: %.0f' % (data.sumEntries())
    
elif opts.runMCGenToySim:
    print "performing Toy Generation from MC:"
    print "Generating ", opts.extdiboson, " diboson events"
    dibosonfiles = getattr(pars, 'dibosonFiles')
    dibosontoymodels = [-1]
    dibosonPdf = fitter.makeComponentPdf('dibosontoy',dibosonfiles,dibosontoymodels)
    dibosontoymc = dibosonPdf.generate(fitter.ws.set('obsSet'),opts.extdiboson,RooFit.Name('data_obs'))
    dibosontoymc.Print()
    gentoymc=dibosontoymc
    print "Generating ", opts.extWpJ, " WpJ events"
コード例 #50
0
ファイル: FitData.py プロジェクト: nhanvtran/cmsdas2014
gROOT.ForceStyle()
gROOT.SetStyle('tdrStyle')

filename = 'dijetHisto_data_signal.root'

inf = TFile.Open(filename)
h   = inf.Get('h_mjj')

x = RooRealVar('mjj','mjj',900,4500)
NBINS = 180
p1 = RooRealVar('p1','p1',5,0,20)
p2 = RooRealVar('p2','p2',5,0,20)
p3 = RooRealVar('p3','p3',0.1,0,1)

model = RooGenericPdf('model','pow(1-@0/8000,@1)/pow(@0/8000,@2+@3*log(@0/8000))',RooArgList(x,p1,p2,p3))
roohist = RooDataHist('roohist','roohist',RooArgList(x),h)
res = model.fitTo(roohist)


can = TCanvas('can_Mjj_Data','can_Mjj_Data',900,600)
gPad.SetLogy() 
can.cd(1).SetBottomMargin(0.4);

frame1 = x.frame()
frame2 = x.frame();
roohist.plotOn(frame1,RooFit.Binning(NBINS))
model.plotOn(frame1)
hpull = frame1.pullHist();
frame2.addPlotable(hpull,'p');

frame1.SetMinimum(0.5)
コード例 #51
0
				h_target_residuals_nbp_vs_p_6hit.Fill(momentum, delta_y)
				h_gbl_target_residuals_bp_vs_p_6hit.Fill(momentum, gbl_delta_x)
				h_gbl_target_residuals_nbp_vs_p_6hit.Fill(momentum, gbl_delta_y)


canvas.Print("track_parameters.pdf[")

#--- Fit the D0 plots ---#
#------------------------#

track_d0 = RooRealVar("track_d0", "D0 (mm)", -1.5, 1.5)
track_d0_mean = RooRealVar("track_d0_mean", "Track D0 Mean", 0, -1.5, 1.5)
track_d0_sigma = RooRealVar("track_d0_sigma", "Track D0 Sigma", .5, 0, 2)
track_d0_gaussian = RooGaussModel("track_d0_gaussian", "Track D0 Gaussian", track_d0, track_d0_mean, track_d0_sigma)

track_d0_data = RooDataHist("track_d0_data", "Track D0 Data", RooArgList(track_d0), h_track_d0)
track_d0_plot = track_d0.frame()
track_d0_plot.SetTitle("")
track_d0_data.plotOn(track_d0_plot, RooFit.MarkerColor(kAzure+2), RooFit.LineColor(kAzure+2))

track_d0_gaussian.fitTo(track_d0_data)
track_d0_gaussian.plotOn(track_d0_plot, RooFit.LineColor(kAzure+2))

gbl_track_d0 = RooRealVar("gbl_track_d0", "D0 (mm)", -1.5, 1.5)
gbl_track_d0_mean = RooRealVar("gbl_track_d0_mean", "Track D0 Mean", 0, -1.5, 1.5)
gbl_track_d0_sigma = RooRealVar("gbl_track_d0_sigma", "Track D0 Sigma", .5, 0, 2)
gbl_track_d0_gaussian = RooGaussModel("gbl_track_d0_gaussian", "Track D0 Gaussian", gbl_track_d0, gbl_track_d0_mean, gbl_track_d0_sigma)

gbl_track_d0_data = RooDataHist("track_d0_data", "Track D0 Data", RooArgList(gbl_track_d0), h_gbl_track_d0)
gbl_track_d0_plot = gbl_track_d0.frame()
gbl_track_d0_plot.SetTitle("")
コード例 #52
0
#tree_sig.Project("hist_mass_1GeV","mjj","deltaETAjj<1.3")
hSig.Print()
hSig.Draw()

#hSig   = infSig.Get(inputHistName)
#hSig.Rebin(20)


# -----------------------------------------
# define observable
#test -- restrict mjj range
#x = RooRealVar('mjj','mjj',1500,6000)
#x = RooRealVar('mjj','mjj',1118,6099)
x = RooRealVar('mjj','mjj',1118,9067)

dataHist_data=RooDataHist("RooDataHist","RooDataHist",RooArgList(x),hDat)

if fitSig: 

    # define parameters for signal fit
    m = RooRealVar('mean','mean',float(mass),float(mass)-200,float(mass)+200)
    s = RooRealVar('sigma','sigma',0.1*float(mass),0,10000)
    a = RooRealVar('alpha','alpha',1,-10,10)
    n = RooRealVar('n','n',1,0,100)
    sig = RooCBShape('sig','sig',x,m,s,a,n)        

    p  = RooRealVar('p','p',1,0,5)
    x0 = RooRealVar('x0','x0',1000,100,5000)

    bkg = RooGenericPdf('bkg','1/(exp(pow(@0/@1,@2))+1)',RooArgList(x,x0,p))
コード例 #53
0
  	qcdhist.Scale(doubleBfake)
  	sigWhist.Scale(doubleBfake)
  	sigZhist.Scale(0.1512*doubleBeff+(1.-0.1512)*doubleBfake)
      if category=="anti-btag":
  	qcdhist.Scale(1.-doubleBfake)
  	sigWhist.Scale(1.-doubleBfake)
  	sigZhist.Scale(0.1512*(1.-doubleBeff)+(1.-0.1512)*(1.-doubleBfake))
      sighist=sigWhist.Clone("sighist")
      sighist.Add(sigZhist)
      sbhist=hqcd.Clone("sbhist")
      sbhist.Add(sighist,signalweight)
    
      if fit=="data":
  	data=pseudodata[name]
      elif fit=="b":
  	data=RooDataHist("data"+name,"QCD",RooArgList(mass),qcdhist)
      elif fit=="sb":
  	data=RooDataHist("data"+name,"QCD + V+jets",RooArgList(mass),sbhist)
      signal=RooDataHist("signal"+name,"signal",RooArgList(mass),sighist)
      signalW=RooDataHist("signalW"+name,"signalW",RooArgList(mass),sigWhist)
      signalZ=RooDataHist("signalZ"+name,"signalZ",RooArgList(mass),sigZhist)

      nsigbkg=RooRealVar("nsigbkg"+name,"number of signal background events",sighist.Integral(),0,10*sighist.Integral())
      nbkg=RooRealVar("nbkg"+name,"number of background events",qcdhist.Integral(),0,10*qcdhist.Integral())
      nbkg1=RooRealVar("nbkg1"+name,"number of background events",qcdhist.Integral(),0,10*qcdhist.Integral())
      nbkg2=RooRealVar("nbkg2"+name,"number of background events",qcdhist.Integral(),0,10*qcdhist.Integral())

      l0=RooRealVar("l0","l0",100.,0.,1000.)
      l1=RooRealVar("l1","l1",1.,0.,1000.)
      l2=RooRealVar("l2","l2",1.,0.,1000.)
      #sigbkg=RooPolynomial("sigbkg"+name,"bkg",mass,RooArgList(l0,l1,l2))
コード例 #54
0
ファイル: doFits.py プロジェクト: CMSDIJET/DijetRootTreeMaker
    x0 = RooRealVar('x0','x0',1000,100,5000)

    bkg = RooGenericPdf('bkg','1/(exp(pow(@0/@1,@2))+1)',RooArgList(x,x0,p))

    fsig= RooRealVar('fsig','fsig',0.5,0.,1.)
    signal = RooAddPdf('signal','signal',sig,bkg,fsig)

    # -----------------------------------------
    # fit signal
    canSname = 'can_Mjj'+str(mass)
    if useSub:
      canSname = 'can_Sub_Mjj'+str(mass)
    canS = TCanvas(canSname,canSname,900,600)
    #gPad.SetLogy() 

    roohistSig = RooDataHist('roohist','roohist',RooArgList(x),hSig)

    signal.fitTo(roohistSig)
    frame = x.frame()
    roohistSig.plotOn(frame)
    signal.plotOn(frame)
    signal.plotOn(frame,RooFit.Components('bkg'),RooFit.LineColor(ROOT.kRed),RooFit.LineWidth(2),RooFit.LineStyle(ROOT.kDashed))
    frame.GetXaxis().SetRangeUser(900,4500)
    frame.GetXaxis().SetTitle('m_{jj} (GeV)')
    frame.Draw()

    parsSig = signal.getParameters(roohistSig)
    parsSig.setAttribAll('Constant', True)

if fitDat: 
コード例 #55
0
def rf501_simultaneouspdf():
    # C r e a t e   m o d e l   f o r   p h y s i c s   s a m p l e
    # -------------------------------------------------------------

    # Create observables
    x = RooRealVar("x", "x", 40, 200)
    nsig = RooRealVar("nsig", "#signal events", 200, 0.0, 10000)
    nbkg = RooRealVar("nbkg", "#background events", 800, 0.0, 200000)
    # Construct signal pdf
    mean = RooRealVar("mean", "mean", mu4, 40, 200)
    sigma = RooRealVar("sigma", "sigma", sigma4, 0.1, 20)
    gx = RooGaussian("gx", "gx", x, mean, sigma)

    # Construct background pdf
    mean_bkg = RooRealVar("mean_bkg", "mean_bkg", mu3, 40, 200)
    sigma_bkg = RooRealVar("sigma_bkg", "sigma_bkg", sigma3, 0.1, 20)
    px = RooGaussian("px", "px", x, mean_bkg, sigma_bkg)

    # Construct composite pdf
    model = RooAddPdf("model", "model", RooArgList(gx, px), RooArgList(nsig, nbkg))

    # C r e a t e   m o d e l   f o r   c o n t r o l   s a m p l e
    # --------------------------------------------------------------

    # Construct signal pdf.
    # NOTE that sigma is shared with the signal sample model
    y = RooRealVar("y", "y", 40, 200)

    mean_ctl = RooRealVar("mean_ctl", "mean_ctl", mu2, 40, 200)
    sigma_ctl = RooRealVar("sigma", "sigma", sigma2, 0.1, 10)
    gx_ctl = RooGaussian("gx_ctl", "gx_ctl", y, mean_ctl, sigma_ctl)

    # Construct the background pdf
    mean_bkg_ctl = RooRealVar("mean_bkg_ctl", "mean_bkg_ctl", mu1, 40, 200)
    sigma_bkg_ctl = RooRealVar("sigma_bkg_ctl", "sigma_bkg_ctl", sigma1, 0.1, 20)
    px_ctl = RooGaussian("px_ctl", "px_ctl", y, mean_bkg_ctl, sigma_bkg_ctl)

    # Construct the composite model
    #     f_ctl = RooRealVar( "f_ctl", "f_ctl", 0.5, 0., 20. )
    model_ctl = RooAddPdf("model_ctl", "model_ctl", RooArgList(gx_ctl, px_ctl), RooArgList(nsig, nbkg))

    # G e t   e v e n t s   f o r   b o t h   s a m p l e s
    # ---------------------------------------------------------------
    real_data, real_data_ctl = get_data()
    real_data_hist = RooDataHist("real_data_hist", "real_data_hist", RooArgList(x), real_data)
    real_data_ctl_hist = RooDataHist("real_data_ctl_hist", "real_data_ctl_hist", RooArgList(y), real_data_ctl)
    input_hists = MapStrRootPtr()
    input_hists.insert(StrHist("physics", real_data))
    input_hists.insert(StrHist("control", real_data_ctl))

    # C r e a t e   i n d e x   c a t e g o r y   a n d   j o i n   s a m p l e s
    # ---------------------------------------------------------------------------
    # Define category to distinguish physics and control samples events
    sample = RooCategory("sample", "sample")
    sample.defineType("physics")
    sample.defineType("control")

    # Construct combined dataset in (x,sample)
    combData = RooDataHist("combData", "combined data", RooArgList(x), sample, input_hists)

    # C o n s t r u c t   a   s i m u l t a n e o u s   p d f   i n   ( x , s a m p l e )
    # -----------------------------------------------------------------------------------

    # Construct a simultaneous pdf using category sample as index
    simPdf = RooSimultaneous("simPdf", "simultaneous pdf", sample)

    # Associate model with the physics state and model_ctl with the control state
    simPdf.addPdf(model, "physics")
    simPdf.addPdf(model_ctl, "control")

    # P e r f o r m   a   s i m u l t a n e o u s   f i t
    # ---------------------------------------------------
    model.fitTo(real_data_hist)
    summary = "fit in signal region\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    model_ctl.fitTo(real_data_ctl_hist)
    summary += "fit in control region\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    # Perform simultaneous fit of model to data and model_ctl to data_ctl
    simPdf.fitTo(combData)
    summary += "Combined fit\n"
    summary += "nsig: " + str(nsig.getValV()) + " +- " + str(nsig.getError()) + "\n"
    summary += "nbkg: " + str(nbkg.getValV()) + " +- " + str(nbkg.getError()) + "\n"

    # P l o t   m o d e l   s l i c e s   o n   d a t a    s l i c e s
    # ----------------------------------------------------------------

    # Make a frame for the physics sample
    frame1 = x.frame(RooFit.Bins(30), RooFit.Title("Physics sample"))

    # Plot all data tagged as physics sample
    combData.plotOn(frame1, RooFit.Cut("sample==sample::physics"))

    # Plot "physics" slice of simultaneous pdf.
    # NBL You _must_ project the sample index category with data using ProjWData
    # as a RooSimultaneous makes no prediction on the shape in the index category
    # and can thus not be integrated
    simPdf.plotOn(frame1, RooFit.Slice(sample, "physics"), RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(
        frame1,
        RooFit.Slice(sample, "physics"),
        RooFit.Components("px"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )

    # The same plot for the control sample slice
    frame2 = y.frame(RooFit.Bins(30), RooFit.Title("Control sample"))
    combData.plotOn(frame2, RooFit.Cut("sample==sample::control"))
    simPdf.plotOn(frame2, RooFit.Slice(sample, "control"), RooFit.ProjWData(RooArgSet(sample), combData))
    simPdf.plotOn(
        frame2,
        RooFit.Slice(sample, "control"),
        RooFit.Components("px_ctl"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )
    simPdf.plotOn(
        frame2,
        RooFit.Slice(sample, "control"),
        RooFit.Components("gx_ctl"),
        RooFit.ProjWData(RooArgSet(sample), combData),
        RooFit.LineStyle(kDashed),
    )

    c = TCanvas("rf501_simultaneouspdf", "rf403_simultaneouspdf", 800, 400)
    c.Divide(2)
    c.cd(1)
    gPad.SetLeftMargin(0.15)
    frame1.GetYaxis().SetTitleOffset(1.4)
    frame1.Draw()
    c.cd(2)
    gPad.SetLeftMargin(0.15)
    frame2.GetYaxis().SetTitleOffset(1.4)
    frame2.Draw()

    print summary
    raw_input()
コード例 #56
0
def fitLandauGaus(hist, full = False):

    ## c1 = ROOT.TCanvas()
    ## c1.Divide(2)
    ## c1.cd(1)
    ## hist.Draw()
    neg_landau = False
    if hist.GetMean() < 0.:
        neg_landau = True
    if neg_landau:
        hist = turnHisto(hist)

    hist.Rebin(2)
    hist.SetTitle('')
    hist.SetName('hSignal')
    ## c1.cd(2)
    ## hist.Draw('hist')
    ## c1.SaveAs('foobar.pdf')

    ### #if neg_landau:
    ### #    func = ROOT.TF1('my_landau','[0] * TMath::Landau(-x,[1],[2])', hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax())
    ### #    func.SetParameters(1, hist.GetMean(), hist.GetRMS() )
    ### #else:
    ### func = ROOT.TF1('my_landau','[0] * TMath::Landau(x,[1],[2])', hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax())
    ### func.SetParameters(1, hist.GetMean(), hist.GetRMS() )

    ### hist.Fit('my_landau','q')
    ### fit_res = []
    ### fit_res.append(func.GetParameter(0) if not neg_landau else     func.GetParameter(0))
    ### fit_res.append(func.GetParameter(1) if not neg_landau else -1.*func.GetParameter(1))
    ### fit_res.append(func.GetParameter(2) if not neg_landau else     func.GetParameter(2))
    ### return hist, fit_res

## ROOFIT VERSION

    xmin = hist.GetXaxis().GetXmin()
    xmax = hist.GetXaxis().GetXmax()
    mean = hist.GetMean()
    mp = hist.GetXaxis().GetBinCenter(hist.GetMaximumBin())
    rms = hist.GetRMS()
    flandau = ROOT.TF1('flandau','landau',mp-20,mp+40)
    flandau.SetLineWidth(1)
    flandau.SetLineColor(ROOT.kBlue)
    hist2 = hist.Clone(hist.GetName()+'_2')
    hist2.Scale(1./hist2.GetBinContent(hist2.GetMaximumBin()))
    hist2.Fit(flandau,'Q','',mp-20,mp+40)

    flandau2 = flandau.Clone('flandau2')
    flandau2.SetRange(0,500)
    flandau2.SetLineStyle(2)

    for i in range(flandau.GetNpar()):
        flandau2.SetParLimits(i,flandau.GetParameter(i),flandau.GetParameter(i))
    hist2.Fit(flandau2,'Q+')#,'same',mp-20,mp+40)
    for i in range(flandau.GetNpar()):
        hist2.GetFunction('flandau2').SetParameter(i,flandau.GetParameter(i))

    for i in range(flandau.GetNpar()):
        print flandau.GetParameter(i),flandau2.GetParameter(i)

    x   = RooRealVar('x', 'signal / adc', 0,500)
    x.setRange("signal",mp - 40, mp+90)
    x.setRange("draw",0,500)
    ral = RooArgList(x)
    dh  = RooDataHist('dh', 'dh', ral, RooFit.Import(hist))
    
    
    if full: 
        ml     = RooRealVar('ml', 'mean landau' , mp, mp-20., mp+30)
        sl     = RooRealVar('sl', 'sigma landau', 10, 1., 25.)
    else:
        ml     = RooRealVar('ml', 'mean landau' , mean, mean-40., mean)
        sl     = RooRealVar('sl', 'sigma landau', 10., 6., 14.)
    landau = RooLandau ('lx', 'lx', x, ml, sl)
    
    mean = 0
    if full: 
        mg     = RooRealVar ('mg', 'mean gaus' , 0,0,0)
        sg     = RooRealVar ('sg', 'sigma gaus', flandau.GetParameter(2), 0.1, 30.)
    else:
        mg     = RooRealVar ('mg', 'mean gaus' , 0,0,0) #mean, mean-30.,  mean+30.)
        sg     = RooRealVar ('sg', 'sigma gaus', 2., 0.1, 20.)
    gaus   = RooGaussian('gx', 'gx', x, mg, sg)
    
    x.setBins(1000,'cache')
    
    ## Construct landau (x) gauss
    lxg = RooFFTConvPdf('lxg','landau (x) gaus', x, landau, gaus)
    lxg.fitTo(dh,RooFit.Range("signal"))
    #,RooFit.Normalization(ROOT.RooAbsReal.NumEvent,1))
    a = lxg.getParameters(dh)

    print 'fit par0                                     %+6.1f'%flandau.GetParameter(0)
    print 'fit par1                                     %+6.1f'%flandau.GetParameter(1)
    print 'fit par2                                     %+6.1f'%flandau.GetParameter(2)
    print 'mp                                           %+6.1f'%mp
    print 'rms                                          %+6.1f'%rms
    print 'lxg.getParameters(dh).getRealValue(\'ml\'):  %+6.1f'% a.getRealValue('ml')
    print 'lxg.getParameters(dh).getRealValue(\'sl\'):  %+6.1f'% a.getRealValue('sl')
    print 'lxg.getParameters(dh).getRealValue(\'sg\'):  %+6.1f'% a.getRealValue('sg')

    frame = x.frame(RooFit.Title('landau (x) gauss convolution'),RooFit.Range("draw"))
    #,RooFit.Normalization(ROOT.RooAbsReal.NumEvent,1))
    dh.plotOn(frame,RooFit.Range("draw"))
    #,RooFit.Normalization(1./dh.numEntries(),ROOT.RooAbsReal.Raw))
    lxg.plotOn(frame,RooFit.LineColor(ROOT.kRed),RooFit.Range("draw"))
    #,RooFit.Normalization(1,ROOT.RooAbsReal.Raw))
    #lxg.plotOn(frame,RooFit.LineColor(ROOT.kBlue),RooFit.Range("signal"),RooFit.Components('lx,gx'))
    
    # c = ROOT.TCanvas('lg_convolution','landau (x) gaus', 600, 600)
    # c.Divide(2)
    # c.cd(1)
    # hist.Draw()
    # c.cd(2)
    # ROOT.gPad.SetLeftMargin(0.15)
    # frame.GetYaxis().SetTitleOffset(1.4)
    # frame.Draw()
    # c.SaveAs('histograms/outputhisto'+hist.GetName().split('pz')[1]+'.pdf')
    return dh, copy.deepcopy(a), copy.deepcopy(frame),copy.deepcopy(hist2)
コード例 #57
0
ファイル: studyVqqResolution.py プロジェクト: UMN-CMS/PFCal
def studyVqqResolution(rootFile):

    #get all from file
    histos={}
    inF=TFile.Open(rootFile)
    keys=inF.GetListOfKeys()
    for k in keys:
        obj=inF.Get(k.GetName())
        obj.SetDirectory(0)
        histos[k.GetName()]=obj
    inF.Close()

    #plot
    gROOT.SetBatch()
    gROOT.SetStyle('Plain')
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(1111)
    gStyle.SetOptTitle(0)
    gStyle.SetStatFont(42)

    kin=['','30to40','40to50','50to75','75to100','100toInf']
    for k in kin:        
        c=TCanvas('c','c',600,600)
        c.cd()
        c.SetCanvasSize(1000,500)
        c.SetWindowSize(1000,500)
        c.Divide(2,1)
        c.cd(1)
        histos['deta'+k+'barrel'].SetLineWidth(2)
        histos['deta'+k+'barrel'].SetTitle('barrel')
        histos['deta'+k+'barrel'].Draw('hist')
        histos['deta'+k+'endcap'].SetLineWidth(2)
        histos['deta'+k+'endcap'].SetLineStyle(7)
        histos['deta'+k+'endcap'].SetTitle('endcap')
        histos['deta'+k+'endcap'].Draw('histsame')
        leg=TLegend(0.6,0.92,0.9,0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(histos['deta'+k+'barrel'],'barrel','f')
        leg.AddEntry(histos['deta'+k+'endcap'],'endcap','f')
        leg.SetNColumns(2)
        leg.Draw()
        drawHeader()
        c.cd(2)
        histos['dphi'+k+'barrel'].SetLineWidth(2)
        histos['dphi'+k+'barrel'].SetTitle('barrel')
        histos['dphi'+k+'barrel'].Draw('hist')
        histos['dphi'+k+'endcap'].SetLineWidth(2)
        histos['dphi'+k+'endcap'].SetLineStyle(7)
        histos['dphi'+k+'endcap'].SetTitle('endcap')
        histos['dphi'+k+'endcap'].Draw('histsame')
        c.Modified()
        c.Update()
        c.SaveAs('dr_%s.png'%k)


    labels=[]
    responseVars=['dpt','den','dphi','deta','dr']
    for r in responseVars:
        barrelResponse=TGraphErrors()
        barrelResponse.SetName(r+'barrelresponse')
        barrelResponse.SetLineWidth(2)
        barrelResponse.SetFillStyle(0)
        barrelResponse.SetMarkerStyle(20)
        barrelCoreResponse=barrelResponse.Clone(r+'barrelcoreresponse')
        endcapResponse=TGraphErrors()
        endcapResponse.SetName(r+'endcapresponse')
        endcapResponse.SetLineWidth(2)
        endcapResponse.SetFillStyle(0)
        endcapResponse.SetMarkerStyle(24)
        endcapCoreResponse=endcapResponse.Clone(r+'endcapresponse')
        for k in kin: 
            c.cd()
            c.Clear()
            c.SetWindowSize(1000,500)
            c.Divide(2,1)
            for i in [1,2] :
                c.cd(i)
                reg='barrel'
                if i==2: reg='endcap' 

                h=histos[r+k+reg]
                x=RooRealVar("x", h.GetXaxis().GetTitle(), h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax())
                data=RooDataHist("data", "dataset with x", RooArgList(x), h)
                frame=x.frame()
                RooAbsData.plotOn( data, frame, RooFit.DataError(RooAbsData.SumW2) )

                mean1=RooRealVar("mean1","mean1",0,-0.5,0.5);
                sigma1=RooRealVar("sigma1","sigma1",0.1,0.01,1.0);
                gauss1=RooGaussian("g1","g",x,mean1,sigma1)
                
                if r=='dpt' or r=='den' :
                    mean2=RooRealVar("mean2","mean2",0,-0.5,0.5);
                    sigma2=RooRealVar("sigma2","sigma2",0.1,0.01,1.0);
                    alphacb=RooRealVar("alphacb","alphacb",1,0.1,3);
                    ncb=RooRealVar("ncb","ncb",4,1,100)
                    gauss2 = RooCBShape("cb2","cb",x,mean2,sigma2,alphacb,ncb);
                else:
                    mean1.setRange(0,0.5)
                    mean2=RooRealVar("mean2","mean",0,0,1);
                    sigma2=RooRealVar("sigma2","sigma",0.1,0.01,1.0);
                    gauss2=RooGaussian("g2","g",x,mean2,sigma2) ;

                frac = RooRealVar("frac","fraction",0.9,0.0,1.0)
                if data.sumEntries()<100 :
                    frac.setVal(1.0)
                    frac.setConstant(True)
                model = RooAddPdf("sum","g1+g2",RooArgList(gauss1,gauss2), RooArgList(frac))

                status=model.fitTo(data,RooFit.Save()).status()
                if status!=0 : continue

                model_cdf=model.createCdf(RooArgSet(x)) ;
                cl=0.90
                ul=0.5*(1.0+cl)
                closestToCL=1.0
                closestToUL=-1
                closestToMedianCL=1.0
                closestToMedian=-1
                for ibin in xrange(1,h.GetXaxis().GetNbins()*10):
                    xval=h.GetXaxis().GetXmin()+(ibin-1)*h.GetXaxis().GetBinWidth(ibin)/10.
                    x.setVal(xval)
                    cdfValToCL=math.fabs(model_cdf.getVal()-ul)
                    if cdfValToCL<closestToCL:
                        closestToCL=cdfValToCL
                        closestToUL=xval
                    cdfValToCL=math.fabs(model_cdf.getVal()-0.5)
                    if cdfValToCL<closestToMedianCL:
                        closestToMedianCL=cdfValToCL
                        closestToMedian=xval

                RooAbsPdf.plotOn(model,frame)
                frame.Draw()

                if i==1: drawHeader()
                labels.append( TPaveText(0.6,0.92,0.9,0.98,'brNDC') )
                ilab=len(labels)-1
                labels[ilab].SetName(r+k+'txt')
                labels[ilab].SetBorderSize(0)
                labels[ilab].SetFillStyle(0)
                labels[ilab].SetTextFont(42)
                labels[ilab].SetTextAlign(12)
                kinReg=k.replace('to','-')
                kinReg=kinReg.replace('Inf','#infty')
                labels[ilab].AddText('['+reg+'] '+kinReg)
                labels[ilab].Draw()
                
                resolutionVal=math.fabs(closestToUL-closestToMedian)
                responseGr=barrelResponse
                responseCoreGr=barrelCoreResponse
                coreResolutionVal=sigma1.getVal()
                coreResolutionErr=sigma1.getError()
                if frac.getVal()<0.7 and (sigma2.getVal()<sigma1.getVal()) :
                    coreResolutionVal=sigma2.getVal()
                    coreResolutionErr=sigma2.getError()


                if i==2 : 
                    responseGr=endcapResponse
                    responseCoreGr=endcapCoreResponse
                if k!='' :
                    nrespPts=responseGr.GetN()
                    kinAvg=150
                    kinWidth=50
                    if k=='30to40' : 
                        kinAvg=35
                        kinWidth=5
                    if k=='40to50' : 
                        kinAvg=45
                        kinWidth=5
                    if k=='50to75' : 
                        kinAvg=62.5
                        kinWidth=12.5
                    elif k=='75to100' :
                        kinAvg=87.5
                        kinWidth=12.5
                    responseGr.SetPoint(nrespPts,kinAvg,resolutionVal)
                    responseCoreGr.SetPoint(nrespPts,kinAvg,coreResolutionVal)
                    responseCoreGr.SetPointError(nrespPts,kinWidth,coreResolutionErr)

                labels.append( TPaveText(0.15,0.7,0.4,0.9,'brNDC') )
                ilab=len(labels)-1
                labels[ilab].SetName(r+k+'fitrestxt')
                labels[ilab].SetBorderSize(0)
                labels[ilab].SetFillStyle(0)
                labels[ilab].SetTextFont(42)
                labels[ilab].SetTextAlign(12)
                labels[ilab].AddText('Gaussian #1 (f=%3.3f)'%frac.getVal())
                labels[ilab].AddText('#mu=%3.3f#pm%3.3f'%(mean1.getVal(),mean1.getError()))
                labels[ilab].AddText('#sigma=%3.3f#pm%3.3f'%(sigma1.getVal(),sigma1.getError()))
                labels[ilab].AddText('Gaussian #2 (f=%3.3f)'%(1-frac.getVal()))
                labels[ilab].AddText('#mu=%3.3f#pm%3.3f'%(mean2.getVal(),mean2.getError()))
                labels[ilab].AddText('#sigma=%3.3f#pm%3.3f'%(sigma2.getVal(),sigma2.getError()))
                
                labels[ilab].Draw()

            c.Modified()
            c.Update()
            c.SaveAs(r+'res_'+k+'.png')
        
        frame=TGraphErrors()
        frame.SetPoint(0,0,0)
        frame.SetPoint(1,200,0.3)
        frame.SetMarkerStyle(1)
        frame.SetFillStyle(0)
        frame.SetName('frame')
        cresp=TCanvas('cresp','cresp',500,500)
        cresp.cd()
        frame.Draw('ap')
        barrelResponse.Draw('pl')
        endcapResponse.Draw('pl')
        frame.GetXaxis().SetTitle("Quark transverse momentum [GeV]") 
        frame.GetYaxis().SetTitle("Resolution %3.2f C.L."%cl )
        frame.GetYaxis().SetTitleOffset(1.4)
        frame.GetYaxis().SetNdivisions(10)
        drawHeader()
        leg=TLegend(0.6,0.92,0.9,0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(barrelResponse,'barrel','fp')
        leg.AddEntry(endcapResponse,'endcap','fp')
        leg.SetNColumns(2)
        leg.Draw()
        cresp.Modified()
        cresp.Update()
        cresp.SaveAs(r+'res_evol.png')

        frameCore=frame.Clone('framecore')
        cresp.Clear()
        frameCore.Draw('ap')
        barrelCoreResponse.Draw('pl')
        endcapCoreResponse.Draw('pl')
        frameCore.GetXaxis().SetTitle("Quark transverse momentum [GeV]") 
        frameCore.GetYaxis().SetTitle("Core resolution")
        frameCore.GetYaxis().SetTitleOffset(1.4)
        frameCore.GetYaxis().SetNdivisions(10)
        frameCore.GetYaxis().SetRangeUser(0,0.2)
        drawHeader()
        leg=TLegend(0.6,0.92,0.9,0.98)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(42)
        leg.AddEntry(barrelCoreResponse,'barrel','fp')
        leg.AddEntry(endcapCoreResponse,'endcap','fp')
        leg.SetNColumns(2)
        leg.Draw()
        cresp.Modified()
        cresp.Update()
        cresp.SaveAs(r+'rescore_evol.png')

    bosons=['h','z','w']
    kin=['','50','100']
    region=['','bb','eb','ee']
    for k in kin:        
        for r in region:

            c=TCanvas('c','c',600,600)
            c.cd()
            histos['mjj'+k+r].Rebin()
            histos['mjj'+k+r].Draw()
            ic=1
            leg=TLegend(0.6,0.92,0.9,0.98)
            leg.SetFillStyle(0)
            leg.SetBorderSize(0)
            leg.SetTextFont(42)
            leg.AddEntry(histos['mjj'+k+r],'inclusive','f')
            for b in bosons:
                if histos[b+'mjj'+k+r].Integral()<=0 : continue 
                ic=ic+1
                histos[b+'mjj'+k+r].Rebin()
                histos[b+'mjj'+k+r].SetLineColor(ic)
                histos[b+'mjj'+k+r].SetLineWidth(2)
                histos[b+'mjj'+k+r].SetMarkerColor(ic)
                histos[b+'mjj'+k+r].SetMarkerStyle(1)
                histos[b+'mjj'+k+r].SetFillStyle(3000+ic)
                histos[b+'mjj'+k+r].SetFillColor(ic)
                histos[b+'mjj'+k+r].Draw('histsame')
                leg.AddEntry(histos[b+'mjj'+k+r],b,"f")
            leg.SetNColumns(ic)
            leg.Draw()
            drawHeader()
            labels.append( TPaveText(0.65,0.8,0.9,0.9,'brNDC') )
            ilab=len(labels)-1
            labels[ilab].SetName(k+r+'mjj')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            regionTitle="inclusive"
            if r == 'bb' : regionTitle='barrel-barrel'
            if r == 'eb' : regionTitle='endcap-barrel'
            if r == 'ee' : regionTitle='endcap-endcap'
            labels[ilab].AddText(regionTitle)
            ptthreshold=30
            if k!='' : ptthreshold=float(k)
            labels[ilab].AddText('p_{T}>%3.0f GeV'%ptthreshold)
            labels[ilab].Draw()
            
            c.Modified()
            c.Update()
            c.SaveAs('mjj'+k+r+'.png')


    massResolutionGrs=[]
    for r in region:
        massResolution=TGraphErrors()
        massResolution.SetName(r+'dm')
        massResolution.SetLineWidth(2)
        massResolution.SetFillStyle(0)
        massResolution.SetMarkerStyle(20+len(massResolutionGrs))
        massResolution.SetMarkerColor(1+len(massResolutionGrs))
        massResolution.SetLineColor(1+len(massResolutionGrs))
        massResolution.SetFillColor(1+len(massResolutionGrs))
        massResolutionGrs.append(massResolution)
        
        for k in kin:        

            c=TCanvas('c','c',600,600)
            c.cd()
            h=histos['dmjj'+k+r]
            x=RooRealVar("x", h.GetXaxis().GetTitle(), h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax())
            data=RooDataHist("data", "dataset with x", RooArgList(x), h)
            frame=x.frame()
            RooAbsData.plotOn( data, frame, RooFit.DataError(RooAbsData.SumW2) )
            
            mean1=RooRealVar("mean1","mean1",0,-0.5,0.5);
            sigma1=RooRealVar("sigma1","sigma1",0.1,0.01,1.0);
            gauss1=RooGaussian("g1","g",x,mean1,sigma1)
            mean2=RooRealVar("mean2","mean2",0,-0.5,0.5);
            sigma2=RooRealVar("sigma2","sigma2",0.1,0.01,1.0);
            alphacb=RooRealVar("alphacb","alphacb",1,0.1,3);
            ncb=RooRealVar("ncb","ncb",4,1,100)
            gauss2 = RooCBShape("cb2","cb",x,mean2,sigma2,alphacb,ncb);
            frac = RooRealVar("frac","fraction",0.9,0.0,1.0)
            model = RooAddPdf("sum","g1+g2",RooArgList(gauss1,gauss2), RooArgList(frac))
            status=model.fitTo(data,RooFit.Save()).status()
            if status!=0 : continue
            RooAbsPdf.plotOn(model,frame)
            frame.Draw()

            labels.append( TPaveText(0.6,0.65,0.85,0.9,'brNDC') )
            ilab=len(labels)-1
            labels[ilab].SetName(r+k+'dmfitrestxt')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            labels[ilab].AddText('Gaussian #1 (f=%3.3f)'%frac.getVal())
            labels[ilab].AddText('#mu=%3.3f#pm%3.3f'%(mean1.getVal(),mean1.getError()))
            labels[ilab].AddText('#sigma=%3.3f#pm%3.3f'%(sigma1.getVal(),sigma1.getError()))
            labels[ilab].AddText('Gaussian #2 (f=%3.3f)'%(1-frac.getVal()))
            labels[ilab].AddText('#mu=%3.3f#pm%3.3f'%(mean2.getVal(),mean2.getError()))
            labels[ilab].AddText('#sigma=%3.3f#pm%3.3f'%(sigma2.getVal(),sigma2.getError()))
            labels[ilab].Draw()

            drawHeader()
            labels.append( TPaveText(0.15,0.8,0.4,0.9,'brNDC') )
            ilab=len(labels)-1
            labels[ilab].SetName(k+r+'dmjj')
            labels[ilab].SetBorderSize(0)
            labels[ilab].SetFillStyle(0)
            labels[ilab].SetTextFont(42)
            labels[ilab].SetTextAlign(12)
            regionTitle="inclusive"
            if r == 'bb' : regionTitle='barrel-barrel'
            if r == 'eb' : regionTitle='endcap-barrel'
            if r == 'ee' : regionTitle='endcap-endcap'
            labels[ilab].AddText(regionTitle)
            ptthreshold=30
            if k!='' : ptthreshold=float(k)
            labels[ilab].AddText('p_{T}>%3.0f GeV'%ptthreshold)
            labels[ilab].Draw()

            c.Modified()
            c.Update()
            c.SaveAs('dmjj'+k+r+'.png')

            massResolution.SetTitle(regionTitle)
            ip=massResolution.GetN()
            x=40
            xerr=10
            if k=='50' :
                x=75
                xerr=25
            elif k=='100':
                x=150
                xerr=50
            y=sigma1.getVal()
            yerr=sigma1.getError()
            if frac.getVal()<0.8:
                if sigma2.getVal()<sigma1.getVal():
                    y=sigma2.getVal()
                    ey=sigma2.getError()
            massResolution.SetPoint(ip,x,y)
            massResolution.SetPointError(ip,xerr,yerr)
            

    frame=TGraphErrors()
    frame.SetPoint(0,0,0)
    frame.SetPoint(1,200,0.2)
    frame.SetMarkerStyle(1)
    frame.SetFillStyle(0)
    frame.SetName('dmframe')
    cdmevol=TCanvas('cdmevol','cdmevol',500,500)
    cdmevol.cd()
    frame.Draw('ap')
    leg=TLegend(0.6,0.92,0.9,0.98)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    for dmGr in massResolutionGrs :
        dmGr.Draw('pl')
        leg.AddEntry(dmGr,dmGr.GetTitle(),'fp')
    frame.GetXaxis().SetTitle("Leading quark transverse momentum [GeV]") 
    frame.GetYaxis().SetTitle("Core resolution")
    frame.GetYaxis().SetTitleOffset(1.4)
    frame.GetYaxis().SetNdivisions(10)
    drawHeader()
    leg.SetNColumns(2)
    leg.Draw()
    cdmevol.Modified()
    cdmevol.Update()
    cdmevol.SaveAs('dm_evol.png')


    c=TCanvas('c','c',600,600)
    c.cd()
    histos['sel'].Draw('histtext')
    drawHeader()
    c.Modified()
    c.Update()
    c.SaveAs('selection.png')


    return
コード例 #58
0
ファイル: FitSignal.py プロジェクト: nhanvtran/cmsdas2014
n = RooRealVar('n','n',1,0,100)
sig = RooCBShape('sig','sig',x,m,s,a,n)        

p  = RooRealVar('p','p',1,0,5)
x0 = RooRealVar('x0','x0',1000,100,5000)

bkg = RooGenericPdf('bkg','1/(exp(pow(@0/@1,@2))+1)',RooArgList(x,x0,p))

fsig= RooRealVar('fsig','fsig',0.5,0.,1.)
model = RooAddPdf('model','model',sig,bkg,fsig)

can = TCanvas('can_Mjj'+str(mass),'can_Mjj'+str(mass),900,600)
h.Draw()
gPad.SetLogy() 

roohist = RooDataHist('roohist','roohist',RooArgList(x),h)


model.fitTo(roohist)
frame = x.frame()
roohist.plotOn(frame)
model.plotOn(frame)
model.plotOn(frame,RooFit.Components('bkg'),RooFit.LineColor(ROOT.kRed),RooFit.LineWidth(2),RooFit.LineStyle(ROOT.kDashed))
frame.Draw('same')

w = RooWorkspace('w','workspace')
getattr(w,'import')(model)
getattr(w,'import')(roohist)  
w.Print()
w.writeToFile('RS'+str(mass)+'_workspace.root')