elif opt == '-n': 
            configMgr.nTOYs = int(arg)
        elif opt == '-c': 
            configMgr.calculatorType = int(arg)       
        elif opt == '-i':
            runInterpreter = True
        elif opt == '-v':
            configMgr.setVerbose( int(arg) )
        elif opt == '-l':
            printLimits = True
        elif opt == '-p':
            doHypoTests = True
        elif opt == '-s':
            configMgr.toySeedSet = True
            configMgr.toySeed = int(arg)
            RooRandom.randomGenerator().SetSeed(int(arg))
        elif opt == '-a':
            configMgr.useAsimovSet = True
        elif opt == '-g':
            sigSamples = arg.split(',')
        elif opt == '-x':
            fixSigXSec = True

        pass
    gROOT.SetBatch(not runInterpreter)


    if configMgr.calculatorType == 2:
        configMgr.nTOYs = -1

    
Exemple #2
0
    )
# safe settings for numerical integration (if needed)
RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-9)
RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-9)
RooAbsReal.defaultIntegratorConfig().getConfigSection(
    'RooAdaptiveGaussKronrodIntegrator1D').setCatLabel('method','15Points')
RooAbsReal.defaultIntegratorConfig().getConfigSection(
    'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')
RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')

# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# start building the fit
from B2DXFitters.WS import WS

ws = RooWorkspace('ws')
one = WS(ws, RooConstVar('one', '1', 1.0))
zero = WS(ws, RooConstVar('zero', '0', 0.0))

# start by defining observables
time = WS(ws, RooRealVar('time', 'time [ps]', 0.2, 15.0))
qf = WS(ws, RooCategory('qf', 'final state charge'))
qf.defineType('h+', +1)
qf.defineType('h-', -1)
qt = WS(ws, RooCategory('qt', 'tagging decision'))
        print "\nr0=GenerateFitAndPlot(configMgr.topLvls[0])"
        print "r1=GenerateFitAndPlot(configMgr.topLvls[1])"
        print "r2=GenerateFitAndPlot(configMgr.topLvls[2])"
        pass
    
    if printLimits:
        configMgr.cppMgr.doUpperLimitAll()
        #for tl in configMgr.topLvls:
        #    GetLimits(tl,f)
        #    pass
        
        pass

    if doHypoTests:
        configMgr.cppMgr.doHypoTestAll()
        pass

    if configMgr.nTOYs>0 and doHypoTests==False and printLimits==False and runFit==False:
        RooRandom.randomGenerator().SetSeed( configMgr.toySeed )
        configMgr.cppMgr.runToysAll()
        pass
        
    if runInterpreter:
        from code import InteractiveConsole
        from ROOT import Util
        cons = InteractiveConsole(locals())
        cons.interact("Continuing interactive session... press Ctrl+d to exit")
        pass

    print "Leaving HistFitter... Bye!"
