def GetBayesianInterval(filename="workspace.root", wsname='myWS', interactive=False): # this function loads a workspace and computes # a Bayesian upper limit pInFile = ROOT.TFile(filename, "read") # load workspace pWs = pInFile.Get(wsname) if not pWs: print "workspace ", wsname, " not found" return -1 # printout workspace content pWs.Print() # load and print data from workspace data = pWs.data("data") data.Print() # load and print S+B Model Config pSbHypo = pWs.obj("SbHypo") pSbHypo.Print() # create RooStats Bayesian calculator and set parameters bCalc = RooStats.BayesianCalculator(data, pSbHypo) bCalc.SetName("myBC") bCalc.SetConfidenceLevel(0.95) bCalc.SetLeftSideTailFraction(0.0) #bcalc->SetIntegrationType("ROOFIT") # estimate credible interval # NOTE: unfortunate notation: the UpperLimit() name refers # to the upper boundary of an interval, # NOT to the upper limit on the parameter of interest # (it just happens to be the same for the one-sided # interval starting at 0) pSInt = bCalc.GetInterval() upper_bound = pSInt.UpperLimit() lower_bound = pSInt.LowerLimit() print "one-sided 95%.C.L. bayesian credible interval for xsec: ", "[", lower_bound, ", ", upper_bound, "]" # make posterior PDF plot for POI c1 = ROOT.TCanvas("posterior", "posterior") bCalc.SetScanOfPosterior(100) pPlot = bCalc.GetPosteriorPlot() pPlot.Draw() ROOT.gPad.Update() c1.SaveAs("bayesian_num_posterior.pdf") if interactive: raw_input("\npress <enter> to continue")
def limitBayesian(w=initializeWorkspace(), B=1, dB=0.35, S=1, dS=0.1): w.var("B").setVal(B) w.var("dB").setVal(dB) w.var("S").setVal(S) w.var("dS").setVal(dS) w.var("N").setVal(B) obs = ROOT.RooArgSet(w.var("N")) data = ROOT.RooDataSet("data", "data", obs) data.add(obs) # insert entry rbackup = w.var("r").getMax() nuisances = ROOT.RooArgSet() if dB != 0: nuisances.add(w.var("thetaB")) w.var("thetaB").setConstant(False) else: w.var("thetaB").setConstant(True) if dS != 0: nuisances.add(w.var("thetaS")) w.var("thetaS").setConstant(False) else: w.var("thetaS").setConstant(True) poi = ROOT.RooArgSet(w.var("r")) model = w.pdf({True: "model_s", False: "modelStat_s"}[dS > 0 or dB > 0]) prior = w.pdf("prior") nuisSet = {True: nuisances, False: None}[dS > 0 or dB > 0] bcalc = RooStats.BayesianCalculator(data, model, poi, prior, nuisSet) bcalc.SetLeftSideTailFraction(0) bcalc.SetConfidenceLevel(0.95) interval = bcalc.GetInterval() ret = interval.UpperLimit() while ret > 0.5 * w.var("r").getMax(): #print "Got ",ret,"too close to the upper bound",w.var("r").getMax() if (w.var("r").getMax() > 200): break w.var("r").setMax(w.var("r").getMax() * 2) interval = bcalc.GetInterval() ret = interval.UpperLimit() w.var("r").setMax(rbackup) return ret
def bayesian(self, ws, debug=0): if self.sBayes not in self.items: if debug > 0: print self.legend, 'no Bayesian Calculator section in the config file' print self.legend, 'cannot configure Bayesian calculator' return {'status': 'fail'} legend = '[' + self.sBayes + ']:' _name = 'exostBayes' # getting items as a dictionary bayes_items = {} bayes_items.update(self.items[self.sBayes]) print legend, 'Configuring Bayesian calculator... ' # check if a CL is specified m_conf_name = self.check_value(self.sBayes, 'model_config') if m_conf_name == -1: print legend, 'Error: model config is not specified' print legend, 'Error:', self.sBayes, 'cannot be configured' return {'status': 'fail'} # check if data is specified data_name = self.check_value(self.sBayes, 'data') data_valid = False if data_name != -1: data_valid = True if ws.data(data_name) != None: data = ws.data(data_name) else: data_valid = False print legend, 'Error: dataset', data_name, 'is not defined' if data_valid == False: print legend, 'Error:', self.sBayes, 'cannot be configured' return {'status': 'fail'} # check if a CL is specified conf_level = self.check_value(self.sBayes, 'confidence_level') if conf_level == -1: print legend, 'Warning: desired confidence level is not specified, setting to 0.90' conf_level = 0.90 # check if a posterior plot is requested post_plot = self.check_value(self.sBayes, 'posterior_plot') b_post_plot = False if post_plot == -1: print legend, 'will generate a posterior plot' b_post_plot = True elif post_plot == 'True': b_post_plot = True else: b_post_plot = False # plot format if post_plot: plot_format = self.check_value(self.sBayes, 'plot_format') if plot_format == -1: plot_format = 'png' # to suppress messgaes when pdf goes to zero RooMsgService.instance().setGlobalKillBelow(RooFit.FATAL) #mconf = ws.obj('exostModelConfig') mconf = ws.obj(m_conf_name) if mconf == None: if debug > 0: print self.legend, 'fail to get Model Config' print self.legend, 'unable to configure Bayesian calculator' print self.legend, 'calculator will not be imported into the workspace' return {'status': 'fail'} bCalc = RooStats.BayesianCalculator(data, mconf) bCalc.SetConfidenceLevel(float(conf_level)) ############# FIXME: debug test #bInt = bCalc.GetInterval() #print legend, 'DEBUG3*******************************' # #cl = bCalc.ConfidenceLevel() #print legend, str(cl)+'% CL central interval: [', bInt.LowerLimit(), ' - ', bInt.UpperLimit(), ']' #print legend, 'or', str(cl+(1.0-cl)/2), '% CL limits' ############################## #size = 1.0 - float(conf_level) #bCalc.SetTestSize(size) # import the calculator into the Workspace getattr(ws, 'import')(bCalc, _name) print legend, 'Bayesian calculator', _name, 'is configured and added to workspace', ws.GetName( ) print legend, 'done' return { 'do_posterior_plot': b_post_plot, 'status': 'success', 'model_config_name': m_conf_name, 'plot_format': plot_format }
observables = RooArgList( wspace.set("observables") ) data = RooDataSet.read("counting_data_3.ascii", observables) data . SetName("data") getattr(wspace, 'import')(data) # model config modelConfig = RooStats.ModelConfig("counting_model_config") modelConfig . SetWorkspace(wspace) modelConfig . SetPdf(wspace.pdf("model_likelihood")) modelConfig . SetPriorPdf(wspace.pdf("prior_pdf")) modelConfig . SetParametersOfInterest(wspace.set("poi")) modelConfig . SetNuisanceParameters(wspace.set("nuisance_parameters")) getattr(wspace, 'import')(modelConfig, "counting_model_config") # Bayesian Calculator bc = RooStats.BayesianCalculator(data, modelConfig) bc.SetName("exostBayes") getattr(wspace, 'import')(bc) # inspect workspace wspace . Print() # save workspace to file wspace . writeToFile("myWS.root") # run Bayesian calculation #bc.SetConfidenceLevel(0.95) #bInt = bc.GetInterval() # make plots #c1 = TCanvas("c1")