def doFit(hist,output,rap="BB",flavour="DATA",trackType="TunePNew",funct="doubleCB"): sig = [] sige = [] meanList = [] meanListe = [] nChi2 = [] gSystem.Load("./RooCruijff_cxx.so") gSystem.Load("./RooDCBShape_cxx.so") for i,h in enumerate(hist): ws = RooWorkspace("tempWS") mass = RooRealVar('mass','mass',91, xLow, xHigh ) getattr(ws,'import')(mass,RooCmdArg()) dataHist = RooDataHist("hist","hist",RooArgList(ws.var("mass")),h) getattr(ws,'import')(dataHist,RooCmdArg()) ws.writeToFile("tmpWorkspace.root") subprocess.call(["python","fitCapsule.py",output,rap,flavour,trackType,funct,"%d"%xLow,"%d"%xHigh,"%d"%rebinFactor,"%d"%i]) returnFile = TFile("tmpWorkspaceReturn.root","OPEN") wsReturn = returnFile.Get("tempWS") sig.append(wsReturn.var("Sig").getVal()) sige.append(wsReturn.var("Sige").getVal()) meanList.append(wsReturn.var("Mean").getVal()) meanListe.append(wsReturn.var("Meane").getVal()) nChi2.append(wsReturn.var("chi2").getVal()/wsReturn.var("nDOF").getVal()) return meanList,meanListe,sig,sige, nChi2
def main(options,args): gROOT.Reset() #load our super special Polarization PDF gROOT.ProcessLine('.L RooPolarizationPdf.cxx+') gROOT.ProcessLine('.L RooPolarizationConstraint.cxx+') #setup integration intConf = ROOT.RooAbsReal.defaultIntegratorConfig() #intConf.Print('v') # intConf.method1D().setLabel('RooAdaptiveGaussKronrodIntegrator1D') intConf.setEpsAbs(1e-13) intConf.setEpsRel(1e-13) print intConf.epsAbs() print intConf.epsRel() # intConf.method2D().setLabel('RooMCIntegrator') # intConf.methodND().setLabel('RooMCIntegrator') output = TFile.Open(options.workspaceName+'.root','RECREATE') print options.gen #BfracNow = jpsi.pTRange[1][1][1] #p_bin = 1 #sigMaxMass = jpsi.polMassJpsi[p_bin] theWS = RooWorkspace(options.workspaceName,1) #save the polarization PDF code in the RooWorkspace theWS.importClassCode('RooPolarization*',True) buildDataAndCategories(theWS,options,args) buildMassAndLifetimePDF(theWS) # if options.fitFrame is not None: # buildPolarizationPDF(theWS,options) #root is stupid output.cd() theWS.Print('v') ROOT.RooMsgService.instance().Print() doFit(theWS,options) theWS.Print('v') theWS.Write() output.Close()
def _runPath(self): # Hook to registerd file fileName = self.cfg.get('fileName', "") if os.path.exists(fileName): self.ifile = self.process.filemanager.open(str(hex(id(self))), fileName, 'READ') #Open Wspace File #Pritam # Load wspace wspaceName = "wspace.{0}.{1}".format(str(self.process.cfg['args'].Year), self.cfg['wspaceTag']) # print("sourcemanager: ", self.process.sourcemanager.keys()) if wspaceName in self.process.sourcemanager.keys(): self.wspace = self.process.sourcemanager.get(wspaceName) elif not self.ifile == None: self.wspace = self.ifile.Get(wspaceName) # Load desired objects if self.wspace == None: self.logger.logINFO("RooWorkspace {0} not found. Create new workspace without booking target objects.".format(wspaceName)) self.wspace = RooWorkspace(wspaceName) self.cfg['source'][wspaceName] = self.wspace # Update results only for new workspace. # By design you CANNOT overwrite items in RooWorkspace by `Write` or `writeToFile`. self.bookEndSeq() else: self.logger.logINFO("RooWorkspace {0} found. Loading objects...".format(wspaceName)) self.cfg['source'][wspaceName] = self.wspace def readObjs(): """Exactly define how to read varaiables, read `wspace_key` from wspace and book as `source_key`""" for source_key, wspace_key in self.cfg['obj'].items(): if source_key in self.process.sourcemanager.keys(): self.cfg['source'][source_key] = self.process.sourcemanager.get(source_key) else: obj = self.wspace.obj(wspace_key) if obj == None: self.logger.logWARNING("No Variable {0} is found.".format(wspace_key)) else: self.cfg['source'][source_key] = obj def readAll(iArgs): def bookOne(arg): argName = arg.GetName() if argName in self.process.sourcemanager: self.cfg['source'][argName] = self.process.sourcemanager.get(argName) else: self.cfg['source'][argName+".{0}".format(str(self.process.cfg['args'].Year))] = arg FitterCore.ArgLooper(iArgs, bookOne) if self.cfg['obj']: readObjs() else: readAll(self.wspace.allFunctions()) readAll(self.wspace.allPdfs()) readAll(self.wspace.allVars())
def rooFit510(): print ">>> create and fill workspace..." workspace = RooWorkspace("workspace") # RooWorkspace fillWorkspace(workspace) print ">>>\n>>> retrieve model from workspace..." # Exploit convention encoded in named set "parameters" and "observables" # to use workspace contents w/o need for introspected model = workspace.pdf("model") # RooAbsPdf print ">>> generate and fit data in given observables" data = model.generate(workspace.set("observables"), 1000) # RooDataSet model.fitTo(data) print ">>> plot model and data of first observables..." frame1 = workspace.set("observables").first().frame() # RooPlot data.plotOn(frame1, Name("data"), Binning(50)) model.plotOn(frame1, Name("model")) print ">>> overlay plots with reference parameters as stored in snapshots..." workspace.loadSnapshot("reference_fit") model.plotOn(frame1, LineColor(kRed), Name("model_ref")) workspace.loadSnapshot("reference_fit_bkgonly") model.plotOn(frame1, LineColor(kRed), LineStyle(kDashed), Name("bkg_ref")) print "\n>>> draw on canvas..." canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600) legend = TLegend(0.2, 0.8, 0.4, 0.6) legend.SetTextSize(0.032) legend.SetBorderSize(0) legend.SetFillStyle(0) gPad.SetLeftMargin(0.15) gPad.SetRightMargin(0.02) frame1.GetYaxis().SetLabelOffset(0.008) frame1.GetYaxis().SetTitleOffset(1.5) frame1.GetYaxis().SetTitleSize(0.045) frame1.GetXaxis().SetTitleSize(0.045) frame1.Draw() legend.AddEntry("data", "data", 'LEP') legend.AddEntry("model", "model", 'L') legend.AddEntry("model_ref", "model fit", 'L') legend.AddEntry("bkg_ref", "background only fit", 'L') legend.Draw() canvas.SaveAs("rooFit510.png") # Print workspace contents workspace.Print() # Workspace will remain in memory after macro finishes gDirectory.Add(workspace)
def update(self,wsname,fname,storelist=[]): """Stores the current model (and observable) into a ROOT.Workspace, persistified in a root file Parameters ---------- wsname: str Name to be given to the ROOT.Workspace fname: str Name to be given to the ROOT file storelist: list(ROOT.RooDataSet,ROOT.RooRealVar,...), optional List of RooFit objects to be stored in the same workspace """ import os from ROOT import RooWorkspace, TFile # Create the ws with the model and data available w = RooWorkspace(wsname,'Workspace') wsImport = getattr(w,'import') # Put the models for rawtuple in self.__models.values(): model = rawtuple[0] anythingelse = rawtuple[1:] wsImport(model) # Put whatever the user want to store for _item in storelist: wsImport(_item) # Check if the fname already exist file_exist = os.path.isfile(fname) if file_exist: # Create a new auxiliar file, to provisionaly # store the ws auxfname = '_auxroot.root' w.writeToFile(auxfname) # Previously delete the old Workspace, if any _rootfile = TFile(fname) _rootfile.Delete(wsname+';*') _rootfile.Delete("ProcessID*;*") _rootfile.Close() # Open the auxiliary file _aux = TFile(auxfname) # and copy the ws to the rootfile w = _aux.Get(wsname) # and copy the ws to the rootfile w.writeToFile(fname,False) if file_exist: # And closing and removing auxfile _aux.Close() os.remove(auxfname)
def fit(self, save_to, signal_name=None, fix_p3=False, fit_range=[300., 1200.], fit_strategy=1): # Run a RooFit fit # Create background PDF p1 = RooRealVar('p1','p1',args.p1,0.,100.) p2 = RooRealVar('p2','p2',args.p2,0.,60.) p3 = RooRealVar('p3','p3',args.p3,-10.,10.) if args.fix_p3: p3.setConstant() background_pdf = RooGenericPdf('background_pdf','(pow(1-@0/%.1f,@1)/pow(@0/%.1f,@2+@3*log(@0/%.1f)))'%(self.collision_energy,self.collision_energy,self.collision_energy),RooArgList(self.mjj_,p1,p2,p3)) background_pdf.Print() data_integral = data_histogram.Integral(data_histogram.GetXaxis().FindBin(float(fit_range[0])),data_histogram.GetXaxis().FindBin(float(fit_range[1]))) background_norm = RooRealVar('background_norm','background_norm',data_integral,0.,1e+08) background_norm.Print() # Create signal PDF and fit model if signal_name: signal_pdf = RooHistPdf('signal_pdf', 'signal_pdf', RooArgSet(self.mjj_), self.signal_roohistograms_[signal_name]) signal_pdf.Print() signal_norm = RooRealVar('signal_norm','signal_norm',0,-1e+05,1e+05) signal_norm.Print() model = RooAddPdf("model","s+b",RooArgList(background_pdf,signal_pdf),RooArgList(background_norm,signal_norm)) else: model = RooAddPdf("model","b",RooArgList(background_pdf),RooArgList(background_norm)) # Run fit res = model.fitTo(data_, RooFit.Save(kTRUE), RooFit.Strategy(fit_strategy)) # Save to workspace self.workspace_ = RooWorkspace('w','workspace') #getattr(w,'import')(background,ROOT.RooCmdArg()) getattr(self.workspace_,'import')(background_pdf,RooFit.Rename("background")) getattr(self.workspace_,'import')(background_norm,ROOT.RooCmdArg()) getattr(self.workspace_,'import')(self.data_roohistogram_,RooFit.Rename("data_obs")) getattr(self.workspace_, 'import')(model, RooFit.Rename("model")) if signal_name: getattr(self.workspace_,'import')(signal_roohistogram,RooFit.Rename("signal")) getattr(self.workspace_,'import')(signal_pdf,RooFit.Rename("signal_pdf")) getattr(self.workspace_,'import')(signal_norm,ROOT.RooCmdArg()) self.workspace_.Print() self.workspace_.writeToFile(save_to) if signal_name: roofit_results[signal_name] = save_to else: roofit_results["background"] = save_to
def create_master_workspaces(meta_data): pwd = gDirectory.GetPath() ws_list = {} for (sample,chanlist) in meta_data.getAssociation().iteritems(): ws_list[sample] = {} for (channel,proclist) in chanlist.iteritems(): #make the workspace we're going to use this_ws = RooWorkspace('%s-%s'%(channel,sample)) initialize_workspace(this_ws) ws_list[sample][channel] = {} for (process,subproclist) in proclist.iteritems(): print sample, channel, process if 'HToZG'in process: ws_list[sample][channel][process] = [] for (subproc,info) in subproclist.iteritems(): print '\tprocessing: %s'%subproc input_file = info['input_file'] info['num_mc_events'] = -1 if input_file == '': print '\t no input file found! Skipping!' continue if 'data' not in process: print '\t mc input = %s'%input_file.split('/')[-1] if 'HToZG' in subproc: info['num_mc_events'] = \ extract_higgs_data_in_categories(subproc, input_file, this_ws) ws_list[sample][channel][process].append(subproc) else: info['num_mc_events'] = \ extract_bkg_data_in_categories(subproc, input_file, this_ws) else: print '\t data input = %s'%input_file.split('/')[-1] extract_data_in_categories(channel,input_file,this_ws) #end loop over processes and data fout_name = '%s_%s_master_workspace.root'%(channel,sample) fout = TFile.Open(fout_name,'recreate') fout.cd() this_ws.Write() fout.Close() gDirectory.cd(pwd) ws_list[sample][channel]['filename'] = fout_name return ws_list
def __init__ (self, pars): self.pars = pars self.ws = RooWorkspace('wjj2dfitter') self.utils = Wjj2DFitterUtils(self.pars) self.useImportPars = False self.rangeString = None obs = [] for v in self.pars.var: try: vName = self.pars.varNames[v] except AttributeError: vName = v obs.append(vName) var1 = self.ws.factory('%s[%f,%f]' % (vName, self.pars.varRanges[v][1], self.pars.varRanges[v][2]) ) var1.setUnit('GeV') try: var1.SetTitle(self.pars.varTitles[v]) except AttributeError: var1.SetTitle('m_{jj}') var1.setPlotLabel(var1.GetTitle()) if len(self.pars.varRanges[v][3]) > 1: vbinning = RooBinning(len(self.pars.varRanges[v][3]) - 1, array('d', self.pars.varRanges[v][3]), '%sBinning' % vName) var1.setBinning(vbinning) else: var1.setBins(self.pars.varRanges[v][0]) var1.Print() if v in self.pars.exclude: var1.setRange('signalRegion', self.pars.exclude[v][0], self.pars.exclude[v][1]) var1.setRange('lowSideband', var1.getMin(), self.pars.exclude[v][0]) var1.setRange('highSideband', self.pars.exclude[v][1], var1.getMax()) self.rangeString = 'lowSideband,highSideband' self.ws.defineSet('obsSet', ','.join(obs))
def rooFit502(): print ">>> setup model components..." x = RooRealVar("x", "x", 0, 10) mean = RooRealVar("mean", "mean of gaussians", 5, 0, 10) sigma1 = RooRealVar("sigma1", "width of gaussians", 0.5) sigma2 = RooRealVar("sigma2", "width of gaussians", 1) sig1 = RooGaussian("sig1", "Signal component 1", x, mean, sigma1) sig2 = RooGaussian("sig2", "Signal component 2", x, mean, sigma2) a0 = RooRealVar("a0", "a0", 0.5, 0., 1.) a1 = RooRealVar("a1", "a1", -0.2, 0., 1.) bkg = RooChebychev("bkg", "Background", x, RooArgList(a0, a1)) print ">>> sum model components..." sig1frac = RooRealVar("sig1frac", "fraction of component 1 in signal", 0.8, 0., 1.) sig = RooAddPdf("sig", "Signal", RooArgList(sig1, sig2), RooArgList(sig1frac)) bkgfrac = RooRealVar("bkgfrac", "fraction of background", 0.5, 0., 1.) model = RooAddPdf("model", "g1+g2+a", RooArgList(bkg, sig), RooArgList(bkgfrac)) print ">>> generate data..." data = model.generate(RooArgSet(x), 1000) # RooDataSet print ">>> create workspace, import data and model..." workspace = RooWorkspace("workspace", "workspace") # empty RooWorkspace getattr(workspace, 'import')(model) # import model and all its components getattr(workspace, 'import')(data) # import data #workspace.import(model) # causes synthax error in python #workspace.import(data) # causes synthax error in python print "\n>>> print workspace contents:" workspace.Print() print "\n>>> save workspace in file..." workspace.writeToFile("rooFit502_workspace.root") print ">>> save workspace in memory (gDirectory)..." gDirectory.Add(workspace)
def __init__ (self, pars): self.pars = pars self.ws = RooWorkspace('wjj2dfitter') self.utils = Wjj2DFitterUtils(self.pars) self.useImportPars = False self.rangeString = None obs = [] for v in self.pars.var: try: vName = self.pars.varNames[v] except AttributeError: vName = v obs.append(vName) var1 = self.ws.factory('%s[%f,%f]' % (vName, self.pars.varRanges[v][1], self.pars.varRanges[v][2]) ) var1.setUnit('GeV') try: var1.SetTitle(self.pars.varTitles[v]) except AttributeError: var1.SetTitle('m_{jj}') var1.setPlotLabel(var1.GetTitle()) if len(self.pars.varRanges[v][3]) > 1: vbinning = RooBinning(len(self.pars.varRanges[v][3]) - 1, array('d', self.pars.varRanges[v][3]), '%sBinning' % vName) var1.setBinning(vbinning) else: var1.setBins(self.pars.varRanges[v][0]) var1.Print() if v in self.pars.exclude: var1.setRange('signalRegion', self.pars.exclude[v][0], self.pars.exclude[v][1]) var1.setRange('lowSideband', var1.getMin(), self.pars.exclude[v][0]) var1.setRange('highSideband', self.pars.exclude[v][1], var1.getMax()) self.rangeString = 'lowSideband,highSideband' if hasattr(self.pars, 'plotRanges'): var1.setRange('plotRange', self.pars.plotRanges[v][1], self.pars.plotRanges[v][2]) var1.setBins(self.pars.plotRanges[v][0], 'plotBins') else: var1.setRange('plotRange', var1.getMin(), var1.getMax()) var1.setBins(var1.getBins(), 'plotBins') self.ws.defineSet('obsSet', ','.join(obs))
def test(): workspace = RooWorkspace("testworkspace") model = buildModel(workspace) mass = workspace.var('mass') # data = model.generate(RooArgSet(mass), 1000) data = getData(workspace, nevents = 10000, sigma1 = 0.015, mean1=1., sigma2 = 0.015, mean2=1.) model.fitTo(data, NumCPU(3)) mframe = mass.frame(Range(50,130)) data.plotOn(mframe) model.plotOn(mframe) #, Range(50,130)) #, LineColor(ROOT.kRed), LineStyle(ROOT.kDashed)) model.paramOn(mframe, Format('NEU', AutoPrecision(2) ), Layout(.55, 0.92, 0.92) ) mframe.Draw() return workspace
def doMCFit(dataSet, x_var, addTitlePlot=''): cuts_str = '' data = dataSet.reduce( RooFit.Cut(cuts_str) ) x=RooRealVar(x_var, 'm_{#tau}',1757,1797,'MeV') numBins = 100 # define here so that if I change it also the ndof change accordingly x.setBins(numBins) ###################################################### # DEFINE PDF ###################################################### w = RooWorkspace('w') getattr(w,'import')(x) w.factory('''RooDSCBShape::DSCB({0}, #mu[1777, 1760,1790], #sigma[5,0,10], #alpha[1.2], n[50, 1, 150], #alpha, n )'''.format(x_var)) #w.var('n').setConstant(False) signal = w.pdf('DSCB') # w.factory('''RooGaussian::GG({0}, # #mu, #sigma # )'''.format(x_var)) # signal = w.pdf('GG') # Fit fit_region = x.setRange('fit_region',1757,1797) result = signal.fitTo(dataSet, RooFit.Save(), RooFit.Range('fit_region')) # Frame frame = x.frame(RooFit.Title(' Combined mass KK#mu '+addTitlePlot)) dataSet.plotOn(frame) signal.plotOn(frame, RooFit.LineWidth(2)) # Legends signal.paramOn(frame, RooFit.Layout(0.6,0.9,0.9)) chi2 = round(frame.chiSquare(),2) leg = TLegend(0.3,0,.10,.10) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.AddEntry(0,'#chi^{2} ='+str(chi2),'') frame.addObject(leg) c1 = TCanvas('c1', 'c1') frame.Draw() c1.Update() for prm in ('#mu', '#sigma', '#alpha', 'n'): # TODO: automatize finding of variables from the function w.var(prm).setConstant() return w, c1
def __init__(self, pars): self.pars = pars self.ws = RooWorkspace("wjj2dfitter") self.utils = Wjj2DFitterUtils(self.pars) self.useImportPars = False self.rangeString = None obs = [] for v in self.pars.var: try: vName = self.pars.varNames[v] except AttributeError: vName = v obs.append(vName) var1 = self.ws.factory("%s[%f,%f]" % (vName, self.pars.varRanges[v][1], self.pars.varRanges[v][2])) var1.setUnit("GeV") try: var1.SetTitle(self.pars.varTitles[v]) except AttributeError: var1.SetTitle("m_{jj}") var1.setPlotLabel(var1.GetTitle()) if len(self.pars.varRanges[v][3]) > 1: vbinning = RooBinning( len(self.pars.varRanges[v][3]) - 1, array("d", self.pars.varRanges[v][3]), "%sBinning" % vName ) var1.setBinning(vbinning) else: var1.setBins(self.pars.varRanges[v][0]) var1.Print() if v in self.pars.exclude: var1.setRange("signalRegion", self.pars.exclude[v][0], self.pars.exclude[v][1]) var1.setRange("lowSideband", var1.getMin(), self.pars.exclude[v][0]) var1.setRange("highSideband", self.pars.exclude[v][1], var1.getMax()) self.rangeString = "lowSideband,highSideband" if hasattr(self.pars, "plotRanges"): var1.setRange("plotRange", self.pars.plotRanges[v][1], self.pars.plotRanges[v][2]) var1.setBins(self.pars.plotRanges[v][0], "plotBins") else: var1.setRange("plotRange", var1.getMin(), var1.getMax()) var1.setBins(var1.getBins(), "plotBins") self.ws.defineSet("obsSet", ",".join(obs))
def Split_DS(Save_DS=False): ws_file = TFile( "/afs/cern.ch/user/" + prefix + "/" + user + "/eos/lhcb/user/" + prefix + "/" + user + "/WrongSign/2015/WorkSpaces/Merged_Merged_WS.root", "read") wsp = ws_file.Get("wspace") ws_file.Close() LOG_D0_IPCHI2_OWNPV = wsp.var("LOG_D0_IPCHI2_OWNPV") Dst_DTF_D0_CTAU = wsp.var("Dst_DTF_D0_CTAU") Dst_DTF_D0_M = wsp.var("Dst_DTF_D0_M") DTF_D0sPi_M = wsp.var("DTF_D0sPi_M") DTF_D0sPi_M.setMax(2020) DTF_D0sPi_M.setMin(2000) dataset_RS_tot = wsp.data("dataset_RS") dataset_RS_tot.SetName("dataset_RS_tot") varset = RooArgSet("varset") varset.add(LOG_D0_IPCHI2_OWNPV) varset.add(DTF_D0sPi_M) varset.add(Dst_DTF_D0_CTAU) varset.add(Dst_DTF_D0_M) for i, bin in enumerate(decaytime_binnning): start = datetime.now() dataset_RS_dtb_init = RooDataSet( "dataset_RS_dtb_init", "Decaytime bin" + str(i), dataset_RS_tot, varset, "Dst_DTF_D0_CTAU>" + str(bin[0] * ctau) + "&&Dst_DTF_D0_CTAU<" + str(bin[1] * ctau) + "&&" + offline_cut) dataset_RS = Subtract_Distribution(dataset_RS_dtb_init, DTF_D0sPi_M, LOG_D0_IPCHI2_OWNPV, str(i)) dataset_RS.SetName("dataset_RS") wspace = RooWorkspace("wspace") wsfile2 = TFile( "~/eos/lhcb/user/" + prefix + "/" + user + "/WrongSign/2015/WorkSpaces/Merged_WS_Bin_" + str(i) + ".root", "recreate") wspace.rfimport(varset) wspace.rfimport(dataset_RS) wspace.Write("wspace") wsfile2.Close() print "Dataset " + str(i) + " creation took " + str(datetime.now() - start) + " \n" return True
def getWspace(self): """Read workspace""" wspaceName = "wspace.{0}".format(self.cfg.get('wspaceTag', "DEFAULT")) if wspaceName in self.process.sourcemanager.keys(): wspace = self.process.sourcemanager.get(wspaceName) else: if not isDEBUG: self.logger.logERROR( "RooWorkspace '{0}' not found".format(wspaceName)) self.logger.logDEBUG( "Please access RooWorkspace with WspaceReader") raise RuntimeError wspace = RooWorkspace(wspaceName) self.process.sourcemanager.update(wspaceName, wspace) wspace.addClassDeclImportDir(modulePath) #+ '/cpp') wspace.addClassImplImportDir(modulePath) #+ '/cpp') return wspace
def make_workspace(self): """Make RooWorkspace and dump to a file""" gSystem.AddIncludePath("-I$CMSSW_BASE/src/ "); gSystem.Load("$CMSSW_BASE/lib/slc5_amd64_gcc472/libHiggsAnalysisCombinedLimit.so"); gSystem.AddIncludePath("-I$ROOFITSYS/include"); self.w = RooWorkspace('w') #run all functions_and_definitions: for factory_statement in self.d_input['functions_and_definitions']: self.w.factory(factory_statement) for p in self.process_list: self.log.debug('Checking for shape in {0}/{1}'.format(self.datacard_name, p)) try: self.d_input[p]['shape'] except KeyError: pass else: if self.d_input[p]['shape']: self.shapes_exist = True self.w.factory(self.d_input[p]['shape']) self.log.debug('Printing workspace...') self.data_obs = self.w.pdf('ggH').generate(RooArgSet(self.w.var('mass4l')), self._get_observation()) self.data_obs.SetNameTitle('data_obs','data_obs') getattr(self.w,'import')(self.data_obs) if self.DEBUG: print 20*"----" self.w.Print() print 20*"----" self.w.writeToFile(self.shapes_output_file) self.log.debug('Datacard workspace written to {0}'.format(self.shapes_output_file))
def main(options, args): gROOT.Reset() #load our super special Polarization PDF gROOT.ProcessLine('.L RooPolarizationPdf.cxx+') gROOT.ProcessLine('.L RooPolarizationConstraint.cxx+') #setup integration intConf = ROOT.RooAbsReal.defaultIntegratorConfig() #intConf.Print('v') # intConf.method1D().setLabel('RooAdaptiveGaussKronrodIntegrator1D') intConf.setEpsAbs(1e-13) intConf.setEpsRel(1e-13) print intConf.epsAbs() print intConf.epsRel() # intConf.method2D().setLabel('RooMCIntegrator') # intConf.methodND().setLabel('RooMCIntegrator') output = TFile.Open(options.workspaceName + '.root', 'RECREATE') theWS = RooWorkspace(options.workspaceName, 1) #save the polarization PDF code in the RooWorkspace theWS.importClassCode('RooPolarization*', True) buildDataAndCategories(theWS, options, args) buildMassAndLifetimePDF(theWS) # if options.fitFrame is not None: # buildPolarizationPDF(theWS,options) #root is stupid output.cd() theWS.Print('v') ROOT.RooMsgService.instance().Print() doFit(theWS, options) theWS.Write() output.Close()
dcFN = outdir_datacards + 'Qstar' + str(mass) + '_datacard_nuisance.txt' wsFN = outdir_datacards + 'Qstar' + str(mass) + '_workspace_nuisance.root' #dcFN = outdir_datacards+'Qstar'+str(mass)+'_datacard_nuisance_testForSignificance.txt' #wsFN = outdir_datacards+'Qstar'+str(mass)+'_workspace_nuisance_testForSignificance.root' else: dcFN = outdir_datacards + 'Qstar' + str( mass) + '_datacard_' + name + '.txt' wsFN = outdir_datacards + 'Qstar' + str( mass) + '_workspace_' + name + '.root' nObs = dataHist_data.sumEntries() #nObs = roohistBkg.sumEntries(); #nBkg = roohistBkg.sumEntries(); w = RooWorkspace('w', 'workspace') getattr(w, 'import')(signal) getattr(w, 'import')(background) getattr(w, 'import')(background_norm) getattr(w, 'import')(roohistBkg, RooFit.Rename("data_obs")) #getattr(w,'import')(dataHist_data,RooFit.Rename("data_obs")) #getattr(w,'import')(background_f6) #getattr(w,'import')(background_f6_norm) w.Print() w.writeToFile(wsFN) # ----------------------------------------- # write a datacard ##not needed #ExpectedSignalRate = signalCrossSection*LUMI*signalEfficiency
#tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_ZMuMu.root") tree.Add( "/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012A.root" ) tree.Add( "/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012B.root" ) tree.Add( "/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012C.root" ) tree.Add( "/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012D.root" ) # Prepare the workspace ws = RooWorkspace("ws", "workspace") Workspace.buildPdf(ws, p) mass = ws.var("mass") sample = ws.cat("sample") simPdf = ws.pdf("simPdf") efficiency = ws.var("efficiency") meanB = ws.var("meanB") # prepare_datasets(ws, p) # Prepare datasets datasetAllMap = {} datasetPassMap = {} hAllMap = {} hPassMap = {}
setattr(RooWorkspace, "Import", getattr(RooWorkspace, "import")) ## Here starts the meat. nentries = -1 ## Pairs of photon scale and extra smearing. sTest = [-2, 0.5] rTest = [1, 0.5] phoPtRange = (15,20) chains = getChains('v11') mcTree = chains['z'] dataTree = chains['data'] w = RooWorkspace('w') massShift = 90 + 1.03506 ## Define variables mmgMass = w.factory('mmgMass[40, 180]') mmgMassShifted = w.factory('mmgMassShifted[-50, 90]') mmgGenMass = w.factory('mmgGenMass[0, 300]') mmgMassPhoGenE = w.factory('mmgMassPhoGenE[0, 300]') mmgMassShiftedPhoGenE = w.factory('mmgMassShiftedPhoGenE[-90, 210]') mmgMassPhoSmear = w.factory('mmgMassPhoSmear[-30,30]') mmgMassPhoSmear.SetTitle('mmgMass - mmgMassPhoGenE') phoERes = w.factory('phoERes[-0.3,3]') mmMass = w.factory('mmMass[10, 180]') weight = w.factory('weight[1]') phoScale = w.factory('phoScale[0,-50,50]')
print "WWTo4Q events: ", h[2][k].Integral() print "ZZTo4Q events: ", h[3][k].Integral() print "WZ events: ", h[4][k].Integral() print "TTWJetsToQQ events:", h[5][k].Integral() print "TTZToQQ events: ", h[6][k].Integral() print "ZJetsToQQ events: ", h[7][k].Integral() print "WJetsToQQ events: ", h[8][k].Integral() print "TTH events: ", h[0][k].Integral() dataf.cd() hData.append(TH1F("data_obsCAT" + str(NCAT[k]), "data_obsCAT" + str(NCAT[k]), 25, -1, 1)) datatree = dataf.Get("hadtop/events") hpu = dataf.Get("hadtop/pileup") datatree.Draw("mva>>" + hData[k].GetName(), CUT1[k]) workspace = RooWorkspace("w","workspace") RooSigHist = [] MVA = [] RooObsHist = [] RooSigHist = [] RooQCDHist = [] RooTTJHist = [] RooWWTo4QHist = [] RooZZTo4QHist = [] RooWZHist = [] RooTTWJetsToQQHist = [] RooTTZToQQHist = [] RooZJetsToQQHist = [] RooWJetsToQQHist = [] RooVVHist = []
def main(options,args): cfg = options.config workspaceName = cfg.get('Global','workspace') ws = RooWorkspace(workspaceName) #ws.Print("v") setupWorkspace(ws,options) #create -log(likelihood) theNLL = ws.pdf('TopLevelPdf').createNLL(ws.data('allcountingdata'), RooFit.NumCPU(1), RooFit.ConditionalObservables(ws.set('condObs')), RooFit.Verbose(True)) ws.saveSnapshot('standardmodel',ws.allVars()) minuit = ROOT.RooMinuit(theNLL) minuit.setPrintLevel(1) minuit.setPrintEvalErrors(-1) minuit.setErrorLevel(.5) #find the values of the parameters that minimize the likelihood minuit.setStrategy(2) minuit.simplex() minuit.migrad() minuit.hesse() #ws.var('err_gl').setConstant(True) #ws.var('err_gs').setConstant(True) #ws.var('err_gb').setConstant(True) ws.defineSet('POI', ROOT.RooArgSet(ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))), ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))))) ws.saveSnapshot('%s_fitresult'%cfg.get('Global','couplingType'), ws.allVars()) #create profile likelihood level_68 = ROOT.TMath.ChisquareQuantile(.68,2)/2.0 # delta NLL for 68% confidence level for -log(LR) level_95 = ROOT.TMath.ChisquareQuantile(.95,2)/2.0 # delta NLL for 95% confidence level for -log(LR) print print '68% CL Delta-NLL 2 DOF=',level_68 print '95% CL Delta-NLL 2 DOF=',level_95 minuit.setPrintLevel(1) minuit.setPrintEvalErrors(-1) minuit.migrad() minuit.minos(ws.set('POI')) thePlot = minuit.contour(ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))), ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))), sqrt(2*level_95),sqrt(2*level_68)) # here the error is in sigmas thePlot.SetName('%s_%s_%s_contour'%(cfg.get('Global','par1Name'), cfg.get('Global','par2Name'), cfg.get('Global','couplingType'))) thePlot.SetTitle('68% & 95% CL on the Best Fit Values of '+cfg.get('Global','par1Name')+' and '+cfg.get('Global','par2Name')) legend = ROOT.TLegend(2.01612903225806439e-01,7.86016949152542388e-01, 7.15725806451612989e-01,9.13135593220338992e-01) legend.SetNColumns(2) thePlot.addObject(legend) # 1-D Limits level_95 = ROOT.TMath.ChisquareQuantile(.95,1)/2.0 # delta NLL for -log(LR) with 1 dof print '95% CL Delta-NLL 1 DOF=',level_95 minuit.setErrorLevel(level_95) #set 1-D limits on parameter 1 with parameter 2 == 0 ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))).setVal(0.0) ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))).setConstant(True) minuit.minos(ws.set('POI')) parm1 = ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))) print 'parameter 1 value: '+str(parm1.getVal()) if not (0 < parm1.getVal()+parm1.getErrorHi() and 0 > parm1.getVal()+parm1.getErrorLo()): print '95% CL does not cover SM for parameter 1' else: print '95% CL covers SM for parameter 1' par1Line = ROOT.TLine(parm1.getVal()+parm1.getErrorLo(),0, parm1.getVal()+parm1.getErrorHi(),0) par1Line.SetLineWidth(2) par1Line.SetLineColor(ROOT.kRed) thePlot.addObject(par1Line) #set 1-D limits on parameter 2 with parameter 1 == 0 ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))).setConstant(False) ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))).setVal(0.0) ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))).setConstant(True) minuit.minos(ws.set('POI')) parm2 = ws.var('%s_%s'%(cfg.get('Global','par2Name'),cfg.get('Global','couplingType'))) print 'parameter 2 value: '+str(parm2.getVal()) if not (0 < parm2.getVal()+parm2.getErrorHi() and 0 > parm2.getVal()+parm2.getErrorLo()): print '95% CL does not cover SM for parameter 2' else: print '95% CL covers SM for parameter 2' par2Line = ROOT.TLine(0,parm2.getVal()+parm2.getErrorLo(), 0,parm2.getVal()+parm2.getErrorHi()) par2Line.SetLineWidth(2) par2Line.SetLineColor(ROOT.kRed) thePlot.addObject(par2Line) ws.var('%s_%s'%(cfg.get('Global','par1Name'),cfg.get('Global','couplingType'))).setConstant(False) #construct likelihood scan histograms plot = parm1.frame() parm1.setBins(200) parm2.setBins(200) scanHist = ROOT.TH2F('scan2d_plot','2D Scan of the Likelihood', 200,parm1.getMin(),parm1.getMax(), 200,parm2.getMin(),parm2.getMax()) for i in range(200): for j in range(200): parm1.setVal(parm1.getMin() + (i+.5)*(parm1.getMax()-parm1.getMin())/200) parm2.setVal(parm2.getMin() + (j+.5)*(parm2.getMax()-parm2.getMin())/200) scanHist.SetBinContent(i+1,j+1,theNLL.getVal()) profNLL_par1 = theNLL.createProfile(RooArgSet(parm1)) profNLL_par1_plot = parm1.frame() profNLL_par1.plotOn(profNLL_par1_plot) profNLL_par2 = theNLL.createProfile(RooArgSet(parm2)) profNLL_par2_plot = parm2.frame() profNLL_par2.plotOn(profNLL_par2_plot) initCMSStyle() output = TFile.Open(workspaceName+'.root','RECREATE') ws.Write() contCanvas = ROOT.TCanvas('contour_canvas','',500,500) thePlot.Draw() prettyContour(contCanvas,cfg) contCanvas.Write() thePlot.Write() scanCanvas2D = ROOT.TCanvas('scan2d_canvas','',500,500) scanHist.Draw('colz') prettyScan(scanCanvas2D,cfg) scanCanvas2D.Write() scanHist.Write() par1ScanCanvas = ROOT.TCanvas('scan1d_par1','',500,500) par1ScanCanvas.cd() profNLL_par1_plot.Draw() par1ScanCanvas.Write() profNLL_par1_plot.Write() par2ScanCanvas = ROOT.TCanvas('scan1d_par2','',500,500) par2ScanCanvas.cd() profNLL_par2_plot.Draw() par2ScanCanvas.Write() profNLL_par2_plot.Write() prettyObsPlots(ws,cfg) output.Close() if options.makeCards: print print "Creating cards for Higgs Combined Limit calculator!" makeHCLCards(ws,cfg) return 0
gROOT.LoadMacro("tdrstyle.C") gROOT.ProcessLine("setTDRStyle()") #TH1.SetDefaultSumw2() gStyle.SetMarkerSize(0.7) kBlue = 600 latex = TLatex() latex.SetNDC() latex.SetTextAlign(12) latex.SetTextFont(42) latex.SetTextSize(0.035) ws = RooWorkspace("ws") x = RooRealVar("x", "p_{T}^{reco}/p_{T}^{parton}", xlow,xup) obs = RooArgList(x) c1 = TCanvas("c1", "c1",600,600) ; if logy: c1.SetLogy() # Loop over input files (currently disabled) infile = TFile.Open(infilename) for ih in xrange(ih_,ih_+1): h = getattr(infile, "hh1_%i" % ih) data = RooDataHist("data_%i" %ih, "", obs, h) getattr(ws, 'import')(data) hl = getattr(infile, "hl_%i" % ih)
def signal(category): interPar = True n = len(genPoints) cColor = color[category] if category in color else 4 nBtag = category.count('b') isAH = False #relict from using Alberto's more complex script if not os.path.exists(PLOTDIR + "MC_signal_" + YEAR): os.makedirs(PLOTDIR + "MC_signal_" + YEAR) #*******************************************************# # # # Variables and selections # # # #*******************************************************# X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV") j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV") jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.) jbtag_WP_1 = RooRealVar("jbtag_WP_1", "", -1., 4.) jbtag_WP_2 = RooRealVar("jbtag_WP_2", "", -1., 4.) fatjetmass_1 = RooRealVar("fatjetmass_1", "", -1., 2500.) fatjetmass_2 = RooRealVar("fatjetmass_2", "", -1., 2500.) jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.) jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.) jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.) jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.) jnmuons_loose_1 = RooRealVar("jnmuons_loose_1", "jnmuons_loose_1", -1., 8.) jnmuons_loose_2 = RooRealVar("jnmuons_loose_2", "jnmuons_loose_2", -1., 8.) nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.) nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.) HLT_AK8PFJet500 = RooRealVar("HLT_AK8PFJet500", "", -1., 1.) HLT_PFJet500 = RooRealVar("HLT_PFJet500", "", -1., 1.) HLT_CaloJet500_NoJetID = RooRealVar("HLT_CaloJet500_NoJetID", "", -1., 1.) HLT_PFHT900 = RooRealVar("HLT_PFHT900", "", -1., 1.) HLT_AK8PFJet550 = RooRealVar("HLT_AK8PFJet550", "", -1., 1.) HLT_PFJet550 = RooRealVar("HLT_PFJet550", "", -1., 1.) HLT_CaloJet550_NoJetID = RooRealVar("HLT_CaloJet550_NoJetID", "", -1., 1.) HLT_PFHT1050 = RooRealVar("HLT_PFHT1050", "", -1., 1.) #HLT_DoublePFJets100_CaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets100_CaloBTagDeepCSV_p71" , "", -1., 1. ) #HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. ) #HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. ) #HLT_DoublePFJets200_CaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets200_CaloBTagDeepCSV_p71" , "", -1., 1. ) #HLT_DoublePFJets350_CaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets350_CaloBTagDeepCSV_p71" , "", -1., 1. ) #HLT_DoublePFJets40_CaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets40_CaloBTagDeepCSV_p71" , "", -1., 1. ) weight = RooRealVar("eventWeightLumi", "", -1.e9, 1.e9) # Define the RooArgSet which will include all the variables defined before # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add' variables = RooArgSet(X_mass) variables.add( RooArgSet(j1_pt, jj_deltaEta, jbtag_WP_1, jbtag_WP_2, fatjetmass_1, fatjetmass_2, jnmuons_1, jnmuons_2, weight)) variables.add( RooArgSet(nmuons, nelectrons, jid_1, jid_2, jnmuons_loose_1, jnmuons_loose_2)) variables.add( RooArgSet(HLT_AK8PFJet500, HLT_PFJet500, HLT_CaloJet500_NoJetID, HLT_PFHT900, HLT_AK8PFJet550, HLT_PFJet550, HLT_CaloJet550_NoJetID, HLT_PFHT1050)) #variables.add(RooArgSet(HLT_DoublePFJets100_CaloBTagDeepCSV_p71, HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets200_CaloBTagDeepCSV_p71, HLT_DoublePFJets350_CaloBTagDeepCSV_p71, HLT_DoublePFJets40_CaloBTagDeepCSV_p71)) X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax()) X_mass.setRange("X_integration_range", X_mass.getMin(), X_mass.getMax()) if VARBINS: binsXmass = RooBinning(len(abins) - 1, abins) X_mass.setBinning(binsXmass) 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 X_mass.setBinning(plot_binning, "PLOT") #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()) #X_mass.setBinning(binsXmass, "PLOT") massArg = RooArgSet(X_mass) # Cuts if BTAGGING == 'semimedium': SRcut = aliasSM[category] #SRcut = aliasSM[category+"_vetoAK8"] else: SRcut = alias[category].format(WP=working_points[BTAGGING]) #SRcut = alias[category+"_vetoAK8"].format(WP=working_points[BTAGGING]) if ADDSELECTION: SRcut += SELECTIONS[options.selection] print " Cut:\t", SRcut #*******************************************************# # # # Signal fits # # # #*******************************************************# treeSign = {} setSignal = {} vmean = {} vsigma = {} valpha1 = {} vslope1 = {} valpha2 = {} vslope2 = {} smean = {} ssigma = {} salpha1 = {} sslope1 = {} salpha2 = {} sslope2 = {} sbrwig = {} signal = {} signalExt = {} signalYield = {} signalIntegral = {} signalNorm = {} signalXS = {} frSignal = {} frSignal1 = {} frSignal2 = {} frSignal3 = {} # Signal shape uncertainties (common amongst all mass points) xmean_jes = RooRealVar( "CMS" + YEAR + "_sig_" + category + "_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.02, -1., 1.) #0.001 smean_jes = RooRealVar( "CMS" + YEAR + "_sig_" + category + "_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10) xsigma_jer = RooRealVar( "CMS" + YEAR + "_sig_" + category + "_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.10, -1., 1.) ssigma_jer = RooRealVar( "CMS" + YEAR + "_sig_" + category + "_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10) xmean_jes.setConstant(True) smean_jes.setConstant(True) xsigma_jer.setConstant(True) ssigma_jer.setConstant(True) for m in massPoints: signalMass = "%s_M%d" % (stype, m) signalName = "ZpBB_{}_{}_M{}".format(YEAR, category, m) sampleName = "ZpBB_M{}".format(m) signalColor = sample[sampleName][ 'linecolor'] if signalName in sample else 1 # define the signal PDF vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m * 0.96, m * 1.05) smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)", RooArgList(vmean[m], xmean_jes, smean_jes)) vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m * 0.0233, m * 0.019, m * 0.025) ssigma[m] = RooFormulaVar( signalName + "_sigma", "@0*(1+@1*@2)", RooArgList(vsigma[m], xsigma_jer, ssigma_jer)) valpha1[m] = RooRealVar( signalName + "_valpha1", "Crystal Ball alpha 1", 0.2, 0.05, 0.28 ) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0", RooArgList(valpha1[m])) #vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 0.1, 20.) # slope of the power tail vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 13., 10., 20.) # slope of the power tail sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0", RooArgList(vslope1[m])) valpha2[m] = RooRealVar(signalName + "_valpha2", "Crystal Ball alpha 2", 1.) valpha2[m].setConstant(True) salpha2[m] = RooFormulaVar(signalName + "_alpha2", "@0", RooArgList(valpha2[m])) #vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", 6., 2.5, 15.) # slope of the higher power tail ## FIXME test FIXME vslope2_estimation = -5.88111436852 + m * 0.00728809389442 + m * m * ( -1.65059568762e-06) + m * m * m * (1.25128996309e-10) vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", vslope2_estimation, vslope2_estimation * 0.9, vslope2_estimation * 1.1) # slope of the higher power tail ## FIXME end FIXME sslope2[m] = RooFormulaVar( signalName + "_slope2", "@0", RooArgList(vslope2[m])) # slope of the higher power tail signal[m] = RooDoubleCrystalBall(signalName, "m_{%s'} = %d GeV" % ('X', m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m], salpha2[m], sslope2[m]) # extend the PDF with the yield to perform an extended likelihood fit signalYield[m] = RooRealVar(signalName + "_yield", "signalYield", 50, 0., 1.e15) signalNorm[m] = RooRealVar(signalName + "_norm", "signalNorm", 1., 0., 1.e15) signalXS[m] = RooRealVar(signalName + "_xs", "signalXS", 1., 0., 1.e15) signalExt[m] = RooExtendPdf(signalName + "_ext", "extended p.d.f", signal[m], signalYield[m]) # ---------- if there is no simulated signal, skip this mass point ---------- if m in genPoints: if VERBOSE: print " - Mass point", m # define the dataset for the signal applying the SR cuts treeSign[m] = TChain("tree") if YEAR == 'run2': pd = sample[sampleName]['files'] if len(pd) > 3: print "multiple files given than years for a single masspoint:", pd sys.exit() for ss in pd: if not '2016' in ss and not '2017' in ss and not '2018' in ss: print "unknown year given in:", ss sys.exit() else: pd = [x for x in sample[sampleName]['files'] if YEAR in x] if len(pd) > 1: print "multiple files given for a single masspoint/year:", pd sys.exit() for ss in pd: if options.unskimmed: j = 0 while True: if os.path.exists(NTUPLEDIR + ss + "/" + ss + "_flatTuple_{}.root".format(j)): treeSign[m].Add(NTUPLEDIR + ss + "/" + ss + "_flatTuple_{}.root".format(j)) j += 1 else: print "found {} files for sample:".format(j), ss break else: if os.path.exists(NTUPLEDIR + ss + ".root"): treeSign[m].Add(NTUPLEDIR + ss + ".root") else: print "found no file for sample:", ss if treeSign[m].GetEntries() <= 0.: if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..." signalNorm[m].setVal(-1) vmean[m].setConstant(True) vsigma[m].setConstant(True) salpha1[m].setConstant(True) sslope1[m].setConstant(True) salpha2[m].setConstant(True) sslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) continue #setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar("eventWeightLumi*BTagAK4Weight_deepJet"), RooFit.Import(treeSign[m])) setSignal[m] = RooDataSet("setSignal_" + signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m])) if VERBOSE: print " - Dataset with", setSignal[m].sumEntries( ), "events loaded" # FIT entries = setSignal[m].sumEntries() if entries < 0. or entries != entries: entries = 0 signalYield[m].setVal(entries) # Instead of eventWeightLumi #signalYield[m].setVal(entries * LUMI / (300000 if YEAR=='run2' else 100000) ) if treeSign[m].GetEntries(SRcut) > 5: if VERBOSE: print " - Running fit" frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1)) if VERBOSE: print "********** Fit result [", m, "] **", category, "*" * 40, "\n", frSignal[ m].Print(), "\n", "*" * 80 if VERBOSE: frSignal[m].correlationMatrix().Print() drawPlot(signalMass + "_" + category, stype + category, X_mass, signal[m], setSignal[m], frSignal[m]) else: print " WARNING: signal", stype, "and mass point", m, "in category", category, "has 0 entries or does not exist" # Remove HVT cross sections #xs = getCrossSection(stype, channel, m) xs = 1. signalXS[m].setVal(xs * 1000.) signalIntegral[m] = signalExt[m].createIntegral( massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range")) boundaryFactor = signalIntegral[m].getVal() if boundaryFactor < 0. or boundaryFactor != boundaryFactor: boundaryFactor = 0 if VERBOSE: print " - Fit normalization vs integral:", signalYield[ m].getVal(), "/", boundaryFactor, "events" signalNorm[m].setVal(boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal() ) # here normalize to sigma(X) x Br = 1 [fb] vmean[m].setConstant(True) vsigma[m].setConstant(True) valpha1[m].setConstant(True) vslope1[m].setConstant(True) valpha2[m].setConstant(True) vslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) #*******************************************************# # # # Signal interpolation # # # #*******************************************************# ### FIXME FIXME just for a test FIXME FIXME #print #print #print "slope2 fit results:" #print #y_vals = [] #for m in genPoints: # y_vals.append(vslope2[m].getVal()) #print "m =", genPoints #print "y =", y_vals #sys.exit() ### FIXME FIXME test end FIXME FIXME # ====== CONTROL PLOT ====== color_scheme = [ 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633 ] c_signal = TCanvas("c_signal", "c_signal", 800, 600) c_signal.cd() frame_signal = X_mass.frame() for j, m in enumerate(genPoints): if m in signalExt.keys(): #print "color:",(j%9)+1 #print "signalNorm[m].getVal() =", signalNorm[m].getVal() #print "RooAbsReal.NumEvent =", RooAbsReal.NumEvent signal[m].plotOn( frame_signal, RooFit.LineColor(color_scheme[j]), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range")) frame_signal.GetXaxis().SetRangeUser(0, 10000) frame_signal.Draw() drawCMS(-1, "Simulation Preliminary", year=YEAR) #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) #drawCMS(-1, "", year=YEAR, suppressCMS=True) drawAnalysis(category) drawRegion(category) c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_Signal.pdf") c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_Signal.png") #if VERBOSE: raw_input("Press Enter to continue...") # ====== CONTROL PLOT ====== # Normalization gnorm = TGraphErrors() gnorm.SetTitle(";m_{X} (GeV);integral (GeV)") gnorm.SetMarkerStyle(20) gnorm.SetMarkerColor(1) gnorm.SetMaximum(0) inorm = TGraphErrors() inorm.SetMarkerStyle(24) fnorm = TF1("fnorm", "pol9", 700, 3000) fnorm.SetLineColor(920) fnorm.SetLineStyle(7) fnorm.SetFillColor(2) fnorm.SetLineColor(cColor) # Mean gmean = TGraphErrors() gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)") gmean.SetMarkerStyle(20) gmean.SetMarkerColor(cColor) gmean.SetLineColor(cColor) imean = TGraphErrors() imean.SetMarkerStyle(24) fmean = TF1("fmean", "pol1", 0, 10000) fmean.SetLineColor(2) fmean.SetFillColor(2) # Width gsigma = TGraphErrors() gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)") gsigma.SetMarkerStyle(20) gsigma.SetMarkerColor(cColor) gsigma.SetLineColor(cColor) isigma = TGraphErrors() isigma.SetMarkerStyle(24) fsigma = TF1("fsigma", "pol1", 0, 10000) fsigma.SetLineColor(2) fsigma.SetFillColor(2) # Alpha1 galpha1 = TGraphErrors() galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha") galpha1.SetMarkerStyle(20) galpha1.SetMarkerColor(cColor) galpha1.SetLineColor(cColor) ialpha1 = TGraphErrors() ialpha1.SetMarkerStyle(24) falpha1 = TF1("falpha", "pol1", 0, 10000) #pol0 falpha1.SetLineColor(2) falpha1.SetFillColor(2) # Slope1 gslope1 = TGraphErrors() gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)") gslope1.SetMarkerStyle(20) gslope1.SetMarkerColor(cColor) gslope1.SetLineColor(cColor) islope1 = TGraphErrors() islope1.SetMarkerStyle(24) fslope1 = TF1("fslope", "pol1", 0, 10000) #pol0 fslope1.SetLineColor(2) fslope1.SetFillColor(2) # Alpha2 galpha2 = TGraphErrors() galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha") galpha2.SetMarkerStyle(20) galpha2.SetMarkerColor(cColor) galpha2.SetLineColor(cColor) ialpha2 = TGraphErrors() ialpha2.SetMarkerStyle(24) falpha2 = TF1("falpha", "pol1", 0, 10000) #pol0 falpha2.SetLineColor(2) falpha2.SetFillColor(2) # Slope2 gslope2 = TGraphErrors() gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)") gslope2.SetMarkerStyle(20) gslope2.SetMarkerColor(cColor) gslope2.SetLineColor(cColor) islope2 = TGraphErrors() islope2.SetMarkerStyle(24) fslope2 = TF1("fslope", "pol1", 0, 10000) #pol0 fslope2.SetLineColor(2) fslope2.SetFillColor(2) n = 0 for i, m in enumerate(genPoints): if not m in signalNorm.keys(): continue if signalNorm[m].getVal() < 1.e-6: continue if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal()) gnorm.SetPoint(n, m, signalNorm[m].getVal()) #gnorm.SetPointError(i, 0, signalNorm[m].getVal()/math.sqrt(treeSign[m].GetEntriesFast())) gmean.SetPoint(n, m, vmean[m].getVal()) gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal() * 0.02)) gsigma.SetPoint(n, m, vsigma[m].getVal()) gsigma.SetPointError( n, 0, min(vsigma[m].getError(), vsigma[m].getVal() * 0.05)) galpha1.SetPoint(n, m, valpha1[m].getVal()) galpha1.SetPointError( n, 0, min(valpha1[m].getError(), valpha1[m].getVal() * 0.10)) gslope1.SetPoint(n, m, vslope1[m].getVal()) gslope1.SetPointError( n, 0, min(vslope1[m].getError(), vslope1[m].getVal() * 0.10)) galpha2.SetPoint(n, m, salpha2[m].getVal()) galpha2.SetPointError( n, 0, min(valpha2[m].getError(), valpha2[m].getVal() * 0.10)) gslope2.SetPoint(n, m, sslope2[m].getVal()) gslope2.SetPointError( n, 0, min(vslope2[m].getError(), vslope2[m].getVal() * 0.10)) #tmpVar = w.var(var+"_"+signalString) #print m, tmpVar.getVal(), tmpVar.getError() n = n + 1 gmean.Fit(fmean, "Q0", "SAME") gsigma.Fit(fsigma, "Q0", "SAME") galpha1.Fit(falpha1, "Q0", "SAME") gslope1.Fit(fslope1, "Q0", "SAME") galpha2.Fit(falpha2, "Q0", "SAME") gslope2.Fit(fslope2, "Q0", "SAME") # gnorm.Fit(fnorm, "Q0", "", 700, 5000) #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S")) #gnorm.Fit(fnorm, "Q", "SAME", 700, 6000) gnorm.Fit(fnorm, "Q", "SAME", 1800, 8000) ## adjusted recently for m in massPoints: if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.) # Interpolation method syield = gnorm.Eval(m) spline = gnorm.Eval(m, 0, "S") sfunct = fnorm.Eval(m) #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield)) delta = abs(1. - spline / sfunct) if sfunct > 0 else 0 syield = spline if interPar: #jmean = gmean.Eval(m) #jsigma = gsigma.Eval(m) #jalpha1 = galpha1.Eval(m) #jslope1 = gslope1.Eval(m) #jalpha2 = galpha2.Eval(m) #jslope2 = gslope2.Eval(m) jmean = gmean.Eval(m, 0, "S") jsigma = gsigma.Eval(m, 0, "S") jalpha1 = galpha1.Eval(m, 0, "S") jslope1 = gslope1.Eval(m, 0, "S") jalpha2 = galpha2.Eval(m, 0, "S") jslope2 = gslope2.Eval(m, 0, "S") else: jmean = fmean.GetParameter( 0) + fmean.GetParameter(1) * m + fmean.GetParameter(2) * m * m jsigma = fsigma.GetParameter(0) + fsigma.GetParameter( 1) * m + fsigma.GetParameter(2) * m * m jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter( 1) * m + falpha1.GetParameter(2) * m * m jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter( 1) * m + fslope1.GetParameter(2) * m * m jalpha2 = falpha2.GetParameter(0) + falpha2.GetParameter( 1) * m + falpha2.GetParameter(2) * m * m jslope2 = fslope2.GetParameter(0) + fslope2.GetParameter( 1) * m + fslope2.GetParameter(2) * m * m inorm.SetPoint(inorm.GetN(), m, syield) signalNorm[m].setVal(max(0., syield)) imean.SetPoint(imean.GetN(), m, jmean) if jmean > 0: vmean[m].setVal(jmean) isigma.SetPoint(isigma.GetN(), m, jsigma) if jsigma > 0: vsigma[m].setVal(jsigma) ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1) if not jalpha1 == 0: valpha1[m].setVal(jalpha1) islope1.SetPoint(islope1.GetN(), m, jslope1) if jslope1 > 0: vslope1[m].setVal(jslope1) ialpha2.SetPoint(ialpha2.GetN(), m, jalpha2) if not jalpha2 == 0: valpha2[m].setVal(jalpha2) islope2.SetPoint(islope2.GetN(), m, jslope2) if jslope2 > 0: vslope2[m].setVal(jslope2) #### newly introduced, not yet sure if helpful: vmean[m].removeError() vsigma[m].removeError() valpha1[m].removeError() valpha2[m].removeError() vslope1[m].removeError() vslope2[m].removeError() #signalNorm[m].setConstant(False) ## newly put here to ensure it's freely floating in the combine fit #c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200 #c1.Divide(2, 3) c1 = TCanvas("c1", "Crystal Ball", 1800, 800) c1.Divide(3, 2) c1.cd(1) gmean.SetMinimum(0.) gmean.Draw("APL") imean.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME c1.cd(2) gsigma.SetMinimum(0.) gsigma.Draw("APL") isigma.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME c1.cd(3) galpha1.Draw("APL") ialpha1.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME galpha1.GetYaxis().SetRangeUser(0., 1.1) #adjusted upper limit from 5 to 2 c1.cd(4) gslope1.Draw("APL") islope1.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME gslope1.GetYaxis().SetRangeUser(0., 150.) #adjusted upper limit from 125 to 60 if True: #isAH: c1.cd(5) galpha2.Draw("APL") ialpha2.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME galpha2.GetYaxis().SetRangeUser(0., 2.) c1.cd(6) gslope2.Draw("APL") islope2.Draw("P, SAME") drawRegion(category) drawCMS(-1, "Simulation Preliminary", year=YEAR) ## new FIXME gslope2.GetYaxis().SetRangeUser(0., 20.) c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_SignalShape.pdf") c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_SignalShape.png") c2 = TCanvas("c2", "Signal Efficiency", 800, 600) c2.cd(1) gnorm.SetMarkerColor(cColor) gnorm.SetMarkerStyle(20) gnorm.SetLineColor(cColor) gnorm.SetLineWidth(2) gnorm.Draw("APL") inorm.Draw("P, SAME") gnorm.GetXaxis().SetRangeUser(genPoints[0] - 100, genPoints[-1] + 100) gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum() * 1.25) drawCMS(-1, "Simulation Preliminary", year=YEAR) #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) #drawCMS(-1, "", year=YEAR, suppressCMS=True) drawAnalysis(category) drawRegion(category) c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_SignalNorm.pdf") c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category + "_SignalNorm.png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# # create workspace w = RooWorkspace("Zprime_" + YEAR, "workspace") for m in massPoints: getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName())) getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName())) getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName())) w.writeToFile(WORKDIR + "MC_signal_%s_%s.root" % (YEAR, category), True) print "Workspace", WORKDIR + "MC_signal_%s_%s.root" % ( YEAR, category), "saved successfully"
candArr = array.array('d') limitHist=TH2D("limit","limit",n_massbins,xedges,n_epsbins,yedges) detectableHist=TH2D("detectable","detectable",n_massbins,xedges,n_epsbins,yedges) gammactHist=TH2D("gammact","gammact",n_massbins,xedges,n_epsbins,yedges) allzHist=TH2D("detectable_allz","detectable_allz",n_massbins,xedges,n_epsbins,yedges) prodHist=TH2D("production","production",n_massbins,xedges,n_epsbins,yedges) candHist=TH1D("candidates","candidates",n_massbins,xedges) fcLowerHist=TH2D("fcLowerLimit","fcLowerLimit",n_massbins,xedges,n_epsbins,yedges) fcUpperHist=TH2D("fcUpperLimit","fcUpperLimit",n_massbins,xedges,n_epsbins,yedges) plrPvalHist=TH2D("plrPval","plrPval",n_massbins,xedges,n_epsbins,yedges) plrSigHist=TH2D("plrSig","plrSig",n_massbins,xedges,n_epsbins,yedges) logplrHist=TH2D("logplr","logplr",n_massbins,xedges,n_epsbins,yedges) candRescaledHist=TH1D("candidates_rescaled","candidates_rescaled",100,0,1.0) candRescaled2DHist=TH2D("candidates_rescaled_2d","candidates_rescaled_2d",n_massbins,xedges,100,0,1.0) w = RooWorkspace("w") w.factory("{0}[0,0.1]".format(massVar)) w.factory("uncVZ[-100,100]") w.factory("uncP[0,10]") w.factory("cut[0,1]") w.defineSet("myVars","{0},uncVZ".format(massVar)) dataset = RooDataSet("data","data",events,w.set("myVars"),"") w.factory("Gaussian::vtx_model(uncVZ,mean[-50,50],sigma[0,50])") gauss_pdf = w.pdf("vtx_model") w.factory("EXPR::gaussExp('exp( ((@0-@1)<@3)*(-0.5*(@0-@1)^2/@2^2) + ((@0-@1)>=@3)*(-0.5*@3^2/@2^2-(@0-@1-@3)/@4))',uncVZ,gauss_mean[-5,-20,20],gauss_sigma[5,1,50],exp_breakpoint[10,0,50],exp_length[3,0.5,20])") gaussexp_pdf = w.pdf("gaussExp") w.defineSet("obs_1d","uncVZ") obs=w.set("obs_1d")
RooMsgService.instance().setGlobalKillBelow(RooFit.FATAL) hidatafile = 'data/dimuonTree_150mub.root' ppdatafile = 'data/dimuonTree_2011_pp.root' mmin = 7. mmax = 14. cuts = '(muPlusPt > %0.1f) && (muMinusPt > %0.1f) && (abs(upsRapidity)<2.4) && (vProb > 0.05)' \ % (opts.pt, opts.pt) simparamfile = opts.paramfile useKeys = opts.keys ## cuts = '(muPlusPt > 3.5) && (muMinusPt > 3.5) && (abs(upsRapidity)<2.4)' ## simparamfile = 'nom3.5SimFit.txt' ws = RooWorkspace("ws","ws") readData(ws, hidatafile, ppdatafile, cuts, mmin, mmax) mass = ws.var('invariantMass') ppBkgModel = 1 bkgModel = 0 if useKeys: bkgModel = 2 mass.Print() buildPdf(ws, False, ppBkgModel, True) buildPdf(ws, True, bkgModel, True) simPdf = buildSimPdf(ws, ws.cat('dataCat'))
minPed = TMath.MinElement(dataTree.GetSelectedRows(), dataTree.GetV1()) maxPed = TMath.MaxElement(dataTree.GetSelectedRows(), dataTree.GetV1()) #print 'minPed:',minPed,'maxPed:',maxPed minPed = int(minPed) - 2.5 maxPed = int(maxPed) + 2.5 print 'minPed:',minPed,'maxPed:',maxPed while int((maxPed-minPed)/2.)*2. < (maxPed-minPed): maxPed += 1. print 'minPed:',minPed,'maxPed:',maxPed dataTree.Draw('{0}>>pedhist({1},{2:0.1f},{3:0.1f}'.format(HOTower, int(maxPed-minPed), minPed,maxPed), pedCut, 'goff') pedhist = gDirectory.Get('pedhist') ws = RooWorkspace('ws') x = RooRealVar('x', 'energy', minPed, maxPed, 'fC') x.Print() ds = fillDataSet(dataTree.GetV1(), x, dataTree.GetSelectedRows()) getattr(ws, 'import')(ds) findOnePe(pedhist, ws, Npe=opts.npe) pedPlusOne = ws.pdf('pedPlusOne') peMean = ws.var('peMean') pedMean = ws.var('pedMean') ## pedhist.Draw() ## onePeF.Draw('same') xf = x.frame(x.getMin(), x.getMax(), int(x.getMax()-x.getMin())) ds.plotOn(xf)
binWidth = 1. if opts.sipm: # maxMip = int(maxPed + pedRms*80) + 0.5 maxMip = int(maxPed + pedRms * 100) + 0.5 binWidth = 5. else: maxMip = int(maxPed + pedRms * 20) + 0.5 while int((maxMip - minMip) / binWidth) * binWidth < (maxMip - minMip): maxMip += 1 Nbins = int((maxMip - minMip) / binWidth + 0.5) print 'ped min: {0:0.2f} max: {1:0.2f}'.format(minPed,maxPed), \ 'sig min: {0:0.1f} max: {1:0.1f}'.format(minMip, maxMip) ws = RooWorkspace('ws') x = RooRealVar('x', 'energy', minMip, maxMip, 'fC') dataTree.Draw( '{0}>>ped_hist({1},{2:0.1f},{3:0.1f})'.format(HOTower, 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:
hData) rooDataHist.Print() if args.runFit: res = model.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy)) if not args.decoBkg: res.Print() # decorrelated background parameters for Bayesian limits if args.decoBkg: signal_norm.setConstant() res = model.fitTo(rooDataHist, RooFit.Save(kTRUE), RooFit.Strategy(args.fitStrategy)) res.Print() ## temp workspace for the PDF diagonalizer w_tmp = RooWorkspace("w_tmp") deco = PdfDiagonalizer("deco", w_tmp, res) # here diagonalizing only the shape parameters since the overall normalization is already decorrelated background_deco = deco.diagonalize(background) print "##################### workspace for decorrelation" w_tmp.Print("v") print "##################### original parameters" background.getParameters(rooDataHist).Print("v") print "##################### decorrelated parameters" # needed if want to evaluate limits without background systematics if args.fixBkg: w_tmp.var("deco_eig1").setConstant() w_tmp.var("deco_eig2").setConstant() if not args.fixP3: w_tmp.var("deco_eig3").setConstant() background_deco.getParameters(rooDataHist).Print("v") print "##################### original pdf"
#!/usr/bin/env python from ROOT import TFile, TH1F, TH1D, TCanvas, RooRealVar, RooDataHist, RooDataSet, RooArgSet, RooArgList from ROOT import RooGaussian, RooAddPdf, RooPolynomial, RooExponential, RooCBShape, RooArgusBG, RooFit, RooWorkspace, RooGenericPdf inF = TFile.Open('a.root') space = RooWorkspace('space', False) # fit lbtkMass in 2016Data {{{ space.factory('mass[5.100,7.]') mass = space.var('mass') inH = inF.Get('lbtkCombBKG') datahist = RooDataHist('histogram', 'histogram', RooArgList(mass), inH) # create target PDF. #space.factory('EXPR::cPDF( "( exp(-1.*(mass-mShift)/(cPar1+cPar2)) - exp(-1.*(mass-mShift)/cPar1) )", mass, mShift[4.8,0.1,10.0], cPar1[0.44,0.001,100.],cPar2[0.0025,0.0000001,10.] )') space.factory( 'EXPR::cPDF( "( exp(-1.*(mass-mShift)/(cPar1+cPar2)) - exp(-1.*(mass-mShift)/cPar1) )", mass, mShift[4.8,0.1,10.0], cPar1[0.44,0.001,100.],cPar2[0.0025,0.0000001,10.] )' ) myPDF = space.pdf('cPDF') myPDF.fitTo(datahist) myPDF.fitTo(datahist) myPDF.fitTo(datahist) myFrame = mass.frame() datahist.plotOn(myFrame) myPDF.plotOn(myFrame) canv = TCanvas('c1', 'c1', 1600, 1000) myFrame.Draw() canv.SaveAs('store_fig/hout_simpleFit_lbDist_from2016Data.png')
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]) # start building the fit ws = RooWorkspace('ws_%s' % config['Context']) 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')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 # HACK (1/2): be careful about lower bound on eta, since mistagpdf below # is zero below a certain value - generation in accept/reject would get # stuck eta = WS( ws, RooRealVar( 'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']), 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qt, qf, time, eta, timeerr] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context']], 'FIT' in config['Context']) # float for fitting if 'GEN' in config['Context']: acc = accnorm # use normalised acceptance for generation # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) # build a (mock) mistag distribution mistagpdfparams = {} # start with parameters of mock distribution for sfx in ('omega0', 'omegaavg', 'f'): mistagpdfparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['TrivialMistagParams'][sfx])) # build mistag pdf itself mistagpdf = WS( ws, MistagDistribution('Bs2DsPi_mistagpdf', 'Bs2DsPi_mistagpdf', eta, mistagpdfparams['omega0'], mistagpdfparams['omegaavg'], mistagpdfparams['f'])) # build mistag calibration mistagcalibparams = {} # start with parameters of calibration for sfx in ('p0', 'p1', 'etaavg'): mistagcalibparams[sfx] = WS( ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['MistagCalibParams'][sfx])) for sfx in ('p0', 'p1'): # float calibration paramters mistagcalibparams[sfx].setConstant(False) mistagcalibparams[sfx].setError(0.1) # build mistag pdf itself omega = WS( ws, MistagCalibration('Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta, mistagcalibparams['p0'], mistagcalibparams['p1'], mistagcalibparams['etaavg'])) # build mock decay time error distribution (~ timeerr^6 * exp(-timerr / # (timerr_av / 7)) terrpdf_shape = WS( ws, RooConstVar('timeerr_ac', 'timeerr_ac', config['DecayTimeResolutionAvg'] / 7.)) terrpdf_truth = WS( ws, RooTruthModel('terrpdf_truth', 'terrpdf_truth', timeerr)) terrpdf_i0 = WS( ws, RooDecay('terrpdf_i0', 'terrpdf_i0', timeerr, terrpdf_shape, terrpdf_truth, RooDecay.SingleSided)) terrpdf_i1 = WS( ws, RooPolynomial('terrpdf_i1', 'terrpdf_i1', timeerr, RooArgList(zero, zero, zero, zero, zero, zero, one), 0)) terrpdf = WS(ws, RooProdPdf('terrpdf', 'terrpdf', terrpdf_i0, terrpdf_i1)) # build the time pdf pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[omega]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=terrpdf, mistagpdf=[mistagpdf], mistagobs=eta) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
setattr(RooWorkspace, "Import", getattr(RooWorkspace, "import")) ## Here starts the meat. nentries = -1 ## Pairs of photon scale and extra smearing. sTest = [-2, 0.5] rTest = [1, 0.5] phoPtRange = (15, 20) chains = getChains("v11") mcTree = chains["z"] dataTree = chains["data"] w = RooWorkspace("w") massShift = 90 + 1.03506 ## Define variables mmgMass = w.factory("mmgMass[40, 180]") mmgMassShifted = w.factory("mmgMassShifted[-50, 90]") mmgGenMass = w.factory("mmgGenMass[0, 300]") mmgMassPhoGenE = w.factory("mmgMassPhoGenE[0, 300]") mmgMassShiftedPhoGenE = w.factory("mmgMassShiftedPhoGenE[-90, 210]") mmgMassPhoSmear = w.factory("mmgMassPhoSmear[-30,30]") mmgMassPhoSmear.SetTitle("mmgMass - mmgMassPhoGenE") phoERes = w.factory("phoERes[-0.3,3]") mmMass = w.factory("mmMass[10, 180]") weight = w.factory("weight[1]") phoScale = w.factory("phoScale[0,-50,50]")
def signal(channel, stype): if 'VBF' in channel: stype = 'XZHVBF' else: stype = 'XZH' # HVT model if stype.startswith('X'): signalType = 'HVT' genPoints = [800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000] massPoints = [x for x in range(800, 5000+1, 100)] interPar = True else: print "Signal type", stype, "not recognized" return n = len(genPoints) category = channel cColor = color[category] if category in color else 1 nElec = channel.count('e') nMuon = channel.count('m') nLept = nElec + nMuon nBtag = channel.count('b') if '0b' in channel: nBtag = 0 X_name = "VH_mass" if not os.path.exists(PLOTDIR+stype+category): os.makedirs(PLOTDIR+stype+category) #*******************************************************# # # # Variables and selections # # # #*******************************************************# X_mass = RooRealVar( "X_mass", "m_{ZH}", XBINMIN, XBINMAX, "GeV") J_mass = RooRealVar( "H_mass", "jet mass", LOWMIN, HIGMAX, "GeV") V_mass = RooRealVar( "V_mass", "V jet mass", -9., 1.e6, "GeV") CSV1 = RooRealVar( "H_csv1", "", -999., 2. ) CSV2 = RooRealVar( "H_csv2", "", -999., 2. ) DeepCSV1= RooRealVar( "H_deepcsv1", "", -999., 2. ) DeepCSV2= RooRealVar( "H_deepcsv2", "", -999., 2. ) H_ntag = RooRealVar( "H_ntag", "", -9., 9. ) H_dbt = RooRealVar( "H_dbt", "", -2., 2. ) H_tau21 = RooRealVar( "H_tau21", "", -9., 2. ) H_eta = RooRealVar( "H_eta", "", -9., 9. ) H_tau21_ddt = RooRealVar( "H_ddt", "", -9., 2. ) MaxBTag = RooRealVar( "MaxBTag", "", -10., 2. ) H_chf = RooRealVar( "H_chf", "", -1., 2. ) MinDPhi = RooRealVar( "MinDPhi", "", -1., 99. ) DPhi = RooRealVar( "DPhi", "", -1., 99. ) DEta = RooRealVar( "DEta", "", -1., 99. ) Mu1_relIso = RooRealVar( "Mu1_relIso", "", -1., 99. ) Mu2_relIso = RooRealVar( "Mu2_relIso", "", -1., 99. ) nTaus = RooRealVar( "nTaus", "", -1., 99. ) Vpt = RooRealVar( "V.Pt()", "", -1., 1.e6 ) V_pt = RooRealVar( "V_pt", "", -1., 1.e6 ) H_pt = RooRealVar( "H_pt", "", -1., 1.e6 ) VH_deltaR=RooRealVar( "VH_deltaR", "", -1., 99. ) isZtoNN = RooRealVar( "isZtoNN", "", 0., 2. ) isZtoEE = RooRealVar( "isZtoEE", "", 0., 2. ) isZtoMM = RooRealVar( "isZtoMM", "", 0., 2. ) isHtobb = RooRealVar( "isHtobb", "", 0., 2. ) isVBF = RooRealVar( "isVBF", "", 0., 2. ) isMaxBTag_loose = RooRealVar( "isMaxBTag_loose", "", 0., 2. ) weight = RooRealVar( "eventWeightLumi", "", -1.e9, 1.e9 ) Xmin = XBINMIN Xmax = XBINMAX # Define the RooArgSet which will include all the variables defined before # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add' variables = RooArgSet(X_mass, J_mass, V_mass, CSV1, CSV2, H_ntag, H_dbt, H_tau21) variables.add(RooArgSet(DEta, DPhi, MaxBTag, MinDPhi, nTaus, Vpt)) variables.add(RooArgSet(DeepCSV1, DeepCSV2,VH_deltaR, H_tau21_ddt)) variables.add(RooArgSet(isZtoNN, isZtoEE, isZtoMM, isHtobb, isMaxBTag_loose, weight)) variables.add(RooArgSet(isVBF, Mu1_relIso, Mu2_relIso, H_chf, H_pt, V_pt,H_eta)) #X_mass.setRange("X_extended_range", X_mass.getMin(), X_mass.getMax()) X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax()) X_mass.setRange("X_integration_range", Xmin, Xmax) X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/100)) binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax()) X_mass.setBinning(binsXmass, "PLOT") massArg = RooArgSet(X_mass) # Cuts SRcut = selection[category]+selection['SR'] print " Cut:\t", SRcut #*******************************************************# # # # Signal fits # # # #*******************************************************# treeSign = {} setSignal = {} vmean = {} vsigma = {} valpha1 = {} vslope1 = {} smean = {} ssigma = {} salpha1 = {} sslope1 = {} salpha2 = {} sslope2 = {} a1 = {} a2 = {} sbrwig = {} signal = {} signalExt = {} signalYield = {} signalIntegral = {} signalNorm = {} signalXS = {} frSignal = {} frSignal1 = {} frSignal2 = {} frSignal3 = {} # Signal shape uncertainties (common amongst all mass points) xmean_fit = RooRealVar("sig_p1_fit", "Variation of the resonance position with the fit uncertainty", 0.005, -1., 1.) smean_fit = RooRealVar("CMSRunII_sig_p1_fit", "Change of the resonance position with the fit uncertainty", 0., -10, 10) xmean_jes = RooRealVar("sig_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.010, -1., 1.) #0.001 smean_jes = RooRealVar("CMSRunII_sig_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10) xmean_e = RooRealVar("sig_p1_scale_e", "Variation of the resonance position with the electron energy scale", 0.001, -1., 1.) smean_e = RooRealVar("CMSRunII_sig_p1_scale_e", "Change of the resonance position with the electron energy scale", 0., -10, 10) xmean_m = RooRealVar("sig_p1_scale_m", "Variation of the resonance position with the muon energy scale", 0.001, -1., 1.) smean_m = RooRealVar("CMSRunII_sig_p1_scale_m", "Change of the resonance position with the muon energy scale", 0., -10, 10) xsigma_fit = RooRealVar("sig_p2_fit", "Variation of the resonance width with the fit uncertainty", 0.02, -1., 1.) ssigma_fit = RooRealVar("CMSRunII_sig_p2_fit", "Change of the resonance width with the fit uncertainty", 0., -10, 10) xsigma_jes = RooRealVar("sig_p2_scale_jes", "Variation of the resonance width with the jet energy scale", 0.010, -1., 1.) #0.001 ssigma_jes = RooRealVar("CMSRunII_sig_p2_jes", "Change of the resonance width with the jet energy scale", 0., -10, 10) xsigma_jer = RooRealVar("sig_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.020, -1., 1.) ssigma_jer = RooRealVar("CMSRunII_sig_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10) xsigma_e = RooRealVar("sig_p2_scale_e", "Variation of the resonance width with the electron energy scale", 0.001, -1., 1.) ssigma_e = RooRealVar("CMSRunII_sig_p2_scale_e", "Change of the resonance width with the electron energy scale", 0., -10, 10) xsigma_m = RooRealVar("sig_p2_scale_m", "Variation of the resonance width with the muon energy scale", 0.040, -1., 1.) ssigma_m = RooRealVar("CMSRunII_sig_p2_scale_m", "Change of the resonance width with the muon energy scale", 0., -10, 10) xalpha1_fit = RooRealVar("sig_p3_fit", "Variation of the resonance alpha with the fit uncertainty", 0.03, -1., 1.) salpha1_fit = RooRealVar("CMSRunII_sig_p3_fit", "Change of the resonance alpha with the fit uncertainty", 0., -10, 10) xslope1_fit = RooRealVar("sig_p4_fit", "Variation of the resonance slope with the fit uncertainty", 0.10, -1., 1.) sslope1_fit = RooRealVar("CMSRunII_sig_p4_fit", "Change of the resonance slope with the fit uncertainty", 0., -10, 10) xmean_fit.setConstant(True) smean_fit.setConstant(True) xmean_jes.setConstant(True) smean_jes.setConstant(True) xmean_e.setConstant(True) smean_e.setConstant(True) xmean_m.setConstant(True) smean_m.setConstant(True) xsigma_fit.setConstant(True) ssigma_fit.setConstant(True) xsigma_jes.setConstant(True) ssigma_jes.setConstant(True) xsigma_jer.setConstant(True) ssigma_jer.setConstant(True) xsigma_e.setConstant(True) ssigma_e.setConstant(True) xsigma_m.setConstant(True) ssigma_m.setConstant(True) xalpha1_fit.setConstant(True) salpha1_fit.setConstant(True) xslope1_fit.setConstant(True) sslope1_fit.setConstant(True) # the alpha method is now done. for m in massPoints: signalString = "M%d" % m signalMass = "%s_M%d" % (stype, m) signalName = "%s%s_M%d" % (stype, category, m) signalColor = sample[signalMass]['linecolor'] if signalName in sample else 1 # define the signal PDF vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.5, m*1.25) smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)", RooArgList(vmean[m], xmean_e, smean_e, xmean_m, smean_m, xmean_jes, smean_jes, xmean_fit, smean_fit)) vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.035, m*0.01, m*0.4) sigmaList = RooArgList(vsigma[m], xsigma_e, ssigma_e, xsigma_m, ssigma_m, xsigma_jes, ssigma_jes, xsigma_jer, ssigma_jer) sigmaList.add(RooArgList(xsigma_fit, ssigma_fit)) ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)*(1+@9*@10)", sigmaList) valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha", 1., 0., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0*(1+@1*@2)", RooArgList(valpha1[m], xalpha1_fit, salpha1_fit)) vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope", 10., 1., 60.) # slope of the power tail #10 1 60 sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0*(1+@1*@2)", RooArgList(vslope1[m], xslope1_fit, sslope1_fit)) salpha2[m] = RooRealVar(signalName + "_alpha2", "Crystal Ball alpha", 2, 1., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right sslope2[m] = RooRealVar(signalName + "_slope2", "Crystal Ball slope", 10, 1.e-1, 115.) # slope of the power tail #define polynomial #a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", m, 0.5*m, 2*m) a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", 0.001*m, 0.0005*m, 0.01*m) a2[m] = RooRealVar(signalName + "_a2", "par 2 for polynomial", 0.05, -1.,1.) #if channel=='nnbbVBF' or channel=='nn0bVBF': # signal[m] = RooPolynomial(signalName,"m_{%s'} = %d GeV" % (stype[1], m) , X_mass, RooArgList(a1[m],a2[m])) #else: # signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel # extend the PDF with the yield to perform an extended likelihood fit signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 100, 0., 1.e6) signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e6) signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e6) signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m]) vslope1[m].setMax(50.) vslope1[m].setVal(20.) #valpha1[m].setVal(1.0) #valpha1[m].setConstant(True) if 'bb' in channel and 'VBF' not in channel: if 'nn' in channel: valpha1[m].setVal(0.5) elif '0b' in channel and 'VBF' not in channel: if 'nn' in channel: if m==800: valpha1[m].setVal(2.) vsigma[m].setVal(m*0.04) elif 'ee' in channel: valpha1[m].setVal(0.8) if m==800: #valpha1[m].setVal(1.2) valpha1[m].setVal(2.5) vslope1[m].setVal(50.) elif 'mm' in channel: if m==800: valpha1[m].setVal(2.) vsigma[m].setVal(m*0.03) else: vmean[m].setVal(m*0.9) vsigma[m].setVal(m*0.08) elif 'bb' in channel and 'VBF' in channel: if 'nn' in channel: if m!=1800: vmean[m].setVal(m*0.8) vsigma[m].setVal(m*0.08) valpha1[m].setMin(1.) elif 'ee' in channel: valpha1[m].setVal(0.7) elif 'mm' in channel: if m==800: vslope1[m].setVal(50.) valpha1[m].setVal(0.7) elif '0b' in channel and 'VBF' in channel: if 'nn' in channel: valpha1[m].setVal(3.) vmean[m].setVal(m*0.8) vsigma[m].setVal(m*0.08) valpha1[m].setMin(1.) elif 'ee' in channel: if m<2500: valpha1[m].setVal(2.) if m==800: vsigma[m].setVal(m*0.05) elif m==1000: vsigma[m].setVal(m*0.03) elif m>1000 and m<1800: vsigma[m].setVal(m*0.04) elif 'mm' in channel: if m<2000: valpha1[m].setVal(2.) if m==1000 or m==1800: vsigma[m].setVal(m*0.03) elif m==1200 or m==1600: vsigma[m].setVal(m*0.04) #if m < 1000: vsigma[m].setVal(m*0.06) # If it's not the proper channel, make it a gaussian #if nLept==0 and 'VBF' in channel: # valpha1[m].setVal(5) # valpha1[m].setConstant(True) # vslope1[m].setConstant(True) # salpha2[m].setConstant(True) # sslope2[m].setConstant(True) # ---------- if there is no simulated signal, skip this mass point ---------- if m in genPoints: if VERBOSE: print " - Mass point", m # define the dataset for the signal applying the SR cuts treeSign[m] = TChain("tree") for j, ss in enumerate(sample[signalMass]['files']): treeSign[m].Add(NTUPLEDIR + ss + ".root") if treeSign[m].GetEntries() <= 0.: if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..." signalNorm[m].setVal(-1) vmean[m].setConstant(True) vsigma[m].setConstant(True) salpha1[m].setConstant(True) sslope1[m].setConstant(True) salpha2[m].setConstant(True) sslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) continue setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m])) if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded" # FIT signalYield[m].setVal(setSignal[m].sumEntries()) if treeSign[m].GetEntries(SRcut) > 5: if VERBOSE: print " - Running fit" frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1)) if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80 if VERBOSE: frSignal[m].correlationMatrix().Print() drawPlot(signalMass, stype+channel, X_mass, signal[m], setSignal[m], frSignal[m]) else: print " WARNING: signal", stype, "and mass point", m, "in channel", channel, "has 0 entries or does not exist" # Remove HVT cross section (which is the same for Zlep and Zinv) if stype == "XZHVBF": sample_name = 'Zprime_VBF_Zh_Zlephinc_narrow_M-%d' % m else: sample_name = 'ZprimeToZHToZlepHinc_narrow_M%d' % m xs = xsection[sample_name]['xsec'] signalXS[m].setVal(xs * 1000.) signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range")) boundaryFactor = signalIntegral[m].getVal() if VERBOSE: print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events" if channel=='nnbb' and m==5000: signalNorm[m].setVal(2.5) elif channel=='nn0b' and m==5000: signalNorm[m].setVal(6.7) else: signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br(X->VH) = 1 [fb] a1[m].setConstant(True) a2[m].setConstant(True) vmean[m].setConstant(True) vsigma[m].setConstant(True) valpha1[m].setConstant(True) vslope1[m].setConstant(True) salpha2[m].setConstant(True) sslope2[m].setConstant(True) signalNorm[m].setConstant(True) signalXS[m].setConstant(True) #*******************************************************# # # # Signal interpolation # # # #*******************************************************# # ====== CONTROL PLOT ====== c_signal = TCanvas("c_signal", "c_signal", 800, 600) c_signal.cd() frame_signal = X_mass.frame() for m in genPoints[:-2]: if m in signalExt.keys(): signal[m].plotOn(frame_signal, RooFit.LineColor(sample["%s_M%d" % (stype, m)]['linecolor']), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range")) frame_signal.GetXaxis().SetRangeUser(0, 6500) frame_signal.Draw() drawCMS(-1, YEAR, "Simulation") drawAnalysis(channel) drawRegion(channel) c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.pdf") c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.png") #if VERBOSE: raw_input("Press Enter to continue...") # ====== CONTROL PLOT ====== # Normalization gnorm = TGraphErrors() gnorm.SetTitle(";m_{X} (GeV);integral (GeV)") gnorm.SetMarkerStyle(20) gnorm.SetMarkerColor(1) gnorm.SetMaximum(0) inorm = TGraphErrors() inorm.SetMarkerStyle(24) fnorm = TF1("fnorm", "pol9", 800, 5000) #"pol5" if not channel=="XZHnnbb" else "pol6" #pol5*TMath::Floor(x-1800) + ([5]*x + [6]*x*x)*(1-TMath::Floor(x-1800)) fnorm.SetLineColor(920) fnorm.SetLineStyle(7) fnorm.SetFillColor(2) fnorm.SetLineColor(cColor) # Mean gmean = TGraphErrors() gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)") gmean.SetMarkerStyle(20) gmean.SetMarkerColor(cColor) gmean.SetLineColor(cColor) imean = TGraphErrors() imean.SetMarkerStyle(24) fmean = TF1("fmean", "pol1", 0, 5000) fmean.SetLineColor(2) fmean.SetFillColor(2) # Width gsigma = TGraphErrors() gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)") gsigma.SetMarkerStyle(20) gsigma.SetMarkerColor(cColor) gsigma.SetLineColor(cColor) isigma = TGraphErrors() isigma.SetMarkerStyle(24) fsigma = TF1("fsigma", "pol1", 0, 5000) fsigma.SetLineColor(2) fsigma.SetFillColor(2) # Alpha1 galpha1 = TGraphErrors() galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha") galpha1.SetMarkerStyle(20) galpha1.SetMarkerColor(cColor) galpha1.SetLineColor(cColor) ialpha1 = TGraphErrors() ialpha1.SetMarkerStyle(24) falpha1 = TF1("falpha", "pol0", 0, 5000) falpha1.SetLineColor(2) falpha1.SetFillColor(2) # Slope1 gslope1 = TGraphErrors() gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)") gslope1.SetMarkerStyle(20) gslope1.SetMarkerColor(cColor) gslope1.SetLineColor(cColor) islope1 = TGraphErrors() islope1.SetMarkerStyle(24) fslope1 = TF1("fslope", "pol0", 0, 5000) fslope1.SetLineColor(2) fslope1.SetFillColor(2) # Alpha2 galpha2 = TGraphErrors() galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha") galpha2.SetMarkerStyle(20) galpha2.SetMarkerColor(cColor) galpha2.SetLineColor(cColor) ialpha2 = TGraphErrors() ialpha2.SetMarkerStyle(24) falpha2 = TF1("falpha", "pol0", 0, 5000) falpha2.SetLineColor(2) falpha2.SetFillColor(2) # Slope2 gslope2 = TGraphErrors() gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)") gslope2.SetMarkerStyle(20) gslope2.SetMarkerColor(cColor) gslope2.SetLineColor(cColor) islope2 = TGraphErrors() islope2.SetMarkerStyle(24) fslope2 = TF1("fslope", "pol0", 0, 5000) fslope2.SetLineColor(2) fslope2.SetFillColor(2) n = 0 for i, m in enumerate(genPoints): if not m in signalNorm.keys(): continue if signalNorm[m].getVal() < 1.e-6: continue signalString = "M%d" % m signalName = "%s_M%d" % (stype, m) if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal()) gnorm.SetPoint(n, m, signalNorm[m].getVal()) gmean.SetPoint(n, m, vmean[m].getVal()) gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02)) gsigma.SetPoint(n, m, vsigma[m].getVal()) gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05)) galpha1.SetPoint(n, m, valpha1[m].getVal()) galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10)) gslope1.SetPoint(n, m, vslope1[m].getVal()) gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10)) galpha2.SetPoint(n, m, salpha2[m].getVal()) galpha2.SetPointError(n, 0, min(salpha2[m].getError(), salpha2[m].getVal()*0.10)) gslope2.SetPoint(n, m, sslope2[m].getVal()) gslope2.SetPointError(n, 0, min(sslope2[m].getError(), sslope2[m].getVal()*0.10)) n = n + 1 print "fit on gmean:" gmean.Fit(fmean, "Q0", "SAME") print "fit on gsigma:" gsigma.Fit(fsigma, "Q0", "SAME") print "fit on galpha:" galpha1.Fit(falpha1, "Q0", "SAME") print "fit on gslope:" gslope1.Fit(fslope1, "Q0", "SAME") galpha2.Fit(falpha2, "Q0", "SAME") gslope2.Fit(fslope2, "Q0", "SAME") #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S")) gnorm.Fit(fnorm, "Q", "SAME", 700, 5000) for m in massPoints: signalName = "%s_M%d" % (stype, m) if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.) # Interpolation method syield = gnorm.Eval(m) spline = gnorm.Eval(m, 0, "S") sfunct = fnorm.Eval(m) #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield)) delta = abs(1.-spline/sfunct) if sfunct > 0 else 0 syield = spline if interPar: jmean = gmean.Eval(m) jsigma = gsigma.Eval(m) jalpha1 = galpha1.Eval(m) jslope1 = gslope1.Eval(m) else: jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m inorm.SetPoint(inorm.GetN(), m, syield) signalNorm[m].setVal(syield) imean.SetPoint(imean.GetN(), m, jmean) if jmean > 0: vmean[m].setVal(jmean) isigma.SetPoint(isigma.GetN(), m, jsigma) if jsigma > 0: vsigma[m].setVal(jsigma) ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1) if not jalpha1==0: valpha1[m].setVal(jalpha1) islope1.SetPoint(islope1.GetN(), m, jslope1) if jslope1 > 0: vslope1[m].setVal(jslope1) c1 = TCanvas("c1", "Crystal Ball", 1200, 800) c1.Divide(2, 2) c1.cd(1) gmean.SetMinimum(0.) gmean.Draw("APL") imean.Draw("P, SAME") drawRegion(channel) c1.cd(2) gsigma.SetMinimum(0.) gsigma.Draw("APL") isigma.Draw("P, SAME") drawRegion(channel) c1.cd(3) galpha1.Draw("APL") ialpha1.Draw("P, SAME") drawRegion(channel) galpha1.GetYaxis().SetRangeUser(0., 5.) c1.cd(4) gslope1.Draw("APL") islope1.Draw("P, SAME") drawRegion(channel) gslope1.GetYaxis().SetRangeUser(0., 125.) if False: c1.cd(5) galpha2.Draw("APL") ialpha2.Draw("P, SAME") drawRegion(channel) c1.cd(6) gslope2.Draw("APL") islope2.Draw("P, SAME") drawRegion(channel) gslope2.GetYaxis().SetRangeUser(0., 10.) c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.pdf") c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.png") c2 = TCanvas("c2", "Signal Efficiency", 800, 600) c2.cd(1) gnorm.SetMarkerColor(cColor) gnorm.SetMarkerStyle(20) gnorm.SetLineColor(cColor) gnorm.SetLineWidth(2) gnorm.Draw("APL") inorm.Draw("P, SAME") gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100) gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25) drawCMS(-1,YEAR , "Simulation") drawAnalysis(channel) drawRegion(channel) c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.pdf") c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# # create workspace w = RooWorkspace("ZH_RunII", "workspace") for m in massPoints: getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName())) getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName())) getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName())) w.writeToFile("%s%s.root" % (WORKDIR, stype+channel), True) print "Workspace", "%s%s.root" % (WORKDIR, stype+channel), "saved successfully" sys.exit()
setattr(RooWorkspace, "Import", getattr(RooWorkspace, "import")) ## Here starts the meat. nentries = -1 ## sTest = [-20, -10, -5, -2, -1, -0.5, 0, 0.5, 1, 2, 5, 10, 20] ## sTest = [-5, -2, -1, -0.5, 0, 0.5, 1, 2, 5] sTest = [0] phoPtRange = (12,15) # chains = getChains('v11') chains = pmvTrees.getChains('v15') mcTree = chains['z'] dataTree = chains['data'] w = RooWorkspace('w') ## Define variables mmgMass = w.factory('mmgMass[40, 140]') mmMass = w.factory('mmMass[10, 140]') weight = w.factory('weight[1]') phoScale = w.factory('phoScale[0,-50,50]') weight.SetTitle('pileup.weight') phoScale.setUnit('%') ## Photon scaling fraction, dlog(m_uuy)/dlog(E_y) fPho = w.factory('fPho[0.15*91.2,0,100]') fPhoFunc = w.factory('''FormulaVar::fPhoFunc( "mmgMass * (0.5 - 0.5 * mmMass^2 / mmgMass^2)", {mmMass, mmgMass}
class Wjj2DFitter: def __init__ (self, pars): self.pars = pars self.ws = RooWorkspace('wjj2dfitter') self.utils = Wjj2DFitterUtils(self.pars) self.useImportPars = False self.rangeString = None obs = [] for v in self.pars.var: try: vName = self.pars.varNames[v] except AttributeError: vName = v obs.append(vName) var1 = self.ws.factory('%s[%f,%f]' % (vName, self.pars.varRanges[v][1], self.pars.varRanges[v][2]) ) var1.setUnit('GeV') try: var1.SetTitle(self.pars.varTitles[v]) except AttributeError: var1.SetTitle('m_{jj}') var1.setPlotLabel(var1.GetTitle()) if len(self.pars.varRanges[v][3]) > 1: vbinning = RooBinning(len(self.pars.varRanges[v][3]) - 1, array('d', self.pars.varRanges[v][3]), '%sBinning' % vName) var1.setBinning(vbinning) else: var1.setBins(self.pars.varRanges[v][0]) var1.Print() if v in self.pars.exclude: var1.setRange('signalRegion', self.pars.exclude[v][0], self.pars.exclude[v][1]) var1.setRange('lowSideband', var1.getMin(), self.pars.exclude[v][0]) var1.setRange('highSideband', self.pars.exclude[v][1], var1.getMax()) self.rangeString = 'lowSideband,highSideband' if hasattr(self.pars, 'plotRanges'): var1.setRange('plotRange', self.pars.plotRanges[v][1], self.pars.plotRanges[v][2]) var1.setBins(self.pars.plotRanges[v][0], 'plotBins') else: var1.setRange('plotRange', var1.getMin(), var1.getMax()) var1.setBins(var1.getBins(), 'plotBins') self.ws.defineSet('obsSet', ','.join(obs)) def loadDataFromWorkspace(self, other, cut = None): #pull unbinned data from other workspace unbinnedData = other.data('data_unbinned') if not unbinnedData: unbinnedData = other.data('data_obs') if cut: unbinnedData = unbinnedData.reduce(cut) unbinnedData.Print() if self.pars.binData: #bin and import data unbinnedData.SetName('data_unbinned') getattr(self.ws, 'import')(unbinnedData) data = RooDataHist('data_obs', 'data_obs', other.set('obsSet'), unbinnedData) getattr(self.ws, 'import')(data) else: #just import data unbinnedData.SetName('data_obs') getattr(self.ws, 'import')(unbinnedData) def loadHistogramsFromWorkspace(self, other): #pull RooHist pdfs from other workspace pdfs = other.allPdfs() pdfIter = pdfs.createIterator() pdf = pdfIter.Next() while pdf: if pdf.IsA().InheritsFrom('RooHistPdf'): print 'importing',pdf.GetName(),'from old workspace' getattr(self.ws, 'import')(pdf) pdf = pdfIter.Next() def loadWorkspaceFromFile(self, filename, wsname = 'w', getFloatPars = True): print 'loading data workspace %s from file %s' % (wsname, filename) fin = TFile.Open(filename) if not fin: print 'failed to open the file',filename import os print 'cwd:',os.getcwd() print 'access of',filename,os.access(filename, os.R_OK) print 'list of root files in cwd' for f in os.listdir(os.getcwd()): if f[-5:] == '.root': print f,len(f),len(filename) fin = TFile.Open(os.getcwd() + '/' + filename) assert(fin) other = fin.Get(wsname) #pull unbinned data from other workspace self.loadDataFromWorkspace(other) #pull in histogram pdfs to save time self.loadHistogramsFromWorkspace(other) if getFloatPars and other.loadSnapshot('fitPars'): self.useImportPars = True self.ws.saveSnapshot('importParams', other.set('floatingParams'), True) # self.ws.Print() # put together a fitting model and return the pdf def makeFitter(self, useAlternateModels = False): if self.ws.pdf('total'): return self.ws.pdf('total') compPdfs = [] for component in self.pars.backgrounds: # print 'getting compModels' compModels = getattr(self.pars, '%sModels' % component) if hasattr(self.pars, '%sConvModels' % component): convModels = getattr(self.pars, '%sConvModels' % component) else: convModels = None if useAlternateModels: print 'loading Alternate Models' compModels = getattr(self.pars, '%sModelsAlt' % component) convModels = getattr(self.pars, '%sConvModelsAlt' % component) # print 'compModels = %s' % compModels compFiles = getattr(self.pars, '%sFiles' % component) compPdf = self.makeComponentPdf(component, compFiles, compModels, useAlternateModels, convModels) norm = self.ws.factory('prod::f_%s_norm' % component + \ '(n_%s[0.,1e6],' % component + \ '%s_nrm[1.,-0.5,5.])' % component) self.ws.var('n_%s' % component).setConstant(True) if hasattr(self, '%sExpected' % component): self.ws.var('n_%s' % component).setVal( getattr(self, '%sExpected' % component)) compPdfs.append( self.ws.factory('RooExtendPdf::%s_extended(%s,%s)' % \ (compPdf.GetName(), compPdf.GetName(), norm.GetName()) ) ) self.ws.factory('r_signal[0., -200., 200.]') self.ws.var('r_signal').setConstant(False) try: obs = [ self.pars.varNames[x] for x in self.pars.var ] except AttributeError: obs = self.pars.var for component in self.pars.signals: compFile = getattr(self.pars, '%sFiles' % component) compModels = getattr(self.pars, '%sModels' % component) if hasattr(self.pars, '%sConvModels' % component): convModels = getattr(self.pars, '%sConvModels' % component) else: convModels = None compPdf = self.makeComponentPdf(component, compFiles, compModels, useAlternateModels, convModels) norm = self.ws.factory( "prod::f_%s_norm(n_%s[0., 1e6],r_signal)" % \ (component, component) ) self.ws.var('n_%s' % component).setConstant(True) if hasattr(self, '%sExpected' % component): self.ws.var('n_%s' % component).setVal( getattr(self, '%sExpected' % component)) pdf = self.ws.factory('RooExtendPdf::%s_extended(%s,%s)' % \ (compPdf.GetName(), compPdf.GetName(), norm.GetName()) ) if (hasattr(self.pars, '%sInterference' % component)) and \ getattr(self.pars, '%sInterference' % component): getattr(self.ws, 'import') \ (pdf, RooFit.RenameAllNodes('interf_%sUp' % component), RooFit.RenameAllVariablesExcept('interf_%sUp' % component, ','.join(obs)), RooFit.Silence() ) getattr(self.ws, 'import') \ (pdf, RooFit.RenameAllNodes('interf_%sDown' % component), RooFit.RenameAllVariablesExcept('interf_%sDown'%component, ','.join(obs)), RooFit.Silence() ) if self.pars.includeSignal: compPdfs.append(pdf) #print compPdfs prodList = [ '%s' % (pdf.GetName()) \ for (idx, pdf) in enumerate(compPdfs) ] comps = RooArgList(self.ws.argSet(','.join(prodList))) getattr(self.ws, 'import')(RooAddPdf('total', 'total', comps)) return self.ws.pdf('total') # define the constraints on the yields, etc that will be part of the fit. def makeConstraints(self): if self.ws.set('constraintSet'): return self.ws.set('constraintSet') constraints = [] constrainedParameters = [] for constraint in self.pars.yieldConstraints: theYield = self.ws.var('%s_nrm' % constraint) if not theYield.isConstant(): self.ws.factory('RooGaussian::%s_const(%s, 1.0, %f)' % \ (constraint, theYield.GetName(), self.pars.yieldConstraints[constraint]) ) constraints.append('%s_const' % constraint) constrainedParameters.append(theYield.GetName()) if hasattr(self.pars, 'constrainShapes'): for component in self.pars.constrainShapes: pc = self.ws.pdf(component).getParameters(self.ws.set('obsSet')) parIter = pc.createIterator() par = parIter.Next() while par: if not par.isConstant(): theConst = self.ws.factory('RooGaussian::%s_const' % \ (par.GetName()) + \ '(%s, %f, %f)' % \ (par.GetName(), par.getVal(), par.getError()) ) constraints.append(theConst.GetName()) constrainedParameters.append(par.GetName()) par = parIter.Next() pc.IsA().Destructor(pc) self.ws.defineSet('constraintSet', ','.join(constraints)) self.ws.defineSet('constrainedSet', ','.join(constrainedParameters)) return self.ws.set('constraintSet') # make the constrained fitter def makeConstrainedFitter(self): if self.ws.pdf('totalFit_const'): return self.ws.pdf('totalFit_const') constraintSet = self.makeConstraints() fitter = self.makeFitter() print '\nfit constraints' constIter = constraintSet.createIterator() constraint = constIter.Next() constraints = [] while constraint: constraint.Print() constraints.append(constraint.GetName()) constraint = constIter.Next() if constraintSet.getSize() > 0: constraints.append(fitter.GetName()) fitter = self.ws.factory('PROD::totalFit_const(%s)' % \ (','.join(constraints)) ) return fitter # fit the data using the pdf def fit(self, keepParameterValues = False, overrideRangeCmd = False): print 'construct fit pdf ...' fitter = self.makeFitter() print 'load data ...' data = self.loadData() self.resetYields() constraintSet = self.makeConstraints() if not keepParameterValues: self.readParametersFromFile() self.resetYields() # print constraints, self.pars.yieldConstraints constraintCmd = RooCmdArg.none() if constraintSet.getSize() > 0: fitter = self.makeConstrainedFitter() constraintCmd = RooFit.Constrained() # constraintCmd = RooFit.ExternalConstraints(self.ws.set('constraintSet')) if self.useImportPars: self.ws.loadSnapshot('importParams') self.ws.Print() # for constraint in pars.constraints: # self.ws.pdf(constraint).Print() # print rangeCmd = RooCmdArg.none() if self.rangeString and self.pars.doExclude and not overrideRangeCmd: rangeCmd = RooFit.Range(self.rangeString) # print 'scanning parameter values...' # fitter.fitTo(data, RooFit.Minos(False), # RooFit.PrintEvalErrors(-1), # RooFit.Warnings(False), # RooFit.Minimizer("Minuit2", "scan"), # RooFit.PrintLevel(0), # constraintCmd, # rangeCmd) print 'fitting ...' fr = fitter.fitTo(data, RooFit.Save(True), # RooFit.Extended(True), RooFit.Minos(False), RooFit.PrintEvalErrors(-1), RooFit.Warnings(False), RooFit.Minimizer("Minuit2", "minimize"), constraintCmd, rangeCmd ) fr.Print('v') return fr # determine the fitting model for each component and return them def makeComponentPdf(self, component, files, models, useAlternateModels, convModels): print 'making ComponentPdf %s' % component # print 'models = %s' % models # print 'files = %s' % files if convModels and not (convModels[0] == -1): thePdf = self.makeConvolvedPdf(component, files, models, useAlternateModels, convModels) elif (models[0] == -1): thePdf = self.makeComponentHistPdf(component, files) elif (models[0] == -2): thePdf = self.makeMorphingPdf(component, useAlternateModels, convModels) elif (models[0] == -3): pass else: thePdf = self.makeComponentAnalyticPdf(component, models, useAlternateModels) return thePdf #create a simple 2D histogram pdf def makeComponentHistPdf(self, component, files): if self.ws.pdf(component): return self.ws.pdf(component) compHist = self.utils.newEmptyHist('hist%s' % component) sumYields = 0. sumxsec = 0. sumExpected = 0. for (idx,fset) in enumerate(files): if hasattr(self.pars, '%scuts' % component): cutOverride = getattr(self.pars, '%scuts' % component) else: cutOverride = None filename = fset[0] tmpHist = self.utils.File2Hist(filename, 'hist%s_%i' % (component, idx), False,cutOverride,False,True,0) sumYields += tmpHist.Integral() sumxsec += fset[2] compHist.Add(tmpHist, self.pars.integratedLumi*fset[2]/fset[1]) sumExpected += tmpHist.Integral()*fset[2]* \ self.pars.integratedLumi/fset[1] print filename,'acc x eff: %.3g' % (tmpHist.Integral()/fset[1]) print filename,'N_expected: %.1f' % \ (tmpHist.Integral()*fset[2]*self.pars.integratedLumi/fset[1]) #tmpHist.Print() #compHist.Print() print '%s acc x eff: %.3g' % \ (component, sumExpected/sumxsec/self.pars.integratedLumi) print 'Number of expected %s events: %.1f' % (component, sumExpected) setattr(self, '%sExpected' % component, sumExpected) return self.utils.Hist2Pdf(compHist, component, self.ws, self.pars.order) #create a pdf which is a convolution of any two pdf def makeConvolvedPdf(self, component, files, models, useAlternateModels, convModels): if self.ws.pdf(component): return self.ws.pdf(component) #If a morphing model is selected, then convolve each individual component first and then morph if (models[0] == -2): return self.makeMorphingPdf(component, useAlternateModels, convModels) basePdf = self.makeComponentPdf('%s_base' % component, files, models, useAlternateModels, [-1]) convComponent = 'Global' ##Overwrite to use the same convolution model for all Pdfs convModel = getattr(self.pars, '%sConvModels' % convComponent) if useAlternateModels: convModel = getattr(self.pars, '%sConvModelsAlt' % convComponent) convPdf = self.makeComponentPdf('%s_conv' % convComponent, files, convModel, useAlternateModels, [-1]) var = self.pars.var[0] try: vName = self.pars.varNames[var] except AttributeError: vName = var self.ws.factory('RooFFTConvPdf::%s(%s,%s,%s)' % \ (component, vName, basePdf.GetName(), convPdf.GetName())) return self.ws.pdf(component) # create a pdf using the "template morphing" technique def makeMorphingPdf(self, component, useAlternateModels, convModels): if self.ws.pdf(component): return self.ws.pdf(component) filesNom = getattr(self.pars, '%s_NomFiles' % component) modelsNom = getattr(self.pars, '%s_NomModels' % component) filesMU = getattr(self.pars, '%s_MUFiles' % component) modelsMU = getattr(self.pars, '%s_MUModels' % component) filesMD = getattr(self.pars, '%s_MDFiles' % component) modelsMD = getattr(self.pars, '%s_MDModels' % component) filesSU = getattr(self.pars, '%s_SUFiles' % component) modelsSU = getattr(self.pars, '%s_SUModels' % component) filesSD = getattr(self.pars, '%s_SDFiles' % component) modelsSD = getattr(self.pars, '%s_SDModels' % component) if useAlternateModels: modelsNom = getattr(self.pars, '%s_NomModelsAlt' % component) modelsMU = getattr(self.pars, '%s_MUModelsAlt' % component) modelsMD = getattr(self.pars, '%s_MDModelsAlt' % component) modelsSU = getattr(self.pars, '%s_SUModelsAlt' % component) modelsSD = getattr(self.pars, '%s_SDModelsAlt' % component) # Adds five (sub)components for the component with suffixes Nom, MU, MD, SU, SD NomPdf = self.makeComponentPdf('%s_Nom' % component, filesNom, modelsNom, False, convModels) if hasattr(self, '%s_NomExpected' % component): setattr(self, '%sExpected' % component, getattr(self, '%s_NomExpected' % component)) MUPdf = self.makeComponentPdf('%s_MU' % component, filesMU, modelsMU, False, convModels) MDPdf = self.makeComponentPdf('%s_MD' % component, filesMD, modelsMD, False, convModels) SUPdf = self.makeComponentPdf('%s_SU' % component, filesSU, modelsSU, False, convModels) SDPdf = self.makeComponentPdf('%s_SD' % component, filesSD, modelsSD, False, convModels) fMU_comp = self.ws.factory("fMU_%s[0., -1., 1.]" % component) fSU_comp = self.ws.factory("fSU_%s[0., -1., 1.]" % component) fMU = RooFormulaVar("f_fMU_%s" % component, "1.0*@0*(@0 >= 0.)", RooArgList( fMU_comp ) ) fMD = RooFormulaVar("f_fMD_%s" % component, "-1.0*@0*(@0 < 0.)", RooArgList( fMU_comp ) ) fSU = RooFormulaVar("f_fSU_%s" % component, "@0*(@0 >= 0.)", RooArgList( fSU_comp ) ) fSD = RooFormulaVar("f_fSD_%s" % component, "@0*(-1)*(@0 < 0.)", RooArgList( fSU_comp ) ) fNom = RooFormulaVar("f_fNom_%s" % component, "(1.-abs(@0)-abs(@1))", RooArgList(fMU_comp,fSU_comp) ) morphPdf = RooAddPdf(component,component, RooArgList(MUPdf,MDPdf,SUPdf,SDPdf,NomPdf), RooArgList(fMU, fMD, fSU, fSD, fNom)) morphPdf.SetName(component) getattr(self.ws, 'import')(morphPdf) return self.ws.pdf(component) # create a pdf using an analytic function. def makeComponentAnalyticPdf(self, component, models, useAlternateModels): if self.ws.pdf(component): return self.ws.pdf(component) pdfList = [] systMult = None if ( hasattr(self.pars, '%sInterference' % component) and \ getattr(self.pars, '%sInterference' % component) and \ hasattr(self.pars, "%sdoSystMult" % component) and \ getattr(self.pars, "%sdoSystMult" % component) ): systMult = getattr(self.pars, "%sSystMult" % component) for (idx,model) in enumerate(models): var = self.pars.var[idx] try: vName = self.pars.varNames[var] except AttributeError: vName = var auxModel = None if useAlternateModels: if hasattr(self.pars, '%sAuxModelsAlt' % component): auxModel = getattr(self.pars, '%sAuxModelsAlt' % component)[idx] else: if hasattr(self.pars, '%sAuxModels' % component): auxModel = getattr(self.pars, '%sAuxModels' % component)[idx] pdfList.append(self.utils.analyticPdf(self.ws, vName, model, '%s_%s'%(component,vName), '%s_%s'%(component,vName), auxModel, systMult ) ) pdfListNames = [ pdf.GetName() for pdf in pdfList ] if len(pdfList) > 1: self.ws.factory('PROD::%s(%s)' % \ (component, ','.join(pdfListNames))) else: pdfList[0].SetName(component) return self.ws.pdf(component) def loadData(self, weight = False): if self.ws.data('data_obs'): return self.ws.data('data_obs') unbinnedName = 'data_obs' if self.pars.binData: unbinnedName = 'data_unbinned' data = self.utils.File2Dataset(self.pars.DataFile, unbinnedName, self.ws, weighted = weight) if self.pars.binData: data = RooDataHist('data_obs', 'data_obs', self.ws.set('obsSet'), data) getattr(self.ws, 'import')(data) data = self.ws.data('data_obs') return data def stackedPlot(self, var, logy = False, pdfName = None, Silent = False): if not pdfName: pdfName = 'total' xvar = self.ws.var(var) nbins = xvar.getBins() # if hasattr(self.pars, 'plotRanges') and not xvar.hasRange('plotRange'): # xvar.setRange('plotRange', self.pars.plotRanges[var][1], # self.pars.plotRanges[var][2]) # xvar.setBins(self.pars.plotRanges[var][0], 'plotBins') # elif not xvar.hasRange('plotRange'): # xvar.setRange('plotRange', xvar.getMin(), xvar.getMax()) # xvar.setBins(nbins, 'plotBins') sframe = xvar.frame(RooFit.Range('plotRange'), RooFit.Bins(xvar.getBins('plotBins'))) sframe.SetName("%s_stacked" % var) pdf = self.ws.pdf(pdfName) if isinstance(pdf, RooAddPdf): compList = RooArgList(pdf.pdfList()) else: compList = None data = self.ws.data('data_obs') nexp = pdf.expectedEvents(self.ws.set('obsSet')) if not Silent: print pdf.GetName(),'expected: %.0f' % (nexp) print 'data events: %.0f' % (data.sumEntries()) if nexp < 1: nexp = data.sumEntries() theComponents = [] if self.pars.includeSignal: theComponents += self.pars.signals theComponents += self.pars.backgrounds data.plotOn(sframe, RooFit.Invisible(), RooFit.Binning('plotBins')) # dataHist = RooAbsData.createHistogram(data,'dataHist_%s' % var, xvar, # RooFit.Binning('%sBinning' % var)) # #dataHist.Scale(1., 'width') # invData = RooHist(dataHist, 1., 1, RooAbsData.SumW2, 1.0, False) # #invData.Print('v') # sframe.addPlotable(invData, 'pe', True, True) for (idx,component) in enumerate(theComponents): if not Silent: print 'plotting',component,'...', if hasattr(self.pars, '%sPlotting' % (component)): plotCharacteristics = getattr(self.pars, '%sPlotting' % \ (component)) else: plotCharacteristics = {'color' : colorwheel[idx%6], 'title' : component } compCmd = RooCmdArg.none() if compList: compSet = RooArgSet(compList) if compSet.getSize() > 0: compCmd = RooFit.Components(compSet) removals = compList.selectByName('%s*' % component) compList.remove(removals) if not Silent: print 'events', self.ws.function('f_%s_norm' % component).getVal() sys.stdout.flush() if abs(self.ws.function('f_%s_norm' % component).getVal()) >= 1.: pdf.plotOn(sframe, #RooFit.ProjWData(data), RooFit.DrawOption('LF'), RooFit.FillStyle(1001), RooFit.FillColor(plotCharacteristics['color']), RooFit.LineColor(plotCharacteristics['color']), RooFit.VLines(), RooFit.Range('plotRange'), RooFit.NormRange('plotRange'), RooFit.Normalization(nexp, RooAbsReal.NumEvent), compCmd ) tmpCurve = sframe.getCurve() tmpCurve.SetName(component) tmpCurve.SetTitle(plotCharacteristics['title']) if 'visible' in plotCharacteristics: sframe.setInvisible(component, plotCharacteristics['visible']) data.plotOn(sframe, RooFit.Name('theData'), RooFit.Binning('plotBins')) sframe.getHist('theData').SetTitle('data') # theData = RooHist(dataHist, 1., 1, RooAbsData.SumW2, 1.0, True) # theData.SetName('theData') # theData.SetTitle('data') # sframe.addPlotable(theData, 'pe') if (logy): sframe.SetMinimum(0.01) sframe.SetMaximum(1.0e6) else: sframe.SetMaximum(sframe.GetMaximum()*1.35) pass excluded = (var in self.pars.exclude) bname = var if not excluded: for v in self.pars.exclude: if hasattr(self.pars, 'varNames') and \ (self.pars.varNames[v] == var): excluded = True bname = v if excluded: blinder = TBox(self.pars.exclude[bname][0], sframe.GetMinimum(), self.pars.exclude[bname][1], sframe.GetMaximum()) # blinder.SetName('blinder') # blinder.SetTitle('signal region') blinder.SetFillColor(kBlack) if self.pars.blind: blinder.SetFillStyle(1001) else: blinder.SetFillStyle(0) blinder.SetLineStyle(2) sframe.addObject(blinder) elif self.pars.blind: if not Silent: print "blind but can't find exclusion region for", var print 'excluded',excluded,self.pars.exclude print 'hiding data points' sframe.setInvisible('theData', True) else: sframe.setInvisible('theData', False) #sframe.GetYaxis().SetTitle('Events / GeV') # dataHist.IsA().Destructor(dataHist) if not Silent: print xvar.setBins(nbins) return sframe def readParametersFromFile(self, fname=None): if (not fname): fname = self.pars.initialParametersFile if isinstance(fname, str): flist = [ fname ] else: flist = fname for tmpName in flist: if len(tmpName) > 0: print 'loading parameters from file',tmpName self.ws.allVars().readFromFile(tmpName) def expectedFromPars(self): components = self.pars.signals + self.pars.backgrounds for component in components: theYield = self.ws.var('n_%s' % component) setattr(self, '%sExpected' % component, theYield.getVal()) def initFromExplicitVals(self,opts): #,init_diboson= -1.0,init_WpJ=-1.0,init_top=-1.0,init_ZpJ=-1.0,init_QCD=-1.0 components = ['diboson', 'top', 'WpJ', 'ZpJ', 'QCD', 'WHbb'] for component in components: #double init init = getattr(opts, 'ext%s' % component) #init = -2.0 #setattr(self,init, 'init_%s' % component) #init = init_%s % component #print "init=", init #init = self.ws.var('init_%s' % component) #init.setVal(100.0) #init.setVal('init_%s' % component) #init = theYield.getVal() if (init>0.): print 'setting initial value for ',component,' to ',init setattr(self, '%sInitial' % component, init) def resetYields(self): if self.ws.data('data_obs'): Ndata = self.ws.data('data_obs').sumEntries() else: Ndata = 10000. print 'resetting yields...' components = self.pars.signals + self.pars.backgrounds for component in components: theYield = self.ws.var('n_%s' % component) theNorm = self.ws.var('%s_nrm' % component) if hasattr(self, '%sInitial' % component): print 'explicitly setting initial value for ',component theYield.setVal(getattr(self, '%sInitial' % component)) theNorm.setVal(1.0) theNorm.setConstant() else: fracofdata = -1. if hasattr(self.pars, '%sFracOfData' % component): fracofdata = getattr(self.pars, '%sFracOfData' % component) if (fracofdata >= 0.): print 'explicitly setting ', component,' yield to be', fracofdata,' of data' theYield.setVal(fracofdata*Ndata) elif hasattr(self, '%sExpected' % component): theYield.setVal(getattr(self, '%sExpected' % component)) else: print 'no expected value for',component theYield.setVal(Ndata/len(components)) if theNorm and not theNorm.isConstant(): theNorm.setVal(1.0) if component in self.pars.yieldConstraints: theYield.setError(theYield.getVal() * \ self.pars.yieldConstraints[component]) if theNorm: theNorm.setError(self.pars.yieldConstraints[component]) else: theYield.setError(sqrt(theYield.getVal())) theYield.Print() def generateToyMCSet(self,var,inputPdf,outFileName,NEvts): fMC = TFile(outFileName, "RECREATE"); # thevar = self.ws.var(var); print 'thevar=' print var # print thevar print '...' # varList = RooArgList() # varList.add(self.ws.var(var)) toymc = inputPdf.generate(RooArgSet(self.ws.var(var)),NEvts); tMC = toymc.tree(); fMC.cd(); tMC.Write(); fMC.Close(); def legend4Plot(plot, left = False): if left: theLeg = TLegend(0.2, 0.62, 0.55, 0.92, "", "NDC") else: theLeg = TLegend(0.60, 0.62, 0.92, 0.92, "", "NDC") theLeg.SetName('theLegend') theLeg.SetBorderSize(0) theLeg.SetLineColor(0) theLeg.SetFillColor(0) theLeg.SetFillStyle(0) theLeg.SetLineWidth(0) theLeg.SetLineStyle(0) theLeg.SetTextFont(42) theLeg.SetTextSize(.045) entryCnt = 0 for obj in range(0, int(plot.numItems())): objName = plot.nameOf(obj) if (not plot.getInvisible(objName)): theObj = plot.getObject(obj) objTitle = theObj.GetTitle() if len(objTitle) < 1: objTitle = objName dopts = plot.getDrawOptions(objName).Data() # print 'obj:',theObj,'title:',objTitle,'opts:',dopts,'type:',type(dopts) if theObj.IsA().InheritsFrom('TNamed'): theLeg.AddEntry(theObj, objTitle, dopts) entryCnt += 1 theLeg.SetY1NDC(0.9 - 0.05*entryCnt - 0.005) theLeg.SetY1(theLeg.GetY1NDC()) return theLeg legend4Plot = staticmethod(legend4Plot)
#drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True) drawCMS(-1, "", year=YEAR, suppressCMS=True) drawAnalysis(category) drawRegion(category) c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.pdf") c2.Print(PLOTDIR+"MC_signal_"+YEAR+"/"+stype+"_"+category+"_SignalNorm.png") #*******************************************************# # # # Generate workspace # # # #*******************************************************# # create workspace w = RooWorkspace("Zprime_"+YEAR, "workspace") for m in massPoints: getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName())) getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName())) getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName())) w.writeToFile(WORKDIR+"MC_signal_%s_%s.root" % (YEAR, category), True) print "Workspace", WORKDIR+"MC_signal_%s_%s.root" % (YEAR, category), "saved successfully" def drawPlot(name, channel, variable, model, dataset, fitRes=[], norm=-1, reg=None, cat="", alt=None, anorm=-1, signal=None, snorm=-1): isData = norm>0 isMass = "Mass" in name isSignal = '_M' in name mass = name[8:12] isCategory = reg is not None #isBottomPanel = not isSignal
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
del gaus_nll del truth_pow_sigm getattr(ws,'import')(biasData) # if being executed run bias study if __name__ == '__main__': ntoys = int(sys.argv[1]) category = int(sys.argv[2]) mass = float(sys.argv[3]) channel = sys.argv[4] order = int(sys.argv[5]) turnon = sys.argv[6] #fitted turn on type!!! truth = sys.argv[7] #truth model type!!! bs = RooWorkspace('bias_study') bs.factory("procWeight[0]") bs.factory("puWeight[0]") bs.factory("weight[0]") bs.factory("Mzg[100,180]") bs.var("Mzg").setRange("ROI",mass-1.5,mass+1.5) bs.var("Mzg").setBins(40000,"cache") bs.factory("Mz[0]") #bs.factory("dMzg[0,25]") #bs.factory("dMz[0,25]") bs.factory("r94cat[cat1=1,cat2=2,cat3=3,cat4=4]") bs.defineSet("observables", "Mzg,Mz,r94cat,procWeight,puWeight") bs.defineSet("observables_weight", "Mzg,Mz,r94cat,procWeight,puWeight,weight")
def main(o,args): variables = options.variables procs = options.procs cats = options.cats print "****variables***" print variables #from configfile import variables, procs, cats if 0 and options.files.startswith("/store"): filepath = "root://eoscms/"+str(options.files) else: filepath = options.files print 'filepath is '+str(filepath) infile = TFile.Open(filepath) infile.Print() wspace = infile.Get("tagsDumper/cms_hgg_13TeV") wspace.Print() isData=False dname="" print variables for varset in variables: print 'we look at the variable ...' print varset if not varset[-1]: #varset[-1]=varset[-2] varset = (varset[0], varset[1], varset[2], varset[2]) if not varset[1]: varset = (varset[0], varset[0], varset[2], [1,1]) isData=True datasetsReduced={} c=TCanvas("c","",1) binning1=varset[-2] binning1[-1]=binning1[-2]*1.2 print binning1 binning2=varset[-1] binning2[-1]=binning2[-2]*1.2 print binning2 th2sigtot=TH2D("signalEv_"+str(varset[0])+"_vs_"+str(varset[1])+"_all", "signalEv_"+str(varset[0])+"_vs_"+str(varset[1])+"_all", len(binning1)-1, np.asarray(binning1), len(binning2)-1, np.asarray(binning2)) th2sigtot.GetXaxis().SetTitle(str(varset[0])) th2sigtot.GetYaxis().SetTitle(str(varset[1])) for proc in procs: for cat in cats: print "reading ds "+str(proc)+"_"+str(cat)+" from ws" dataset = wspace.data(str(proc)+"_"+str(cat)) dataset.Print() th2sig = TH2D("signalEv_"+str(varset[0])+"_vs_"+str(varset[1])+"_"+str(proc)+"_"+str(cat), "signalEv_"+str(varset[0])+"_vs_"+str(varset[1])+"_"+str(proc)+"_"+str(cat), len(binning1)-1, np.asarray(binning1), len(binning2)-1, np.asarray(binning2)) th2sig.GetXaxis().SetTitle(str(varset[0])) th2sig.GetYaxis().SetTitle(str(varset[1])) for bound1 in range(len(varset[-2])-1): for bound2 in range(len(varset[-1])-1): if isData: dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1]) else: # dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_Vs_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) dname = str(proc.split('_',1)[0])+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_"+str(proc.split('_',1)[1])+"_"+str(cat)+"_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) datRed = dataset.Clone(dname) datRed.reset() datasetsReduced[ dname ] = datRed val=0. maxEntries = dataset.numEntries() if options.maxEntries != -1: maxEntries = options.maxEntries for i in range(maxEntries): if i%10000==0: print i iset = dataset.get(i) val1 = iset.getRealValue(varset[0]) val2 = iset.getRealValue(varset[1]) # print val1,val2 for bound1, bound2 in ((b1,b2) for b1 in range(len(varset[-2])-1) for b2 in range(len(varset[-1])-1) ): if isData: selCondition = (val1 > varset[-2][bound1]) and (val1 < varset[-2][bound1+1]) dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1]) else: selCondition = (val1 > varset[-2][bound1]) and (val1 < varset[-2][bound1+1]) and (val2 > varset[-1][bound2]) and (val2 < varset[-1][bound2+1]) # dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_Vs_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) dname = str(proc.split('_',1)[0])+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_"+str(proc.split('_',1)[1])+"_"+str(cat)+"_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) if selCondition: # print "filling dataset" ## print dataset.weight() datasetsReduced[dname].add(iset, dataset.weight()) break for bound1 in range(len(varset[-2])-1): for bound2 in range(len(varset[-1])-1): if isData: dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1]) else: dname = str(proc.split('_',1)[0])+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_"+str(proc.split('_',1)[1])+"_"+str(cat)+"_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) print "binning1 ",float(binning1[bound1])+(float(binning1[bound1+1])-float(binning1[bound1]))/2. print binning1[bound1+1] print binning1[bound1] print "cat1 ",(float(varset[-2][bound1+1])-float(varset[-2][bound1]))/2. print "binning2 ",float(binning2[bound2])+(float(binning2[bound2+1])-float(binning2[bound2]))/2. print binning2[bound2+1] print binning2[bound2] print "cat2 ",(float(varset[-1][bound2+1])-float(varset[-1][bound2]))/2. print "sumentries ",datasetsReduced[dname].sumEntries() th2sig.Fill( float(binning1[bound1])+(float(binning1[bound1+1])-float(binning1[bound1]))/2., float(binning2[bound2])+(float(binning2[bound2+1])-float(binning2[bound2]))/2., datasetsReduced[dname].sumEntries()) th2sig.Print("V") c.cd() if options.logz: c.SetLogz(1) th2sigtot.Add(th2sig) th2sig.Draw("colz") for fmt in savefmts: savename = th2sig.GetName() if options.logz: savename = str(savename)+"_logz" c.SaveAs(str(savename)+str(fmt)) c.cd() if options.logz: c.SetLogz(1) th2sigtot.Draw("colz") savename = th2sigtot.GetName() if options.logz: savename = str(savename)+"_logz" for fmt in savefmts: c.SaveAs(str(savename)+str(fmt)) # print "#### Compare reductions ####" new_wspace = RooWorkspace("cms_hgg_13TeV") getattr(new_wspace, 'import')(wspace.var("CMS_hgg_mass")) getattr(new_wspace, 'import')(wspace.var("IntLumi")) if not isData: getattr(new_wspace, 'import')(wspace.var("dZ")) getattr(new_wspace, 'import')(wspace.var("weight")) # alldata = new_wspace.allData() # for ds in alldata : # new_wspace.removeSet(str(ds.GetName())) outfilename = options.outfile.split('.')[0]+'_'+str(varset[0])+'_3th2.root' outfile = TFile(outfilename, 'RECREATE') stepsize=int(len(datasetsReduced.keys())/10) iteration = 0 while(len(datasetsReduced.keys())>0): print 'iteration '+str(iteration) iteration=iteration+1 try: outfile except NameError: outfile = TFile(outfilename, 'UPDATE') try: new_wspace except NameError: outfile.ls() new_wspace = outfile.Get("cms_hgg_13TeV") print "cms_hgg_13TeV;1" gDirectory.Delete("cms_hgg_13TeV;1") outfile.ls() # if not 'outfile' in globals(): # print 'outfile is not defined' # outfile = TFile(options.outfile, 'UPDATE') # if not 'new_wspace' in globals(): # new_wspace = outfile.Get("cms_hgg_13TeV") # print 'newspace is not defined' written=[] if stepsize > len(datasetsReduced.keys()): stepsize = len(datasetsReduced.keys()) for ikey in range(stepsize): # for ikey in range(len(datasetsReduced.keys())): # dataset.Print("V") # if dataset.numEntries() > 100: getattr(new_wspace, 'import')(datasetsReduced[datasetsReduced.keys()[ikey]]) datasetsReduced[datasetsReduced.keys()[ikey]].Write() written.append(datasetsReduced.keys()[ikey]) print 'Number of data in ws ' print len(new_wspace.allData()) #new_wspace.Print() new_wspace.Write() outfile.Write() outfile.Close() for wkey in written: del datasetsReduced[wkey] del new_wspace del outfile
def main(o, args): variables = options.variables procs = options.procs cats = options.cats print "****variables***" print variables #from configfile import variables, procs, cats if 0 and options.files.startswith("/store"): filepath = "root://eoscms/" + str(options.files) else: filepath = options.files print 'filepath is ' + str(filepath) infile = TFile.Open(filepath) infile.Print() wspace = infile.Get("tagsDumper/cms_hgg_13TeV") wspace.Print() isData = False dname = "" print variables for varset in variables: print 'we look at the variable ...' print varset if not varset[-1]: #varset[-1]=varset[-2] varset = (varset[0], varset[1], varset[2], varset[2]) if not varset[1]: varset = (varset[0], varset[0], varset[2], [1, 1]) isData = True datasetsReduced = {} c = TCanvas("c", "", 1) binning1 = varset[-2] binning1[-1] = binning1[-2] * 1.2 print binning1 binning2 = varset[-1] binning2[-1] = binning2[-2] * 1.2 print binning2 th2sigtot = TH2D( "signalEv_" + str(varset[0]) + "_vs_" + str(varset[1]) + "_all", "signalEv_" + str(varset[0]) + "_vs_" + str(varset[1]) + "_all", len(binning1) - 1, np.asarray(binning1), len(binning2) - 1, np.asarray(binning2)) th2sigtot.GetXaxis().SetTitle(str(varset[0])) th2sigtot.GetYaxis().SetTitle(str(varset[1])) for proc in procs: for cat in cats: print "reading ds " + str(proc) + "_" + str(cat) + " from ws" dataset = wspace.data(str(proc) + "_" + str(cat)) dataset.Print() th2sig = TH2D( "signalEv_" + str(varset[0]) + "_vs_" + str(varset[1]) + "_" + str(proc) + "_" + str(cat), "signalEv_" + str(varset[0]) + "_vs_" + str(varset[1]) + "_" + str(proc) + "_" + str(cat), len(binning1) - 1, np.asarray(binning1), len(binning2) - 1, np.asarray(binning2)) th2sig.GetXaxis().SetTitle(str(varset[0])) th2sig.GetYaxis().SetTitle(str(varset[1])) for bound1 in range(len(varset[-2]) - 1): for bound2 in range(len(varset[-1]) - 1): if isData: dname = str(proc) + "_" + str( cat) + "_" + varset[0] + "_" + str( varset[-2][bound1]) + "to" + str( varset[-2][bound1 + 1]) else: # dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_Vs_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) dname = str( proc.split('_', 1)[0] ) + "_" + varset[0] + "_" + str( varset[-2][bound1] ) + "to" + str(varset[-2][bound1 + 1]) + "_" + str( proc.split('_', 1)[1]) + "_" + str( cat) + "_" + varset[1] + "_" + str( varset[-1][bound2]) + "to" + str( varset[-1][bound2 + 1]) datRed = dataset.Clone(dname) datRed.reset() datasetsReduced[dname] = datRed val = 0. maxEntries = dataset.numEntries() if options.maxEntries != -1: maxEntries = options.maxEntries for i in range(maxEntries): if i % 10000 == 0: print i iset = dataset.get(i) val1 = iset.getRealValue(varset[0]) val2 = iset.getRealValue(varset[1]) # print val1,val2 for bound1, bound2 in ( (b1, b2) for b1 in range(len(varset[-2]) - 1) for b2 in range(len(varset[-1]) - 1)): if isData: selCondition = (val1 > varset[-2][bound1]) and ( val1 < varset[-2][bound1 + 1]) dname = str(proc) + "_" + str( cat) + "_" + varset[0] + "_" + str( varset[-2][bound1]) + "to" + str( varset[-2][bound1 + 1]) else: selCondition = (val1 > varset[-2][bound1]) and ( val1 < varset[-2][bound1 + 1]) and ( val2 > varset[-1][bound2]) and ( val2 < varset[-1][bound2 + 1]) # dname = str(proc)+"_"+str(cat)+"_"+varset[0]+"_"+str(varset[-2][bound1])+"to"+str(varset[-2][bound1+1])+"_Vs_"+varset[1]+"_"+str(varset[-1][bound2])+"to"+str(varset[-1][bound2+1]) dname = str( proc.split('_', 1)[0] ) + "_" + varset[0] + "_" + str( varset[-2][bound1] ) + "to" + str(varset[-2][bound1 + 1]) + "_" + str( proc.split('_', 1)[1]) + "_" + str( cat) + "_" + varset[1] + "_" + str( varset[-1][bound2]) + "to" + str( varset[-1][bound2 + 1]) if selCondition: # print "filling dataset" ## print dataset.weight() datasetsReduced[dname].add(iset, dataset.weight()) break for bound1 in range(len(varset[-2]) - 1): for bound2 in range(len(varset[-1]) - 1): if isData: dname = str(proc) + "_" + str( cat) + "_" + varset[0] + "_" + str( varset[-2][bound1]) + "to" + str( varset[-2][bound1 + 1]) else: dname = str( proc.split('_', 1)[0] ) + "_" + varset[0] + "_" + str( varset[-2][bound1] ) + "to" + str(varset[-2][bound1 + 1]) + "_" + str( proc.split('_', 1)[1]) + "_" + str( cat) + "_" + varset[1] + "_" + str( varset[-1][bound2]) + "to" + str( varset[-1][bound2 + 1]) print "binning1 ", float(binning1[bound1]) + ( float(binning1[bound1 + 1]) - float(binning1[bound1])) / 2. print binning1[bound1 + 1] print binning1[bound1] print "cat1 ", (float(varset[-2][bound1 + 1]) - float(varset[-2][bound1])) / 2. print "binning2 ", float(binning2[bound2]) + ( float(binning2[bound2 + 1]) - float(binning2[bound2])) / 2. print binning2[bound2 + 1] print binning2[bound2] print "cat2 ", (float(varset[-1][bound2 + 1]) - float(varset[-1][bound2])) / 2. print "sumentries ", datasetsReduced[ dname].sumEntries() th2sig.Fill( float(binning1[bound1]) + (float(binning1[bound1 + 1]) - float(binning1[bound1])) / 2., float(binning2[bound2]) + (float(binning2[bound2 + 1]) - float(binning2[bound2])) / 2., datasetsReduced[dname].sumEntries()) th2sig.Print("V") c.cd() if options.logz: c.SetLogz(1) th2sigtot.Add(th2sig) th2sig.Draw("colz") for fmt in savefmts: savename = th2sig.GetName() if options.logz: savename = str(savename) + "_logz" c.SaveAs(str(savename) + str(fmt)) c.cd() if options.logz: c.SetLogz(1) th2sigtot.Draw("colz") savename = th2sigtot.GetName() if options.logz: savename = str(savename) + "_logz" for fmt in savefmts: c.SaveAs(str(savename) + str(fmt)) # print "#### Compare reductions ####" new_wspace = RooWorkspace("cms_hgg_13TeV") getattr(new_wspace, 'import')(wspace.var("CMS_hgg_mass")) getattr(new_wspace, 'import')(wspace.var("IntLumi")) if not isData: getattr(new_wspace, 'import')(wspace.var("dZ")) getattr(new_wspace, 'import')(wspace.var("weight")) # alldata = new_wspace.allData() # for ds in alldata : # new_wspace.removeSet(str(ds.GetName())) outfilename = options.outfile.split('.')[0] + '_' + str( varset[0]) + '_3th2.root' outfile = TFile(outfilename, 'RECREATE') stepsize = int(len(datasetsReduced.keys()) / 10) iteration = 0 while (len(datasetsReduced.keys()) > 0): print 'iteration ' + str(iteration) iteration = iteration + 1 try: outfile except NameError: outfile = TFile(outfilename, 'UPDATE') try: new_wspace except NameError: outfile.ls() new_wspace = outfile.Get("cms_hgg_13TeV") print "cms_hgg_13TeV;1" gDirectory.Delete("cms_hgg_13TeV;1") outfile.ls() # if not 'outfile' in globals(): # print 'outfile is not defined' # outfile = TFile(options.outfile, 'UPDATE') # if not 'new_wspace' in globals(): # new_wspace = outfile.Get("cms_hgg_13TeV") # print 'newspace is not defined' written = [] if stepsize > len(datasetsReduced.keys()): stepsize = len(datasetsReduced.keys()) for ikey in range(stepsize): # for ikey in range(len(datasetsReduced.keys())): # dataset.Print("V") # if dataset.numEntries() > 100: getattr(new_wspace, 'import')( datasetsReduced[datasetsReduced.keys()[ikey]]) datasetsReduced[datasetsReduced.keys()[ikey]].Write() written.append(datasetsReduced.keys()[ikey]) print 'Number of data in ws ' print len(new_wspace.allData()) #new_wspace.Print() new_wspace.Write() outfile.Write() outfile.Close() for wkey in written: del datasetsReduced[wkey] del new_wspace del outfile
p = Properties(minMass, maxMass, ptBinsX, ptBinsY, triggerMatchDeltaR, NoBkgd) # Trigger efficiency for new trigger over old trigger oldTrigger = "HLT_L2DoubleMu23_NoVertex_v" newTrigger = "HLT_L2DoubleMu23_NoVertex_2Cha_Angle2p5_v" # Load the input file tree = ROOT.TChain("T") #tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_ZMuMu.root") tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012A.root") tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012B.root") tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012C.root") tree.Add("/afs/cern.ch/user/d/demattia/public/TagAndProbe/TagAndProbe_Run2012D.root") # Prepare the workspace ws = RooWorkspace("ws", "workspace") Workspace.buildPdf(ws, p) mass = ws.var("mass") sample = ws.cat("sample") simPdf = ws.pdf("simPdf") efficiency = ws.var("efficiency") meanB = ws.var("meanB") # prepare_datasets(ws, p) # Prepare datasets datasetAllMap = {} datasetPassMap = {} hAllMap = {} hPassMap = {}
vtb = 0.999105 # http://pdg.lbl.gov/2018/reviews/rpp2018-rev-ckm-matrix.pdf vts_term_bWsW = 2 * (vts**2) * (vtb**2) # + vts**4 vts_term_bWbW = (vtb**2)**2 f = ROOT.TFile( "/cms/ldap_home/wjjang/wj_nanoAOD_CMSSW_9_4_4/src/nano/analysis/test/vts/tmva/output/vts_dR_04_Jet.root" ) t = f.Get(str(sys.argv[1]) + "/Method_BDT/BDT") t2 = f.Get(str(sys.argv[2]) + "/Method_BDT/BDT") h_sig = t.Get("MVA_BDT_S") h_bkg = t.Get("MVA_BDT_B") h_sig2 = t2.Get("MVA_BDT_S") h_bkg2 = t2.Get("MVA_BDT_B") w = RooWorkspace() c = ROOT.TCanvas("plots", "plots", 1920, 1080) c.Divide(4, 2) w.factory("bdt[-1,1]") rooh_sig = ROOT.RooDataHist("sigHist", "sigHist", ROOT.RooArgList(w.var("bdt")), h_sig) rooh_bkg = ROOT.RooDataHist("bkgHist", "bkgHist", ROOT.RooArgList(w.var("bdt")), h_bkg) getattr(w, 'import')(rooh_sig) getattr(w, 'import')(rooh_bkg) if t.GetPath().find("_JKS_") is not -1 or t.GetPath().find("JKS_") is not -1: w.factory( "Gaussian::sig_1(bdt, meanSig1[-0.0317964,-1, 1.], sigmaSig1[0.0654243,0, 1])" )
def makeCard(TYPE, mZp, mChi, DIR): # Setup input and output files indir = DIR old_str = "" new_str = "" if (TYPE == "BARY"): old_str = "sig_ZpBaryonic_mZP10_mChi1" new_str = "sig_ZpBaryonic_mZP" + mZp + "_mChi" + mChi if (TYPE == "2HDM"): old_str = "sig_2HDM_mZP600_mA0300" new_str = "sig_2HDM_mZP" + mZp + "_mA0" + mChi fin = open(indir + "dataCard_" + old_str + "_13TeV.txt", "r") fout = open(indir + "dataCard_" + new_str + "_13TeV.txt", "w") rin = ROOT.TFile(indir + old_str + "_13TeV.root") rout = ROOT.TFile(indir + new_str + "_13TeV.root", "RECREATE") # Copy the datacard for new mass point for line in fin: if old_str in line: line = line.replace(old_str, new_str) fout.write(line) # Get the old and new eff mZ = float(mZp) mDM = float(mChi) old_efflowMET = 1.0 old_effhighMET = 1.0 new_efflowMET = 1.0 new_effhighMET = 1.0 if (TYPE == "BARY"): old_efflowMET = getEffBary(0, 10, 1) old_effhighMET = getEffBary(1, 10, 1) new_efflowMET = getEffBary(0, mZ, mDM) new_effhighMET = getEffBary(1, mZ, mDM) if (TYPE == "2HDM"): old_efflowMET = getEff2HDM(0, 600, 300) old_effhighMET = getEff2HDM(1, 600, 300) new_efflowMET = getEff2HDM(0, mZ, mDM) new_effhighMET = getEff2HDM(1, mZ, mDM) scale_lowMET = new_efflowMET / old_efflowMET scale_highMET = new_effhighMET / old_effhighMET #print("Old eff: low = %f, high = %f" %(old_efflowMET,old_effhighMET)) #print("New eff: low = %f, high = %f" %(new_efflowMET,new_effhighMET)) #print("Scale: low = %f, high = %f" %(scale_lowMET,scale_highMET)) # Copy the input file in_TObjString = TObjString(rin.cfg) out_TObjString = in_TObjString.Clone() in_RooWorkspace = RooWorkspace(rin.wtemplates) #in_RooWorkspace.Print() # print obj in input rooWorkspace w1 = ROOT.RooWorkspace("wtemplates") w1.rooImport = getattr(w1, 'import') var1 = in_RooWorkspace.var('mgg') var2 = in_RooWorkspace.var('model_signal_' + old_str + '_13TeV_met0-130_norm') var3 = in_RooWorkspace.var('model_signal_' + old_str + '_13TeV_met130_norm') # multiply old normalization by new scale valnorm_lowMET = scale_lowMET * var2.getValV() valnorm_highMET = scale_highMET * var3.getValV() norm1 = RooRealVar("model_signal_" + new_str + "_13TeV_met0-130_norm", "model_signal" + new_str + "13TeV_met0-130_norm", valnorm_lowMET) norm2 = RooRealVar("model_signal_" + new_str + "_13TeV_met130_norm", "model_signal" + new_str + "13TeV_met130_norm", valnorm_highMET) varlist = ROOT.RooArgList(var1, norm1, norm2) #print("%f * %f" %(scale_lowMET,var2.getValV())) #print("%f" %valnorm_lowMET) #print("%f" %norm1.getValV()) # get old pdfs and change names pdf1 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met0-130') pdf2 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met0-130_energyScalemet0-130Down') pdf3 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met0-130_energyScalemet0-130Up') pdf4 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met130') pdf5 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met130_energyScalemet130Down') pdf6 = in_RooWorkspace.pdf('model_signal_' + old_str + '_13TeV_met130_energyScalemet130Up') pdf1new = ROOT.RooHistPdf(pdf1, "model_signal_" + new_str + "_13TeV_met0-130") pdf2new = ROOT.RooHistPdf( pdf2, "model_signal_" + new_str + "_13TeV_met0-130_energyScalemet0-130Down") pdf3new = ROOT.RooHistPdf( pdf3, "model_signal_" + new_str + "_13TeV_met0-130_energyScalemet0-130Up") pdf4new = ROOT.RooHistPdf(pdf4, "model_signal_" + new_str + "_13TeV_met130") pdf5new = ROOT.RooHistPdf( pdf5, "model_signal_" + new_str + "_13TeV_met130_energyScalemet130Down") pdf6new = ROOT.RooHistPdf( pdf6, "model_signal_" + new_str + "_13TeV_met130_energyScalemet130Up") # these are null pointers -- probably don't have right classes (missing from dipho analysis) to read them # but they are also not needed for running higgs combine so left out for now dat1 = in_RooWorkspace.data('signal_' + old_str + '_13TeV_met130') dat2 = in_RooWorkspace.data('signalforPdf_' + old_str + '_13TeV_met130') dat3 = in_RooWorkspace.data('signal_' + old_str + '_13TeV_met0-130') dat4 = in_RooWorkspace.data('signalforPdf_' + old_str + '_13TeV_met0-130') #print("%f" %dat1.sumEntries()) # Write to output file #out_TObjString.Write() w1.rooImport(var1) w1.rooImport(norm1) w1.rooImport(norm2) w1.rooImport(pdf1new) w1.rooImport(pdf2new) w1.rooImport(pdf3new) w1.rooImport(pdf4new) w1.rooImport(pdf5new) w1.rooImport(pdf6new) #w1.Print() # print contents of workspace w1.Write() rout.Close()
def setup_workspace(config): import ROOT from ROOT import RooWorkspace, gROOT, gStyle, RooAbsReal, RooMsgService, RooFit #from ROOT import RooFit, gROOT, gDirectory, gStyle, gPad, TTree, RooCmdArg,RooBinning #from ROOT import RooRealVar, RooMappedCategory, RooCategory, RooFormulaVar, RooAbsData #from ROOT import RooBMixDecay, RooMCStudy, RooAddModel, RooEffProd, RooMsgService #from ROOT import RooWorkspace, TCanvas, TFile, kFALSE, kTRUE, RooDataSet, TStopwatch #from ROOT import RooArgSet, RooArgList, RooRandom, RooMinuit, RooAbsReal, RooDataHist #from ROOT import TBrowser, TH2F, TF1, TH1F, RooGenericPdf, RooLinkedList from math import sqrt gROOT.SetStyle("Plain") gStyle.SetPalette(1) gStyle.SetOptStat(0) gStyle.SetOptFit(0) gStyle.SetOptStat(1111) gStyle.SetOptFit(10111) gStyle.SetOptTitle(1) #gROOT.ProcessLine(".L RooGaussianTrunk.cxx+") #gROOT.ProcessLine(".L RooCBShapeTrunk.cxx+") #gROOT.ProcessLine(".L RooChebychevTrunk.cxx+") #from ROOT import RooGaussianTrunk, RooChebychevTrunk, RooCBShapeTrunk #RooAbsReal.defaultIntegratorConfig().Print() RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-8) RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-8) #RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-6) #RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-6) RooAbsReal.defaultIntegratorConfig().Print() print "Numeric integration set up" #TODO: is the integration acceptable? ##This controls the logging output from RooFit #RooMsgService.instance().addStream(RooFit.DEBUG,RooFit.Topic(RooFit.Fitting)) RooMsgService.instance().deleteStream(1) #RooMsgService.instance().addStream(RooFit.INFO,RooFit.Topic(RooFit.Generation + RooFit.Minization + RooFit.Plotting + RooFit.Fitting + RooFit.Integration + RooFit.LinkStateMgmt + RooFit.Eval + RooFit.Caching + RooFit.Optimization + RooFit.ObjectHandling + RooFit.InputArguments + RooFit.Tracing + RooFit.Contents + RooFit.DataHandling + RooFit.NumericIntegration)) RooMsgService.instance().addStream(RooFit.INFO,RooFit.Topic(RooFit.LinkStateMgmt + RooFit.Caching + RooFit.ObjectHandling + RooFit.InputArguments + RooFit.Tracing)) RooMsgService.instance().Print() print "Message service set up" w = RooWorkspace("w",False) w.factory("RAND[0,1]") if "norm" not in config["mode"]: D0_Mass = w.factory("D0_Mass[1815,1915]") else: D0_Mass = w.factory("D0_Mass[1800,1930]") D0_Mass.setUnit("MeV") D0_Mass.setBins(60) Del_Mass = w.factory("Del_Mass[139,155]") Del_Mass.setUnit("MeV") Del_Mass.setBins(60) if "norm" not in config["mode"]: Dataset = w.factory("DataSet[BDT1,BDT2,BDT3]") else: Dataset = w.factory("DataSet[Norm]") w.factory("classID[Sig=0,Bkg=1]") w.factory("BDT_ada[-1,1]") w.factory("x1_PIDe[-2,20]") w.factory("x2_ProbNNmu[0,1]") #D0_Mass.setRange("blinded",1700.,1900.) if "norm" not in config["mode"]: dataCats = ["", "BDT1", "BDT2", "BDT3"] else: dataCats = ["", "Norm"] for data in dataCats: for dst_side in ["", "delsig", "delhigh", "dellow"]: for d_side in ["", "dsig", "dhigh", "dlow", "dhigh1", "dlow1", "dhigh2", "dlow2"]: name = data+dst_side+d_side if data == "BDT1": Dataset.setRange(name,"BDT1") elif data == "BDT2": Dataset.setRange(name,"BDT2") elif data == "BDT3": Dataset.setRange(name,"BDT3") elif data == "Norm": Dataset.setRange(name,"Norm") if dst_side == "delhigh": Del_Mass.setRange(name,148.,155.) elif dst_side == "delsig": Del_Mass.setRange(name,143.,148.) elif dst_side == "dellow": Del_Mass.setRange(name,139.,143.) if d_side == "dhigh2": D0_Mass.setRange(name,1910.,1930.) elif d_side == "dhigh1": D0_Mass.setRange(name,1890.,1910.) elif d_side == "dhigh": D0_Mass.setRange(name,1890.,1930.) elif d_side == "dsig": D0_Mass.setRange(name,1840.,1890.) elif d_side == "dlow": D0_Mass.setRange(name,1800.,1840.) elif d_side == "dlow1": D0_Mass.setRange(name,1820.,1840.) elif d_side == "dlow2": D0_Mass.setRange(name,1800.,1820.) w.defineSet("args","D0_Mass,Del_Mass,DataSet") w.defineSet("argsBasic","D0_Mass,Del_Mass") #w.defineSet("argsPreCut","D0_Mass,Del_Mass,RAND,classID,BDT_ada") w.defineSet("argsPreCut","D0_Mass,Del_Mass,RAND,classID,BDT_ada,x1_PIDe,x2_ProbNNmu") w.defineSet("argsPreCutPiPi","D0_Mass,Del_Mass,RAND") w.defineSet("argsPreCutKPi","D0_Mass,Del_Mass,RAND") # --- Norm --- if config['norm'] is "kpi": w.factory("{D0_Mass,Norm_D0M_Min[1815],Norm_D0M_Max[1915]}") else: w.factory("{D0_Mass,Norm_D0M_Min[1826],Norm_D0M_Max[1920]}") w.factory("RooGenericPdf::Norm_D0M_Range('(D0_Mass>Norm_D0M_Min&&D0_Mass<Norm_D0M_Max)',{D0_Mass,Norm_D0M_Min,Norm_D0M_Max})") w.factory("RooFormulaVar::Norm_D0M_Sig_Gaus2_Sigma('Norm_D0M_Sig_Gaus1_Sigma+Norm_D0M_Sig_Gaus2_Sigma_Diff',{Norm_D0M_Sig_Gaus1_Sigma[5,0,10],Norm_D0M_Sig_Gaus2_Sigma_Diff[5,0.,10.]})") w.factory("RooFormulaVar::Norm_D0M_Sig_Gaus3_Sigma('Norm_D0M_Sig_Gaus1_Sigma+Norm_D0M_Sig_Gaus2_Sigma_Diff+Norm_D0M_Sig_Gaus3_Sigma_Diff',{Norm_D0M_Sig_Gaus1_Sigma,Norm_D0M_Sig_Gaus2_Sigma_Diff,Norm_D0M_Sig_Gaus3_Sigma_Diff[2,0.,20.]})") w.factory("RooFormulaVar::Norm_D0M_Sig_Gaus1_Sigma_Scaled('Norm_D0M_Sig_Gaus1_Sigma*Norm_D0M_Sig_Gaus_Sigma_Scale',{Norm_D0M_Sig_Gaus1_Sigma,Norm_D0M_Sig_Gaus_Sigma_Scale[1]})") w.factory("RooFormulaVar::Norm_D0M_Sig_Gaus2_Sigma_Scaled('(Norm_D0M_Sig_Gaus1_Sigma+Norm_D0M_Sig_Gaus2_Sigma_Diff)*Norm_D0M_Sig_Gaus_Sigma_Scale',{Norm_D0M_Sig_Gaus1_Sigma,Norm_D0M_Sig_Gaus2_Sigma_Diff,Norm_D0M_Sig_Gaus_Sigma_Scale})") w.factory("RooFormulaVar::Norm_D0M_Sig_Gaus3_Sigma_Scaled('(Norm_D0M_Sig_Gaus1_Sigma+Norm_D0M_Sig_Gaus2_Sigma_Diff+Norm_D0M_Sig_Gaus3_Sigma_Diff)*Norm_D0M_Sig_Gaus_Sigma_Scale',{Norm_D0M_Sig_Gaus1_Sigma,Norm_D0M_Sig_Gaus2_Sigma_Diff,Norm_D0M_Sig_Gaus3_Sigma_Diff,Norm_D0M_Sig_Gaus_Sigma_Scale})") # D0_Mass Signal w.factory("RooCBShape::Norm_D0M_Sig_Gaus1(D0_Mass,Norm_D0M_Sig_Gaus_Mean[1867,1850,1880],Norm_D0M_Sig_Gaus1_Sigma_Scaled,Norm_D0M_Sig_Gaus1_alpha[1.5,0,6],Norm_D0M_Sig_Gaus1_n[2,0,20])") #w.factory("RooGaussian::Norm_D0M_Sig_Gaus1(D0_Mass,Norm_D0M_Sig_Gaus_Mean[1867,1850,1880],Norm_D0M_Sig_Gaus1_Sigma_Scaled)") w.factory("RooCBShape::Norm_D0M_Sig_Gaus2(D0_Mass,Norm_D0M_Sig_Gaus_Mean,Norm_D0M_Sig_Gaus2_Sigma_Scaled,Norm_D0M_Sig_Gaus2_alpha[1.5,0,6],Norm_D0M_Sig_Gaus2_n[2,0,20])") #w.factory("RooGaussian::Norm_D0M_Sig_Gaus2(D0_Mass,Norm_D0M_Sig_Gaus_Mean,Norm_D0M_Sig_Gaus2_Sigma_Scaled)") #w.factory("RooGaussian::Norm_D0M_Sig_Gaus3(D0_Mass,Norm_D0M_Sig_Gaus3_Mean[1867,1850,1880],Norm_D0M_Sig_Gaus3_Sigma_Scaled)") w.factory("RooGaussian::Norm_D0M_Sig_Gaus3(D0_Mass,Norm_D0M_Sig_Gaus_Mean,Norm_D0M_Sig_Gaus3_Sigma_Scaled)") #w.factory("RooCBShape::Norm_D0M_Sig_Gaus3(D0_Mass,Norm_D0M_Sig_Gaus_Mean,Norm_D0M_Sig_Gaus3_Sigma_Scaled,Norm_D0M_Sig_Gaus3_alpha[1.5,0,6],Norm_D0M_Sig_Gaus3_n[0.5,0,20])") #w.factory("SUM::Norm_D0M_Sig(Norm_D0M_Sig_Gaus1_Frac[0.4,0,1]*Norm_D0M_Sig_Gaus1,Norm_D0M_Sig_Gaus3_Frac[0.1,0,1]*Norm_D0M_Sig_Gaus3,Norm_D0M_Sig_Gaus2)") w.factory("SUM::Norm_D0M_Sig(Norm_D0M_Sig_Gaus1_Frac[0.4,0,1]*Norm_D0M_Sig_Gaus1,Norm_D0M_Sig_Gaus2)") #w.factory("PROD::Norm_D0M_Sig(Norm_D0M_Sig_Sum,Norm_D0M_Range)") # D0_Mass MisId #w.factory("RooGaussian::Norm_D0M_MisId_Gaus1(D0_Mass,Norm_D0M_MisId_Gaus_Mean[1790,1720,1820],Norm_D0M_Sig_Gaus1_Sigma)") #w.factory("RooGaussian::Norm_D0M_MisId_Gaus2(D0_Mass,Norm_D0M_MisId_Gaus_Mean,Norm_D0M_Sig_Gaus2_Sigma)") #w.factory("SUM::Norm_D0M_MisId(Norm_D0M_Sig_Gaus1_Frac*Norm_D0M_MisId_Gaus1,Norm_D0M_MisId_Gaus2)") ##w.factory("PROD::Norm_D0M_MisId(Norm_D0M_MisId_Sum,Norm_D0M_Range)") ##w.factory("RooExponential::Norm_D0M_MisId_Exp(D0_Mass,Norm_D0M_MisId_Exp_Const[-0.15,-.3,-.1])") ##w.factory("PROD::Norm_D0M_MisId(Norm_D0M_MisId_Exp,Norm_D0M_Range)") # D0_Mass Combinatorical w.factory('{Norm_D0M_Bkg_Cheby_1[-0.5,-1,1]}') #w.factory("RooChebychev::Norm_D0M_Bkg_Poly(D0_Mass,{Norm_D0M_Bkg_Cheby_1[-0.25,-1.5,1]})") #w.factory("PROD::Norm_D0M_Bkg(Norm_D0M_Bkg_Poly,Norm_D0M_Range)") w.factory("RooExponential::Norm_D0M_Bkg(D0_Mass,Norm_D0M_Bkg_Exp_c[-0.0088,-0.05,-0.001])") #w.factory("RooChebychev::Norm_D0M_Bkg(D0_Mass,{Norm_D0M_Bkg_Cheby_1})") #w.factory("RooChebychev::Norm_D0M_Bkg(D0_Mass,{Norm_D0M_Bkg_Cheby_1,Norm_D0M_Bkg_Cheby_2[-0.1,-0.7,1]})") w.factory("RooFormulaVar::Norm_DelM_Sig_Gaus_Mean_Shifted('Norm_DelM_Sig_Gaus_Mean+Norm_DelM_Sig_Gaus_Mean_Shift',{Norm_DelM_Sig_Gaus_Mean[145.5,145,146],Norm_DelM_Sig_Gaus_Mean_Shift[0]})") w.factory("RooFormulaVar::Norm_DelM_Sig_Gaus3_Mean_Shifted('Norm_DelM_Sig_Gaus3_Mean+Norm_DelM_Sig_Gaus_Mean_Shift',{Norm_DelM_Sig_Gaus3_Mean[145.7,144,155],Norm_DelM_Sig_Gaus_Mean_Shift})") w.factory("RooFormulaVar::Norm_DelM_Sig_Gaus2_Sigma('Norm_DelM_Sig_Gaus1_Sigma+Norm_DelM_Sig_Gaus2_Sigma_Diff',{Norm_DelM_Sig_Gaus1_Sigma[.4,0,1],Norm_DelM_Sig_Gaus2_Sigma_Diff[0.4,0.,1.]})") w.factory("RooFormulaVar::Norm_DelM_Sig_Gaus3_Sigma('Norm_DelM_Sig_Gaus1_Sigma+Norm_DelM_Sig_Gaus2_Sigma_Diff+Norm_DelM_Sig_Gaus3_Sigma_Diff',{Norm_DelM_Sig_Gaus1_Sigma,Norm_DelM_Sig_Gaus2_Sigma_Diff,Norm_DelM_Sig_Gaus3_Sigma_Diff[0.4,0.,3.]})") # Del_Mass signal w.factory("{Norm_DelM_Sig_Gaus3_Frac[0.01,0,.7]}") #w.factory("RooCBShape::Norm_DelM_Sig_Gaus1(Del_Mass,Norm_DelM_Sig_Gaus_Mean_Shifted,Norm_DelM_Sig_Gaus1_Sigma[.4,0,1],Norm_DelM_Sig_CB1_alpha[1.5,0,6], BDT%(n)i_D0M_Sig_CB1_n[2,0,10] )") w.factory("RooGaussian::Norm_DelM_Sig_Gaus1(Del_Mass,Norm_DelM_Sig_Gaus_Mean_Shifted,Norm_DelM_Sig_Gaus1_Sigma)") w.factory("RooGaussian::Norm_DelM_Sig_Gaus2(Del_Mass,Norm_DelM_Sig_Gaus_Mean_Shifted,Norm_DelM_Sig_Gaus2_Sigma)") w.factory("RooGaussian::Norm_DelM_Sig_Gaus3(Del_Mass,Norm_DelM_Sig_Gaus3_Mean_Shifted,Norm_DelM_Sig_Gaus3_Sigma)") w.factory("SUM::Norm_DelM_Sig(Norm_DelM_Sig_Gaus1_Frac[0.1,0,.7]*Norm_DelM_Sig_Gaus1,Norm_DelM_Sig_Gaus3_Frac*Norm_DelM_Sig_Gaus3,Norm_DelM_Sig_Gaus2)") #w.factory("SUM::Norm_DelM_Sig(Norm_DelM_Sig_Gaus1_Frac[0.1,0,.7]*Norm_DelM_Sig_Gaus1,Norm_DelM_Sig_Gaus2)") # mis recod w.factory("RooGaussian::Norm_DelM_MisRecod_Gaus1(Del_Mass,Norm_DelM_MisRecod_Gaus_Mean[145.5,145,146],Norm_DelM_MisRecod_Gaus_Sigma1[1.2,0,5] )") w.factory("RooChebychev::Norm_D0M_MisRecod(D0_Mass,{Norm_D0M_MisRecod_Cheby_1[0,-1,1]})") # Del_Mass Combinatorical #w.factory("RooDstD0BG::Norm_DelM_Bkg(Del_Mass,Norm_DelM_Bkg_m0[139.5,137.5,140.5],Norm_DelM_Bkg_c[40,7,350],Norm_DelM_Bkg_a[-20,-100,-1],Norm_DelM_Bkg_b[0.4,-1,2])") w.factory("RooDstD0BG::Norm_DelM_Bkg(Del_Mass,Norm_DelM_Bkg_m0[139.5,137.5,140.5],Norm_DelM_Bkg_m0,Norm_DelM_Bkg_a[-20,-100,-1],Norm_DelM_Bkg_b[0.4,-1,2])") w.factory("{Norm_DelM_Bkg_c[40,7,350]}") # Del_Mass signal w.factory("RooGaussian::Norm_DelM_MisId(Del_Mass,Norm_DelM_Sig_Gaus_Mean,Norm_DelM_MisId_Gaus_Sigma1[1,0,3])") w.factory("PROD::Norm_Sig(Norm_DelM_Sig,Norm_D0M_Sig)") w.factory("PROD::Norm_Comb(Norm_DelM_Bkg,Norm_D0M_Bkg)") w.factory("PROD::Norm_MisRecod(Norm_DelM_MisRecod_Gaus1,Norm_D0M_MisRecod)") #w.factory("PROD::Norm_MisId(Norm_DelM_MisId,Norm_D0M_MisId)") #w.factory("PROD::Norm_MisId(Norm_DelM_Sig,Norm_D0M_MisId)") #w.factory("PROD::Norm_MisId_Prompt(Norm_DelM_Bkg,Norm_D0M_MisId)") w.factory("PROD::Norm_Prompt(Norm_DelM_Bkg,Norm_D0M_Sig)") w.factory("{Norm_N_Sig[65000,20000,500000],Norm_N_MisId[1300,100,3000],Norm_N_MisRecod[5000,100,30000],Norm_N_MisId_Prompt[500,10,1000]}") # --- eMu --- #w.factory("EMu_N_Sig[1000,0,100000]") for n in (1,2,3): w.factory("BDT%(n)i_Sig_Eff[0.3,0,1]"%({"n":n})) w.factory("EMu_Eff[%f]"%(config['emuEff'])) w.factory("EMu_BR[1e-8,-1e-7,1e-7]") if config['norm'] is 'pipi': w.factory("Norm_Eff[%f]"%(config['pipiEff'])) w.factory("Norm_BR[%f]"%(config['pipiBR'][0])) w.obj("Norm_BR").setError(config['pipiBR'][1]) elif config['norm'] is 'kpi': w.factory("Norm_Eff[%f]"%(config['kpiEff'])) w.factory("Norm_BR[%f]"%(config['kpiBR'][0])) w.obj("Norm_BR").setError(config['kpiBR'][1]) w.factory("RooFormulaVar::N_PiPi('Norm_N_Sig*(%f)',{Norm_N_Sig})"%(config['pipiAsEmuEff']*config['pipiBR'][0]/config['kpiBR'][0]/config['kpiEff'],)) w.factory("RooFormulaVar::EMu_N_Sig('abs(Norm_N_Sig*((EMu_BR*EMu_Eff)/(Norm_BR*Norm_Eff)))',{Norm_BR,EMu_BR,EMu_Eff,Norm_Eff,Norm_N_Sig})") w.factory("{EMu_D0M_Min[1815],EMu_D0M_Max[1915]}") w.factory("RooGaussian::Norm_Constraint(Norm_N_Sig,%f,%f)"%(config["normEvents"][0],config["normEvents"][1])) # D0_Mass Combinatorical w.factory("RooGenericPdf::BDT_D0M_Blind('(D0_Mass<1700||D0_Mass>1900)',{D0_Mass})") w.factory("RooGenericPdf::BDT_D0M_Range('(D0_Mass>EMu_D0M_Min&&D0_Mass<EMu_D0M_Max)',{D0_Mass,EMu_D0M_Min,EMu_D0M_Max})") w.factory("RooChebychev::BDT_D0M_Bkg(D0_Mass,{BDT_D0M_Bkg_Cheby_1[-0.7,-3.0,0.0],BDT_D0M_Bkg_Cheby_2[-0.2,-3.0,0.0]})") w.factory("PROD::BDT_D0M_Bkg_Blind(BDT_D0M_Bkg,BDT_D0M_Blind)") # Del_Mass Combinatorical w.factory("RooDstD0BG::BDT_DelM_Bkg(Del_Mass,BDT_DelM_Bkg_m0[139.5,137.5,140.5],BDT_DelM_Bkg_c[40,7,350],BDT_DelM_Bkg_a[-20,-100,-1],BDT_DelM_Bkg_b[-0.1,-2,1])"%({"n":n})) w.factory("{BDT_D0M_Sig_CB1_alphaleft[0.3,0,1]}") w.factory("{BDT_D0M_Sig_CB2_alpharight[-0.5,-5,0]}") for n in (1,2,3): if n is not 3: w.factory("RooFormulaVar::BDT%(n)i_N_Sig('EMu_N_Sig*BDT%(n)i_Sig_Eff',{EMu_N_Sig,BDT%(n)i_Sig_Eff})"%({"n":n})) else: w.factory("RooFormulaVar::BDT%(n)i_N_Sig('EMu_N_Sig*(1-(BDT1_Sig_Eff+BDT2_Sig_Eff))',{EMu_N_Sig,BDT1_Sig_Eff,BDT2_Sig_Eff})"%({"n":n})) # D0_Mass Signal w.factory("{BDT%(n)i_D0M_Sig_CB2_alpharight[-0.5,-5,0],BDT%(n)i_D0M_Sig_CB1_alphaleft[0.3,0,1]}"%({"n":n})) w.factory("RooCBShape:BDT%(n)i_D0M_Sig_CB1(D0_Mass, BDT%(n)i_D0M_Sig_CB_Mean[1850,1750,1900], BDT%(n)i_D0M_Sig_CB1_Sigma[10,1,30], BDT_D0M_Sig_CB1_alphaleft, BDT%(n)i_D0M_Sig_CB1_n[2,0,10])"%({"n":n})) w.factory("RooCBShape:BDT%(n)i_D0M_Sig_CB2(D0_Mass, BDT%(n)i_D0M_Sig_CB_Mean, BDT%(n)i_D0M_Sig_CB2_Sigma[3,1,30], BDT_D0M_Sig_CB2_alpharight, BDT%(n)i_D0M_Sig_CB2_n[5,0,50])"%({"n":n})) w.factory("SUM::BDT%(n)i_D0M_Sig(BDT%(n)i_D0M_Sig_CB1_Frac[0.8,0,1]*BDT%(n)i_D0M_Sig_CB1,BDT%(n)i_D0M_Sig_CB2)"%({"n":n})) # Del_Mass signal w.factory("{BDT%(n)i_DelM_Sig_Gaus1_Frac[0.75,0,1]}"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_Sig_Gaus1(Del_Mass,BDT%(n)i_DelM_Sig_Gaus_Mean[145.5,143,148],BDT%(n)i_DelM_Sig_Gaus_Sigma1[1,0,5] )"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_Sig_Gaus2(Del_Mass,BDT%(n)i_DelM_Sig_Gaus_Mean,BDT%(n)i_DelM_Sig_Gaus_Sigma2[.1,0,2] )"%({"n":n})) #w.factory("{BDT%(n)i_DelM_Sig_Gaus3_Frac[0.05,0,0.1],BDT%(n)i_DelM_Sig_Gaus_Mean_2[148,143,152],BDT%(n)i_DelM_Sig_Gaus_Sigma3[10,0,20]}"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_Sig_Gaus3(Del_Mass,BDT%(n)i_DelM_Sig_Gaus_Mean_3[148,143,152],BDT%(n)i_DelM_Sig_Gaus_Sigma3[10,0,20] )"%({"n":n})) w.factory("SUM::BDT%(n)i_DelM_Sig(BDT%(n)i_DelM_Sig_Gaus3_Frac[0.05,0,0.1]*BDT%(n)i_DelM_Sig_Gaus3,BDT%(n)i_DelM_Sig_Gaus2_Frac[0.2,0,1]*BDT%(n)i_DelM_Sig_Gaus2,BDT%(n)i_DelM_Sig_Gaus1)"%({"n":n})) #w.factory("SUM::BDT%(n)i_DelM_Sig(BDT%(n)i_DelM_Sig_Gaus2_Frac[0.2,0,1]*BDT%(n)i_DelM_Sig_Gaus2,BDT%(n)i_DelM_Sig_Gaus1)"%({"n":n})) w.factory("PROD::BDT%(n)i_Sig(BDT%(n)i_DelM_Sig,BDT%(n)i_D0M_Sig)"%({"n":n})) w.factory("PROD::BDT%(n)i_Comb_Blind(BDT_DelM_Bkg,BDT_D0M_Bkg_Blind)"%({"n":n})) w.factory("PROD::BDT%(n)i_Comb(BDT_DelM_Bkg,BDT_D0M_Bkg)"%({"n":n})) w.factory("{BDT1_PiPi_Eff[0.5,0,1],BDT2_PiPi_Eff[0.3,0,1]}") w.factory("{BDT_D0M_PiPi_CB2_alpharight[-0.5,-5,0],BDT_D0M_PiPi_CB1_alphaleft[0.8,0,3]}") for n in (1,2,3): if n is not 3: w.factory("RooFormulaVar::BDT%(n)i_N_PiPi('N_PiPi*BDT%(n)i_PiPi_Eff',{N_PiPi,BDT%(n)i_PiPi_Eff})"%({"n":n})) else: w.factory("RooFormulaVar::BDT%(n)i_N_PiPi('N_PiPi*(1-(BDT1_PiPi_Eff+BDT2_PiPi_Eff))',{N_PiPi,BDT1_PiPi_Eff,BDT2_PiPi_Eff})"%({"n":n})) # D0_Mass PiPi w.factory("{BDT%(n)i_D0M_PiPi_CB2_alpharight[-0.5,-5,0],BDT%(n)i_D0M_PiPi_CB1_alphaleft[0.8,0,3]}"%({"n":n})) w.factory("RooCBShape:BDT%(n)i_D0M_PiPi_CB1(D0_Mass, BDT%(n)i_D0M_PiPi_CB_Mean[1850,1750,1900], BDT%(n)i_D0M_PiPi_CB1_Sigma[10,1,30], BDT_D0M_PiPi_CB1_alphaleft, BDT%(n)i_D0M_PiPi_CB1_n[2,0,10])"%({"n":n})) w.factory("RooCBShape:BDT%(n)i_D0M_PiPi_CB2(D0_Mass, BDT%(n)i_D0M_PiPi_CB_Mean, BDT%(n)i_D0M_PiPi_CB2_Sigma[3,1,30], BDT_D0M_PiPi_CB2_alpharight, BDT%(n)i_D0M_PiPi_CB2_n[5,0,50])"%({"n":n})) w.factory("SUM::BDT%(n)i_D0M_PiPi(BDT%(n)i_D0M_PiPi_CB1_Frac[0.8,0,1]*BDT%(n)i_D0M_PiPi_CB1,BDT%(n)i_D0M_PiPi_CB2)"%({"n":n})) # Del_Mass signal w.factory("{BDT%(n)i_DelM_PiPi_Gaus1_Frac[0.75,0,1]}"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_PiPi_Gaus1(Del_Mass,BDT%(n)i_DelM_PiPi_Gaus_Mean[145.5,143,148],BDT%(n)i_DelM_PiPi_Gaus_Sigma1[1,0,5] )"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_PiPi_Gaus2(Del_Mass,BDT%(n)i_DelM_PiPi_Gaus_Mean_2[145.5,143,148],BDT%(n)i_DelM_PiPi_Gaus_Sigma2[.1,0,2] )"%({"n":n})) #w.factory("{BDT%(n)i_DelM_PiPi_Gaus3_Frac[0.05,0,0.1],BDT%(n)i_DelM_PiPi_Gaus_Mean_2[148,143,152],BDT%(n)i_DelM_PiPi_Gaus_Sigma3[10,0,20]}"%({"n":n})) w.factory("RooGaussian::BDT%(n)i_DelM_PiPi_Gaus3(Del_Mass,BDT%(n)i_DelM_PiPi_Gaus_Mean_3[148,143,152],BDT%(n)i_DelM_PiPi_Gaus_Sigma3[10,0,20] )"%({"n":n})) w.factory("SUM::BDT%(n)i_DelM_PiPi(BDT%(n)i_DelM_PiPi_Gaus3_Frac[0.05,0,0.1]*BDT%(n)i_DelM_PiPi_Gaus3,BDT%(n)i_DelM_PiPi_Gaus2_Frac[0.2,0,1]*BDT%(n)i_DelM_PiPi_Gaus2,BDT%(n)i_DelM_PiPi_Gaus1)"%({"n":n})) #w.factory("SUM::BDT%(n)i_DelM_Sig(BDT%(n)i_DelM_PiPi_Gaus2_Frac[0.2,0,1]*BDT%(n)i_DelM_PiPi_Gaus2,BDT%(n)i_DelM_PiPi_Gaus1)"%({"n":n})) w.factory("PROD::BDT%(n)i_PiPi(BDT%(n)i_DelM_PiPi,BDT%(n)i_D0M_PiPi)"%({"n":n})) #w.factory("SUM::BDT%(n)i_Final_PDF_Blind(BDT%(n)i_N_Sig*BDT%(n)i_Sig,BDT%(n)i_N_Comb[1000,0,10000]*BDT%(n)i_Comb_Blind)"%({"n":n})) #w.factory("SUM::BDT%(n)i_Final_PDF(BDT%(n)i_N_Sig*BDT%(n)i_Sig,BDT%(n)i_N_Comb*BDT%(n)i_Comb)"%({"n":n})) w.factory("SUM::BDT%(n)i_Final_PDF_Blind(BDT%(n)i_N_Sig*BDT%(n)i_Sig,BDT%(n)i_N_Comb[1000,0,10000]*BDT%(n)i_Comb_Blind,BDT%(n)i_N_PiPi*BDT%(n)i_PiPi)"%({"n":n})) w.factory("SUM::BDT%(n)i_Final_PDF(BDT%(n)i_N_Sig*BDT%(n)i_Sig,BDT%(n)i_N_Comb*BDT%(n)i_Comb,BDT%(n)i_N_PiPi*BDT%(n)i_PiPi)"%({"n":n})) w.factory("PROD::BDT%(n)i_Final_PDF_Constrained(BDT%(n)i_Final_PDF,Norm_Constraint)"%({"n":n})) #w.obj('Norm_D0M_Sig_Gaus1_Frac').setMin(0.0) ; w.obj('Norm_D0M_Sig_Gaus1_Frac').setMax(1.0) #w.obj('Norm_D0M_Sig_Gaus1_Frac').setVal(0.429624062534) ; w.obj('Norm_D0M_Sig_Gaus1_Frac').setError(0.0289511133792) #w.obj('Norm_D0M_Sig_Gaus1_Frac').setConstant(False) #w.obj('Norm_D0M_Sig_Gaus_Mean').setMin(1850.0) ; w.obj('Norm_D0M_Sig_Gaus_Mean').setMax(1880.0) #w.obj('Norm_D0M_Sig_Gaus_Mean').setVal(1867.01515277) ; w.obj('Norm_D0M_Sig_Gaus_Mean').setError(0.0296569841856) #w.obj('Norm_D0M_Sig_Gaus_Mean').setConstant(False) #w.obj('Norm_D0M_Sig_Gaus1_Sigma').setMin(0.0) ; w.obj('Norm_D0M_Sig_Gaus1_Sigma').setMax(10.0) #w.obj('Norm_D0M_Sig_Gaus1_Sigma').setVal(6.92118344347) ; w.obj('Norm_D0M_Sig_Gaus1_Sigma').setError(0.117795059995) #w.obj('Norm_D0M_Sig_Gaus1_Sigma').setConstant(False) #w.obj('Norm_D0M_Sig_Gaus2_Sigma').setMin(5.0) ; w.obj('Norm_D0M_Sig_Gaus2_Sigma').setMax(20.0) #w.obj('Norm_D0M_Sig_Gaus2_Sigma').setVal(10.3140938882) ; w.obj('Norm_D0M_Sig_Gaus2_Sigma').setError(0.117955520203) #w.obj('Norm_D0M_Sig_Gaus2_Sigma').setConstant(False) #w.obj('Norm_DelM_Bkg_a').setMin(-100.0) ; w.obj('Norm_DelM_Bkg_a').setMax(-1.0) #w.obj('Norm_DelM_Bkg_a').setVal(-16.1932460031) ; w.obj('Norm_DelM_Bkg_a').setError(0.43302849663) #w.obj('Norm_DelM_Bkg_a').setConstant(False) #w.obj('Norm_DelM_Bkg_b').setMin(-0.5) ; w.obj('Norm_DelM_Bkg_b').setMax(2.0) #w.obj('Norm_DelM_Bkg_b').setVal(0.178920942238) ; w.obj('Norm_DelM_Bkg_b').setError(0.0376477247211) #w.obj('Norm_DelM_Bkg_b').setConstant(False) #w.obj('Norm_DelM_Bkg_c').setMin(7.0) ; w.obj('Norm_DelM_Bkg_c').setMax(350.0) #w.obj('Norm_DelM_Bkg_c').setVal(36.1602832374) ; w.obj('Norm_DelM_Bkg_c').setError(5.19925002062) #w.obj('Norm_DelM_Bkg_c').setConstant(False) #w.obj('Norm_DelM_Bkg_m0').setMin(137.5) ; w.obj('Norm_DelM_Bkg_m0').setMax(140.5) #w.obj('Norm_DelM_Bkg_m0').setVal(139.316358242) ; w.obj('Norm_DelM_Bkg_m0').setError(5.10021351516e-05) #w.obj('Norm_DelM_Bkg_m0').setConstant(False) #w.obj('Norm_DelM_Sig_Gaus1_Frac').setMin(0.0) ; w.obj('Norm_DelM_Sig_Gaus1_Frac').setMax(1.) #w.obj('Norm_DelM_Sig_Gaus1_Frac').setVal(0.279248861884) ; w.obj('Norm_DelM_Sig_Gaus1_Frac').setError(0.0191547718614) #w.obj('Norm_DelM_Sig_Gaus1_Frac').setConstant(False) #w.obj('Norm_DelM_Sig_Gaus_Mean').setMin(145.0) ; w.obj('Norm_DelM_Sig_Gaus_Mean').setMax(146.0) #w.obj('Norm_DelM_Sig_Gaus_Mean').setVal(145.448069656) ; w.obj('Norm_DelM_Sig_Gaus_Mean').setError(0.00294967951486) #w.obj('Norm_DelM_Sig_Gaus_Mean').setConstant(False) #w.obj('Norm_DelM_Sig_Gaus1_Sigma').setMin(0.0) ; w.obj('Norm_DelM_Sig_Gaus1_Sigma').setMax(1.0) #w.obj('Norm_DelM_Sig_Gaus1_Sigma').setVal(0.429900766218) ; w.obj('Norm_DelM_Sig_Gaus1_Sigma').setError(0.0119155696871) #w.obj('Norm_DelM_Sig_Gaus1_Sigma').setConstant(False) #w.obj('Norm_DelM_Sig_Gaus2_Sigma').setMin(0.1) ; w.obj('Norm_DelM_Sig_Gaus2_Sigma').setMax(2.0) #w.obj('Norm_DelM_Sig_Gaus2_Sigma').setVal(0.827483577936) ; w.obj('Norm_DelM_Sig_Gaus2_Sigma').setError(0.00898522299303) #w.obj('Norm_DelM_Sig_Gaus2_Sigma').setConstant(False) if config['mode'] == 'mc': w.factory("SIMUL::Final_PDF(DataSet,BDT1=BDT1_Sig,BDT2=BDT2_Sig,BDT3=BDT3_Sig)") #w.obj("Final_PDF").Print("v") #w.obj("BDT1_Sig").Print("v") elif config['mode'] == 'mcpipi': w.factory("SIMUL::Final_PDF(DataSet,BDT1=BDT1_PiPi,BDT2=BDT2_PiPi,BDT3=BDT3_PiPi)") elif config['mode'] == 'datapretoy': w.factory("SIMUL::Final_PDF(DataSet,BDT1=BDT1_Comb_Blind,BDT2=BDT2_Comb_Blind,BDT3=BDT3_Comb_Blind)") elif config['mode'] == 'toy': w.factory("SIMUL::Final_PDF(DataSet,Norm=Norm_Final_PDF,BDT1=BDT1_Final_PDF,BDT2=BDT2_Final_PDF,BDT3=BDT3_Final_PDF)") w.factory("SIMUL::Final_PDF_Background(DataSet,Norm=Norm_Final_PDF,BDT1=BDT1_Comb,BDT2=BDT2_Comb,BDT3=BDT3_Comb)") w.factory("SIMUL::Final_PDF_Constrained(DataSet,BDT1=BDT1_Final_PDF_Constrained,BDT2=BDT2_Final_PDF_Constrained,BDT3=BDT3_Final_PDF_Constrained)") elif config['mode'] == 'mcnorm': w.factory("SIMUL::Final_PDF(DataSet,Norm=Norm_Sig)") elif config['mode'] == 'norm': #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId[1300,100,3000]*Norm_MisId,Norm_N_MisId_Prompt[500,10,1000]*Norm_MisId_Prompt)") #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId[1300,100,3000]*Norm_MisId)") #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId_Prompt[500,10,1000]*Norm_MisId_Prompt)") #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisRecod*Norm_MisRecod)") w.factory("SUM::Norm_Final_PDF(Norm_N_Sig*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb)") w.factory("SIMUL::Final_PDF(DataSet,Norm=Norm_Final_PDF)") elif config['mode'] == 'data': #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId[1300,100,3000]*Norm_MisId,Norm_N_MisId_Prompt[500,10,1000]*Norm_MisId_Prompt)") #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId[1300,100,3000]*Norm_MisId)") #w.factory("SUM::Norm_Final_PDF(Norm_N_Sig[65000,20000,110000]*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb,Norm_N_MisId_Prompt[500,10,1000]*Norm_MisId_Prompt)") w.factory("SUM::Norm_Final_PDF(Norm_N_Sig*Norm_Sig,Norm_N_Prompt[35000,20000,60000]*Norm_Prompt,Norm_N_Comb[67000,1000,90000]*Norm_Comb)") w.factory("SIMUL::Final_PDF(DataSet,Norm=Norm_Final_PDF,BDT1=BDT1_Final_PDF,BDT2=BDT2_Final_PDF,BDT3=BDT3_Final_PDF)") w.factory("SIMUL::Final_PDF_Background(DataSet,Norm=Norm_Final_PDF,BDT1=BDT1_Comb,BDT2=BDT2_Comb,BDT3=BDT3_Comb)") w.factory("SIMUL::Final_PDF_Constrained(DataSet,BDT1=BDT1_Final_PDF_Constrained,BDT2=BDT2_Final_PDF_Constrained,BDT3=BDT3_Final_PDF_Constrained)") w.obj('Norm_N_Comb').setMin(2000.0*config["normScale"]) ; w.obj('Norm_N_Comb').setMax(15000.0*config["normScale"]) w.obj('Norm_N_Comb').setVal(7850.56516616*config["normScale"]) ; w.obj('Norm_N_Comb').setError(177.821454726/sqrt(config["normScale"])) w.obj('Norm_N_MisRecod').setMin(100.0*config["normScale"]) ; w.obj('Norm_N_MisRecod').setMax(40000.0*config["normScale"]) w.obj('Norm_N_MisRecod').setVal(20316.944222*config["normScale"]) ; w.obj('Norm_N_MisRecod').setError(248.324102117/sqrt(config["normScale"])) w.obj('Norm_N_Prompt').setMin(6000.0*config["normScale"]) ; w.obj('Norm_N_Prompt').setMax(60000.0*config["normScale"]) w.obj('Norm_N_Prompt').setVal(29326.825063*config["normScale"]) ; w.obj('Norm_N_Prompt').setError(247.656992623/sqrt(config["normScale"])) w.obj('Norm_N_Sig').setMin(2000.0*config["normScale"]) ; w.obj('Norm_N_Sig').setMax(270000.0*config["normScale"]) w.obj('Norm_N_Sig').setVal(135370.*config["normScale"]) ; w.obj('Norm_N_Sig').setError(430./sqrt(config["normScale"])) if mode_later_than('mcnorm',config['mode']): # nll analyse, nlls up to 1610.0 on Thu Jul 31 15:14:35 2014 run on fitResult.norm_kpi_2011_6.0.0.4.root # # WARNING derivitive_ratio bottom is zero 169 689.330300 696.763943 696.763943 # INFO extrapolate lower edge [False, -0.2368609160806532, 1610.0] # INFO extrapolate upper edge [False, 0.300022797868122, 1610.0] w.obj('Norm_D0M_Bkg_Exp_c').setMin(-0.236860916081) ; w.obj('Norm_D0M_Bkg_Exp_c').setMax(0.300022797868) ; w.obj('Norm_D0M_Bkg_Exp_c').setVal(-0.0221074305011) ; w.obj('Norm_D0M_Bkg_Exp_c').setError(0.00127007751403) # WARNING derivitive_ratio bottom is zero 169 5199.217924 5509.102918 5509.102918 w.obj('Norm_D0M_Sig_Gaus1_Sigma').setMin(5.8) ; w.obj('Norm_D0M_Sig_Gaus1_Sigma').setMax(8.6) ; w.obj('Norm_D0M_Sig_Gaus1_Sigma').setVal(7.2) ; w.obj('Norm_D0M_Sig_Gaus1_Sigma').setError(0.0305815254416) # WARNING derivitive_ratio bottom is zero 119 62.077791 62.077791 62.077791 # WARNING Dont want to expand max range 99.112383 too far # INFO extrapolate upper edge [False, 10.5, 1610.0] # WARNING upper edge 10.500000 hits limit 5.000000 w.obj('Norm_D0M_Sig_Gaus1_alpha').setMin(1.14) ; w.obj('Norm_D0M_Sig_Gaus1_alpha').setMax(5.0) ; w.obj('Norm_D0M_Sig_Gaus1_alpha').setVal(2.298) ; w.obj('Norm_D0M_Sig_Gaus1_alpha').setError(0.0393012987558) # WARNING Dont want to expand max range 899.409174 too far # INFO extrapolate upper edge [False, 35.0, 1610.0] # WARNING upper edge 35.000000 hits limit 20.000000 w.obj('Norm_D0M_Sig_Gaus1_n').setMin(0.3375) ; w.obj('Norm_D0M_Sig_Gaus1_n').setMax(20.0) ; w.obj('Norm_D0M_Sig_Gaus1_n').setVal(2.30375) ; w.obj('Norm_D0M_Sig_Gaus1_n').setError(0.537418026352) # WARNING derivitive_ratio bottom is zero 127 1374.893616 1418.388895 1418.388895 # INFO extrapolate upper edge [False, 10.856461576572277, 1610.0] w.obj('Norm_D0M_Sig_Gaus2_Sigma_Diff').setMin(1.25) ; w.obj('Norm_D0M_Sig_Gaus2_Sigma_Diff').setMax(10.8564615766) ; w.obj('Norm_D0M_Sig_Gaus2_Sigma_Diff').setVal(5.09258463063) ; w.obj('Norm_D0M_Sig_Gaus2_Sigma_Diff').setError(0.115261989641) # WARNING derivitive_ratio bottom is zero 100 768.841852 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 101 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 102 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 103 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 104 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 105 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 106 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 107 768.841850 768.841850 768.841850 # WARNING derivitive_ratio bottom is zero 108 768.841850 768.841850 768.841850 # INFO extrapolate upper edge [False, 10.11481217459233, 1610.0] # WARNING upper edge 10.114812 hits limit 5.000000 w.obj('Norm_D0M_Sig_Gaus2_alpha').setMin(1.44) ; w.obj('Norm_D0M_Sig_Gaus2_alpha').setMax(5.0) ; w.obj('Norm_D0M_Sig_Gaus2_alpha').setVal(2.152) ; w.obj('Norm_D0M_Sig_Gaus2_alpha').setError(0.0415387821092) # WARNING derivitive_ratio bottom is zero 230 629.750229 630.182190 630.182190 # INFO extrapolate lower edge [False, -0.9760496583225814, 1610.0] # WARNING Dont want to expand max range 50.491612 too far # INFO extrapolate upper edge [False, 35.0, 1610.0] # WARNING lower edge -0.976050 hits limit 0.000000 # WARNING upper edge 35.000000 hits limit 20.000000 w.obj('Norm_D0M_Sig_Gaus2_n').setMin(0.0) ; w.obj('Norm_D0M_Sig_Gaus2_n').setMax(20.0) ; w.obj('Norm_D0M_Sig_Gaus2_n').setVal(1.0) ; w.obj('Norm_D0M_Sig_Gaus2_n').setError(0.0563707589481) # WARNING derivitive_ratio bottom is zero 102 100475.575388 104489.200281 104489.200281 w.obj('Norm_D0M_Sig_Gaus_Mean').setMin(1864.1) ; w.obj('Norm_D0M_Sig_Gaus_Mean').setMax(1868.6) ; w.obj('Norm_D0M_Sig_Gaus_Mean').setVal(1866.35) ; w.obj('Norm_D0M_Sig_Gaus_Mean').setError(0.0282504176865) # WARNING derivitive_ratio bottom is zero 102 950.574510 1090.331482 1090.331482 # INFO extrapolate upper edge [False, 8.675242367234118, 1610.0] w.obj('Norm_DelM_Bkg_a').setMin(-30.7) ; w.obj('Norm_DelM_Bkg_a').setMax(8.67524236723) ; w.obj('Norm_DelM_Bkg_a').setVal(-14.9499030531) ; w.obj('Norm_DelM_Bkg_a').setError(0.352110679985) # WARNING derivitive_ratio bottom is zero 286 2509.484557 2524.607389 2524.607389 # INFO extrapolate lower edge [False, 135.51700895240305, 1610.0] w.obj('Norm_DelM_Bkg_m0').setMin(135.517008952) ; w.obj('Norm_DelM_Bkg_m0').setMax(140.245) ; w.obj('Norm_DelM_Bkg_m0').setVal(139.29940179) ; w.obj('Norm_DelM_Bkg_m0').setError(0.00278162353152) # WARNING derivitive_ratio bottom is zero 168 12637.921551 12941.900194 12941.900194 w.obj('Norm_DelM_Sig_Gaus1_Sigma').setMin(0.275) ; w.obj('Norm_DelM_Sig_Gaus1_Sigma').setMax(0.58) ; w.obj('Norm_DelM_Sig_Gaus1_Sigma').setVal(0.4275) ; w.obj('Norm_DelM_Sig_Gaus1_Sigma').setError(0.00623690681335) # WARNING derivitive_ratio bottom is zero 140 7646.478871 7794.222379 7794.222379 w.obj('Norm_DelM_Sig_Gaus2_Sigma_Diff').setMin(0.145) ; w.obj('Norm_DelM_Sig_Gaus2_Sigma_Diff').setMax(0.56) ; w.obj('Norm_DelM_Sig_Gaus2_Sigma_Diff').setVal(0.311) ; w.obj('Norm_DelM_Sig_Gaus2_Sigma_Diff').setError(0.00961908230633) # WARNING derivitive_ratio bottom is zero 135 7889.258317 7968.149060 7968.149060 w.obj('Norm_DelM_Sig_Gaus3_Mean').setMin(144.385) ; w.obj('Norm_DelM_Sig_Gaus3_Mean').setMax(147.52) ; w.obj('Norm_DelM_Sig_Gaus3_Mean').setVal(145.9525) ; w.obj('Norm_DelM_Sig_Gaus3_Mean').setError(0.0297743321414) # WARNING derivitive_ratio bottom is zero 127 1441.937761 1456.115731 1456.115731 # INFO extrapolate lower edge [False, -1.562458158266192, 1610.0] # INFO extrapolate upper edge [False, 3.2886360831918586, 1610.0] # WARNING lower edge -1.562458 hits limit 0.000000 w.obj('Norm_DelM_Sig_Gaus3_Sigma_Diff').setMin(0.0) ; w.obj('Norm_DelM_Sig_Gaus3_Sigma_Diff').setMax(3.28863608319) ; w.obj('Norm_DelM_Sig_Gaus3_Sigma_Diff').setVal(0.657727216638) ; w.obj('Norm_DelM_Sig_Gaus3_Sigma_Diff').setError(0.037812360311) # WARNING derivitive_ratio bottom is zero 102 17487.965272 18067.587218 18067.587218 w.obj('Norm_DelM_Sig_Gaus_Mean').setMin(145.25) ; w.obj('Norm_DelM_Sig_Gaus_Mean').setMax(145.6) ; w.obj('Norm_DelM_Sig_Gaus_Mean').setVal(145.425) ; w.obj('Norm_DelM_Sig_Gaus_Mean').setError(0.00389207378424) # WARNING derivitive_ratio bottom is zero 171 1440.310455 1466.512994 1466.512994 # INFO extrapolate lower edge [False, -1161.7298062300902, 1610.0] # INFO extrapolate upper edge [False, 6502.909990291508, 1610.0] # WARNING lower edge -1161.729806 hits limit 0.000000 w.obj('Norm_N_Comb').setMin(0.0*config["normScale"]) ; w.obj('Norm_N_Comb').setMax(6502.90999029*config["normScale"]) ; w.obj('Norm_N_Comb').setVal(1300.58199806*config["normScale"]) ; w.obj('Norm_N_Comb').setError(69.7188799676/sqrt(config["normScale"])) # WARNING derivitive_ratio bottom is zero 142 1629.344232 1679.974917 1679.974917 # INFO extrapolate lower edge [False, 10931.649121116747, 1610.0] w.obj('Norm_N_Prompt').setMin(10931.6491211*config["normScale"]) ; w.obj('Norm_N_Prompt').setMax(30995.7616494*config["normScale"]) ; w.obj('Norm_N_Prompt').setVal(18957.2941324*config["normScale"]) ; w.obj('Norm_N_Prompt').setError(247.513270145/sqrt(config["normScale"])) # WARNING derivitive_ratio bottom is zero 148 1585.358526 1642.672043 1642.672043 # INFO extrapolate lower edge [False, 64907.007351854576, 1610.0] w.obj('Norm_N_Sig').setMin(64907.0073519*config["normScale"]) ; w.obj('Norm_N_Sig').setMax(99148.5248*config["normScale"]) ; w.obj('Norm_N_Sig').setVal(82027.7660759*config["normScale"]) ; w.obj('Norm_N_Sig').setError(349.170253164/sqrt(config["normScale"])) #w.obj('Norm_DelM_Bkg_b').setVal(0) #w.obj('Norm_DelM_Bkg_b').setConstant(True) w.obj('Norm_D0M_Sig_Gaus1_Frac').setVal(0.7) #w.obj('Norm_D0M_Sig_Gaus3_Frac').setVal(0.35) w.obj('Norm_DelM_Sig_Gaus1_Frac').setVal(0.25) w.obj('Norm_DelM_Sig_Gaus3_Frac').setVal(0.15) w.obj('Norm_D0M_Sig_Gaus1_Frac').setConstant(True) #w.obj('Norm_D0M_Sig_Gaus3_Frac').setConstant(True) w.obj('Norm_DelM_Sig_Gaus1_Frac').setConstant(True) w.obj('Norm_DelM_Sig_Gaus3_Frac').setConstant(True) config['postHook'](w) return w
label='ToyMCcheck_{0}'.format(var.GetName()), fitDir=fitDir, figDir=figDir, ) #space.loadSnapshot(snapshot) return None def recTime(mesg): global currenttime rectime=currenttime currenttime=time.time() txtRecFile.write('{0} in {1} minutes\n'.format(mesg,int((currenttime-rectime)/60))) # def functions end }}} recTime('def funcs') space=RooWorkspace('space',False) # new parameters space.factory('lbl0Mass[5.4,5.9]') space.factory('tktkMass[0.5,2.0]') ########## load workspace #################### workspaceFile1=TFile.Open('store_root/workspace_0thStep_LbL0Shape.root') space1st=workspaceFile1.Get('space') space1st.SetName('space1st') load2016Data=True if load2016Data: toyCheck=False
#space.loadSnapshot(snapshot) return None def recTime(mesg): global currenttime rectime = currenttime currenttime = time.time() txtRecFile.write('{0} in {1} minutes\n'.format( mesg, int((currenttime - rectime) / 60))) # def functions end }}} recTime('def funcs') space = RooWorkspace('space', False) # new parameters space.factory('lbl0Mass[5.4,5.9]') space.factory('tktkMass[0.5,2.0]') space.factory('lbl0Pt[0.,200.]') ########## load workspace #################### workspaceFile1 = TFile.Open('store_root/workspace_0thStep_LbL0Shape.root') space1st = workspaceFile1.Get('space') space1st.SetName('space1st') spaceExt = space1st load2016Data = True if load2016Data: toyCheck = False
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]) # start building the fit ws = RooWorkspace('ws_%s' % config['Context']) 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')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qf, qt, time] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context']], 'FIT' in config['Context']) # float for fitting if 'GEN' in config['Context']: acc = accnorm # use normalised acceptance for generation # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) # build the time pdf pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[mistag]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
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')) qt.defineType( 'B+', +1) qt.defineType('Untagged', 0) qt.defineType( 'B-', -1) # now other settings Gamma = WS(ws, RooRealVar( 'Gamma', 'Gamma', 0.661)) # ps^-1
class MjjFit: def __init__(self, mass_range=[0., 2000.]): self.data_histogram_ = None self.data_roohistogram_ = None self.luminosity_ = 0. self.collision_energy_ = 8000. self.signal_histograms_ = {} self.signal_roohistograms_ = {} self.signal_names_ = [] # Fit storage self.simple_fit_ = None self.mjj_ = RooRealVar('mjj','mjj',float(mass_range[0]),float(mass_range[1])) self.workspace_ = None def add_data(self, data_histogram): print "[MjFit.add_data] INFO : Adding data histogram" # Add a data histogram self.data_histogram_ = data_histogram.Clone() self.data_histogram_.SetDirectory(0) self.data_roohistogram_ = RooDataHist('data_roohistogram','data_roohistogram',RooArgList(self.mjj_),self.data_histogram_) self.data_roohistogram_.Print() def add_signal(self, signal_name, signal_histogram): print "[MjjFit.add_signal] INFO : Adding signal histogram " + signal_name # Add a signal histogram. # Scale to sigma=1 (in whatever units the data luminosity is given in), so the 'r' parameter corresponds to the limit on the cross section. if self.luminosity_ == 0: print "[MjjFit.add_signal] ERROR : Please set luminosity first (MjjFit.set_luminosity(###))." sys.exit(1) self.signal_names_.append(signal_name) self.signal_histograms_[signal_name] = signal_histogram.Clone() self.signal_histograms_[signal_name].SetDirectory(0) self.signal_histograms_[signal_name].Scale(1. * self.luminosity_ / self.signal_histograms_[signal_name].Integral()) self.signal_roohistograms_[signal_name] = RooDataHist(signal_histogram.GetName() + "_rdh", signal_histogram.GetName() + "_rdh", RooArgList(self.mjj_), signal_histograms[signal_name]) self.signal_roohistograms_[signal_name].Print() def simple_fit_B(self, fit_range=None): # Run a simple ROOT fit (B only) # - No S+B equivalent. This is done with RooFit. if fit_range: fit_min = fit_range[0] fit_max = fit_range[1] else: fit_min = data_histogram.GetXaxis().GetXmin() fit_max = data_histogram.GetXaxis().GetXmax() fit = TF1(data_histogram.GetName() + "_fit_B", BackgroundFit, fit_min, fit_max, 4) fit.SetParameter(0, 2.e-4) fit.SetParameter(1, 3) fit.SetParameter(2, 10) fit.SetParameter(3, 1) fit.SetParLimits(0, 1.e-6, 1.e2) fit.SetParLimits(1, -25., 25.) fit.SetParLimits(2, -25., 25.) fit.SetParLimits(3, -5., 5.) data_histogram.Fit(fit, "ER0I") fit_ratio = self.make_fit_pull_histogram(data_histogram, fit) print "Fit chi2/ndf = " + str(fit.GetChisquare()) + " / " + str(fit.GetNDF()) + " = " + str(fit.GetChisquare() / fit.GetNDF()) self.simple_fit_ = {"fit":fit, "fit_ratio":fit_ratio} return self.simple_fit_ def make_fit_pull_histogram(self, hist, fit): #print "Fit xmin = " + str(fit.GetXmin()) hist_ratio = hist.Clone() hist_ratio.SetName(hist.GetName() + "_fit_ratio") for bin in xrange(1, hist_ratio.GetNbinsX() + 1): xmin = hist_ratio.GetXaxis().GetBinLowEdge(bin) xmax = hist_ratio.GetXaxis().GetBinUpEdge(bin) if xmax < fit.GetXmin() or xmin > fit.GetXmax(): hist_ratio.SetBinContent(bin, 0.) hist_ratio.SetBinError(bin, 0.) continue fit_integral = fit.Integral(xmin, xmax) if hist.GetBinError(bin) > 0: hist_ratio.SetBinContent(bin, (hist.GetBinContent(bin) * hist.GetBinWidth(bin) - fit_integral) / (hist.GetBinError(bin) * hist.GetBinWidth(bin))) hist_ratio.SetBinError(bin, 0.) else: hist_ratio.SetBinContent(bin, 0.) hist_ratio.SetBinError(bin, 0.) return hist_ratio def fit(self, save_to, signal_name=None, fix_p3=False, fit_range=[300., 1200.], fit_strategy=1): # Run a RooFit fit # Create background PDF p1 = RooRealVar('p1','p1',args.p1,0.,100.) p2 = RooRealVar('p2','p2',args.p2,0.,60.) p3 = RooRealVar('p3','p3',args.p3,-10.,10.) if args.fix_p3: p3.setConstant() background_pdf = RooGenericPdf('background_pdf','(pow(1-@0/%.1f,@1)/pow(@0/%.1f,@2+@3*log(@0/%.1f)))'%(self.collision_energy,self.collision_energy,self.collision_energy),RooArgList(self.mjj_,p1,p2,p3)) background_pdf.Print() data_integral = data_histogram.Integral(data_histogram.GetXaxis().FindBin(float(fit_range[0])),data_histogram.GetXaxis().FindBin(float(fit_range[1]))) background_norm = RooRealVar('background_norm','background_norm',data_integral,0.,1e+08) background_norm.Print() # Create signal PDF and fit model if signal_name: signal_pdf = RooHistPdf('signal_pdf', 'signal_pdf', RooArgSet(self.mjj_), self.signal_roohistograms_[signal_name]) signal_pdf.Print() signal_norm = RooRealVar('signal_norm','signal_norm',0,-1e+05,1e+05) signal_norm.Print() model = RooAddPdf("model","s+b",RooArgList(background_pdf,signal_pdf),RooArgList(background_norm,signal_norm)) else: model = RooAddPdf("model","b",RooArgList(background_pdf),RooArgList(background_norm)) # Run fit res = model.fitTo(data_, RooFit.Save(kTRUE), RooFit.Strategy(fit_strategy)) # Save to workspace self.workspace_ = RooWorkspace('w','workspace') #getattr(w,'import')(background,ROOT.RooCmdArg()) getattr(self.workspace_,'import')(background_pdf,RooFit.Rename("background")) getattr(self.workspace_,'import')(background_norm,ROOT.RooCmdArg()) getattr(self.workspace_,'import')(self.data_roohistogram_,RooFit.Rename("data_obs")) getattr(self.workspace_, 'import')(model, RooFit.Rename("model")) if signal_name: getattr(self.workspace_,'import')(signal_roohistogram,RooFit.Rename("signal")) getattr(self.workspace_,'import')(signal_pdf,RooFit.Rename("signal_pdf")) getattr(self.workspace_,'import')(signal_norm,ROOT.RooCmdArg()) self.workspace_.Print() self.workspace_.writeToFile(save_to) if signal_name: roofit_results[signal_name] = save_to else: roofit_results["background"] = save_to # fitted_signal_shapes = list of fitted S(+B) shapes to plot. # expected_signal_shapes = list of S shapes to plot, scaled to cross sections taken from configuration file def plot(self, save_tag, fitted_signal_shapes=None, expected_signal_shapes=None, log=False, x_range=None): c = TCanvas("c_" + save_tag, "c_" + save_tag, 800, 1600) l = TLegend(0.55, 0.6, 0.88, 0.88) l.SetFillColor(0) l.SetBorderSize(0) top = TPad("top", "top", 0., 0.5, 1., 1.) top.SetBottomMargin(0.03) top.Draw() if log: top.SetLogy() c.cd() bottom = TPad("bottom", "bottom", 0., 0., 1., 0.5) bottom.SetTopMargin(0.02) bottom.SetBottomMargin(0.2) bottom.Draw() ROOT.SetOwnership(c, False) ROOT.SetOwnership(top, False) ROOT.SetOwnership(bottom, False) top.cd() # Frame from background fit if not roofit_results.has_key("background"): print "[MjjFit.plot] ERROR : Please run background-only fit before plotting (e.g. MjjFit.plot(\"bkgd_file.root\"))" f_background = TFile(roofit_results["background"], "READ") w_background = f_background.Get("w") data_rdh = w_background.data("data_obs") if x_range: x_min = x_range[0] x_max = x_range[1] else: x_min = self.mjj_.GetMin() x_max = self.mjj_.GetMax() frame_top = self.mjj_.frame(x_min, x_max) frame_top.GetYaxis().SetTitle("Events / " + str(int(data_histogram.GetXaxis().GetBinWidth(1))) + " GeV") frame_top.GetXaxis().SetTitleSize(0) frame_top.GetXaxis().SetLabelSize(0) #if log: # frame_top.SetMaximum(y_max * 10.) # frame_top.SetMinimum(y_min / 100.) #else: # frame_top.SetMaximum(y_max * 1.3) # frame_top.SetMinimum(0.) frame_top.Draw() data_rdh.plotOn(frame_top, RooFit.Name("Data")) l.AddEntry(frame_top.findObject("Data"), "Data", "pl") background_pdf = w_background.pdf("background") background_pdf.plotOn(frame_top, RooFit.Name("Background Fit"), RooFit.LineColor(seaborn.GetColorRoot("default", 0)), RooFit.LineStyle(1), RooFit.LineWidth(2)) style_counter = 1 if fitted_signal_shapes: for signal_name in fitted_signal_shapes: # Load from workspace if not roofit_results.has_key(signal_name): print "[MjjFit.plot] ERROR : Signal name " + signal_name + " does not exist in roofit_results. Did you run the fit first?" sys.exit(1) f_in = TFile(roofit_results[signal_name], "READ") w = f_in.Get("workspace") fit_pdf = w.pdf("model") fit_pdf_name = "Fit (" + signal_name + ")" fit_pdf.SetName(fit_pdf_name) fit_pdf.plotOn(frame_top, RooFit.Name(fit_pdf_name), RooFit.LineColor(seaborn.GetColorRoot("default", style_counter)), RooFit.LineStyle(1), RooFit.LineWidth(2)) l.AddEntry(frame_top.findObject(signal_name), signal_name, "l") style_counter += 1 f_in.Close() if expected_signal_shapes: for signal_name in expected_signal_shapes: self.signal_roohistograms_[signal_name].plotOn(frame_top, RooFit.Name(signal_name), RooFit.Rescale(cross_section * self.luminosity_ / self.signal_roohistograms_[signal_name].sum()), RooFit.LineColor(seaborn.GetColorRoot("pastel", style_counter)), RooFit.LineStyle(2), RooFit.LineWidth(2)) l.AddEntry(frame_top.findObject(signal_name), signal_name, "l") style_counter += 1 frame_top.Draw() l.Draw() # Pull histogram c.cd() bottom.cd() pull_histogram = frame_top.pullHist("Data", "Background Fit") frame_bottom = self.mjj_.frame(x_min, x_max) pull_histogram.plotOn(frame_bottom, RooFit.Name(fit_pdf_name)) frame_bottom.GetXaxis().SetTitle("m_{jj} [GeV]") frame_bottom.GetYaxis().SetTitle("#frac{Data - Fit}{#sigma(Fit)}") frame_bottom.Draw() c.cd() c.SaveAs("/uscms/home/dryu/Dijets/data/EightTeeEeVeeBee/Results/figures/c_" + save_tag + ".pdf")
alphadArr.append(0.1) alphadArr.append(0.01) alphadArr.append(0.001) nApMass = 50 massApmin = 0.07 massApmax = 0.139 fitfunc = TF1("fitfunc","[0]*exp( ((x-[1])<[3])*(-0.5*(x-[1])^2/[2]^2) + ((x-[1])>=[3])*(-0.5*[3]^2/[2]^2-(x-[1]-[3])/[4]))",-50,50) fitfunc.SetParName(0,"Amplitude") fitfunc.SetParName(1,"Mean") fitfunc.SetParName(2,"Sigma") fitfunc.SetParName(3,"Tail Z") fitfunc.SetParName(4,"Tail length") w = RooWorkspace("w") w.factory("{0}[0,0.1]".format("uncM")) w.factory("uncVZ[-100,100]") w.factory("uncP[0,10]") w.factory("cut[0,1]") w.defineSet("myVars","{0},uncVZ".format("uncM")) events = infile.Get("cut") #eventsrad = radfile.Get("ntuple") eventsprompt = promptfile.Get("cut") dataset = RooDataSet("data","data",events,w.set("myVars"),"") w.factory("Gaussian::vtx_model(uncVZ,mean[-50,50],sigma[0,50])") gauss_pdf = w.pdf("vtx_model") w.factory("EXPR::gaussExp('exp( ((@0-@1)<@3)*(-0.5*(@0-@1)^2/@2^2) + ((@0-@1)>=@3)*(-0.5*@3^2/@2^2-(@0-@1-@3)/@4))',uncVZ,gauss_mean[-5,-20,20],gauss_sigma[5,1,50],exp_breakpoint[10,0,50],exp_length[3,0.5,20])")
hidatafile = 'data/dimuonTree_150mub.root' ppdatafile = 'data/dimuonTree_2011_pp.root' mmin = 7. mmax = 14. cuts = '(muPlusPt > %0.1f) && (muMinusPt > %0.1f) && (abs(upsRapidity)<2.4) && (vProb > 0.05)' \ % (opts.pt, opts.pt) simparamfile = opts.paramfile useKeys = opts.keys ## cuts = '(muPlusPt > 3.5) && (muMinusPt > 3.5) && (abs(upsRapidity)<2.4)' ## simparamfile = 'nom3.5SimFit.txt' ws = RooWorkspace("ws","ws") readData(ws, hidatafile, ppdatafile, cuts, mmin, mmax) mass = ws.var('invariantMass') ppBkgModel = 1 bkgModel = 0 if useKeys: bkgModel = 2 buildPdf(ws, False, ppBkgModel, True) buildPdf(ws, True, bkgModel, True) simPdf = buildSimPdf(ws, ws.cat('dataCat')) #ws.Print()
frame1 = x.frame() roohistoCtl[1].plotOn(frame1) qcd.plotOn(frame1) qcd.plotOn(frame1,RooFit.Components('qcd_gaus1'),RooFit.LineColor(ROOT.kRed),RooFit.LineWidth(2),RooFit.LineStyle(2)) qcd.plotOn(frame1,RooFit.Components('qcd_gaus2'),RooFit.LineColor(ROOT.kGreen+1),RooFit.LineWidth(2),RooFit.LineStyle(2)) frame1.GetXaxis().SetTitle('m_{t} (GeV)') frame1.Draw() gPad.Update() canB.Print(canB.GetName()+".pdf") parsQCD = qcd.getParameters(roohistoCtl[1]) parsQCD.setAttribAll('Constant', True) # ----------------------------------------- w = RooWorkspace('w','workspace') getattr(w,'import')(signal,ROOT.RooCmdArg()) getattr(w,'import')(qcd,ROOT.RooCmdArg()) getattr(w,'import')(x,ROOT.RooCmdArg()) getattr(w,'import')(YieldTT,ROOT.RooCmdArg()) w.Print() w.writeToFile('templates_boosted_workspace.root') #----- keep the GUI alive ------------ if __name__ == '__main__': rep = '' while not rep in ['q','Q']: rep = raw_input('enter "q" to quit: ') if 1 < len(rep): rep = rep[0]
## print "% 5.3g 0.0 " % (100*(xvalues[i]-1.),), ## factor = 100./91.19 ## print "% 8.3g %8.2g " % (params[i][0].getVal() * factor, params[i][0].getError() * factor), ## factor = factor * math.sqrt(2) ## print "% 8.3g %8.2g " % (params[i][1].getVal() * factor, params[i][1].getError() * factor), ## for j in range(2, 4): ## print "% 8.3g %8.2g " % (params[i][j].getVal(), params[i][j].getError(),), ## print nentries = 5000 chains = getChains('v1') mcTree = chains['mc'] test1Tree = chains['test1'] w = RooWorkspace('w') mass = w.factory('mass[60, 120]') trange = (log(mass.getMin()/91.2), log(mass.getMax()/91.2)) t = w.factory('t[%f,%f]' % trange) t.SetTitle('log(mass/91.2)') weight = w.factory('weight[0, 999]') cuts = ['Entry$ < %d' % nentries] mData = dataset.get(tree=mcTree, variable=mass, weight=weight, cuts=cuts, name='mData') m1Data = dataset.get(tree=test1Tree, variable=mass, weight=weight, cuts=cuts, name='m1Data') tData = dataset.get(tree=mcTree, variable=t , weight=weight, cuts=cuts, name='tData')
def buildTimePdf(config, tupleDataSet, tupleDict): from B2DXFitters.WS import WS print 'CONFIGURATION' for k in sorted(config.keys()): print ' %32s: %32s' % (k, config[k]) ws = RooWorkspace('ws_%s' % config['Context']) one = WS(ws, RooConstVar('one', '1', 1.0)) zero = WS(ws, RooConstVar('zero', '0', 0.0)) ###USE FIT CONTEXT """ build time pdf, return pdf and associated data in dictionary """ # start by defining observables time = WS(ws, tupleDataSet.get().find('ct')) #qt = WS(ws, tupleDataSet.get().find('ssDecision')); ''' 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')) qt.defineType('B+', +1) qt.defineType('Untagged', 0) qt.defineType('B-', -1) # now other settings Gamma = WS(ws, RooRealVar('Gamma', 'Gamma', 0.661)) # ps^-1 DGamma = WS(ws, RooRealVar('DGamma', 'DGamma', 0.106)) # ps^-1 Dm = WS(ws, RooRealVar('Dm', 'Dm', 17.719)) # ps^-1 # HACK (1/2): be careful about lower bound on eta, since mistagpdf below # is zero below a certain value - generation in accept/reject would get # stuck if 'GEN' in config['Context'] or 'FIT' in config['Context']: eta = WS( ws, RooRealVar( 'eta', 'eta', 0.35, 0.0 if 'FIT' in config['Context'] else (1. + 1e-5) * max(0.0, config['TrivialMistagParams']['omega0']), 0.5)) mistag = WS(ws, RooRealVar('mistag', 'mistag', 0.35, 0.0, 0.5)) tageff = WS(ws, RooRealVar('tageff', 'tageff', 0.60, 0.0, 1.0)) terrpdf = WS(ws, tupleDataSet.get().find('cterr')) timeerr = WS(ws, RooRealVar('timeerr', 'timeerr', 0.040, 0.001, 0.100)) #MISTAGPDF # fit average mistag # add mistagged #ge rid of untagged events by putting restriction on qf or something when reduceing ds # now build the PDF from B2DXFitters.timepdfutils import buildBDecayTimePdf from B2DXFitters.resmodelutils import getResolutionModel from B2DXFitters.acceptanceutils import buildSplineAcceptance obs = [qf, qt, time] acc, accnorm = buildSplineAcceptance( ws, time, 'Bs2DsPi_accpetance', config['SplineAcceptance']['KnotPositions'], config['SplineAcceptance']['KnotCoefficients'][config['Context'][0:3]], 'FIT' in config['Context']) # float for fitting # get resolution model resmodel, acc = getResolutionModel(ws, config, time, timeerr, acc) mistagpdf = WS( ws, RooArgList(tupleDataSet.get().find('ssMistag'), tupleDataSet.get().find('osMistag'))) #??? ''' if 'GEN' in config['Context']: # build a (mock) mistag distribution mistagpdfparams = {} # start with parameters of mock distribution for sfx in ('omega0', 'omegaavg', 'f'): mistagpdfparams[sfx] = WS(ws, RooRealVar( 'Bs2DsPi_mistagpdf_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx, config['TrivialMistagParams'][sfx])) # build mistag pdf itself mistagpdf = WS(ws, [tupleDataSet.reduce('ssMistag'), tupleDataSet.reduce('osMistag')]); mistagcalibparams = {} # start with parameters of calibration for sfx in ('p0', 'p1', 'etaavg'): mistagcalibparams[sfx] = WS(ws, RooRealVar('Bs2DsPi_mistagcalib_%s' % sfx, 'Bs2DsPi_mistagpdf_%s' % sfx,config['MistagCalibParams'][sfx])); for sfx in ('p0', 'p1'): # float calibration paramters mistagcalibparams[sfx].setConstant(False) mistagcalibparams[sfx].setError(0.1) # build mistag pdf itself omega = WS(ws, MistagCalibration( 'Bs2DsPi_mistagcalib', 'Bs2DsPi_mistagcalib', eta, mistagcalibparams['p0'], mistagcalibparams['p1'], mistagcalibparams['etaavg'])) # build the time pdf if 'GEN' in config['Context']: pdf = buildBDecayTimePdf( config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [ [ omega ] ], [ tageff ], Gamma, DGamma, Dm, C = one, D = zero, Dbar = zero, S = zero, Sbar = zero, timeresmodel = resmodel, acceptance = acc, timeerrpdf, mistagpdf = [mistagpdf], mistagobs = eta) else: pdf = buildBDecayTimePdf( config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [ [ eta ] ], [ tageff ], Gamma, DGamma, Dm, C = one, D = zero, Dbar = zero, S = zero, Sbar = zero, timeresmodel = resmodel, acceptance = acc, timeerrpdf = None) ''' pdf = buildBDecayTimePdf(config, 'Bs2DsPi', ws, time, timeerr, qt, qf, [[eta]], [tageff], Gamma, DGamma, Dm, C=one, D=zero, Dbar=zero, S=zero, Sbar=zero, timeresmodel=resmodel, acceptance=acc, timeerrpdf=terrpdf, mistagpdf=[mistagpdf], mistagobs=eta) return { # return things 'ws': ws, 'pdf': pdf, 'obs': obs }
### make the new workspaces --> loop on the old, create empty new ones iMass = 0 for workspace in list_of_workspace: for gammaVal in GammaOverMass: newfilename = TString(workspace).ReplaceAll(".root", "_NARROW_%.3f.root" % gammaVal) newfilename.ReplaceAll("0.", "_") newfilename.ReplaceAll("_root", ".root") old_file = TFile("%s/%s/%s" % (options.inPath, options.datacardPath, workspace), "READ") old_file.Print() new_file = TFile("%s/%s/%s" % (options.inPath, options.datacardPath, newfilename), "RECREATE") old_workspace = old_file.Get("workspace4limit_") new_workspace = RooWorkspace("workspace4limit_", "workspace4limit_") old_workspace.Print() new_file.cd() ### copy all the pdfs + parameter pdf_workspace = old_workspace.allPdfs() par = pdf_workspace.createIterator() par.Reset() param = par.Next() while param: param.Print() if not TString(par.GetName()).Contains("ggH") and not TString(par.GetName()).Contains("vbfH"): getattr(new_workspace, "import")(param) elif TString(par.GetName()).Contains("ggH"):
RooRealVar(varName, tree1.GetBranch(varName).GetTitle(), tree1.GetMinimum(varName), tree1.GetMaximum(varName)) ] 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);
def getData(workspace, mean1 = 1., sigma1 = 0.01, mean2 = 1., sigma2 = 0.01, nevents = 5000): ## Make a local workspace to use as a factory. w = RooWorkspace('w', 'w') ## Define the PDF's for m, f1 and f2 in m*sqrt(f1*f2) mPdf = w.factory("BreitWigner::mPdf(m[50,130], MZ[91.12], GammaZ[2.5])") f1Pdf = w.factory("Gaussian::f1Pdf(f1[0.5, 2], mean1[%f], sigma1[%f])" % (mean1, sigma1)) f2Pdf = w.factory("Gaussian::f2Pdf(f2[0.5, 2], mean2[%f], sigma2[%f])" % (mean2, sigma2)) ## Import the PDF's in the given workspace. workspace.Import(mPdf, RenameAllVariables("True")) workspace.Import(f1Pdf, RenameAllVariables("True")) workspace.Import(f2Pdf, RenameAllVariables("True")) ## Generate samples of M, F1 and F2 with a 10% margin for boundaries. moreEvents = int(2*nevents) mData = mPdf.generate(RooArgSet(w.var("m")), moreEvents, NumCPU(3)) f1Data = f1Pdf.generate(RooArgSet(w.var("f1")), moreEvents, NumCPU(3)) f2Data = f2Pdf.generate(RooArgSet(w.var("f2")), moreEvents, NumCPU(3)) ## Create the new data with toy reco mass data = RooDataSet('data', 'toy reco Z->ll mass data', RooArgSet(w.factory('mass[40,140]'))) entry = data.get() ## Loop over the generated values and fill the new reco mass data. for i in range(moreEvents): ## Do we have enough entries already? if data.sumEntries() >= nevents: break ## Get the values of the random variables m, f1, f2. m = mData.get(i).first().getVal() f1 = f1Data.get(i).first().getVal() f2 = f2Data.get(i).first().getVal() ## Here comes the formula!! mass = m * sqrt(f1*f2) ## Is the reco mass within its range? if 60. < mass and mass < 120.: ## Add the reco mass to the data entry.first().setVal(mass) data.addFast(entry) ## End of loop over the generated values workspace.Import(data) return data