def GenerateFitAndPlot(tl):
    from ROOT import Util
    from ROOT import RooExpandedFitResult
    print "\n***GenerateFitAndPlot for TopLevelXML %s***\n"%tl.name

    w = Util.GetWorkspaceFromFile(tl.wsFileName,"combined")
    Util.SaveInitialSnapshot(w)
    #   Util.ReadWorkspace(w, tl.wsFileName,"combined")

    plotChannels = ""
    for reg in tl.validationChannels:
        if len(plotChannels)>0:
            plotChannels+=","
            pass
        plotChannels+=reg
    plotChannels = "ALL"

    fitChannels = ""
    for reg in tl.bkgConstrainChannels:
        if len(fitChannels)>0:
            fitChannels+=","
            pass
        fitChannels+=reg
        pass

    fitChannelsCR = fitChannels
    for reg in tl.signalChannels:
        if len(fitChannels)>0:
            fitChannels+=","
            pass
        fitChannels+=reg
    #fitChannels = "ALL"

    lumiConst = not tl.signalSample

    # fit toy MC if specified. When left None, data is fit by default
    toyMC = None
    if configMgr.toySeedSet and not configMgr.useAsimovSet:    # generate a toy dataset
        print "INFO : generating toy MC set for fitting and plotting. Seed = %i" % configMgr.toySeed
        RooRandom.randomGenerator().SetSeed( configMgr.toySeed )
        toyMC = Util.GetToyMC() # this generates one toy dataset
        pass
    elif configMgr.useAsimovSet and not configMgr.toySeedSet:  # 
        print "INFO : using Asimov set for fitting and plotting."
        toyMC = Util.GetAsimovSet(w) # this returns the asimov set
        pass
    else:
        print "INFO : using data for fitting and plotting."

    ## MB : turn on all JES bins. Some are turned off by HistFactory by default
    if True:
        if w.var("gamma_J3_bin_0")!=None: w.var("gamma_J3_bin_0").setConstant(False)
        if w.var("gamma_J3_bin_1")!=None: w.var("gamma_J3_bin_1").setConstant(False)
        if w.var("gamma_J3_bin_2")!=None: w.var("gamma_J3_bin_2").setConstant(False)
        if w.var("gamma_J3_bin_3")!=None: w.var("gamma_J3_bin_3").setConstant(False)
        if w.var("gamma_J3_bin_4")!=None: w.var("gamma_J3_bin_4").setConstant(False)
        if w.var("gamma_J3_bin_5")!=None: w.var("gamma_J3_bin_5").setConstant(False)
        #if w.var("gamma_J4_bin_0")!=None: w.var("gamma_J4_bin_0").setConstant(False)
        #if w.var("gamma_J4_bin_1")!=None: w.var("gamma_J4_bin_1").setConstant(False)
        if w.var("gamma_J4_bin_2")!=None: w.var("gamma_J4_bin_2").setConstant(False)
        if w.var("gamma_J4_bin_3")!=None: w.var("gamma_J4_bin_3").setConstant(False)
        if w.var("gamma_J4_bin_4")!=None: w.var("gamma_J4_bin_4").setConstant(False)
        if w.var("gamma_J4_bin_5")!=None: w.var("gamma_J4_bin_5").setConstant(False)
        if w.var("gamma_JC_bin_0")!=None: w.var("gamma_JC_bin_0").setConstant(False)
        if w.var("gamma_JC_bin_1")!=None: w.var("gamma_JC_bin_1").setConstant(False)
        if w.var("gamma_JC_bin_2")!=None: w.var("gamma_JC_bin_2").setConstant(False)
        if w.var("gamma_JC_bin_3")!=None: w.var("gamma_JC_bin_3").setConstant(False)
        if w.var("gamma_JC_bin_4")!=None: w.var("gamma_JC_bin_4").setConstant(False)
        if w.var("gamma_JC_bin_5")!=None: w.var("gamma_JC_bin_5").setConstant(False)
        if w.var("gamma_JC_bin_6")!=None: w.var("gamma_JC_bin_6").setConstant(False)
        # Soft lepton
    #    if w.var("gamma_JSS_bin_0")!=None: w.var("gamma_JSS_bin_0").setConstant(False)

    # set Errors of all parameters to 'natural' values before plotting/fitting

    Util.resetAllErrors(w)
    mu_Top = w.var("mu_Top")
    print "mu_Top: "
    print mu_Top
    if mu_Top:
        mu_Top.setError(0.001)
    else:
        mu_Top = w.var("mu_Top_Np0")
        if mu_Top:
            mu_Top.setError(0.001)
        mu_Top = w.var("mu_Top_Np1")
        if mu_Top:
            mu_Top.setError(0.001)
        mu_Top = w.var("mu_Top_Np2")
        if mu_Top:
            mu_Top.setError(0.001)
        mu_Top = w.var("mu_Top_Np3")
        if mu_Top:
            mu_Top.setError(0.001)
        mu_Top = w.var("mu_Top_Np4")
        if mu_Top:
            mu_Top.setError(0.001)
        mu_Top = w.var("mu_Top_Np5")
        if mu_Top:
            mu_Top.setError(0.001)
    mu_WZ = w.var("mu_WZ")
    mu_WZpT0GeV   = w.var("mu_WZpT0GeV")
    if mu_WZ:
        mu_WZ.setError(0.001)
    elif mu_WZpT0GeV:
        mu_WZpT0GeV = w.var("mu_WZpT0GeV")
        mu_WZpT0GeV.setError(0.001)
        mu_WZpT0GeV = w.var("mu_WZpT50GeV")
        mu_WZpT0GeV.setError(0.001)
        mu_WZpT0GeV = w.var("mu_WZpT100GeV")
        mu_WZpT0GeV.setError(0.001)
        mu_WZpT0GeV = w.var("mu_WZpT150GeV")
        mu_WZpT0GeV.setError(0.001)
        mu_WZpT0GeV = w.var("mu_WZpT200GeV")
        mu_WZpT0GeV.setError(0.001)
        mu_WZpT0GeV = w.var("mu_WZpT250GeV")
        mu_WZpT0GeV.setError(0.001)
    else:
        mu_WZ = w.var("mu_WZ_Np0")
        mu_WZ.setError(0.001)
        mu_WZ = w.var("mu_WZ_Np1")
        mu_WZ.setError(0.001)
        mu_WZ = w.var("mu_WZ_Np2")
        mu_WZ.setError(0.001)
        mu_WZ = w.var("mu_WZ_Np3")
        mu_WZ.setError(0.001)
        mu_WZ = w.var("mu_WZ_Np4")
        mu_WZ.setError(0.001)
        mu_WZ = w.var("mu_WZ_Np5")
        mu_WZ.setError(0.001)
    
    # set the flag for plotting ratio or pull distribution under the plot
    plotRatio = True  # plotRatio = False means that a pull distribution will be drawn

    # get a list of all floating parameters for all regions
    simPdf = w.pdf("simPdf");
    mc  = Util.GetModelConfig(w)
    obsSet = mc.GetObservables()
    floatPars = Util.getFloatParList(simPdf, obsSet)
    # create an RooExpandedFitResult encompassing all the regions/parameters & save it to workspace
    expResultBefore = RooExpandedFitResult(floatPars)
    #    expResultBefore.Print()
    Util.ImportInWorkspace(w,expResultBefore,"RooExpandedFitResult_beforeFit")
    # plot before fit
    #Util.PlotPdfWithComponents(w,tl.name,plotChannels,"beforeFit_ORIGINAL",None,toyMC)
    Util.PlotPdfWithComponents(w,tl.name,plotChannels,"beforeFit",expResultBefore,toyMC,plotRatio)
    #return

    # fit of CRs only
    # resultCR = Util.FitPdf(w,fitChannelsCR,lumiConst,toyMC)
    # load original snapshot
    #    w.loadSnapshot('snapshot_paramsVals_initial')
    # fit of all regions
    result = Util.FitPdf(w,fitChannels,lumiConst,toyMC)
    # create an RooExpandedFitResult encompassing all the regions/parameters with the result & save it to workspace
    expResultAfter = RooExpandedFitResult(result, floatPars)
    Util.ImportInWorkspace(w,expResultAfter,"RooExpandedFitResult_afterFit")
    # plot after fit
    #Util.PlotPdfWithComponents(w,tl.name,plotChannels,"afterFit_ORIGINAL",result,toyMC)
    Util.PlotPdfWithComponents(w,tl.name,plotChannels,"afterFit",expResultAfter,toyMC,plotRatio)
    # plot each component of each region separately with propagated error after fit  (interesting for debugging)
    #    Util.PlotSeparateComponents(tl.name,plotChannels,"afterFit",result,toyMC)
    # plot correlation matrix for result
    #Util.PlotCorrelationMatrix(result)
    # Util.GetCorrelations(result, 0.85)
    #     plotPLL = False
    #     Util.PlotNLL(w, result, plotPLL, "", toyMC)
    
    if toyMC:
        Util.WriteWorkspace(w, tl.wsFileName,toyMC.GetName())
    else:
        Util.WriteWorkspace(w, tl.wsFileName)
            
    try:
        if not result == None:
            result.Print()
            return result
    except:
        pass
    return
    RooDataHist, RooMsgService, TStopwatch, RooAbsPdf, TBox, kBlack, kRed, \
    kBlue, kOrange, kDashed, RooAbsCollection, RooArgSet, RooStats, Double, \
    RooAbsReal, RooAbsData, TH1F
