RooStats::ModelConfig * Tprime::SetBModel( void ) { // // Define model config and parameter snapshot to describe the b model. // Import to workspace. // std::string legend = "[Tprime::SetBModel]: "; // full signal+background model //RooStats::ModelConfig * pSBModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig"); // let's make the b model (bg-only) from the alt model (s+b) with xsec=0 //RooStats::ModelConfig * pBModel = // new RooStats::ModelConfig(*(RooStats::ModelConfig *)pWs->genobj("ModelConfig")); RooStats::ModelConfig * _sbModel = (RooStats::ModelConfig *)pWs->genobj("ModelConfig"); RooStats::ModelConfig * pBModel = _sbModel->Clone("BModel"); //pBModel->SetName("BModel"); pBModel->SetWorkspace(*pWs); //pBModel->SetParametersOfInterest(RooArgSet()); pWs->import(*pBModel); // set POI to the b model value and take snapshot RooRealVar * pPoi = (RooRealVar *)pBModel->GetParametersOfInterest()->first(); pPoi->setVal(0.0); pBModel->SetSnapshot(*pPoi); pBModel->Print(); return pBModel; }
//#include <typeinfo.h> void addFlatNuisances(std::string fi){ gSystem->Load("libHiggsAnalysisCombinedLimit.so"); TFile *fin = TFile::Open(fi.c_str()); RooWorkspace *wspace = (RooWorkspace*)fin->Get("w_hmumu"); wspace->Print(""); RooStats::ModelConfig *mc = (RooStats::ModelConfig*)wspace->genobj("ModelConfig"); RooArgSet *nuis = (RooArgSet*) mc->GetNuisanceParameters(); std::cout << "Before...." << std::endl; nuis->Print(); RooRealVar *mgg = (RooRealVar*)wspace->var("mmm"); // Get all of the "flat" nuisances to be added to the nusiances: RooArgSet pdfs = (RooArgSet) wspace->allVars(); RooAbsReal *pdf; TIterator *it_pdf = pdfs.createIterator(); while ( (pdf=(RooAbsReal*)it_pdf->Next()) ){ if (!(std::string(pdf->GetName()).find("zmod") != std::string::npos )) { if (!(std::string(pdf->GetName()).find("__norm") != std::string::npos )) { continue; } } pdf->Print(); RooArgSet* pdfpars = (RooArgSet*)pdf->getParameters(RooArgSet(*mgg)); pdfpars->Print(); std::string newname_pdf = (std::string("unconst_")+std::string(pdf->GetName())); wspace->import(*pdf,RooFit::RenameVariable(pdf->GetName(),newname_pdf.c_str())); pdf->SetName(newname_pdf.c_str()); nuis->add(*pdf); } wspace->var("MH")->setVal(125.0); std::cout << "After..." << std::endl; nuis->Print(); mc->SetNuisanceParameters(*nuis); //RooWorkspace *wspace_new = wspace->Clone(); //mc->SetWorkspace(*wspace_new); //wspace_new->import(*mc,true); TFile *finew = new TFile((std::string(fin->GetName())+std::string("_unconst.root")).c_str(),"RECREATE"); //wspace_new->SetName("w"); finew->WriteTObject(wspace); finew->Close(); }
double upper_limit_Bayesian_BAT(Model* model,double confidence,int Niters){ cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl; cout<<"Calculating upper limit with the Bayesian method(BAT)"<<endl; cout<<"///////////////////////////////////////////////////////////////////////////////////////////"<<endl; RooWorkspace* wspace = new RooWorkspace("wspace"); RooStats::ModelConfig* modelConfig = new ModelConfig("bayes"); modelConfig->SetWorkspace(*wspace); modelConfig->SetPdf(*model->get_complete_likelihood()); modelConfig->SetPriorPdf(*model->get_POI_prior()); modelConfig->SetParametersOfInterest(*model->get_POI_set()); modelConfig->SetNuisanceParameters(*model->get_nuisance_set()); cout<<" POI size "<<model->get_POI_set()->getSize()<<endl; //BATCalculator batcalc(model->get_data(), model->get_complete_likelihood(), model->get_POI_set(), model->get_POI_prior()); BATCalculator batcalc(*model->get_data(), *modelConfig); batcalc.SetConfidenceLevel(1-(2*(1-confidence))); batcalc.SetnMCMC(Niters); //batcalc.SetNbins("POI",100); double ul=batcalc.GetInterval()->UpperLimit(); cout<<confidence<<"% CL upper limit: " <<ul<<endl; //double prec=batcalc.GetBrfPrecision(); return ul; }
RooAbsData * Tprime::GetPseudoData( void ) { // // Generate pseudo data, return a pointer. // Class member pointer data set to point to the dataset. // Caller does not take ownership. // static int n_toys = 0; // legend for printouts std::string legend = "[Tprime::GetPseudoData()]: "; delete data; // We will use ToyMCSampler to generate pseudo-data (and test statistic, eventually) // We are responsible for randomizing nuisances and global observables, // ToyMCSampler only generates observables (as of ROOT 5.30.00-rc1 and before) // MC sampler and test statistic if(n_toys == 0) { // on first entry // get B model config from workspace RooStats::ModelConfig * pBModel = (RooStats::ModelConfig *)pWs->obj("BModel"); pBModel->SetWorkspace(*pWs); // get parameter of interest set //const RooArgSet * poi = pSbModel->GetParametersOfInterest(); //RooStats::TestStatistic * pTestStatistic = new RooStats::ProfileLikelihoodTestStat(*pBModel->GetPdf()); //RooStats::ToyMCSampler toymcs(*pTestStatistic, 1); pTestStatistic = new RooStats::ProfileLikelihoodTestStat(*pBModel->GetPdf()); pToyMcSampler = new RooStats::ToyMCSampler(*pTestStatistic, 1); pToyMcSampler->SetPdf(*pBModel->GetPdf()); pToyMcSampler->SetObservables(*pBModel->GetObservables()); pToyMcSampler->SetParametersForTestStat(*pBModel->GetParametersOfInterest()); // just POI pToyMcSampler->SetGlobalObservables(*pBModel->GetGlobalObservables()); } // load parameter point pWs->loadSnapshot("parametersToGenerateData"); RooArgSet dummySet; data = pToyMcSampler->GenerateToyData(dummySet); std::cout << legend << "generated the following background-only pseudo-data:" << std::endl; data->Print(); // count number of generated toys ++n_toys; return data; }
void Raa3S_Workspace(const char* name_pbpb="chad_ws_fits/centFits/ws_PbPbData_262548_263757_0cent10_0.0pt50.0_0.0y2.4.root", const char* name_pp="chad_ws_fits/centFits/ws_PPData_262157_262328_-1cent1_0.0pt50.0_0.0y2.4.root", const char* name_out="fitresult_combo.root"){ //TFile File(filename); //RooWorkspace * ws = test_combine(name_pbpb, name_pp); TFile *f = new TFile("fitresult_combo_333.root") ; RooWorkspace * ws1 = (RooWorkspace*) f->Get("wcombo"); //File.GetObject("wcombo", ws); ws1->Print(); RooAbsData * data = ws1->data("data"); //dataOS, dataSS // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus"); // US_data->SetName("US_data"); // ws->import(* US_data); // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi"); // hi_data->SetName("hi_data"); // ws->import(* hi_data); // hi_data->Print(); RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,-1,1); RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0); RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1); RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge)); ws1->import(step); ws1->factory( "Uniform::flat(raa3)" ); //pp Luminosities, Taa and efficiency ratios Systematics ws1->factory( "Taa_hi[5.662e-9]" ); ws1->factory( "Taa_kappa[1.062]" ); // was 1.057 ws1->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" ); ws1->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" ); ws1->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" ); ws1->factory( "lumipp_hi[5.4]" ); ws1->factory( "lumipp_kappa[1.037]" ); // was 1.06 ws1->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" ); ws1->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" ); ws1->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" ); // ws->factory( "effRat1[1]" ); // ws->factory( "effRat2[1]" ); ws1->factory( "effRat3_hi[0.95]" ); ws1->factory( "effRat_kappa[1.054]" ); ws1->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" ); // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" ); ws1->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" ); // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" ); ws1->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" ); // ws1->factory("Nmb_hi[1.161e9]"); ws1->factory("prod::denominator(Taa_nom,Nmb_hi)"); ws1->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)"); RooAbsReal *lumiOverTaaNmbmodified = ws1->function("lumiOverTaaNmbmodified"); //RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified"); // // RooRealVar *raa1 = ws->var("raa1"); // RooRealVar* nsig1_pp = ws->var("nsig1_pp"); // RooRealVar* effRat1 = ws->function("effRat1_nom"); // RooRealVar *raa2 = ws->var("raa2"); // RooRealVar* nsig2_pp = ws->var("nsig2_pp"); // RooRealVar* effRat2 = ws->function("effRat2_nom"); RooRealVar* nsig3_pp = ws1->var("R_{#frac{3S}{1S}}_pp"); //RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp"); cout << nsig3_pp << endl; RooAbsReal* effRat3 = ws1->function("effRat3_nom"); //RooRealVar* effRat3 = ws->function("effRat3_nom"); // // RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1)); // ws->import(nsig1_hi_modified); // RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2)); // ws->import(nsig2_hi_modified); RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3)); ws1->import(nsig3_hi_modified); // // background yield with systematics ws1->factory( "nbkg_hi_kappa[1.10]" ); ws1->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" ); ws1->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" ); ws1->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" ); RooAbsPdf* sig1S_hi = ws1->pdf("sig1S_hi"); //RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi"); RooAbsPdf* sig2S_hi = ws1->pdf("sig2S_hi"); RooAbsPdf* sig3S_hi = ws1->pdf("sig3S_hi"); RooAbsPdf* LSBackground_hi = ws1->pdf("nbkg_hi_nom"); RooRealVar* nsig1_hi = ws1->var("N_{#Upsilon(1S)}_hi"); RooRealVar* nsig2_hi = ws1->var("R_{#frac{2S}{1S}}_hi"); RooAbsReal* nsig3_hi = ws1->function("nsig3_hi_modified"); //RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified"); cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl; RooRealVar* norm_nbkg_hi = ws1->var("n_{Bkgd}_hi"); RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi); RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi); //////////////////////////////////////////////////////////////////////////////// ws1->factory( "nbkg_pp_kappa[1.03]" ); ws1->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" ); ws1->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" ); ws1->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" ); RooAbsPdf* sig1S_pp = ws1->pdf("sig1S_pp"); //RooAbsPdf* sig1S_pp = ws1->pdf("cbcb_pp"); RooAbsPdf* sig2S_pp = ws1->pdf("sig2S_pp"); RooAbsPdf* sig3S_pp = ws1->pdf("sig3S_pp"); RooAbsPdf* LSBackground_pp = ws1->pdf("nbkg_pp_nom"); RooRealVar* nsig1_pp = ws1->var("N_{#Upsilon(1S)}_pp"); RooRealVar* nsig2_pp = ws1->var("R_{#frac{2S}{1S}}_pp"); //RooRealVar* nsig2_pp = ws1->var("N_{#Upsilon(2S)}_pp"); // RooRealVar* nsig3_pp = ws1->var("N_{#Upsilon(3S)}_pp"); RooRealVar* norm_nbkg_pp = ws1->var("n_{Bkgd}_pp"); RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp); RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp); RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); ws1->import(model_num); ws1->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)"); RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); ws1->import(model_den); ws1->factory("PROD::model_pp(model_den, constr_nbkg_pp)"); ws1->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)"); ///////////////////////////////////////////////////////////////////// RooRealVar * pObs = ws1->var("invariantMass"); // get the pointer to the observable RooArgSet obs("observables"); obs.add(*pObs); obs.add( *ws1->cat("dataCat")); // ///////////////////////////////////////////////////////////////////// ws1->var("glob_lumipp")->setConstant(true); ws1->var("glob_Taa")->setConstant(true); ws1->var("glob_effRat")->setConstant(true); ws1->var("glob_nbkg_pp")->setConstant(true); ws1->var("glob_nbkg_hi")->setConstant(true); RooArgSet globalObs("global_obs"); globalObs.add( *ws1->var("glob_lumipp") ); globalObs.add( *ws1->var("glob_Taa") ); globalObs.add( *ws1->var("glob_effRat") ); globalObs.add( *ws1->var("glob_nbkg_hi") ); globalObs.add( *ws1->var("glob_nbkg_pp") ); cout << "66666" << endl; // ws1->Print(); RooArgSet poi("poi"); poi.add( *ws1->var("raa3") ); cout << "77777" << endl; // create set of nuisance parameters RooArgSet nuis("nuis"); nuis.add( *ws1->var("beta_lumipp") ); nuis.add( *ws1->var("beta_nbkg_hi") ); nuis.add( *ws1->var("beta_nbkg_pp") ); nuis.add( *ws1->var("beta_Taa") ); nuis.add( *ws1->var("beta_effRat") ); cout << "88888" << endl; ws1->var("#alpha_{CB}_hi")->setConstant(true); ws1->var("#alpha_{CB}_pp")->setConstant(true); ws1->var("#sigma_{CB1}_hi")->setConstant(true); ws1->var("#sigma_{CB1}_pp")->setConstant(true); ws1->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true); ws1->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true); //ws1->var("Centrality")->setConstant(true); //delete ws1->var("N_{#varUpsilon(1S)}_hi")->setConstant(true); ws1->var("N_{#varUpsilon(1S)}_pp")->setConstant(true); //ws1->var("N_{#Upsilon(2S)}_hi")->setConstant(true); //ws1->var("N_{#Upsilon(2S)}_pp")->setConstant(true); //ws1->var("N_{#Upsilon(3S)}_pp")->setConstant(true); ws1->var("R_{#frac{2S}{1S}}_hi")->setConstant(true); //new ws1->var("R_{#frac{2S}{1S}}_pp")->setConstant(true); //new ws1->var("R_{#frac{3S}{1S}}_hi")->setConstant(true); //new ws1->var("R_{#frac{3S}{1S}}_pp")->setConstant(true); //new ws1->var("Nmb_hi")->setConstant(true); // ws1->var("QQsign")->setConstant(true); ws1->var("Taa_hi")->setConstant(true); ws1->var("Taa_kappa")->setConstant(true); // ws1->var("beta_Taa")->setConstant(true); // ws1->var("beta_effRat")->setConstant(true); // ws1->var("beta_lumipp")->setConstant(true); // ws1->var("beta_nbkg_hi")->setConstant(true); // ws1->var("beta_nbkg_pp")->setConstant(true); // ws1->var("dataCat")->setConstant(true); ws1->var("decay_hi")->setConstant(true); ws1->var("decay_pp")->setConstant(true); ws1->var("effRat3_hi")->setConstant(true); ws1->var("effRat_kappa")->setConstant(true); // ws1->var("glob_Taa")->setConstant(true); // ws1->var("glob_effRat")->setConstant(true); // ws1->var("glob_lumipp")->setConstant(true); // ws1->var("glob_nbkg_hi")->setConstant(true); // ws1->var("glob_nbkg_pp")->setConstant(true); // ws1->var("invariantMass")->setConstant(true); ws1->var("leftEdge")->setConstant(true); ws1->var("lumipp_hi")->setConstant(true); ws1->var("lumipp_kappa")->setConstant(true); ws1->var("m_{ #varUpsilon(1S)}_hi")->setConstant(true); //ws1->var("mass1S_hi")->setConstant(true); ws1->var("m_{ #varUpsilon(1S)}_pp")->setConstant(true); //ws1->var("mass1S_pp")->setConstant(true); ws1->var("muMinusPt")->setConstant(true); ws1->var("muPlusPt")->setConstant(true); ws1->var("n_{Bkgd}_hi")->setConstant(true); ws1->var("n_{Bkgd}_pp")->setConstant(true); ws1->var("nbkg_hi_kappa")->setConstant(true); ws1->var("nbkg_pp_kappa")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true); ws1->var("n_{CB}_hi")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true); ws1->var("n_{CB}_pp")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true); // ws1->var("raa3")->setConstant(true); ws1->var("rightEdge")->setConstant(true); ws1->var("sigmaFraction_hi")->setConstant(true); ws1->var("sigmaFraction_pp")->setConstant(true); ws1->var("turnOn_hi")->setConstant(true); ws1->var("turnOn_pp")->setConstant(true); ws1->var("dimuPt")->setConstant(true); //ws1->var("upsPt")->setConstant(true); ws1->var("dimuRapidity")->setConstant(true); //ws1->var("upsRapidity")->setConstant(true); ws1->var("vProb")->setConstant(true); ws1->var("width_hi")->setConstant(true); ws1->var("width_pp")->setConstant(true); // ws1->var("x3raw")->setConstant(true); // RooArgSet fixed_again("fixed_again"); // fixed_again.add( *ws1->var("leftEdge") ); // fixed_again.add( *ws1->var("rightEdge") ); // fixed_again.add( *ws1->var("Taa_hi") ); // fixed_again.add( *ws1->var("Nmb_hi") ); // fixed_again.add( *ws1->var("lumipp_hi") ); // fixed_again.add( *ws1->var("effRat1_hi") ); // fixed_again.add( *ws1->var("effRat2_hi") ); // fixed_again.add( *ws1->var("effRat3_hi") ); // fixed_again.add( *ws1->var("nsig3_pp") ); // fixed_again.add( *ws1->var("nsig1_pp") ); // fixed_again.add( *ws1->var("nbkg_hi") ); // fixed_again.add( *ws1->var("alpha") ); // fixed_again.add( *ws1->var("nbkg_kappa") ); // fixed_again.add( *ws1->var("Taa_kappa") ); // fixed_again.add( *ws1->var("lumipp_kappa") ); // fixed_again.add( *ws1->var("mean_hi") ); // fixed_again.add( *ws1->var("mean_pp") ); // fixed_again.add( *ws1->var("width_hi") ); // fixed_again.add( *ws1->var("turnOn_hi") ); // fixed_again.add( *ws1->var("bkg_a1_pp") ); // fixed_again.add( *ws1->var("bkg_a2_pp") ); // fixed_again.add( *ws1->var("decay_hi") ); // fixed_again.add( *ws1->var("raa1") ); // fixed_again.add( *ws1->var("raa2") ); // fixed_again.add( *ws1->var("nsig2_pp") ); // fixed_again.add( *ws1->var("sigma1") ); // fixed_again.add( *ws1->var("nbkg_pp") ); // fixed_again.add( *ws1->var("npow") ); // fixed_again.add( *ws1->var("muPlusPt") ); // fixed_again.add( *ws1->var("muMinusPt") ); // fixed_again.add( *ws1->var("mscale_hi") ); // fixed_again.add( *ws1->var("mscale_pp") ); // // ws1->Print(); cout << "99999" << endl; // create signal+background Model Config RooStats::ModelConfig sbHypo("SbHypo"); sbHypo.SetWorkspace( *ws1 ); sbHypo.SetPdf( *ws1->pdf("joint") ); sbHypo.SetObservables( obs ); sbHypo.SetGlobalObservables( globalObs ); sbHypo.SetParametersOfInterest( poi ); sbHypo.SetNuisanceParameters( nuis ); sbHypo.SetPriorPdf( *ws1->pdf("step") ); // this is optional // ws1->Print(); ///////////////////////////////////////////////////////////////////// RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(10) ); cout << "111111" << endl; RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots cout << "444444" << endl; RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3")); cout << "222222" << endl; pNll->plotOn(framepoi,ShiftToZero()); cout << "333333" << endl; RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values pProfile->plotOn(framepoi,LineColor(kRed)); framepoi->SetMinimum(0); framepoi->SetMaximum(3); TCanvas *cpoi = new TCanvas(); cpoi->cd(); framepoi->Draw(); cpoi->SaveAs("cpoi.pdf"); ((RooRealVar *)poi.first())->setMin(0.); RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance"); // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters()); // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest()); pPoiAndNuisance->add( nuis ); pPoiAndNuisance->add( poi ); sbHypo.SetSnapshot(*pPoiAndNuisance); RooPlot* xframeSB = pObs->frame(Title("SBhypo")); data->plotOn(xframeSB,Cut("dataCat==dataCat::hi")); RooAbsPdf *pdfSB = sbHypo.GetPdf(); RooCategory *dataCat = ws1->cat("dataCat"); pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data)); TCanvas *c1 = new TCanvas(); c1->cd(); xframeSB->Draw(); c1->SaveAs("c1.pdf"); delete pProfile; delete pNll; delete pPoiAndNuisance; ws1->import( sbHypo ); ///////////////////////////////////////////////////////////////////// RooStats::ModelConfig bHypo = sbHypo; bHypo.SetName("BHypo"); bHypo.SetWorkspace(*ws1); pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) ); RooArgSet poiAndGlobalObs("poiAndGlobalObs"); poiAndGlobalObs.add( poi ); poiAndGlobalObs.add( globalObs ); pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables ((RooRealVar *)poi.first())->setVal( 0 ); // set raa3=0 here pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet( "poiAndNuisance" ); pPoiAndNuisance->add( nuis ); pPoiAndNuisance->add( poi ); bHypo.SetSnapshot(*pPoiAndNuisance); RooPlot* xframeB = pObs->frame(Title("Bhypo")); data->plotOn(xframeB,Cut("dataCat==dataCat::hi")); RooAbsPdf *pdfB = bHypo.GetPdf(); pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data)); TCanvas *c2 = new TCanvas(); c2->cd(); xframeB->Draw(); c2->SaveAs("c2.pdf"); delete pProfile; delete pNll; delete pPoiAndNuisance; // import model config into workspace bHypo.SetWorkspace(*ws1); ws1->import( bHypo ); ///////////////////////////////////////////////////////////////////// ws1->Print(); bHypo.Print(); sbHypo.Print(); // save workspace to file ws1 -> SaveAs(name_out); return; }
int GetBayesianInterval( std::string filename = "workspace.root", std::string wsname = "myWS" ){ // // this function loads a workspace and computes // a Bayesian upper limit // // open file with workspace for reading TFile * pInFile = new TFile(filename.c_str(), "read"); // load workspace RooWorkspace * pWs = (RooWorkspace *)pInFile->Get(wsname.c_str()); if (!pWs){ std::cout << "workspace " << wsname << " not found" << std::endl; return -1; } // printout workspace content pWs->Print(); // load and print data from workspace RooAbsData * data = pWs->data("data"); data->Print(); // load and print S+B Model Config RooStats::ModelConfig * pSbHypo = (RooStats::ModelConfig *)pWs->obj("SbHypo"); pSbHypo->Print(); // create RooStats Bayesian MCMC calculator and set parameters // Metropolis-Hastings algorithm needs a proposal function RooStats::SequentialProposal sp(10.0); RooStats::MCMCCalculator mcmc( *data, *pSbHypo ); mcmc.SetConfidenceLevel(0.95); mcmc.SetNumIters(100000); // Metropolis-Hastings algorithm iterations mcmc.SetProposalFunction(sp); mcmc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in mcmc.SetLeftSideTailFraction(0.0); mcmc.SetNumBins(40); // for plotting only - does not affect limit calculation // 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) RooStats::MCMCInterval * pMcmcInt = mcmc.GetInterval(); double upper_bound = pMcmcInt->UpperLimit( *pWs->var("xsec") ); double lower_bound = pMcmcInt->LowerLimit( *pWs->var("xsec") ); std::cout << "one-sided 95%.C.L. bayesian credible interval for xsec: " << "[" << lower_bound << ", " << upper_bound << "]" << std::endl; // make posterior PDF plot for POI TCanvas c1("posterior"); RooStats::MCMCIntervalPlot plot(*pMcmcInt); plot.Draw(); c1.SaveAs("bayesian_mcmc_posterior.pdf"); // make scatter plots to visualise the Markov chain TCanvas c2("xsec_vs_alpha_lumi"); plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_lumi")); c2.SaveAs("scatter_mcmc_xsec_vs_alpha_lumi.pdf"); TCanvas c3("xsec_vs_alpha_efficiency"); plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_efficiency")); c3.SaveAs("scatter_mcmc_xsec_vs_alpha_efficiency.pdf"); TCanvas c4("xsec_vs_alpha_nbkg"); plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_nbkg")); c4.SaveAs("scatter_mcmc_xsec_vs_alpha_nbkg.pdf"); // clean up a little delete pMcmcInt; return 0; }
std::pair<float,float> ComputeLimitForADataset(float m0, RooDataSet* CurrentDataset, REGION region, REGION NonRegion, TString& modelName, RooWorkspace *ws, const char* tag) { ws->var("m0")->setVal(m0); ws->var("m0")->setConstant(1); m0 = float(ws->var("m0")->getVal()); RooRealVar *mu = ws->var(Concatenate("nSig",GetRegion(region))); RooArgSet *poi = new RooArgSet(*mu); RooArgSet *nullParams = (RooArgSet*) poi->snapshot(); nullParams->setRealValue(Concatenate("nSig",GetRegion(region)), 0); RooStats::ModelConfig *model = new RooStats::ModelConfig(); model->SetWorkspace(*ws); model->SetPdf(*ws->pdf(modelName)); model->SetParametersOfInterest(*mu); model->SetObservables(RooArgSet(*ws->var("inv"))); model->SetSnapshot(*mu); RooStats::ModelConfig *nullModel; nullModel = model->Clone(modelName+"BgOnly"); float oldval = ws->var(Concatenate("nSig",GetRegion(region)))->getVal(); ws->var(Concatenate("nSig",GetRegion(region)))->setVal(0); ws->var(Concatenate("nSig",GetRegion(region)))->setConstant(1); nullModel->SetSnapshot(RooArgSet(*ws->var(Concatenate("nSig",GetRegion(region))))); ws->var(Concatenate("nSig",GetRegion(region)))->setConstant(0); ws->var(Concatenate("nSig",GetRegion(region)))->setVal(oldval); nullModel->SetWorkspace(*ws); nullModel->SetParametersOfInterest(*nullParams); RooAbsData *data = CurrentDataset; float UpperLimit,Signif; ComputeUpperLimit(data,model,UpperLimit,Signif,mu,nullParams,ws,region,tag); delete poi; poi=0; delete model; model=0; return make_pair(UpperLimit,Signif); }
void MakeWorkspace( void ){ // // this function implements a RooFit model for a counting experiment // // create workspace RooWorkspace * pWs = new RooWorkspace("myWS"); // observable: number of events pWs->factory( "n[0.0]" ); // integrated luminosity with systematics pWs->factory( "lumi_nom[5000.0, 4000.0, 6000.0]" ); pWs->factory( "lumi_kappa[1.045]" ); pWs->factory( "cexpr::alpha_lumi('pow(lumi_kappa,beta_lumi)',lumi_kappa,beta_lumi[0,-5,5])" ); pWs->factory( "prod::lumi(lumi_nom,alpha_lumi)" ); pWs->factory( "Gaussian::constr_lumi(beta_lumi,glob_lumi[0,-5,5],1)" ); // cross section - parameter of interest pWs->factory( "xsec[0.001,0.0,0.1]" ); // selection efficiency * acceptance with systematics pWs->factory( "efficiency_nom[0.1, 0.05, 0.15]" ); pWs->factory( "efficiency_kappa[1.10]" ); pWs->factory( "cexpr::alpha_efficiency('pow(efficiency_kappa,beta_efficiency)',efficiency_kappa,beta_efficiency[0,-5,5])" ); pWs->factory( "prod::efficiency(efficiency_nom,alpha_efficiency)" ); pWs->factory( "Gaussian::constr_efficiency(beta_efficiency,glob_efficiency[0,-5,5],1)" ); // signal yield pWs->factory( "prod::nsig(lumi,xsec,efficiency)" ); // background yield with systematics pWs->factory( "nbkg_nom[10.0, 5.0, 15.0]" ); pWs->factory( "nbkg_kappa[1.10]" ); pWs->factory( "cexpr::alpha_nbkg('pow(nbkg_kappa,beta_nbkg)',nbkg_kappa,beta_nbkg[0,-5,5])" ); pWs->factory( "prod::nbkg(nbkg_nom,alpha_lumi,alpha_nbkg)" ); pWs->factory( "Gaussian::constr_nbkg(beta_nbkg,glob_nbkg[0,-5,5],1)" ); // full event yield pWs->factory("sum::yield(nsig,nbkg)"); // Core model: Poisson probability with mean signal+bkg pWs->factory( "Poisson::model_core(n,yield)" ); // define Bayesian prior PDF for POI pWs->factory( "Uniform::prior(xsec)" ); // model with systematics pWs->factory( "PROD::model(model_core,constr_lumi,constr_efficiency,constr_nbkg)" ); // create set of observables (will need it for datasets and ModelConfig later) RooRealVar * pObs = pWs->var("n"); // get the pointer to the observable RooArgSet obs("observables"); obs.add(*pObs); // create the dataset pObs->setVal(11); // this is your observed data: we counted ten events RooDataSet * data = new RooDataSet("data", "data", obs); data->add( *pObs ); // import dataset into workspace pWs->import(*data); // create set of global observables (need to be defined as constants) pWs->var("glob_lumi")->setConstant(true); pWs->var("glob_efficiency")->setConstant(true); pWs->var("glob_nbkg")->setConstant(true); RooArgSet globalObs("global_obs"); globalObs.add( *pWs->var("glob_lumi") ); globalObs.add( *pWs->var("glob_efficiency") ); globalObs.add( *pWs->var("glob_nbkg") ); // create set of parameters of interest (POI) RooArgSet poi("poi"); poi.add( *pWs->var("xsec") ); // create set of nuisance parameters RooArgSet nuis("nuis"); nuis.add( *pWs->var("beta_lumi") ); nuis.add( *pWs->var("beta_efficiency") ); nuis.add( *pWs->var("beta_nbkg") ); // create signal+background Model Config RooStats::ModelConfig sbHypo("SbHypo"); sbHypo.SetWorkspace( *pWs ); sbHypo.SetPdf( *pWs->pdf("model") ); sbHypo.SetObservables( obs ); sbHypo.SetGlobalObservables( globalObs ); sbHypo.SetParametersOfInterest( poi ); sbHypo.SetNuisanceParameters( nuis ); sbHypo.SetPriorPdf( *pWs->pdf("prior") ); // this is optional // fix all other variables in model: // everything except observables, POI, and nuisance parameters // must be constant pWs->var("lumi_nom")->setConstant(true); pWs->var("efficiency_nom")->setConstant(true); pWs->var("nbkg_nom")->setConstant(true); pWs->var("lumi_kappa")->setConstant(true); pWs->var("efficiency_kappa")->setConstant(true); pWs->var("nbkg_kappa")->setConstant(true); RooArgSet fixed("fixed"); fixed.add( *pWs->var("lumi_nom") ); fixed.add( *pWs->var("efficiency_nom") ); fixed.add( *pWs->var("nbkg_nom") ); fixed.add( *pWs->var("lumi_kappa") ); fixed.add( *pWs->var("efficiency_kappa") ); fixed.add( *pWs->var("nbkg_kappa") ); // set parameter snapshot that corresponds to the best fit to data RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data ); RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance"); pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters()); pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest()); sbHypo.SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // import S+B ModelConfig into workspace pWs->import( sbHypo ); // create background-only Model Config from the S+B one RooStats::ModelConfig bHypo = sbHypo; bHypo.SetName("BHypo"); bHypo.SetWorkspace(*pWs); // set parameter snapshot for bHypo, setting xsec=0 // it is useful to understand how this block of code works // but you can also use it as a recipe to make a parameter snapshot pNll = bHypo.GetPdf()->createNLL( *data ); RooArgSet poiAndGlobalObs("poiAndGlobalObs"); poiAndGlobalObs.add( poi ); poiAndGlobalObs.add( globalObs ); pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables ((RooRealVar *)poi.first())->setVal( 0 ); // set xsec=0 here pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet( "poiAndNuisance" ); pPoiAndNuisance->add( nuis ); pPoiAndNuisance->add( poi ); bHypo.SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // import model config into workspace pWs->import( bHypo ); // print out the workspace contents pWs->Print(); // save workspace to file pWs -> SaveAs("workspace.root"); return; }
void combinedWorkspace_4WS(const char* name_pbpb_pass="******", const char* name_pbpb_fail="fitresult_pbpb_fail.root", const char* name_pp_pass="******", const char* name_pp_fail="fitresult_pp_fail.root", const char* name_out="fitresult_combo.root", const float systval = 0., const char* subDirName ="wsTest", int nCPU=2){ // subdir: Directory to save workspaces under currentPATH/CombinedWorkspaces/subDir/ // set things silent gErrorIgnoreLevel=kError; RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); bool dosyst = (systval > 0.); TString nameOut(name_out); RooWorkspace * ws = test_combine_4WS(name_pbpb_pass, name_pp_pass, name_pbpb_fail, name_pp_fail, false, nCPU); RooAbsData * data = ws->data("dOS_DATA"); RooRealVar* RFrac2Svs1S_PbPbvsPP_P = ws->var("RFrac2Svs1S_PbPbvsPP_P"); RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",-10); RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",10); RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*RFrac2Svs1S_PbPbvsPP_P, *leftEdge, *rightEdge)); ws->import(step); ws->factory( "Uniform::flat(RFrac2Svs1S_PbPbvsPP_P)" ); // systematics if (dosyst) { ws->factory( Form("kappa_syst[%f]",systval) ); ws->factory( "expr::alpha_syst('kappa_syst*beta_syst',kappa_syst,beta_syst[0,-5,5])" ); ws->factory( "Gaussian::constr_syst(beta_syst,glob_syst[0,-5,5],1)" ); // add systematics into the double ratio ws->factory( "expr::RFrac2Svs1S_PbPbvsPP_P_syst('@0+@1',RFrac2Svs1S_PbPbvsPP_P,alpha_syst)" ); // build the pbpb pdf RooRealVar* effjpsi_pp_P = (RooRealVar*)ws->var("effjpsi_pp_P"); RooRealVar* effpsip_pp_P = (RooRealVar*)ws->var("effpsip_pp_P"); RooRealVar* effjpsi_pp_NP = (RooRealVar*)ws->var("effjpsi_pp_NP"); Double_t Npsi2SPbPbPass = npsip_pbpb_pass_from_doubleratio_prompt(ws, RooArgList(*effjpsi_pp_P,*effpsip_pp_P,*effjpsi_pp_NP),true); // Create and import N_Psi2S_PbPb_pass_syst ws->factory( "SUM::pdfMASS_Tot_PbPb_pass_syst(N_Jpsi_PbPb_pass * pdfMASS_Jpsi_PbPb_pass, N_Psi2S_PbPb_pass_syst * pdfMASS_Psi2S_PbPb_pass, N_Bkg_PbPb_pass * pdfMASS_Bkg_PbPb_pass)" ); ws->factory( "PROD::pdfMASS_Tot_PbPb_pass_constr(pdfMASS_Tot_PbPb_pass_syst,constr_syst)" ); // build the combined pdf ws->factory("SIMUL::simPdf_syst_noconstr(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass_syst,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)"); RooSimultaneous *simPdf = (RooSimultaneous*) ws->pdf("simPdf_syst_noconstr"); RooGaussian *constr_syst = (RooGaussian*) ws->pdf("constr_syst"); RooProdPdf *simPdf_constr = new RooProdPdf("simPdf_syst","simPdf_syst",RooArgSet(*simPdf,*constr_syst)); ws->import(*simPdf_constr); } else { ws->factory("SIMUL::simPdf_syst(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)"); } ws->Print(); if (dosyst) ws->var("beta_syst")->setConstant(kFALSE); ///////////////////////////////////////////////////////////////////// RooRealVar * pObs = ws->var("invMass"); // get the pointer to the observable RooArgSet obs("observables"); obs.add(*pObs); obs.add( *ws->cat("sample")); // ///////////////////////////////////////////////////////////////////// if (dosyst) ws->var("glob_syst")->setConstant(true); RooArgSet globalObs("global_obs"); if (dosyst) globalObs.add( *ws->var("glob_syst") ); // ws->Print(); RooArgSet poi("poi"); poi.add( *ws->var("RFrac2Svs1S_PbPbvsPP_P") ); // create set of nuisance parameters RooArgSet nuis("nuis"); if (dosyst) nuis.add( *ws->var("beta_syst") ); // set parameters constant RooArgSet allVars = ws->allVars(); TIterator* it = allVars.createIterator(); RooRealVar *theVar = (RooRealVar*) it->Next(); while (theVar) { TString varname(theVar->GetName()); // if (varname != "RFrac2Svs1S_PbPbvsPP" // && varname != "invMass" // && varname != "sample" // ) // theVar->setConstant(); if ( varname.Contains("f_Jpsi_PP") || varname.Contains("f_Jpsi_PbPb") || varname.Contains("rSigma21_Jpsi_PP") || varname.Contains("m_Jpsi_PP") || varname.Contains("m_Jpsi_PbPb") || varname.Contains("sigma1_Jpsi_PP") || varname.Contains("sigma1_Jpsi_PbPb") || (varname.Contains("lambda")) || (varname.Contains("_fail") && !varname.Contains("RFrac2Svs1S"))) { theVar->setConstant(); } if (varname=="glob_syst" || varname=="beta_syst" ) { cout << varname << endl; theVar->setConstant(!dosyst); } theVar = (RooRealVar*) it->Next(); } // create signal+background Model Config RooStats::ModelConfig sbHypo("SbHypo"); sbHypo.SetWorkspace( *ws ); sbHypo.SetPdf( *ws->pdf("simPdf_syst") ); sbHypo.SetObservables( obs ); sbHypo.SetGlobalObservables( globalObs ); sbHypo.SetParametersOfInterest( poi ); sbHypo.SetNuisanceParameters( nuis ); sbHypo.SetPriorPdf( *ws->pdf("step") ); // this is optional ///////////////////////////////////////////////////////////////////// RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) ); RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots if (controlPlots) { RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,1),Title("LL and profileLL in RFrac2Svs1S_PbPbvsPP_P")); pNll->plotOn(framepoi,ShiftToZero()); framepoi->SetMinimum(0); framepoi->SetMaximum(10); TCanvas *cpoi = new TCanvas(); cpoi->cd(); framepoi->Draw(); cpoi->SaveAs("cpoi.pdf"); } ((RooRealVar *)poi.first())->setMin(0.); RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance"); pPoiAndNuisance->add( nuis ); pPoiAndNuisance->add( poi ); sbHypo.SetSnapshot(*pPoiAndNuisance); if (controlPlots) { RooPlot* xframeSB_PP_pass = pObs->frame(Title("SBhypo_PP_pass")); data->plotOn(xframeSB_PP_pass,Cut("sample==sample::PP_pass")); RooAbsPdf *pdfSB_PP_pass = sbHypo.GetPdf(); RooCategory *sample = ws->cat("sample"); pdfSB_PP_pass->plotOn(xframeSB_PP_pass,Slice(*sample,"PP_pass"),ProjWData(*sample,*data)); TCanvas *c1 = new TCanvas(); c1->cd(); xframeSB_PP_pass->Draw(); c1->SaveAs("c1.pdf"); RooPlot* xframeSB_PP_fail = pObs->frame(Title("SBhypo_PP_fail")); data->plotOn(xframeSB_PP_fail,Cut("sample==sample::PP_fail")); RooAbsPdf *pdfSB_PP_fail = sbHypo.GetPdf(); pdfSB_PP_fail->plotOn(xframeSB_PP_fail,Slice(*sample,"PP_fail"),ProjWData(*sample,*data)); TCanvas *c2 = new TCanvas(); c2->cd(); xframeSB_PP_fail->Draw(); c2->SaveAs("c1.pdf"); RooPlot* xframeB_PbPb_pass = pObs->frame(Title("SBhypo_PbPb_pass")); data->plotOn(xframeB_PbPb_pass,Cut("sample==sample::PbPb_pass")); RooAbsPdf *pdfB_PbPb_pass = sbHypo.GetPdf(); pdfB_PbPb_pass->plotOn(xframeB_PbPb_pass,Slice(*sample,"PbPb_pass"),ProjWData(*sample,*data)); TCanvas *c3 = new TCanvas(); c3->cd(); xframeB_PbPb_pass->Draw(); c3->SetLogy(); c3->SaveAs("c2.pdf"); RooPlot* xframeB_PbPb_fail = pObs->frame(Title("SBhypo_PbPb_fail")); data->plotOn(xframeB_PbPb_fail,Cut("sample==sample::PbPb_fail")); RooAbsPdf *pdfB_PbPb_fail = sbHypo.GetPdf(); pdfB_PbPb_fail->plotOn(xframeB_PbPb_fail,Slice(*sample,"PbPb_fail"),ProjWData(*sample,*data)); TCanvas *c4 = new TCanvas(); c4->cd(); xframeB_PbPb_fail->Draw(); c4->SetLogy(); c4->SaveAs("c2.pdf"); } delete pNll; delete pPoiAndNuisance; ws->import( sbHypo ); ///////////////////////////////////////////////////////////////////// RooStats::ModelConfig bHypo = sbHypo; bHypo.SetName("BHypo"); bHypo.SetWorkspace(*ws); pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) ); // RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots RooArgSet poiAndGlobalObs("poiAndGlobalObs"); poiAndGlobalObs.add( poi ); poiAndGlobalObs.add( globalObs ); RooAbsReal * pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables ((RooRealVar *)poi.first())->setVal( 0 ); // set RFrac2Svs1S_PbPbvsPP=0 here pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet( "poiAndNuisance" ); pPoiAndNuisance->add( nuis ); pPoiAndNuisance->add( poi ); bHypo.SetSnapshot(*pPoiAndNuisance); delete pNll; delete pPoiAndNuisance; // import model config into workspace bHypo.SetWorkspace(*ws); ws->import( bHypo ); ///////////////////////////////////////////////////////////////////// ws->Print(); bHypo.Print(); sbHypo.Print(); // save workspace to file string mainDIR = gSystem->ExpandPathName(gSystem->pwd()); string wsDIR = mainDIR + "/CombinedWorkspaces/"; string ssubDirName=""; if (subDirName) ssubDirName.append(subDirName); string subDIR = wsDIR + ssubDirName; void * dirp = gSystem->OpenDirectory(wsDIR.c_str()); if (dirp) gSystem->FreeDirectory(dirp); else gSystem->mkdir(wsDIR.c_str(), kTRUE); void * dirq = gSystem->OpenDirectory(subDIR.c_str()); if (dirq) gSystem->FreeDirectory(dirq); else gSystem->mkdir(subDIR.c_str(), kTRUE); const char* saveName = Form("%s/%s",subDIR.c_str(),nameOut.Data()); ws->writeToFile(saveName); }
void makeModel(RooWorkspace& w) { TFile *_file0 = TFile::Open("plots/htotal_root_ZprimeRecomass.root"); TH1F *Histo = (TH1F*)_file0->Get("htotaldata"); RooRealVar invm("invm","invm",200.,4000.); RooDataHist* data = new RooDataHist("data","data",invm,Import(*Histo)) ; // TTree* tree = new TTree("simple","data from ascii file"); // Long64_t nlines = tree->ReadFile("list_mll_200_2016.txt","x1:x2:x3:invm:x5:x6"); // Long64_t nlines = tree->ReadFile("a.txt","x1:x2:x3:invm:x5:x6"); // printf(" found %lld pointsn",nlines); // tree->Write(); // tree->GetEntries(); RooRealVar mass("mass","mass", 300., 200., 1600.); RooRealVar nsig("nsig","Number of signal events", 0., 5000.); RooRealVar nbkg("nbkg","Number of background events", 0., 300000.); w.import(mass); w.import(nsig); w.import(nbkg); // RooRealVar invm("invm","Invariant mass", 200., 4000.); // RooDataSet* data = new RooDataSet("data", "Data", invm, RooFit::Import(*tree)); data->Print("v"); w.import(invm); w.import(*data); w.factory("expr::sigma('invm*(0.01292 + 0.00001835 * invm - 0.0000000002733 * invm*invm)',invm)"); w.factory("expr::width('0.03*invm',invm)"); w.factory("CEXPR::bkgpdf('exp(24.9327 - 2.39287e-03*invm + 3.19926e-07*invm*invm - 3.38799e-11*invm*invm*invm)*pow(invm,-3.3634)',invm)"); w.factory("Voigtian::sigpdf(invm,mass,width,sigma)"); w.factory("SUM::model(nbkg*bkgpdf, nsig*sigpdf)"); RooAbsPdf* sigpdf = w.pdf("sigpdf"); RooAbsPdf* bkgpdf = w.pdf("bkgpdf"); RooAbsPdf* model = w.pdf("model"); RooStats::ModelConfig* mc = new ModelConfig("mc",&w); mc->SetPdf(*w.pdf("model")); mc->SetParametersOfInterest(*w.var("nsig")); mc->SetObservables(*w.var("invm")); w.defineSet("nuisParams","nbkg"); mc->SetNuisanceParameters(*w.set("nuisParams")); w.var("mass")->setConstant(true); w.import(*mc); w.Print("tree"); w.writeToFile("MyModel_workspace.root"); TCanvas* c1 = new TCanvas("c1","Control Plots", 900, 700); RooPlot* plot = w.var("invm")->frame(); w.data("data")->plotOn(plot); w.pdf("model")->plotOn(plot); w.pdf("model")->plotOn(plot, Components("bkgpdf"),LineStyle(kDashed)); w.pdf("model")->plotOn(plot, Components("sigpdf"),LineColor(kRed)); plot->Draw(); return; }
Int_t Tprime::RunMcmc( std::string channel, // ejets, mujets, combined std::string mode, // observed, expected double peak, // resonance mass std::string suffix, // suffix for output file names Int_t ntoys, // number of pseudoexperiments for expected limit Int_t mcmc_iter, // number of MCMC iterations Int_t mcmc_burnin, // number of MCMC burn in steps to be discarded std::string inputdir // input dir name ) { // // Bayesian MCMC calculation // std::string legend = "[tprime::RunMcmc()]: "; // print out inputs std::cout << legend << std::endl; std::cout << legend << "Input parameters specified. Some of them are not used and defaults are entered" << std::endl; std::cout << legend << "------------------------------" << std::endl; std::cout << legend << "channel: " << channel << std::endl; std::cout << legend << "mode: " << mode << std::endl; std::cout << legend << "input directory: " << inputdir << std::endl; std::cout << legend << "resonance peak mass: " << peak << std::endl; std::cout << legend << "suffix: ->" << suffix << "<-" << std::endl; std::cout << legend << "number of pseudo-experiments: "<< ntoys << std::endl; std::cout << legend << std::endl; std::cout << legend << "Bayesian MCMC parameters" << std::endl; std::cout << legend << "------------------------------" << std::endl; std::cout << legend << "number of iterations: " << mcmc_iter << std::endl; std::cout << legend << "number of burn-in steps to discard: " << mcmc_burnin << std::endl; std::cout << legend << std::endl; // compose the workspace file name char buf[1024]; sprintf(buf, "%sresults_%04.0f/tprime_%s_tprimeCrossSection_model.root", inputdir.c_str(), peak, channel.c_str()); std::string _file = buf; std::cout << legend << "guessed name of the file with the workspace: >" << _file << "<" << std::endl; //load workspace LoadWorkspace(_file, channel); // change POI range double poiUpper = GetPoiUpper(channel, peak); std::cout << legend << "setting POI range to [0; " << poiUpper << "]" << std::endl; pWs->var("xsec")->setRange(0.0, poiUpper); // timer TStopwatch t; t.Start(); int pe_counter = 0; std::vector<Double_t> _limits; while (pe_counter < ntoys) { // for mass limit, add k-factor systematics to the nsig systematics // FIXME: this is a correlated part of the uncertainty!!! // - different uncertainties for graviton and Z' models if ( mode.find("mass_") != std::string::npos ) { std::cout << legend << std::endl; std::cout << legend << "this a mass limit calculation," << std::endl; std::cout << legend << "I would add k-factor uncertainty to the nsig uncertainty" << std::endl; std::cout << legend << "I would do it " << ntoys << " times, so one can average. " << pe_counter+1 << " of " << ntoys << std::endl; std::cout << legend << "Not implemented yet " << std::endl; std::cout << legend << std::endl; //Double_t kfactor_err = GetKfactorUncertainty(peak, mode); //double nsig_kappa = ws->var("nsig_kappa_dimuon")->getVal(); //nsig_kappa = sqrt(nsig_kappa*nsig_kappa + kfactor_err*kfactor_err); //ws->var("nsig_kappa_dimuon")->setVal(nsig_kappa); //ntoys = 1; } else if ( mode.find("expected") != std::string::npos ) { std::cout << legend << std::endl; std::cout << legend << "this is pseudoexperiment " << pe_counter+1 << " of " << ntoys << std::endl; std::cout << legend << "for the expected limit estimate" << std::endl; std::cout << legend << std::endl; // prepare PE data GetPseudoData(); } else { // "regular" observed limit std::cout << legend << std::endl; std::cout << legend << "calculating an observed limit..." << std::endl; std::cout << legend << "I will do it " << ntoys << " times, so one can average. " << pe_counter+1 << " of " << ntoys << std::endl; std::cout << legend << std::endl; GetWorkspaceData("obsData"); //ntoys = 1; } mcInt = GetMcmcInterval(0.95, // conf level mcmc_iter, // number of iterations mcmc_burnin, // number of burn-in to discard 0.0, // left side tail fraction, 0 for upper limit 100); // number of bins in posterior, only for plotting ++pe_counter; if (!mcInt) { continue; } else { std::string _outfile = "tprime_"+channel+"_xsec_mcmc_limit_" + suffix + ".ascii"; printMcmcUpperLimit( peak, _outfile ); // limits for averaging/medianing RooStats::ModelConfig * pSbModel = GetModelConfig("ModelConfig"); RooRealVar * firstPOI = (RooRealVar*) pSbModel->GetParametersOfInterest()->first(); double _limit = mcInt->UpperLimit(*firstPOI); _limits.push_back(_limit); } // end of valid mcInt block } // end of while // write median limit to a file if (_limits.size() > 0) { Double_t _median_limit = TMath::Median(_limits.size(), &_limits[0]); std::vector<Double_t> _mass_limit; _mass_limit.push_back(peak); _mass_limit.push_back(_median_limit); std::string _outfile = "tprime_"+channel+"_xsec_mcmc_median_limit_" + suffix + ".ascii"; PrintToFile(_outfile, _mass_limit, "# mass median_limit"); } std::string _outfile = "tprime_"+channel+"_xsec_mcmc_posterior_" + suffix + ".pdf"; makeMcmcPosteriorPlot( _outfile ); // timer t.Print(); return 0; }
Int_t Tprime::SetParameterPoints( std::string sbModelName, std::string bModelName ) { // // Fit the data with S+B model. // Make a snapshot of the S+B parameter point. // Profile with POI=0. // Make a snapshot of the B parameter point // (B model is the S+B model with POI=0 // Double_t poi_value_for_b_model = 0.0; // get S+B model config from workspace RooStats::ModelConfig * pSbModel = (RooStats::ModelConfig *)pWs->obj(sbModelName.c_str()); pSbModel->SetWorkspace(*pWs); // get parameter of interest set const RooArgSet * poi = pSbModel->GetParametersOfInterest(); // get B model config from workspace RooStats::ModelConfig * pBModel = (RooStats::ModelConfig *)pWs->obj(bModelName.c_str()); pBModel->SetWorkspace(*pWs); // make sure that data has been loaded if (!data) return -1; // find parameter point for global maximum with the S+B model, // with conditional MLEs for nuisance parameters // and save the parameter point snapshot in the Workspace RooAbsReal * nll = pSbModel->GetPdf()->createNLL(*data); RooAbsReal * profile = nll->createProfile(RooArgSet()); profile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values RooArgSet * poiAndNuisance = new RooArgSet(); if(pSbModel->GetNuisanceParameters()) poiAndNuisance->add(*pSbModel->GetNuisanceParameters()); poiAndNuisance->add(*pSbModel->GetParametersOfInterest()); pWs->defineSet("SPlusBModelParameters", *poiAndNuisance); pWs->saveSnapshot("SPlusBFitParameters",*poiAndNuisance); pSbModel->SetSnapshot(*poi); RooArgSet * sbModelFitParams = (RooArgSet *)poiAndNuisance->snapshot(); cout << "\nWill save these parameter points that correspond to the fit to data" << endl; sbModelFitParams->Print("v"); delete profile; delete nll; delete poiAndNuisance; delete sbModelFitParams; // // Find a parameter point for generating pseudo-data // with the background-only data. // Save the parameter point snapshot in the Workspace nll = pBModel->GetPdf()->createNLL(*data); profile = nll->createProfile(*poi); ((RooRealVar *)poi->first())->setVal(poi_value_for_b_model); profile->getVal(); // this will do fit and set nuisance parameters to profiled values poiAndNuisance = new RooArgSet(); if(pBModel->GetNuisanceParameters()) poiAndNuisance->add(*pBModel->GetNuisanceParameters()); poiAndNuisance->add(*pBModel->GetParametersOfInterest()); pWs->defineSet("parameterPointToGenerateData", *poiAndNuisance); pWs->saveSnapshot("parametersToGenerateData",*poiAndNuisance); pBModel->SetSnapshot(*poi); RooArgSet * paramsToGenerateData = (RooArgSet *)poiAndNuisance->snapshot(); cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl; paramsToGenerateData->Print("v"); delete profile; delete nll; delete poiAndNuisance; delete paramsToGenerateData; return 0; }