예제 #1
0
def fillDataSet(data, x, N, dsName='ds'):
    cols = RooArgSet(x)
    ds = RooDataSet(dsName, dsName, cols)
    #ds.Print()
    print 'length data:', N
    for datum in range(0, N):
        if (data[datum] < x.getMax()) and (data[datum] > x.getMin()):
            x.setVal(data[datum])
            ds.add(cols)
    ds.Print()
    return ds
예제 #2
0
        ]
        varRenamedList += [RooFit.RenameVariable(varName, tupleDict[varName])]
        #RooFit.RenameVariable(varName, tupleDict[varName]);
        #varList[i].SetName(tupleDict.keys()[i]);

    #tupleDataSet = RooDataSet("treeData","treeData",tree1,RooArgSet(*varList));

    weightvar = RooRealVar("weight", "weight", -1e7, 1e7)
    tupleDataSet = RooDataSet("tupleDataSet", "tupleDataSet",
                              RooArgSet(*varList), RooFit.Import(tree1),
                              RooFit.WeightVar(weightvar))

    ws = RooWorkspace('ws_FIT')
    tupleDataSet = WS(ws, tupleDataSet, varRenamedList)

    tupleDataSet.Print()
    sys.exit(0)
    #qt needs to be a category?
    # Manuel's shit...
    #weightvar = RooRealVar("weight", "weight", -1e7, 1e7)
    #tupleDataSet = RooDataSet("tupleDataSet", "tupleDataSet",
    #    RooArgSet(treetime, treeqt, treeqf, treeeta),
    #    RooFit.Import(tree1), RooFit.WeightVar(weightvar))
    #tupleDS = WS(ws, tupleDS, [
    #    RooFit.RenameVariable("Bs_ctau", "time"), ... ])
    # # note: do not forget to add to fitTo options: RooFit.SumW2Error(True)
    #ROOT.SetOwnership(tupleDataSet,False);

    #tupleDataSet.get().find(varName).Print();
    '''
    for i in range(len(tupleDict)):
 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"
 WpJfiles = getattr(pars, 'WpJFiles')
 WpJtoymodels = [-1]
 WpJPdf = fitter.makeComponentPdf('WpJtoy', WpJfiles, WpJtoymodels)
 WpJtoymc = RooDataSet()
 WpJtoymc = WpJPdf.generate(fitter.ws.set('obsSet'), opts.extWpJ,
                            RooFit.Name('data_obs'))
 WpJtoymc.Print()
 gentoymc.append(WpJtoymc)
 print "Generating ", opts.exttop, " top events"
 topfiles = getattr(pars, 'topFiles')
 toptoymodels = [-1]
 topPdf = fitter.makeComponentPdf('toptoy', topfiles, toptoymodels)
 toptoymc = RooDataSet()
 toptoymc = topPdf.generate(fitter.ws.set('obsSet'), opts.exttop,
                            RooFit.Name('data_obs'))
 toptoymc.Print()
 gentoymc.append(toptoymc)
 data = gentoymc
 if fitter.pars.binData:
     data = RooDataHist('data_obs', 'data_obs', fitter.ws.set('obsSet'),
                        data)
     data.Print('v')
예제 #4
0
decaycat.defineType('DsPi')
decaycat.defineType('DsK')

varlist += [decaycat]

for idx, mode in enumerate(['DsPi', 'DsK']):
    decaycat.setLabel(mode)
    dsetlist[idx].addColumn(decaycat)

dataset = RooDataSet('dataset', 'Combined dataset (DsK + DsPi)',
                     RooArgSet(time, decaycat), RooFit.Import(dsetlist[0]))
dataset.append(dsetlist[1])

for dset in dsetlist:
    dset.Print()
dataset.Print()

## Basic B decay pdf with time resolution
# Resolution model
mean = RooRealVar('mean', 'Mean', 0.)
# scale = RooRealVar('scale', 'Per-event time error scale factor', 1.19)
resmodel = RooGaussModel('resmodel', 'Time resolution model', time, mean,
                         RooRealConstant.value(0.044),
                         RooRealConstant.value(1.0),
                         RooRealConstant.value(1.0))
# RooRealConstant::value(0), scale, dt)
# RooRealConstant::value(0), scale,
# RooRealConstant::value(0.00004))
# Decay model
Bdecay = RooBDecay(
    'Bdecay',
예제 #5
0
class CouplingsFitter2(object):
    def __init__(self):
        self.poiLabels = []
        self.BR = dict(b=0.577,
                       tau=0.063,
                       mu=2.2e-4,
                       c=2.91e-2,
                       g=8.57e-2,
                       gamma=3.82e-3,
                       W=0.215,
                       Z=0.0264,
                       t=0.0)

        self.poi = dict()
        self.poilabels = dict()
        self.constraint = dict()
        self.canvases = dict()
        self._keep = []

    def addPOI(self, poi, label='', minimum=-0.3, maximum=0.3):
        '''Add a parameter of interest.

        Example:
        
        addPOI('Z','Z',-0.05,0.05)
        ->
        Z[0,-0.05,0.05]
        # adds variable Z with value 0,
        # allow it to scale between -0.05 and 0.05
        '''
        self.poi[poi] = ROOT.RooRealVar(poi, poi, 0, minimum, maximum)
        if label == '':
            label = poi
        self.poilabels[poi] = label

    def createWidthDeviation(self):
        '''Compute the width deviation (denoted \kappa_H^2 by M.Peskin in arxiv 1312.4974).
        
        Note that we fit an additive modification of the coupling: (1 + dx)
        is therefore equal to kappa_x
        '''
        expr = '0'
        sumBR = sum(self.BR.values())
        pwidths = []
        for dcoupling, br in self.BR.iteritems():
            pwidth = None
            if dcoupling in self.poi:
                pwidth = str(
                    br /
                    sumBR) + "*(1+" + dcoupling + ")*(1+" + dcoupling + ")"
            else:
                # using sm partial width
                pwidth = str(br / sumBR)
            pwidths.append(pwidth)
        expr = '+'.join(pwidths)
        if 'inv' in self.poi:
            expr = '(' + expr + ')/(1.0-inv)'
        else:
            # setting invisible width to 0.
            expr = '(' + expr + ')'
        dependentlist = RooArgList()
        for dep in self.poi.values():
            dependentlist.add(dep)
        self.width = RooGenericPdf('width', 'width', expr, dependentlist)

    def addConstraint(self, name, expr, deplist, mean, sigma):
        '''Add a constraint on one of the observables
        
        For example, for ZH inclusive: 
        
        f.addConstraint('Zh','(1+Z)*(1+Z)','Z',1,0.004)  

        Z is an additive modification of the gZ coupling w/r to the standard model,
        so 1+Z = \kappa_Z
        
        Zh is the pdf of the ratio of the yield w/r to the one expected in the standard model.
        This pdf depends on Z, as (1+Z)*(1+Z).
        
        ZhObs is the measured value, here 1 so we assume that the SM yield is observed.
        
        The fit varies the parameter of interest Z, thus modifying the pdf,
        while ZhObs is fixed at 1. The likelihood of each value of Z is evaluated at ZhObs on the pdf.
        '''
        print 'constraint:', name
        print expr
        print deplist
        print mean, '+/-', sigma
        deps = self._getdeps(deplist)
        self.constraint[name] = GaussianConstraint(name, expr, deps, mean,
                                                   sigma)

    def _getdeps(self, deplist):
        depnames = deplist
        try:
            depnames = deplist.split(',')
        except:
            pass
        deps = []
        for dep in depnames:
            if dep == 'width':
                deps.append(self.width)
            else:
                deps.append(self.poi[dep])
        return deps

    def addChannel(self, name, mean, sigma, prod, decay=None):
        expr_prod = '(1+{prod})*(1+{prod})'.format(prod=prod)
        expr = expr_prod
        variables = [prod]
        if decay:
            if isinstance(decay, basestring):
                expr_decay = '(1+{decay})*(1+{decay})'.format(decay=decay)
                variables.append(decay)
            else:
                decay_exprs = []
                for decay, fraction in decay:
                    n = mean * fraction
                    decay_expr = '{n}*(1+{decay})*(1+{decay})'.format(
                        n=n, decay=decay)
                    decay_exprs.append(decay_expr)
                    variables.append(decay)
                expr_decay = ' + '.join(decay_exprs)
            expr = '{expr_prod}*({expr_decay})/width'.format(
                expr_prod=expr_prod,
                expr_decay=expr_decay,
            )
            variables.append('width')
        variables = list(set(variables))
        deplist = ','.join(variables)
        self.addConstraint(name, expr, deplist, mean, sigma)

    def addUniformConstraint(self, name, expr):
        '''Adds a uniform constraint with pdf name, and expression expr.
        
        For example:
        
        f.addPOI('inv','inv', 0, 0.01)
        f.addUniformConstraint('Zhinv','inv') ####->Means free floating

        inv (the invisible BR) is free to float between 0 and 1%
        '''
        deps = self._getdeps([expr])
        self.constraint[name] = UniformConstraint(name, expr, deps)

    def info(self):
        for name, constraint in sorted(self.constraint.iteritems()):
            constraint.info()

    def fit(self):
        pdfs = RooArgList()
        obsvars = RooArgSet('set')
        for constraint in self.constraint.values():
            pdfs.add(constraint.pdf_constraint)
            if hasattr(constraint, 'var_obs'):
                obsvars.add(constraint.var_obs)
        self.model = RooProdPdf('model', 'model', pdfs)
        self.data = RooDataSet('data', 'data', obsvars)
        self.data.add(obsvars)
        self.data.Print()
        self.fit_result = self.model.fitTo(self.data,
                                           ROOT.RooFit.PrintLevel(3),
                                           ROOT.RooFit.Optimize(1),
                                           ROOT.RooFit.Hesse(1),
                                           ROOT.RooFit.Minos(1),
                                           ROOT.RooFit.Strategy(2),
                                           ROOT.RooFit.Save(1))

    def canvas(self, name, *args):
        canvas = self.canvases.setdefault(name,
                                          ROOT.TCanvas(name, name, *args))
        canvas.cd()
        return canvas

    def keep(self, obj):
        self._keep.append(obj)
        return obj

    def createSummary(self):
        #sample the covariance matrix for the width
        # ROOT.gStyle.SetOptTitle(0)
        ROOT.gStyle.SetStatW(0.4)
        ROOT.gStyle.SetStatH(0.4)

        self.graph_couplings = ROOT.TGraphAsymmErrors(len(self.poi) + 2)

        order_BR = ['Z', 'W', 'b', 'c', 'g', 'tau', 'mu', 'gamma', 'inv']

        for br in order_BR:
            if not self.poi.get(br, None):
                order_BR.remove(br)

        for i, poiname in enumerate(order_BR):
            poi = self.poi.get(poiname)
            self.graph_couplings.SetPoint(i, i + 0.5, poi.getVal())
            self.graph_couplings.SetPointError(i, 0.0, 0.0,
                                               -poi.getAsymErrorLo(),
                                               poi.getAsymErrorHi())

        print 'Sampling the covariance matrix to propagate error on width'

        self.h_width = ROOT.TH1F('h_width', 'width', 1000, 0.5, 1.5)
        ntoys = 10000
        for i in range(ntoys):
            randomizedPars = self.fit_result.randomizePars()
            for j in range(0, randomizedPars.getSize()):
                self.poi[randomizedPars.at(j).GetName()].setVal(
                    randomizedPars.at(j).getVal())
            self.h_width.Fill(self.width.getVal())
            for cstr in self.constraint.values():
                cstr.fill_pull()
        self.graph_couplings.SetMarkerStyle(20)
        self.graph_couplings.SetLineWidth(3)
        can_couplings = self.canvas('couplings')
        self.graph_couplings.Draw("AP")
        self.graph_couplings.GetYaxis().SetTitle("68% CL on d(A) ")
        self.graph_couplings.GetXaxis().SetNdivisions(0)
        l = self.keep(ROOT.TLine())
        l.SetLineColor(ROOT.kRed)
        l.SetLineWidth(3)
        l.DrawLine(0.0, 0.0, len(self.poi) + 1.5, 0)

        self.graph_couplings.SetPoint(len(self.poi), len(self.poi) + 0.5, 0.0)
        self.graph_couplings.SetPointError(
            len(self.poi), 0.0, 0.0,
            self.h_width.GetRMS() / self.h_width.GetMean(),
            self.h_width.GetRMS() / self.h_width.GetMean())

        for i, poiname in enumerate(order_BR + ['#Gamma_{T}']):
            label = self.poilabels.get(poiname, poiname)
            tex = self.keep(
                ROOT.TLatex(i + 0.5,
                            0.95 * self.graph_couplings.GetYaxis().GetXmin(),
                            label))
            tex.Draw()

        print """
###############################################################
###############################################################
###############################################################
                         RESULTS
###############################################################
###############################################################
############################################################### 
              """

        print 'RESULTS FOR THE CONFIDENCE INTERVALS------>'
        for name in order_BR:
            poi = self.poi[name]
            poiLabel = self.poilabels.get(name, name)
            mind = poi.getAsymErrorLo() * 100
            maxd = poi.getAsymErrorHi() * 100
            avd = abs(maxd - mind) / 2.
            # print poiLabel+':   ('+str(poi.getAsymErrorLo())+','+str(poi.getAsymErrorHi())+'), ' + str(avd)
            print '{label:10}:\t{mind:5.3f}%\t{maxd:5.3f}%\t{avd:5.3f}%'.format(
                label=poiLabel, mind=mind, maxd=maxd, avd=avd)

        can_gamma = self.canvas('gamma')
        self.h_width.GetXaxis().SetTitle("#Gamma_{T}")
        self.h_width.GetYaxis().SetTitle("N toys")
        self.h_width.Draw()
        print 'Relative error on the total width ', self.h_width.GetRMS(
        ) / self.h_width.GetMean()
        print 'Please check the histogram to see that the dist is Gaussian. If not the fit is biased'
        print 'The fit can be biased when floating the width sometimes.'

        can_pulls = self.canvas('pulls', 1000, 1000)
        npulls = len(self.constraint)
        nxy = int(math.ceil(math.sqrt(npulls)))
        can_pulls.Divide(nxy, nxy)
        for i, c in enumerate(self.constraint.values()):
            can_pulls.cd(i + 1)
            c.pulls.Draw()
예제 #6
0
class CouplingsFitterTest(object):
    def __init__(self):
        self.poiLabels = []
        self.poi = dict()
        self.poilabels = dict()
        self.constraint = dict()
        self.canvases = dict()
        self._keep = []

    def addPOI(self, poi, label='', minimum=-0.3, maximum=0.3):
        '''Add a parameter of interest.

        Example:
        
        addPOI('Z','Z',-0.05,0.05)
        ->
        Z[0,-0.05,0.05]
        # adds variable Z with value 0,
        # allow it to scale between -0.05 and 0.05
        '''
        self.poi[poi] = ROOT.RooRealVar(poi, poi, 0, minimum, maximum)
        if label == '':
            label = poi
        self.poilabels[poi] = label

    def addConstraint(self, name, expr, deplist, mean, sigma):
        '''Add a constraint on one of the observables
        
        For example, for ZH inclusive: 
        
        f.addConstraint('Zh','(1+Z)*(1+Z)','Z',1,0.004)  

        Z is an additive modification of the gZ coupling w/r to the standard model,
        so 1+Z = \kappa_Z
        
        Zh is the pdf of the ratio of the yield w/r to the one expected in the standard model.
        This pdf depends on Z, as (1+Z)*(1+Z).
        
        ZhObs is the measured value, here 1 so we assume that the SM yield is observed.
        
        The fit varies the parameter of interest Z, thus modifying the pdf,
        while ZhObs is fixed at 1. The likelihood of each value of Z is evaluated at ZhObs on the pdf.
        '''
        deps = self._getdeps(deplist)
        self.constraint[name] = GaussianConstraint(name, expr, deps, mean,
                                                   sigma)

    def _getdeps(self, deplist):
        depnames = deplist
        try:
            depnames = deplist.split(',')
        except:
            pass
        deps = []
        for dep in depnames:
            if dep == 'width':
                deps.append(self.width)
            else:
                deps.append(self.poi[dep])
        return deps

    def addUniformConstraint(self, name, expr):
        '''Adds a uniform constraint with pdf name, and expression expr.
        
        For example:
        
        f.addPOI('inv','inv', 0, 0.01)
        f.addUniformConstraint('Zhinv','inv') ####->Means free floating

        inv (the invisible BR) is free to float between 0 and 1%
        '''
        deps = self._getdeps([expr])
        self.constraint[name] = UniformConstraint(name, expr, deps)

    def info(self):
        for name, constraint in sorted(self.constraint.iteritems()):
            constraint.info()

    def fit(self):
        pdfs = RooArgList()
        obsvars = RooArgSet('set')
        for constraint in self.constraint.values():
            pdfs.add(constraint.pdf_constraint)
            if hasattr(constraint, 'var_obs'):
                obsvars.add(constraint.var_obs)
        self.model = RooProdPdf('model', 'model', pdfs)
        self.data = RooDataSet('data', 'data', obsvars)
        self.data.add(obsvars)
        self.data.Print()
        self.fit_result = self.model.fitTo(self.data,
                                           ROOT.RooFit.PrintLevel(3),
                                           ROOT.RooFit.Optimize(1),
                                           ROOT.RooFit.Hesse(1),
                                           ROOT.RooFit.Minos(1),
                                           ROOT.RooFit.Strategy(2),
                                           ROOT.RooFit.Save(1))

    def canvas(self, name, *args):
        canvas = self.canvases.setdefault(name,
                                          ROOT.TCanvas(name, name, *args))
        canvas.cd()
        return canvas

    def keep(self, obj):
        self._keep.append(obj)
        return obj

    def createSummary(self):
        #sample the covariance matrix for the width
        # ROOT.gStyle.SetOptTitle(0)
        ##        ROOT.gStyle.SetStatW(0.4);
        ##        ROOT.gStyle.SetStatH(0.4);
        ##
        ##        self.graph_couplings = ROOT.TGraphAsymmErrors(len(self.poi)+2)
        ##
        ##        order_BR = ['Z', 'W', 'b', 'c', 'g', 'tau', 'mu', 'gamma', 'inv']
        ##
        ##        for br in order_BR:
        ##            if not self.poi.get(br, None):
        ##                order_BR.remove(br)
        ##
        ##        for i, poiname in enumerate(order_BR):
        ##            poi = self.poi.get(poiname)
        ##            self.graph_couplings.SetPoint(i, i+0.5, poi.getVal())
        ##            self.graph_couplings.SetPointError(i, 0.0, 0.0, -poi.getAsymErrorLo(), poi.getAsymErrorHi())

        print 'Sampling the covariance matrix to propagate error on width'

        ##        self.h_width = ROOT.TH1F('h_width','width',1000,0.5,1.5)
        ntoys = 10000
        for i in range(ntoys):
            randomizedPars = self.fit_result.randomizePars()
            for j in range(0, randomizedPars.getSize()):
                self.poi[randomizedPars.at(j).GetName()].setVal(
                    randomizedPars.at(j).getVal())
##            self.h_width.Fill(self.width.getVal())
##            for cstr in self.constraint.values():
##                cstr.fill_pull()
##        self.graph_couplings.SetMarkerStyle(20)
##        self.graph_couplings.SetLineWidth(3)
##        can_couplings = self.canvas('couplings')
##        self.graph_couplings.Draw("AP")
##        self.graph_couplings.GetYaxis().SetTitle("68% CL on d(A) ")
##        self.graph_couplings.GetXaxis().SetNdivisions(0)
##        l= self.keep(ROOT.TLine())
##        l.SetLineColor(ROOT.kRed)
##        l.SetLineWidth(3)
##        l.DrawLine(0.0,0.0,len(self.poi)+1.5,0)

##        self.graph_couplings.SetPoint(len(self.poi),len(self.poi)+0.5,0.0)
##        self.graph_couplings.SetPointError(len(self.poi),0.0,0.0,self.h_width.GetRMS()/self.h_width.GetMean(),
##                            self.h_width.GetRMS()/self.h_width.GetMean())
##
##        for i, poiname in enumerate(order_BR+['#Gamma_{T}']):
##            label = self.poilabels.get(poiname, poiname)
##            tex = self.keep(ROOT.TLatex(i+0.5,0.95*self.graph_couplings.GetYaxis().GetXmin(),label))
##            tex.Draw()
##
        print """
###############################################################
###############################################################
###############################################################
                         RESULTS
###############################################################
###############################################################
############################################################### 
              """

        print 'RESULTS FOR THE CONFIDENCE INTERVALS------>'
        for name in self.poi:
            poi = self.poi[name]
            poiLabel = self.poilabels.get(name, name)
            mind = poi.getAsymErrorLo() * 100
            maxd = poi.getAsymErrorHi() * 100
            avd = abs(maxd - mind) / 2.
            # print poiLabel+':   ('+str(poi.getAsymErrorLo())+','+str(poi.getAsymErrorHi())+'), ' + str(avd)
            print '{label:10}:\t{mind:5.3f}%\t{maxd:5.3f}%\t{avd:5.3f}%'.format(
                label=poiLabel, mind=mind, maxd=maxd, avd=avd)
예제 #7
0
def load_set(array, var, dataset):
    for entry in array:
        RooAbsRealLValue.__assign__(var, entry)
        dataset.add(RooArgSet(var))
    return dataset


m = RooRealVar("Jpsi_M", "mass", fit_range[0], fit_range[1])
data_m = RooDataSet("data_m", "data_m", RooArgSet(m))
data_u = RooDataSet("data_u", "data_u", RooArgSet(m))

data_m = load_set(tot_m, m, data_m)
data_u = load_set(tot_u, m, data_u)

data_m.Print("v")
data_u.Print("v")

sample = RooCategory("sample", "sample")
sample.defineType("matched")
sample.defineType("unmatched")

# define the combined set
combData = RooDataSet(
    "combData",
    "combined data",
    RooArgSet(m),
    RooFit.Index(sample),
    RooFit.Import(
        "matched",
        data_m),
예제 #8
0
def rooFit102():

    print ">>> import TH1 into RooDataHist..."
    hist = makeTH1()
    x = RooRealVar("x", "x", -10, 10)
    data_hist = RooDataHist("data_hist", "data_hist", RooArgList(x),
                            Import(hist))

    print ">>> plot and fit RooDataHist...\n"
    mean = RooRealVar("mean", "mean of gaussian", 1, -10, 10)
    sigma = RooRealVar("sigma", "width of gaussian", 1, 0.1, 10)
    gauss = RooGaussian("gauss", "gaussian PDF", x, mean, sigma)
    gauss.fitTo(data_hist)
    frame1 = x.frame(Title("Imported TH1 with Poisson error bars"))  # RooPlot
    data_hist.plotOn(frame1)
    gauss.plotOn(frame1)

    print "\n>>> plot and fit RooDataHist with internal errors..."
    # If histogram has custom error (i.e. its contents is does not originate from a
    # Poisson process but e.g. is a sum of weighted events) you can create data with
    # symmetric 'sum-of-weights' error instead (i.e. same error bars as shown by ROOT)
    frame2 = x.frame(Title("Imported TH1 with internal errors"))
    data_hist.plotOn(frame2, DataError(RooAbsData.SumW2))
    gauss.plotOn(frame2)

    # Please note that error bars shown (Poisson or SumW2) are for visualization only,
    # the are NOT used in a maximum likelihood (ML) fit
    #
    # A (binned) ML fit will ALWAYS assume the Poisson error interpretation of data
    # (the mathematical definition  of likelihood does not take any external definition
    # of errors). Data with non-unit weights can only be correctly fitted with a chi^2
    # fit (see rf602_chi2fit.C)

    print ">>> import TTree into RooDataHist..."
    # Construct unbinned dataset importing tree branches x and y matching between
    # branches and RooRealVars is done by name of the branch/RRV
    #
    # Note that ONLY entries for which x,y have values within their allowed ranges as
    # defined in RooRealVar x and y are imported. Since the y values in the import tree
    # are in the range [-15,15] and RRV y defines a range [-10,10] this means that the
    # RooDataSet below will have less entries than the TTree 'tree'
    tree = makeTTree()
    px = RooRealVar("px", "px", -10, 10)
    py = RooRealVar("py", "py", -10, 10)
    data_set = RooDataSet("data_set", "data_set", RooArgSet(px, py),
                          Import(tree))
    data_set.Print()
    frame3 = py.frame(Title("Unbinned data shown in default frame binning"))
    frame4 = py.frame(Title("Unbinned data shown with custom binning"))
    data_set.plotOn(frame3)  # default frame binning of 100 bins
    data_set.plotOn(frame4, Binning(20))  # custom binning choice

    print ">>> draw pfds and fits on canvas..."
    canvas = TCanvas("canvas", "canvas", 100, 100, 1000, 1200)
    canvas.Divide(2, 2)
    for i, frame in enumerate([frame1, frame2, frame3, frame4], 1):
        canvas.cd(i)
        gPad.SetLeftMargin(0.15)
        gPad.SetRightMargin(0.05)
        frame.GetYaxis().SetTitleOffset(1.6)
        frame.GetYaxis().SetLabelOffset(0.010)
        frame.GetYaxis().SetTitleSize(0.045)
        frame.GetYaxis().SetLabelSize(0.042)
        frame.GetXaxis().SetTitleSize(0.045)
        frame.GetXaxis().SetLabelSize(0.042)
        frame.Draw()
    canvas.SaveAs("rooFit102.png")
예제 #9
0
 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"
 WpJfiles = getattr(pars, 'WpJFiles')
 WpJtoymodels = [-1]
 WpJPdf = fitter.makeComponentPdf('WpJtoy', WpJfiles, WpJtoymodels)
 WpJtoymc = RooDataSet()
 WpJtoymc = WpJPdf.generate(fitter.ws.set('obsSet'), opts.extWpJ,
                            RooFit.Name('data_obs'))
 WpJtoymc.Print()
 gentoymc.append(WpJtoymc)
 print "Generating ", opts.extZpJ, " ZpJ events"
 ZpJfiles = getattr(pars, 'ZpJFiles')
 ZpJtoymodels = [-1]
 ZpJPdf = fitter.makeComponentPdf('ZpJtoy', ZpJfiles, ZpJtoymodels)
 ZpJtoymc = RooDataSet()
 ZpJtoymc = ZpJPdf.generate(fitter.ws.set('obsSet'), opts.extZpJ,
                            RooFit.Name('data_obs'))
 ZpJtoymc.Print()
 gentoymc.append(ZpJtoymc)
 print "Generating ", opts.exttop, " top events"
 topfiles = getattr(pars, 'topFiles')
 toptoymodels = [-1]
 topPdf = fitter.makeComponentPdf('toptoy', topfiles, toptoymodels)
 toptoymc = RooDataSet()
예제 #10
0
canvas = TCanvas('canvas', 'canvas', 800, 600)

## variables
if originSuffix == 'MC':
    weight = RooRealVar('weight', 'weight', -1e9, 1e9)  # MC
else:
    weight = RooRealVar('N_Bs_sw', 'weight', -1e9, 1e9)  # data

time = RooRealVar('Bs_ct', 'B_{s} decay time [ps]', 0.3, 15.0)
bins = 50
time.setBins(bins)
time.setBins(bins * 3, 'cache')

ds = RooDataSet('ds', 'ds', RooArgSet(time, weight), RooFit.Import(tree),
                RooFit.WeightVar(weight))
ds.Print("v")

gamma = RooRealVar('gamma', 'gamma', 0.661)
dGamma = RooRealVar('dGamma', 'dGamma', -0.106)
dM = RooRealVar('dM', 'dM', 17.768)
one = const(1.)
zero = const(0.)
tau = Inverse('tau', 'tau', gamma)
# tauk = Inverse('tauk', 'tauk', kgamma)

## acceptance
spline_knots = [0.5, 1.0, 1.5, 2.0, 3.0, 12.0]
spline_coeffs = [
    4.51762e-01, 7.30942e-01, 1.19231e+00, 1.34329e+00, 1.60870e+00,
    1.55630e+00
]