import pulls

timer = TStopwatch()
timer.Start()

#RooAbsPdf.defaultIntegratorConfig().setEpsRel(1e-9)
#RooAbsPdf.defaultIntegratorConfig().setEpsAbs(1e-9)
if not opts.debug:
    RooMsgService.instance().setGlobalKillBelow(RooFit.WARNING)

if hasattr(opts, "seed") and (opts.seed >= 0):
    print "random seed:", opts.seed
    RooRandom.randomGenerator().SetSeed(opts.seed)

mvaCutOverride = None
if hasattr(opts, "mvaCut"):
    mvaCutOverride = opts.mvaCut

mjjArgs = []
sideArgs = []
mWWArgs = []
for arg in args:
    if arg[-8:] == '_mjj.txt':
        mjjArgs.append(arg)
    elif arg[-8:] == '_mWW.txt':
        mWWArgs.append(arg)
    else:
        mWWArgs.append(arg)
Exemple #6
0
for channel in channels:
    base_dir = os.path.join(analysis_path,channel)
    study_inputs[channel] = \
                          [prepend + os.path.join(base_dir,sample) for sample in input_mc_samples]
    


import ROOT
from ROOT import RooWorkspace, RooMCStudy, RooFit, TFile, gDirectory,\
     RooDataSet, RooFormulaVar, RooConstVar, RooArgList, RooArgSet,\
     RooMinuit, RooMinimizer, RooRandom
