def _convert_rooabsdata_to_th1(x: RooRealVar, roofit_obj: RooAbsData) -> TH1: ''' Convert a RooDataHist into a TH1. Parameters ---------- x : RooRealVar ROOT RooRealVar observable roofit_obj : RooAbsData RooFit dataset Returns ------- TH1 ROOT histogram ''' assert (isinstance(x, RooRealVar) and isinstance(roofit_obj, RooAbsData)) return roofit_obj.createHistogram(x.GetName(), x.getBinning().numBins())
par3GridMin, par3GridMax) newFormatInput = TH3D('bin_content_par1_par2_par3_' + str(i), 'bincontent', nGridPointsForNewF, par1GridMin, par1GridMax, nGridPointsForNewF, par2GridMin, par2GridMax, nGridPointsForNewF, par3GridMin, par3GridMax) if i != len(bins) - 1: binMin = bins[i - 1] binMax = bins[i] if (model == "par1_TH1" or model == "par1_TF1"): sigObj.Draw( par1Name + ' >> theBaseData_' + section + '_' + str(i), # '('+weight.GetName()+'*'+str(efficiencies[i-1])+')'+'*('+cfg.get(section,'obsVar') + # weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # ' > ' + str(binMin) + ' && ' + cfg.get(section, 'obsVar') + ' < ' + str(binMax) + ')', 'goff') elif (model == "par1par2_TH2" or model == "par1par2_TF2"): sigObj.Draw( par2Name + ':' + par1Name + ' >> theBaseData_' + section + '_' + str(i), weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # # '('+weight.GetName()+'/64.4217490480265127)'+'*('+cfg.get(section,'obsVar') + # # '('+weight.GetName()+'*'+efficiencies[i-1]+')'+'*('+cfg.get(section,'obsVar') + # ' > ' + str(binMin) + ' && ' + cfg.get(section, 'obsVar') + ' < ' + str(binMax) + ')', 'goff') elif (model == "par1par2_TH3" or model == "par1par2_TF3"): sigObj.Draw(
int(maxPed - minPed), minPed, maxPed), pedCut, 'goff') ped_hist = gDirectory.Get('ped_hist') ped_hist.SetLineColor(myBlue) xfped = x.frame(minPed, maxPed, int(maxPed - minPed)) if havePeds: pedDS = fillDataSet(dataTree.GetV1(), x, dataTree.GetSelectedRows()) getattr(ws, 'import')(pedDS) if pedDS.numEntries() < 5: havePeds = False else: if opts.sipm: findOnePe(ped_hist, ws, x.GetName()) ws.var('fped').setConstant(True) ws.var('peMean').setConstant(True) else: fitPed(ped_hist, ws, x.GetName()) ws.var('pedMean').setConstant(True) ws.var('pedWidth').setConstant(True) pedDS.plotOn(xfped) if opts.sipm: ws.pdf('pedPlusOne').plotOn(xfped) ws.pdf('pedPlusOne').paramOn(xfped) else: ws.pdf('ped').plotOn(xfped) ws.pdf('ped').paramOn(xfped)
def getCard(sig, ch, ifilename, outdir, mode="histo", unblind=False): try: ifile = ROOT.TFile.Open(ifilename) except IOError: print "Cannot open ", ifilename else: print "Opening file ", ifilename ifile.cd() print syst workdir_ = ifilename.split("/")[:-1] WORKDIR = "/".join(workdir_) + "/" carddir = outdir + "/" + sig + "/" hist_filename = os.getcwd() + "/" + ifilename hist = getHist(ch, sig, ifile) #*******************************************************# # # # Generate workspace # # # #*******************************************************# if (mode == "template"): histBkgData = getHist(ch, "Bkg", ifile) histData = histBkgData if (unblind): print "BE CAREFULL: YOU ARE UNBLINDING" histData = getHist(ch, "data_obs", ifile) print "*********Number of data ", histData.Integral() histSig = getHist(ch, sig, ifile) bkgData = RooDataHist("bkgdata", "Data (MC Bkg)", RooArgList(mT), histBkgData, 1.) obsData = RooDataHist("data_obs", "(pseudo) Data", RooArgList(mT), histData, 1.) sigData = RooDataHist("sigdata", "Data (MC sig)", RooArgList(mT), histSig, 1.) print "Bkg Integral: ", histData.Integral() nBkgEvts = histBkgData.Integral() print "Bkg Events: ", nBkgEvts print "Channel: ", ch modelBkg = fitParam[ch].modelBkg normzBkg = RooRealVar(modelBkg.GetName() + "_norm", "Number of background events", nBkgEvts, 0., 1.e3) print "NormBkg ", nBkgEvts modelExt = RooExtendPdf(modelBkg.GetName() + "_ext", modelBkg.GetTitle(), modelBkg, normzBkg) # create workspace w = RooWorkspace("SVJ", "workspace") # Dataset # ATT: include isData getattr(w, "import")(bkgData, RooFit.Rename("Bkg")) getattr(w, "import")(obsData, RooFit.Rename("data_obs")) getattr(w, "import")(sigData, RooFit.Rename(sig)) for i in xrange(hist.GetNbinsX()): mcstatSysName = "mcstat_%s_%s_bin%d" % (ch, sig, i + 1) #print mcstatSysName #print sig + "_" + mcstatSysName + "Up" mcstatSigUp = getHist(ch, sig + "_" + mcstatSysName + "Up", ifile) #print "Integral ", mcstatSigUp.Integral() mcstatSigDown = getHist(ch, sig + "_" + mcstatSysName + "Down", ifile) mcstatSigHistUp = RooDataHist(sig + "_" + mcstatSysName + "Up", "Data (MC sig)", RooArgList(mT), mcstatSigUp, 1.) mcstatSigHistDown = RooDataHist(sig + "_" + mcstatSysName + "Down", "Data (MC sig)", RooArgList(mT), mcstatSigDown, 1.) getattr(w, "import")(mcstatSigHistUp, RooFit.Rename(sig + "_" + mcstatSysName + "Up")) getattr(w, "import")(mcstatSigHistDown, RooFit.Rename(sig + "_" + mcstatSysName + "Down")) for sysName, sysValue in syst.iteritems(): if (sysValue[0] == "shape" and "mcstat" not in sysName): sysUp = getHist(ch, sig + "_" + sysName + "Up", ifile) sysDown = getHist(ch, sig + "_" + sysName + "Down", ifile) print "==> Trigg sys name: ", sig + "_" + sysName + "Down" sysSigHistUp = RooDataHist(sig + "_" + sysName + "Up", sysName + " uncertainty", RooArgList(mT), sysUp, 1.) sysSigHistDown = RooDataHist(sig + "_" + sysName + "Down", sysName + " uncertainty", RooArgList(mT), sysDown, 1.) getattr(w, "import")(sysSigHistUp, RooFit.Rename(sig + "_" + sysName + "Up")) getattr(w, "import")(sysSigHistDown, RooFit.Rename(sig + "_" + sysName + "Down")) #else: getattr(w, "import")(setToys, RooFit.Rename("data_obs")) getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName())) #getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName())) getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName())) w.writeToFile("%sws_%s_%s_%s.root" % (carddir, sig, ch, mode), True) print "Workspace", "%sws_%s_%s_%s.root" % (carddir, sig, ch, mode), "saved successfully" workfile = "./ws_%s_%s_%s.root" % (sig, ch, mode) # ====== END MODEL GENERATION ====== rates = {} procLine = "" procNumbLine = "" rateLine = "" binString = "" if (mode == "template"): processes.append("Bkg") processes[:-1] = [] rates["Bkg"] = nBkgEvts procLine += ("%-43s") % ("Bkg") rateLine += ("%-43s") % (rates["Bkg"]) binString += (("%-43s") % (ch)) * (2) procNumbLine = 1 else: i = 1 bkgrate = 0 print "===> Backgrounds: ", processes nproc = (len(processes) + 1) for p in processes: print "======================= p for rate", p, " syst, ", syst print "ch is ", ch, " process is ", p, " ifile is ", ifile.GetName( ) rates[p] = getRate(ch, p, ifile) bkgrate = rates[p] if (p == "QCD"): print "qcd: ", bkgrate if (bkgrate == 0): nproc = nproc - 1 continue procNumbLine += ("%-43s") % (i) procLine += ("%-43s") % (p) rateLine += ("%-43.2f") % (bkgrate) i += 1 binString += (("%-43s") % (ch)) * (nproc) if ((not unblind) and (mode == "template")): print "N.B: We are in blind mode. Using MC bkg data for data_obs" rates["data_obs"] = getRate(ch, "Bkg", ifile) print "Pseudo data rate: ", rates["data_obs"] else: rates["data_obs"] = getRate(ch, "data_obs", ifile) rates[sig] = getRate(ch, sig, ifile) card = "imax 1 number of channels \n" card += "jmax * number of backgrounds \n" card += "kmax * number of nuisance parameters\n" card += "-----------------------------------------------------------------------------------\n" if (mode == "template"): # card += "shapes %s %s %s %s %s\n" % (sig, ch, ifilename, "$CHANNEL/$PROCESS", "$CHANNEL/$PROCESS_SYSTEMATIC") # card += "shapes %-15s %-5s %s%s.root %s\n" % (sig, ch, WORKDIR, ch, "SVJ:$PROCESS") card += "shapes %s %s %s %s\n" % (modelBkg.GetName(), ch, workfile, "SVJ:$PROCESS") card += "shapes %s %s %s %s %s\n" % ( sig, ch, workfile, "SVJ:$PROCESS", "SVJ:$PROCESS_$SYSTEMATIC") card += "shapes %s %s %s %s\n" % ("data_obs", ch, workfile, "SVJ:$PROCESS") else: card += "shapes * * %s %s %s\n" % ( hist_filename, "$CHANNEL/$PROCESS", "$CHANNEL/$PROCESS_$SYSTEMATIC") card += "shapes data_obs * %s %s\n" % (hist_filename, "$CHANNEL/$PROCESS") card += "-----------------------------------------------------------------------------------\n" card += "bin %s\n" % ch print "===> Observed data: ", rates["data_obs"] card += "observation %0.d\n" % (rates["data_obs"]) card += "-----------------------------------------------------------------------------------\n" card += "bin %-43s\n" % (binString) card += "process %-43s%-43s\n" % ( sig, procLine) #"roomultipdf" card += "process %-43s%-43s\n" % ( "0", procNumbLine) card += "rate %-43.6f%-43s\n" % ( rates[sig], rateLine) #signalYield[m].getVal(), nevents card += "-----------------------------------------------------------------------------------\n" for sysName, sysValue in syst.iteritems(): print "Systematic Uncertainty: ", sysName if ("2016" in sysName and "2016" not in ch): continue elif ("2017" in sysName and "2017" not in ch): continue elif ("2018" in sysName and "2018" not in ch): continue if ("mu" in sysName and "mu" not in ch): continue elif ("ele" in sysName and "ele" not in ch): continue if (sysValue[0] == "lnN"): card += "%-20s%-20s" % (sysName, sysValue[0]) if (sysValue[1] == "all" and len(sysValue) > 2): if (mode == "template"): card += "%-20s" % (sysValue[2]) * (2) else: card += "%-20s" % (sysValue[2]) * (len(processes) + 1) elif (sysValue[1] == "QCD" and len(sysValue) > 2): if (mode == "template"): card += "%-20s" % (sysValue[2]) * (2) else: card += "%-20s" % (sysValue[2]) * (len(processes) + 1) else: if (sysValue[1] == "all"): sysValue[1] = copy.deepcopy(processes) sysValue[1].append(sig) hsysName = "_" + sysName hsysNameUp = "_" + sysName + "Up" hsysNameDown = "_" + sysName + "Down" #print "Applying syst on ", sysValue[1] if ("sig" in sysValue[1]): if (getRate(ch, sig, ifile) != 0.): sigSys = abs((getRate(ch, sig + hsysNameUp, ifile) - getRate(ch, sig + hsysNameDown, ifile)) / (2 * getRate(ch, sig, ifile))) else: sigSys = 1 if (sigSys < 1. and sigSys > 0.): sigSys = sigSys + 1 card += "%-20s" % (sigSys) else: card += "%-20s" % ("-") for p in processes: if (p in sysValue[1]): if (getRate(ch, p, ifile) != 0.): bkgSys = abs( (getRate(ch, p + hsysNameUp, ifile) - getRate(ch, p + hsysNameDown, ifile)) / (2 * getRate(ch, p, ifile))) else: bkgSys = 1 if (bkgSys < 1. and bkgSys > 0.): bkgSys = bkgSys + 1 card += "%-20s" % (bkgSys) else: card += "%-20s" % ("-") elif (sysValue[0] == "shape"): print "sys shape named ", sysName if ("mcstat" not in sysName and 'autoMCstat' not in sysName): card += "%-20s shape " % (sysName) isbogussys = False #if(getRate(ch, sig+"_"+sysName+"Up", ifile)==0 or getRate(ch, sig+"_"+sysName+"Down", ifile)==0):isbogussys=True if ("sig" in sysValue[1]) and ((getRate(ch, sig, ifile) != 0.) and not isbogussys): #print " signal ",sig," channel, ",ch, " file ",ifile, " rate ",(getRate(ch, sig, ifile)) #print " signal ",sig," channel, ",ch, " file ",ifile, " rate up ",(getRate(ch, sig+"_"+sysName+"Up", ifile)) #print " signal ",sig," channel, ",ch, " file ",ifile, " rate down",(getRate(ch, sig+"_"+sysName+"Down", ifile)) card += "%-20s" % ("1") else: card += "%-20s" % ("-") for p in processes: if (p in sysValue[1]): if "q2SingleTop" in sysName: card += "%-20s" % ("1") else: card += "%-20s" % ("1") #print "adding to channel ", p else: card += "%-20s" % ("-") elif ("mcstat" in sysName): # CAMBIARE NOME DELLA SYST for samp in sysValue[1]: sampName = "" line = "" if (samp == "sig" or samp == "Sig"): line = "%-20s" % ("1") line += "%-20s" % ("-") * (len(processes)) sampName = sig elif (mode != "template"): line = "%-20s" % ("-") lineProc = [ "%-20s" % ("-") for x in xrange(len(processes)) ] if samp in processes: index = processes.index(samp) lineProc[index] = "1" lineProc = " ".join(lineProc) line += lineProc sampName = samp else: continue for i in xrange(hist.GetNbinsX()): sysName = "mcstat_%s_%s_bin%d " % (ch, sampName, i + 1) card += "%-20s shape " % (sysName) card += line card += "\n" if ('autoMCstat' in sysName): card += "%-20s%-20s%-20d\n " % (ch, "autoMCStats", 0) card += "\n" # End for loop on syst unc. for k, v in rateParams.items(): for ch_ in v.chs: if ("2016" in k and "2016" not in ch): continue elif ("2017" in k and "2017" not in ch): continue elif ("2018" in k and "2018" not in ch): continue if ("mu" in k and "mu" not in ch): continue elif ("ele" in k and "ele" not in ch): continue if (ch_ == ("_").join(ch.split("_")[:-1])): if (("2016" in k) or ("2017" in k) or ("2018" in k)): if ('mu' in k and 'mu' in ch): card += "%-20s%-20s%-20s%-20s%-20d\n" % ( k, "rateParam", ch, v.bkg, 1) elif ('ele' in k and 'ele' in ch): card += "%-20s%-20s%-20s%-20s%-20d\n" % ( k, "rateParam", ch, v.bkg, 1) else: sameyear = (("2016" in k and "2016" in ch) or ("2017" in k and "2017" in ch) or ("2018" in k and "2018" in ch)) if (sameyear): card += "%-20s%-20s%-20s%-20s%-20d\n" % ( k, "rateParam", ch, v.bkg, 1) else: card += "%-20s%-20s%-20s%-20s%-20d\n" % (k, "rateParam", ch, v.bkg, 1) card += "\n" if not os.path.isdir(outdir): os.system('mkdir ' + outdir) if not os.path.isdir(outdir + "/" + sig): os.system('mkdir ' + outdir + "/" + sig) outname = "%s%s_%s_%s.txt" % (carddir, sig, ch, mode) cardfile = open(outname, 'w') cardfile.write(card) cardfile.close() #print card return card
def buildDataAndCategories(ws, options, args): #Get the input data inputData = TChain(options.treeName, 'The input data') for arg in args: print 'Adding data from: ', arg inputData.Add(arg) foldname = '' phirange = [0, 90] if not options.folded: foldname = '' phirange = [-180, 180] #variables necessary for j/psi mass,lifetime,polarization fit jPsiMass = RooRealVar('JpsiMass', 'M [GeV]', 2.7, 3.5) jPsiRap = RooRealVar('JpsiRap', '#nu', -2.3, 2.3) jPsiPt = RooRealVar("JpsiPt", "pT [GeV]", 0, 40) jPsicTau = RooRealVar('Jpsict', 'l_{J/#psi} [mm]', -1, 2.5) jPsicTauError = RooRealVar('JpsictErr', 'Error on l_{J/#psi} [mm]', 0, 2) jPsiVprob = RooRealVar('JpsiVprob', '', .01, 1) jPsiHXcosth = None jPsiHXphi = None jPsicTau.setBins(10000, "cache") if options.fitFrame is not None: jPsiHXcosth = RooRealVar('costh_' + options.fitFrame + foldname, 'cos(#theta)_{' + options.fitFrame + '}', -1, 1) jPsiHXphi = RooRealVar('phi_' + options.fitFrame + foldname, '#phi_{' + options.fitFrame + '}', phirange[0], phirange[1]) else: jPsiHXcosth = RooRealVar('costh_CS' + foldname, 'cos(#theta)_{CS}', -1, 1) jPsiHXphi = RooRealVar('phi_CS' + foldname, '#phi_{CS}', phirange[0], phirange[1]) #vars needed for on the fly calc of polarization variables jPsimuPosPx = RooRealVar('muPosPx', '+ Muon P_{x} [GeV]', 0) jPsimuPosPy = RooRealVar('muPosPy', '+ Muon P_{y} [GeV]', 0) jPsimuPosPz = RooRealVar('muPosPz', '+ Muon P_{z} [GeV]', 0) jPsimuNegPx = RooRealVar('muNegPx', '- Muon P_{x} [GeV]', 0) jPsimuNegPy = RooRealVar('muNegPy', '- Muon P_{y} [GeV]', 0) jPsimuNegPz = RooRealVar('muNegPz', '- Muon P_{z} [GeV]', 0) #create RooArgSet for eventual dataset creation dataVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError, jPsimuPosPx, jPsimuPosPy, jPsimuPosPz) #add trigger requirement if specified if options.triggerName: trigger = RooRealVar(options.triggerName, 'Passes Trigger', 0.5, 1.5) dataVars.add(trigger) dataVars.add(jPsiVprob) dataVars.add(jPsimuNegPx) dataVars.add(jPsimuNegPy) dataVars.add(jPsimuNegPz) dataVars.add(jPsiHXcosth) dataVars.add(jPsiHXphi) redVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError) redVars.add(jPsiHXcosth) redVars.add(jPsiHXphi) fitVars = redVars.Clone() ### HERE IS WHERE THE BIT FOR CALCULATING POLARIZATION VARS GOES ctauStates = RooCategory('ctauRegion', 'Cut Region in lifetime') ctauStates.defineType('prompt', 0) ctauStates.defineType('nonPrompt', 1) massStates = RooCategory('massRegion', 'Cut Region in mass') massStates.defineType('signal', 1) massStates.defineType('separation', 0) massStates.defineType('leftMassSideBand', -2) massStates.defineType('rightMassSideBand', -1) states = RooCategory('mlRegion', 'Cut Region in mass') states.defineType('nonPromptSignal', 2) states.defineType('promptSignal', 1) states.defineType('separation', 0) states.defineType('leftMassSideBand', -2) states.defineType('rightMassSideBand', -1) #define corresponding ranges in roorealvars #mass is a little tricky since the sidebands change definitions in each rap bin #define the names here and change as we do the fits #jPsiMass.setRange('NormalizationRangeFormlfit_promptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_nonPromptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_leftMassSideBand',2.7,3.1) #jPsiMass.setRange('NormalizationRangeFormlfit_rightMassSideBand',3.1,3.5) #want the prompt fit only done in prompt region #non-prompt only in non-prompt region #background over entire cTau range #jPsicTau.setRange('NormalizationRangeFormlfit_promptSignal',-1,.1) #jPsicTau.setRange('NormalizationRangeFormlfit_nonPromptSignal',.1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_leftMassSideBand',-1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_rightMassSideBand',-1,2.5) #redVars.add(ctauStates) #redVars.add(massStates) #redVars.add(states) fitVars.add(ctauStates) fitVars.add(massStates) fitVars.add(states) fullData = RooDataSet('fullData', 'The Full Data From the Input ROOT Trees', dataVars, ROOT.RooFit.Import(inputData)) for rap_bin in range(1, len(jpsi.pTRange)): yMin = jpsi.rapForPTRange[rap_bin - 1][0] yMax = jpsi.rapForPTRange[rap_bin - 1][-1] for pt_bin in range(len(jpsi.pTRange[rap_bin])): ptMin = jpsi.pTRange[rap_bin][pt_bin][0] ptMax = jpsi.pTRange[rap_bin][pt_bin][-1] sigMaxMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sigMinMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sbHighMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigBkgHigh * jpsi.sigmaMassJpsi[rap_bin] sbLowMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigBkgLow * jpsi.sigmaMassJpsi[rap_bin] ctauNonPrompt = .1 massFun = RooFormulaVar( 'massRegion', 'Function that returns the mass state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) ctauFun = RooFormulaVar( 'ctauRegion', 'Function that returns the ctau state.', '(' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ')', RooArgList(jPsiMass, jPsicTau)) mlFun = RooFormulaVar( 'mlRegion', 'Function that returns the mass and lifetime state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') + (' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ' && ' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) cutStringPt = '(' + jPsiPt.GetName() + ' > ' + str( ptMin) + ' && ' + jPsiPt.GetName() + ' < ' + str(ptMax) + ')' cutStringY = '( abs(' + jPsiRap.GetName() + ') > ' + str( yMin) + ' && abs(' + jPsiRap.GetName() + ') < ' + str( yMax) + ')' #cutStringM1 = '('+jPsiMass.GetName()+' < '+str(sigMinMass)+' && '+jPsiMass.GetName()+' > '+str(sbLowMass)+')' #cutStringM2 = '('+jPsiMass.GetName()+' < '+str(sbHighMass)+' && '+jPsiMass.GetName()+' > '+str(sigMaxMass)+')' #cutStringMT = '!('+cutStringM1+' || '+cutStringM2+')' cutString = cutStringPt + ' && ' + cutStringY #+' && '+cutStringMT print cutString #get the reduced dataset we'll do the fit on binData = fullData.reduce( ROOT.RooFit.SelectVars(redVars), ROOT.RooFit.Cut(cutString), ROOT.RooFit.Name('data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1)), ROOT.RooFit.Title('Data For Fitting')) binDataWithCategory = RooDataSet( 'data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1), 'Data For Fitting', fitVars) #categorize binData.addColumn(ctauStates) binData.addColumn(massStates) binData.addColumn(states) for ev in range(binData.numEntries()): args = binData.get(ev) jPsiMass.setVal(args.find(jPsiMass.GetName()).getVal()) jPsiRap.setVal(args.find(jPsiRap.GetName()).getVal()) jPsiPt.setVal(args.find(jPsiPt.GetName()).getVal()) jPsicTau.setVal(args.find(jPsicTau.GetName()).getVal()) jPsicTauError.setVal( args.find(jPsicTauError.GetName()).getVal()) jPsiHXcosth.setVal(args.find(jPsiHXcosth.GetName()).getVal()) jPsiHXphi.setVal(args.find(jPsiHXphi.GetName()).getVal()) massStates.setIndex(int(massFun.getVal())) ctauStates.setIndex(int(ctauFun.getVal())) states.setIndex(int(mlFun.getVal())) binDataWithCategory.add(fitVars) getattr(ws, 'import')(binDataWithCategory)
def dijet(category): channel = 'bb' stype = channel isSB = True # relict from using Alberto's more complex script isData = not ISMC nTupleDir = NTUPLEDIR samples = data if isData else back pd = [] for sample_name in samples: if YEAR == 'run2': pd += sample[sample_name]['files'] else: pd += [x for x in sample[sample_name]['files'] if YEAR in x] print "datasets:", pd if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR) if BIAS: print "Running in BIAS mode" order = 0 RSS = {} X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV") weight = RooRealVar("MANtag_weight", "", -1.e9, 1.e9) variables = RooArgSet(X_mass) variables.add(RooArgSet(weight)) if VARBINS: binsXmass = RooBinning(len(abins) - 1, abins) X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow)) plot_binning = RooBinning( int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) else: X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10)) binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(), X_mass.getMax()) plot_binning = binsXmass baseCut = "" print stype, "|", baseCut print " - Reading from Tree" treeBkg = TChain("tree") for ss in pd: if os.path.exists(nTupleDir + ss + "_" + BTAGGING + ".root"): treeBkg.Add(nTupleDir + ss + "_" + BTAGGING + ".root") else: print "found no file for sample:", ss setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeBkg)) nevents = setData.sumEntries() dataMin, dataMax = array('d', [0.]), array('d', [0.]) setData.getRange(X_mass, dataMin, dataMax) xmin, xmax = dataMin[0], dataMax[0] lastBin = X_mass.getMax() if VARBINS: for b in narrow_bins: if b > xmax: lastBin = b break print "Imported", ( "data" if isData else "MC" ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax) #xmax = xmax+binsXmass.averageBinWidth() # start form next bin # 1 parameter print "fitting 1 parameter model" p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0., 2000.) modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)", "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1)) normzBkg1 = RooRealVar( modelBkg1.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) #range dependent of actual number of events! modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext", modelBkg1.GetTitle(), modelBkg1, normzBkg1) fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes1.Print() RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass, [fitRes1], normzBkg1.getVal()) # 2 parameters print "fitting 2 parameter model" p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100., 1000.) p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2", p1_1.getVal(), -100., 600.) modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2)", RooArgList(X_mass, p2_1, p2_2)) normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext", modelBkg2.GetTitle(), modelBkg2, normzBkg2) fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes2.Print() RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass, [fitRes2], normzBkg2.getVal()) # 3 parameters print "fitting 3 parameter model" p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1", p2_1.getVal(), -2000., 2000.) p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2", p2_2.getVal(), -400., 2000.) p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5, -500., 500.) modelBkg3 = RooGenericPdf( "Bkg3", "Bkg. fit (4 par.)", "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))", RooArgList(X_mass, p3_1, p3_2, p3_3)) normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext", modelBkg3.GetTitle(), modelBkg3, normzBkg3) fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes3.Print() RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass, [fitRes3], normzBkg3.getVal()) # 4 parameters print "fitting 4 parameter model" p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1", p3_1.getVal(), -2000., 2000.) p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2", p3_2.getVal(), -2000., 2000.) p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3", p3_3.getVal(), -50., 50.) p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50., 50.) modelBkg4 = RooGenericPdf( "Bkg4", "Bkg. fit (5 par.)", "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))", RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4)) normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm", "Number of background events", nevents, 0., 5. * nevents) modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext", modelBkg4.GetTitle(), modelBkg4, normzBkg4) fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1), RooFit.SumW2Error(not isData), RooFit.Strategy(2), RooFit.Minimizer("Minuit2"), RooFit.PrintLevel(1 if VERBOSE else -1)) fitRes4.Print() RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass, [fitRes4], normzBkg4.getVal()) # Normalization parameters are should be set constant, but shape ones should not # if BIAS: # p1_1.setConstant(True) # p2_1.setConstant(True) # p2_2.setConstant(True) # p3_1.setConstant(True) # p3_2.setConstant(True) # p3_3.setConstant(True) # p4_1.setConstant(True) # p4_2.setConstant(True) # p4_3.setConstant(True) # p4_4.setConstant(True) normzBkg1.setConstant(True) normzBkg2.setConstant(True) normzBkg3.setConstant(True) normzBkg4.setConstant(True) #*******************************************************# # # # Fisher # # # #*******************************************************# # Fisher test with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout: fout.write(r"\begin{tabular}{c|c|c|c|c}") fout.write("\n") fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\") fout.write("\n") fout.write("\hline") fout.write("\n") CL_high = False for o1 in range(1, 5): o2 = min(o1 + 1, 5) fout.write("%d par & %.2f & %.2f & %d & " % (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"] - RSS[o1]["npar"])) if o2 > len(RSS): fout.write(r"\\") fout.write("\n") continue #order==0 and CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1., RSS[o1]["nbins"]) fout.write("CL=%.3f " % (CL)) if CL > 0.10: # The function with less parameters is enough if not CL_high: order = o1 #fout.write( "%d par are sufficient " % (o1+1)) CL_high = True else: #fout.write( "%d par are needed " % (o2+1)) if not CL_high: order = o2 fout.write(r"\\") fout.write("\n") fout.write("\hline") fout.write("\n") fout.write(r"\end{tabular}") print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex" #print "-"*25 #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\" #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\" #print "\\hline" #CL_high = False #for o1 in range(1, 5): # o2 = min(o1 + 1, 5) # print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]), # if o2 > len(RSS): # print "\\\\" # continue #order==0 and # CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"]) # print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL), # if CL > 0.10: # The function with less parameters is enough # if not CL_high: # order = o1 # print "%d par are sufficient" % (o1+1), # CL_high=True # else: # print "%d par are needed" % (o2+1), # if not CL_high: # order = o2 # print "\\\\" #print "\\hline" #print "-"*25 #print "@ Order is", order, "("+category+")" #order = min(3, order) #order = 2 if order == 1: modelBkg = modelBkg1 #.Clone("Bkg") modelAlt = modelBkg2 #.Clone("BkgAlt") normzBkg = normzBkg1 #.Clone("Bkg_norm") fitRes = fitRes1 elif order == 2: modelBkg = modelBkg2 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg2 #.Clone("Bkg_norm") fitRes = fitRes2 elif order == 3: modelBkg = modelBkg3 #.Clone("Bkg") modelAlt = modelBkg4 #.Clone("BkgAlt") normzBkg = normzBkg3 #.Clone("Bkg_norm") fitRes = fitRes3 elif order == 4: modelBkg = modelBkg4 #.Clone("Bkg") modelAlt = modelBkg3 #.Clone("BkgAlt") normzBkg = normzBkg4 #.Clone("Bkg_norm") fitRes = fitRes4 else: print "Functions with", order + 1, "or more parameters are needed to fit the background" exit() modelBkg.SetName("Bkg_" + YEAR + "_" + category) modelAlt.SetName("Alt_" + YEAR + "_" + category) normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm") print "-" * 25 # Generate pseudo data setToys = RooDataSet() setToys.SetName("data_toys") setToys.SetTitle("Data (toys)") if not isData: print " - Generating", nevents, "events for toy data" setToys = modelBkg.generate(RooArgSet(X_mass), nevents) #setToys = modelAlt.generate(RooArgSet(X_mass), nevents) print "toy data generated" if VERBOSE: raw_input("Press Enter to continue...") #*******************************************************# # # # Plot # # # #*******************************************************# print "starting to plot" c = TCanvas("c_" + category, category, 800, 800) c.Divide(1, 2) setTopPad(c.GetPad(1), RATIO) setBotPad(c.GetPad(2), RATIO) c.cd(1) frame = X_mass.frame() setPadStyle(frame, 1.25, True) if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) signal = getSignal( category, stype, 2000) #replacing Alberto's getSignal by own dummy function graphData = setData.plotOn(frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.Invisible()) modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False), RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("FL"), RooFit.Name("1sigma")) modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelBkg.GetName())) modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613), RooFit.FillColor(609), RooFit.FillStyle(1001), RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName())) if not isSB and signal[0] is not None: # FIXME remove /(2./3.) signal[0].plotOn( frame, RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent), RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629), RooFit.DrawOption("L"), RooFit.Name("Signal")) graphData = setData.plotOn( frame, RooFit.Binning(plot_binning), RooFit.Scaling(False), RooFit.XErrorSize(0 if not VARBINS else 1), RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2), RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName())) fixData(graphData.getHist(), True, True, not isData) pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True) chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True) #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2)) frame.GetYaxis().SetTitle("Events / ( 100 GeV )") frame.GetYaxis().SetTitleOffset(1.05) frame.Draw() #print "frame drawn" # Get Chi2 # chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName()) # chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName()) # chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName()) # chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName()) frame.SetMaximum(frame.GetMaximum() * 10) frame.SetMinimum(max(frame.GetMinimum(), 1.e-1)) c.GetPad(1).SetLogy() drawAnalysis(category) drawRegion(category, True) #drawCMS(LUMI, "Simulation Preliminary") drawCMS(LUMI, "Work in Progress", suppressCMS=True) leg = TLegend(0.575, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.AddEntry(setData.GetName(), setData.GetTitle() + " (%d events)" % nevents, "PEL") leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(), "FL") #.SetTextColor(629) leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L") if not isSB and signal[0] is not None: leg.AddEntry("Signal", signal[0].GetTitle(), "L") leg.SetY1(0.9 - leg.GetNRows() * 0.05) leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextFont(42) if not isSB: latex.DrawLatex(leg.GetX1() * 1.16, leg.GetY1() - 0.04, "HVT model B (g_{V}=3)") # latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb") c.cd(2) frame_res = X_mass.frame() setPadStyle(frame_res, 1.25) frame_res.addPlotable(pulls, "P") setBotStyle(frame_res, RATIO, False) if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin) frame_res.GetYaxis().SetRangeUser(-5, 5) frame_res.GetYaxis().SetTitle("pulls(#sigma)") frame_res.GetYaxis().SetTitleOffset(0.3) frame_res.Draw() fixData(pulls, False, True, False) drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True) line = drawLine(X_mass.getMin(), 0, lastBin, 0) if VARBINS: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") else: c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf") c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# if BIAS: gSystem.Load("libHiggsAnalysisCombinedLimit.so") from ROOT import RooMultiPdf cat = RooCategory("pdf_index", "Index of Pdf which is active") pdfs = RooArgList(modelBkg, modelAlt) roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs) normulti = RooRealVar("roomultipdf_norm", "Number of background events", nevents, 0., 1.e6) normzBkg.setConstant( False ) ## newly put here to ensure it's freely floating in the combine fit # create workspace w = RooWorkspace("Zprime_" + YEAR, "workspace") # Dataset if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs")) else: getattr(w, "import")(setToys, RooFit.Rename("data_obs")) #getattr(w, "import")(setData, RooFit.Rename("data_obs")) if BIAS: getattr(w, "import")(cat, RooFit.Rename(cat.GetName())) getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName())) getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName())) getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName())) getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName())) getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName())) w.writeToFile(WORKDIR + "%s_%s.root" % (DATA_TYPE + "_" + YEAR, category), True) print "Workspace", WORKDIR + "%s_%s.root" % ( DATA_TYPE + "_" + YEAR, category), "saved successfully" if VERBOSE: raw_input("Press Enter to continue...")
bins_p_inv = [p_inv.getMin()] for i in range(1, n_bins): bins_p_inv += [p_inv_values[i * di]] bins_p_inv += [p_inv.getMax()] magnet_datas = {} dp_inv = (p_inv.getMax() - p_inv.getMin()) / n_bins dp = (p.getMax() - p.getMin()) / n_bins bins_p = [0 + i * dp for i in range(n_bins + 1)] graphs = {} sigmas = defaultdict(list) sigmas_err = defaultdict(list) av = [] err_x = [] p_vars = {p_inv.GetName(): p_inv, p.GetName(): p} vname = p_inv.GetName() bins = bins_p_inv for i in range(n_bins): ds = magnet_data.reduce('{0} > {1} && {0} < {2}'.format( vname, bins[i], bins[i + 1])) magnet_datas[i] = ds av += [ds.mean(p_vars[vname])] err_x += [0.] for obs, tag in ((pull_xm, 'xm'), (pull_ym, 'ym')): cn = 'fit_canvas_' + tag canvas_fit = TCanvas(cn, cn, 1200, 800) canvas_fit.Divide(3, 3) canvases['fit_' + tag] = canvas_fit
theBaseData = TH3F('theBaseData_'+section+'_'+str(i),'Base Histogram for RooDataHist', nGridPar1Bins,par1GridMin,par1GridMax, nGridPar2Bins,par2GridMin,par2GridMax, nGridPar3Bins,par3GridMin,par3GridMax) newFormatInput = TH3D('bin_content_par1_par2_par3_'+str(i),'bincontent', nGridPointsForNewF,par1GridMin,par1GridMax, nGridPointsForNewF,par2GridMin,par2GridMax, nGridPointsForNewF,par3GridMin,par3GridMax) if i != len(bins) - 1: binMin = bins[i-1] binMax = bins[i] if (model=="par1_TH1" or model=="par1_TF1"): sigObj.Draw(par1Name+' >> theBaseData_'+section+'_'+str(i), '('+weight.GetName()+'*'+str(efficiencies[i-1])+')'+'*('+cfg.get(section,'obsVar') + # # weight.GetName()+'*('+cfg.get(section,'obsVar') + # ' > ' + str(binMin) + ' && ' + cfg.get(section,'obsVar') + ' < ' + str(binMax)+')','goff') elif (model=="par1par2_TH2" or model=="par1par2_TF2"): sigObj.Draw(par2Name+':'+par1Name+' >> theBaseData_'+section+'_'+str(i), weight.GetName()+'*('+cfg.get(section,'obsVar') + # # '('+weight.GetName()+'/64.4217490480265127)'+'*('+cfg.get(section,'obsVar') + # # '('+weight.GetName()+'*'+efficiencies[i-1]+')'+'*('+cfg.get(section,'obsVar') + # ' > ' + str(binMin) + ' && ' + cfg.get(section,'obsVar') + ' < ' + str(binMax)+')','goff') elif (model=="par1par2_TH3" or model=="par1par2_TF3"): sigObj.Draw(par3Name+':'+par2Name+':'+par1Name+' >> theBaseData_'+section+'_'+str(i), weight.GetName()+'*('+cfg.get(section,'obsVar') + #
def fitATGCExpectedYields(ws, cfg, section): pwd = ROOT.gDirectory.GetPath() sigFile = cfg.get(section, 'signal_model').split(':')[0] sigObj = cfg.get(section, 'signal_model').split(':')[1] sigFile = TFile.Open(sigFile) ROOT.gDirectory.cd(pwd) sigObj = sigFile.Get(sigObj) if isinstance(sigObj, ROOT.TTree): sigObj = sigObj.CloneTree() else: print 'Signal model must be a TTree (for now)' exit(1) sigFile.Close() ROOT.gDirectory.cd(pwd) bins = [float(i) for i in cfg.get(section, 'obsBins').split(',')] nObsBins = len(bins) - 1 weightvar = cfg.get(section, 'signal_weight_var') par1Name = cfg.get('Global', 'par1Name') par2Name = cfg.get('Global', 'par2Name') nGridParBins = cfg.getint(section, 'nGridParBins') par1GridMax = cfg.getfloat(section, 'par1GridMax') par2GridMax = cfg.getfloat(section, 'par2GridMax') par1GridMin = cfg.getfloat(section, 'par1GridMin') par2GridMin = cfg.getfloat(section, 'par2GridMin') par1PadSize = (par1GridMax - par1GridMin) / (2 * nGridParBins - 2) par2PadSize = (par2GridMax - par2GridMin) / (2 * nGridParBins - 2) par1GridMax = par1GridMax + par1PadSize #add padding to put values at bin centers, assuming evently spaced points par2GridMax = par2GridMax + par2PadSize par1GridMin = par1GridMin - par1PadSize #add padding to put values at bin centers, assuming evently spaced points par2GridMin = par2GridMin - par2PadSize print "printing:::::::::", par1PadSize, ' ', par2PadSize, ' ', par1GridMin, ' ', par1GridMax, ' ', par2GridMin, ' ', par2GridMax #create the variables for the nxn grid, doesn't go in the workspace obs_mc = ws.var('%s_%s' % (cfg.get(section, 'obsVar'), section)) weight = RooRealVar(weightvar, 'the weight of the data', 0, 1000) hc = TH1F('hc_' + section, 'const term', nObsBins, array('d', bins)) hp0 = TH1F('hp_' + section + '_0', 'h3 linear term', nObsBins, array('d', bins)) hp1 = TH1F('hp_' + section + '_1', 'h4 linear term', nObsBins, array('d', bins)) hp2 = TH1F('hp_' + section + '_2', 'h3h4 cross term', nObsBins, array('d', bins)) hp3 = TH1F('hp_' + section + '_3', 'h3 quadratic term', nObsBins, array('d', bins)) hp4 = TH1F('hp_' + section + '_4', 'h4 quadratic term', nObsBins, array('d', bins)) bins = [float(i) for i in cfg.get(section, 'obsBins').split(',')] for i in range(1, len(bins)): theBaseData = TH2F('theBaseData_' + section + '_' + str(i), 'Base Histogram for RooDataHist', nGridParBins, par1GridMin, par1GridMax, nGridParBins, par2GridMin, par2GridMax) if i != len(bins) - 1: binMin = bins[i - 1] binMax = bins[i] print obs_mc.GetName(), ' > ', str( binMin), ' && ', obs_mc.GetName(), ' < ', str(binMax) print obs_mc.GetName(), ' > ', str(binMin), ' && ', cfg.get( section, 'obsVar'), ' < ', str(binMax), ')' sigObj.Draw( par2Name + '_grid:' + par1Name + '_grid >> theBaseData_' + section + '_' + str(i), weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # ' > ' + str(binMin) + ' && ' + cfg.get(section, 'obsVar') + ' < ' + str(binMax) + ')', 'goff') else: print obs_mc.GetName(), ' > ', str(bins[len(bins) - 2]) # print obs_mc.GetName(),' > ',str(binMin) sigObj.Draw( par2Name + '_grid:' + par1Name + '_grid >> theBaseData_' + section + '_' + str(i), weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # ' > ' + str(bins[len(bins) - 2]) + ')', 'goff') for k in range(1, nGridParBins + 1): for l in range(1, nGridParBins + 1): print(k, l), theBaseData.GetBinContent(k, l) func = TF2('fittingFunction_' + section + '_' + str(i), '[0] + [1]*x + [2]*y + [3]*x*y + [4]*x*x + [5]*y*y', par1GridMin, par1GridMax, par2GridMin, par2GridMax) theBaseData.Fit(func, 'R0', '') getattr(ws, 'import')(theBaseData) hc.SetBinContent(i, func.GetParameter(0)) hc.SetBinError(i, func.GetParError(0)) hp0.SetBinContent(i, func.GetParameter(1)) hp0.SetBinError(i, func.GetParError(1)) hp1.SetBinContent(i, func.GetParameter(2)) hp1.SetBinError(i, func.GetParError(2)) hp2.SetBinContent(i, func.GetParameter(3)) hp2.SetBinError(i, func.GetParError(3)) hp3.SetBinContent(i, func.GetParameter(4)) hp3.SetBinError(i, func.GetParError(4)) hp4.SetBinContent(i, func.GetParameter(5)) hp4.SetBinError(i, func.GetParError(5)) histoToRooHistFunc(ws, cfg, section, hc, 'signal_hc') histoToRooHistFunc(ws, cfg, section, hp0, 'signal_hp0') histoToRooHistFunc(ws, cfg, section, hp1, 'signal_hp1') histoToRooHistFunc(ws, cfg, section, hp2, 'signal_hp2') histoToRooHistFunc(ws, cfg, section, hp3, 'signal_hp3') histoToRooHistFunc(ws, cfg, section, hp4, 'signal_hp4')