ROOT.gSystem.Load("libUWHiggshzg.so")
pwd = gDirectory.GetPath()

RooRandom.randomGenerator().SetSeed(int(time.clock()*1e9))

int_lumi = 19.6*1000 #19.6/fb in /pb

def calculate_median(var,dataset):
    vals = []
    for i in xrange(dataset.numEntries()):
        set = dataset.get(i)        
        vals.append(set.getRealValue(var.GetName()))
        del set
    vals.sort()
    middle = len(vals)/2
    return vals[middle]

def prepare_truth_models(ws,cat,mass,channel,turnon,truth):    
    if channel in study_inputs:
Exemple #7
0
    def run(self, **kwargs):
        from ROOT import RooArgSet

        __check_req_kw__("Observables", kwargs)
        __check_req_kw__("Pdf", kwargs)
        __check_req_kw__("Sigmat", kwargs)
        __check_req_kw__("Time", kwargs)
        __check_req_kw__("SigmaGen", kwargs)
        sigma_gen = kwargs.pop("SigmaGen")
        observables = kwargs.pop("Observables")
        obs_set = RooArgSet(*observables)

        pdf = kwargs.pop("Pdf")
        sigmat = kwargs.pop("Sigmat")
        time = kwargs.pop("Time")

        gen_obs_set = RooArgSet(*observables)

        # Make another ArgSet to put the fit results in
        result_params = RooArgSet("result_params")

        from P2VV.RooFitWrappers import RealVar

        da = RealVar("da", Observable=True, MinMax=(0.01, 1.1))
        dft = RealVar("dft", Observable=True, MinMax=(0.01, 1.1))
        result_params.add(da._target_())
        result_params.add(dft._target_())

        transform = self.transform()
        if transform:
            trans_params = transform.gen_params(gen_obs_set)
            self._gen_params.extend(trans_params)
            for p in trans_params:
                result_params.add(p)

        # Some extra numbers of interest
        from ROOT import RooRealVar

        seed = RooRealVar("seed", "random seed", 0.0)
        result_params.add(seed)

        # The dataset to store the results
        from ROOT import RooDataSet

        self._data = RooDataSet("result_data", "result_data", result_params)
        data_params = self._data.get()

        from ROOT import RooRandom
        import struct, os

        # Reset pdf parameters to initial values. Note: this does not reset the estimated errors...
        args = dict(NumEvents=self.options().nevents)
        if "ProtoData" in kwargs:
            args["ProtoData"] = kwargs.pop("ProtoData")
        spec = pdf.prepareMultiGen(obs_set, **args)

        while self._data.numEntries() < self.options().ntoys:
            # Get a good random seed, set it and store it
            s = struct.unpack("I", os.urandom(4))[0]
            RooRandom.randomGenerator().SetSeed(s)
            seed.setVal(s)

            data = pdf.generate(spec)
            if self.transform():
                old_data = data
                data = self.transform()(old_data)
                if not data:
                    transform.set_params(data_params)
                    self._data.add(data_params)
                    continue

            from P2VV import Dilution

            d_ft = Dilution.dilution_ft(data, time, t_range=2, quiet=True)
            d_a = Dilution.signal_dilution_dg(data, sigmat, *sigma_gen)
            da.setVal(d_a[0])
            da.setError(d_a[1] if d_a[1] != None else 0.0)
            dft.setVal(d_ft[0])
            dft.setError(d_ft[1] if d_ft[1] != None else 0.0)

            if transform:
                transform.set_params(data_params)

            self._data.add(result_params)

        return self.data()
Exemple #8
0
study_inputs = {}

for channel in channels:
    base_dir = os.path.join(analysis_path, channel)
    study_inputs[channel] = \
                          [prepend + os.path.join(base_dir,sample) for sample in input_mc_samples]

import ROOT
from ROOT import RooWorkspace, RooMCStudy, RooFit, TFile, gDirectory,\
     RooDataSet, RooFormulaVar, RooConstVar, RooArgList, RooArgSet,\
     RooMinuit, RooMinimizer, RooRandom
ROOT.gSystem.Load("libUWHiggshzg.so")
pwd = gDirectory.GetPath()

RooRandom.randomGenerator().SetSeed(int(time.clock() * 1e9))

int_lumi = 19.6 * 1000  #19.6/fb in /pb


def calculate_median(var, dataset):
    vals = []
    for i in xrange(dataset.numEntries()):
        set = dataset.get(i)
        vals.append(set.getRealValue(var.GetName()))
        del set
    vals.sort()
    middle = len(vals) / 2
    return vals[middle]

Exemple #9
0
    pipiUnbPruneDataSet = RooDataSet("pipiUnbPruneDataSet", "pipiUnbPruneDataSet", pipiUnbDataSet, w.set("argsBasic"), "D0_Mass>1826 && D0_Mass<1920")
    pipiUnbPruneDataSet.Print()
  elif config['norm'] is 'kpi':
    pipiFile = TFile(config['kpiFile'],"OPEN")
    normTree = pipiFile.Get("subTree")

    pipiUnbDataSet = RooDataSet("pipiUnbDataSet", "pipiUnbDataSet", normTree, w.set("argsPreCutKPi"), "Del_Mass>139.4 && RAND < %f" % (config["normScale"]))
    pipiUnbDataSet.Print()

    pipiUnbPruneDataSet = RooDataSet("pipiUnbPruneDataSet", "pipiUnbPruneDataSet", pipiUnbDataSet, w.set("argsBasic"), "D0_Mass>1800 && D0_Mass<1920")
    pipiUnbPruneDataSet.Print()


if config['mode'] is "toy":
  print "Setting random seed to 1"
  RooRandom.randomGenerator().SetSeed(1)
  print "Generating dataset 1 ..."
  bdt1UnbToyDataSet = w.obj("BDT1_Comb").generate(w.set("argsBasic"),int(round(toyRatio*bdt1UnbPruneDataSet.numEntries())))
  print "Generating dataset 2 ..."
  bdt2UnbToyDataSet = w.obj("BDT2_Comb").generate(w.set("argsBasic"),int(round(toyRatio*bdt2UnbPruneDataSet.numEntries())))
  print "Generating dataset 3 ..."
  bdt3UnbToyDataSet = w.obj("BDT3_Comb").generate(w.set("argsBasic"),int(round(toyRatio*bdt3UnbPruneDataSet.numEntries())))

  fullUnbDataSet = RooDataSet("fullUnbDataSet",
                              "fullUnbDataSet",
                              w.set("argsBasic"),
                              RooFit.Index(w.cat("DataSet")),
                              RooFit.Import("BDT1",bdt1UnbToyDataSet),
                              RooFit.Import("BDT2",bdt2UnbToyDataSet),
                              RooFit.Import("BDT3",bdt3UnbToyDataSet),
                              RooFit.Import("Norm",pipiUnbPruneDataSet))
Exemple #10
0
    def run(self, **kwargs):
        from ROOT import RooArgSet

        __check_req_kw__("Observables", kwargs)
        __check_req_kw__("Pdf", kwargs)

        observables = kwargs.pop("Observables")
        obs_set = RooArgSet(*observables)

        pdf = kwargs.pop("Pdf")
        genPdf = kwargs.pop("GenPdf", pdf)

        gen_obs_set = RooArgSet()
        for o in list(observables) + list(genPdf.ConditionalObservables()):
            gen_obs_set.add(o._target_())
        gen_pdf_params = genPdf.getParameters(gen_obs_set).snapshot(True)

        genPdf = genPdf.clone(genPdf.GetName() + "_toy_clone")
        genPdf.recursiveRedirectServers(gen_pdf_params)

        fit_obs_set = RooArgSet()
        for o in list(observables) + list(pdf.ConditionalObservables()):
            fit_obs_set.add(o._target_())
        params = pdf.getParameters(fit_obs_set)

        pdf_params = RooArgSet()
        for p in params:
            if p.isConstant():
                continue
            pdf_params.add(p)
        ## for param in pdf_params:
        ##     if param.GetName() not in ['Gamma', 'dGamma']:
        ##         param.setConstant()
        self._gen_params = pdf_params.snapshot(True)

        # Make another ArgSet to put the fit results in
        result_params = RooArgSet(pdf_params, "result_params")

        transform = self.transform()
        if transform:
            trans_params = transform.gen_params(gen_obs_set)
            for p in trans_params:
                result_params.add(p)

        # Some extra numbers of interest
        from ROOT import RooRealVar

        NLL = RooRealVar("NLL", "-log(Likelihood)", 1.0)
        ngen = RooRealVar("ngen", "number of generated events", self.options().nevents)
        seed = RooRealVar("seed", "random seed", 0.0)
        from ROOT import RooCategory

        status = RooCategory("status", "fit status")
        status.defineType("success", 0)
        status.defineType("one", 1)
        status.defineType("two", 2)
        status.defineType("three", 3)
        status.defineType("other", 4)
        result_params.add(status)
        result_params.add(NLL)
        result_params.add(ngen)
        result_params.add(seed)

        # The dataset to store the results
        from ROOT import RooDataSet

        self._data = RooDataSet("result_data", "result_data", result_params)
        data_params = self._data.get()

        from ROOT import RooRandom
        import struct, os

        while self._data.numEntries() < self.options().ntoys:
            # Get a good random seed, set it and store it
            s = struct.unpack("I", os.urandom(4))[0]
            RooRandom.randomGenerator().SetSeed(s)
            seed.setVal(s)

            # Reset pdf parameters to initial values. Note: this does not reset the estimated errors...
            pdf_params.assignValueOnly(self.gen_params())
            args = dict(NumEvents=self.options().nevents)
            if "ProtoData" in kwargs:
                args["ProtoData"] = kwargs.pop("ProtoData")

            genPdf.getParameters(obs_set).assignValueOnly(gen_pdf_params)
            data = genPdf.generate(obs_set, **args)
            if transform:
                data = transform(data)
                if not data:
                    # Transform has failed
                    transform.set_params(data_params)
                    self._data.add(data_params)
                    continue

            if data.isWeighted() and "SumW2Error" not in self.fit_opts():
                self.fit_opts()["SumW2Error"] = False

            j = 0
            while j < 4:
                fit_result = pdf.fitTo(data, NumCPU=self.options().ncpu, **(self.fit_opts()))
                if fit_result.status() == 0:
                    fit_result.Print()
                    break
                j += 1
            if fit_result.status() != 0:
                print "Fit result status = %s" % fit_result.status()
            NLL.setVal(fit_result.minNll())
            if fit_result.status() < 4:
                status.setIndex(fit_result.status())
            else:
                status.setIndex(4)
            for result_param in result_params:
                data_param = data_params.find(result_param.GetName())
                if isinstance(result_param, RooCategory):
                    data_param.setIndex(result_param.getIndex())
                else:
                    data_param.setVal(result_param.getVal())
                    # This sets a symmetric error, but since we don't run Minos, that's ok
                    data_param.setError(result_param.getError())
            if transform:
                transform.set_params(data_params)

            self._data.add(data_params)

        return self.data()
Exemple #11
0
        elif opt == '-n':
            configMgr.nTOYs = int(arg)
        elif opt == '-c':
            configMgr.calculatorType = int(arg)
        elif opt == '-i':
            runInterpreter = True
        elif opt == '-v':
            configMgr.setVerbose(int(arg))
        elif opt == '-l':
            printLimits = True
        elif opt == '-p':
            doHypoTests = True
        elif opt == '-s':
            configMgr.toySeedSet = True
            configMgr.toySeed = int(arg)
            RooRandom.randomGenerator().SetSeed(int(arg))
        elif opt == '-a':
            configMgr.useAsimovSet = True
        elif opt == '-g':
            sigSamples = arg.split(',')
        elif opt == '-x':
            fixSigXSec = True

        pass
    gROOT.SetBatch(not runInterpreter)

    if configMgr.calculatorType == 2:
        configMgr.nTOYs = -1

    print "------------------------ Now running hypo test :"
    print "calculatorType : ", configMgr.calculatorType
# print parameters
print 120 * '='
print 'genBs2JpsiKKSignal: observables in PDF:'
pdfObs.Print('v')
print 'genBs2JpsiKKSignal: parameters in PDF:'
pdfPars.Print('v')


###########################################################################################################################################
## generate data ##
###################

# set seed of RooFit random-number generator
from ROOT import RooRandom
RooRandom.randomGenerator().SetSeed(args.jobID)

# get observables to generate and create prototype dataset
genObsSet = [ ws[var] for var in [ 'time', 'helcosthetaK', 'helcosthetaL', 'helphi' ] ]
condObsSet = [ var for var in inputData.get() if not any( var.GetName() == genVar.GetName() for genVar in genObsSet ) ]
if condObsSet :
    protoData = inputData.reduce( ArgSet = condObsSet )
    #protoData = protoData.reduce( Cut = 'hlt1_excl_biased==1' )
    print 'genBs2JpsiKKSignal: proto-data set:'
    protoData.Print()
else :
    protoData = inputData

# set maximum value of PDF function
from P2VV.RooFitWrappers import SimultaneousPdf
if isinstance( pdf, SimultaneousPdf ) :
Exemple #13
0
momsW.initCovariances()

# initialize variables for calculation of covariances
covs  = dict( [ ( name1, dict( [ ( name2, 0. ) for name2 in funcNames ] ) ) for name1 in funcNames ] )
covsW = dict( [ ( name1, dict( [ ( name2, 0. ) for name2 in funcNames ] ) ) for name1 in funcNames ] )

# generate data and compute moments in loop
import sys
from ROOT import RooRandom
for it in range(nIters) :
    if it % 100 == 0 :
        print 'iteration %d' % it
        sys.stdout.flush()

    # generate data with (1 + x) / 2
    RooRandom.randomGenerator().SetSeed( 100000 + it )
    noWeightData.reset()
    weightData.reset()
    for evIt in range(nEvents) :
        weight = RooRandom.uniform()
        obs.setVal( 2. * weight - 1. )
        if RooRandom.uniform() <= weight :
            noWeightData.add(obsSet)
        weightData.add( obsSet, weight )

    # compute moments of functions
    moms.compute(  noWeightData, ResetFirst = True, Verbose = False )
    momsW.compute( weightData,   ResetFirst = True, Verbose = False )

    # update covariance sums
    momCoefs  = moms.coefficients()
        log.info("Python commands executed: %s" % HistFitterArgs.cmd)
        exec(HistFitterArgs.cmd) ## python execute

    gROOT.SetBatch(not runInterpreter)

    """
    mandatory user-defined configuration file
    """
    execfile(HistFitterArgs.configFile[0]) #[0] since any extra arguments (sys.argv[-1], etc.) are caught here

    """
    standard execution from now on
    """
    configMgr.initialize()

    RooRandom.randomGenerator().SetSeed(configMgr.toySeed)

    ReduceCorrMatrix = configMgr.ReduceCorrMatrix

    """
    runs Trees->histos and/or histos->workspace according to specifications
    """
    if configMgr.readFromTree or configMgr.executeHistFactory:
        if doCodeProfiling:
            import cProfile
            cProfile.run('configMgr.executeAll()')
        else:
            configMgr.executeAll()

    """
    shows systematics
Exemple #15
0
    )
# safe settings for numerical integration (if needed)
RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-9)
RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-9)
RooAbsReal.defaultIntegratorConfig().getConfigSection(
    'RooAdaptiveGaussKronrodIntegrator1D').setCatLabel('method','15Points')
RooAbsReal.defaultIntegratorConfig().getConfigSection(
    'RooAdaptiveGaussKronrodIntegrator1D').setRealValue('maxSeg', 1000)
RooAbsReal.defaultIntegratorConfig().method1D().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')
RooAbsReal.defaultIntegratorConfig().method1DOpen().setLabel(
    'RooAdaptiveGaussKronrodIntegrator1D')

# seed the Random number generator
rndm = TRandom3(SEED + 1)
RooRandom.randomGenerator().SetSeed(int(rndm.Uniform(4294967295)))
del rndm

# as things become more complicated, it's useful to have "build-it-all"
# routine, which works for both generation and fitting; this also allows for
# easier setups of scenarios where you build with one pdf and fit with a
# different one (e.g. per-event mistag in generation, average in fit to see
# the gain in sensitivity from the per-event mistag)
def buildTimePdf(config):
    """
    build time pdf, return pdf and associated data in dictionary
    """
    from B2DXFitters.WS import WS
    print 'CONFIGURATION'
    for k in sorted(config.keys()):
        print '    %32s: %32s' % (k, config[k])
Exemple #16
0
config = __import__(opts.modeConfig)
import RooWjj2DFitter

from ROOT import TCanvas, RooFit, RooLinkedListIter, TMath, RooRandom, TFile, \
    RooDataHist, RooMsgService, TStopwatch
import pulls

timer = TStopwatch()
timer.Start()

if not opts.debug:
    RooMsgService.instance().setGlobalKillBelow(RooFit.WARNING)

if hasattr(opts, "seed") and (opts.seed >= 0):
    print "random seed:", opts.seed
    RooRandom.randomGenerator().SetSeed(opts.seed)
pars = config.theConfig(Nj=opts.Nj,
                        mH=opts.mH,
                        isElectron=opts.isElectron,
                        initFile=args,
                        includeSignal=opts.includeSignal)

fitter = RooWjj2DFitter.Wjj2DFitter(pars)

totalPdf = fitter.makeFitter()

if opts.ws:
    fitter.loadWorkspaceFromFile(opts.ws, getFloatPars=opts.reuse)

#fitter.loadData()
fitter.readParametersFromFile()
Exemple #17
0
def makeTree(outFile_name, cuts, fittedVariable):

    rootupla_Chib1_Sel = '../../store/ChiB_1P_1_Upsilon2SPt.root'
    rootupla_Chib2_Sel = '../../store/ChiB_1P_2_Upsilon2SPt.root'
    rootupla_2012Data = "../../store/2012_AllData.root"

    mass_chib1_1P =  9.89278
    mass_chib2_1P =  9.91221
   

    rootFile = TFile(outFile_name, 'recreate')
    tree = TTree('numChib', 'tree with number of chibs')

    numChib1 = array('i', [0])
    numChib2 = array('i', [0])
    ratio = array('d', [0])
    
    mean1 = array('d', [0])
    sigma1 = array('d', [0])
    a1_1 = array('d', [0])
    a2_1 = array('d', [0])
        
    mean2 = array('d', [0])
    sigma2 = array('d', [0])
    a1_2 = array('d', [0])
    a2_2 = array('d', [0])
        
    reducedChi2 = array('d', [0])
    
    

    tree.Branch('numChib1', numChib1, 'numChib1/I')
    tree.Branch('numChib2', numChib2, 'numChib2/I')
    tree.Branch('ratio', ratio, 'ratio/D')

    tree.Branch('mean1', mean1, 'mean1/D')
    tree.Branch('sigma1', sigma1, 'sigma1/D')
    tree.Branch('a1_1', a1_1, 'a1_1/D')
    tree.Branch('a2_1', a2_1, 'a2_1/D')
    

    tree.Branch('mean2', mean2, 'mean2/D')
    tree.Branch('sigma2', sigma2, 'sigma2/D')
    tree.Branch('a1_2', a1_2, 'a1_2/D')
    tree.Branch('a2_2', a2_2, 'a2_2/D')
    
    tree.Branch('reducedChi2', reducedChi2, 'reducedChi2/D')

    

    Chib1_fitResult = doMCFit(inputfile_name=rootupla_Chib1_Sel, mass_chib=mass_chib1_1P, cuts=cuts, fittedVariable=fittedVariable, returnOnlyFitResult = True)
    Chib2_fitResult = doMCFit(inputfile_name=rootupla_Chib2_Sel, mass_chib=mass_chib2_1P, cuts=cuts, fittedVariable=fittedVariable, returnOnlyFitResult = True)

    # make dataset outside the loop only once to speed up the process
    print "Creating DataSet from file "+str(rootupla_2012Data)
    dataSet = makeRooDataset(rootupla_2012Data)
    RooRandom.randomGenerator().SetSeed(int(time.time()*256))

    for i in range(100):
        print '\nstarting data fit number ' + str(i) + '\n'
        Chib1_listParams = Chib1_fitResult.randomizePars()
        Chib2_listParams = Chib2_fitResult.randomizePars()

        Chib1_parameters = CB_parameters(a1 = Chib1_listParams[0].getVal(),
                                         a2 = Chib1_listParams[1].getVal(),
                                         mean = Chib1_listParams[2].getVal(),
                                         n1 = 2.5,
                                         n2 = 3,
                                         sigma = Chib1_listParams[3].getVal(),
                                         s_sigma = Chib1_listParams[3].getError())

        Chib2_parameters = CB_parameters(a1 = Chib2_listParams[0].getVal(),
                                         a2 = Chib2_listParams[1].getVal(),
                                         mean = Chib2_listParams[2].getVal(),
                                         n1 = 2.5,
                                         n2 = 3,
                                         sigma = Chib2_listParams[3].getVal(),
                                         s_sigma = Chib2_listParams[3].getError())

        numChib, chi2r = doDataFit(RooDataSet = dataSet,Chib1_parameters=Chib1_parameters,Chib2_parameters=Chib2_parameters, cuts=cuts, fittedVariable=fittedVariable, noPlots = True)

        numChib1[0] = int(numChib.numChib1)
        numChib2[0] = int(numChib.numChib2)
        ratio[0] = numChib.calcRatio()
       
        a1_1[0] = Chib1_listParams[0].getVal()
        a2_1[0] = Chib1_listParams[1].getVal()
        mean1[0] = Chib1_listParams[2].getVal()
        sigma1[0] = Chib1_listParams[3].getVal()
        
        a1_2[0] = Chib2_listParams[0].getVal()
        a2_2[0] = Chib2_listParams[1].getVal()
        mean2[0] = Chib2_listParams[2].getVal()
        sigma2[0] = Chib2_listParams[3].getVal()

        reducedChi2[0] = chi2r
        
        tree.Fill()

    rootFile.Write()
    rootFile.Close()