void gen1(const char* output, const char* suffix) { // S e t u p m o d e l // --------------------- gRandom = new TRandom(); gRandom->SetSeed(0); RooWorkspace *ws = new RooWorkspace("workspace"); // Declare variables x,mean,sigma with associated name, title, initial value and allowed range ws->factory("invMass[2,5]"); RooRealVar *invMass = ws->var("invMass"); RooRealVar *weight = new RooRealVar("weight","weight",1,0,1e6); ws->factory(Form("Gaussian::siga_nonorm_%s(invMass,m_%s[3,2.5,3.5],sigmaa_%s[0.02,0.,0.5])",suffix,suffix,suffix)); ws->factory(Form("Gaussian::sigb_nonorm_%s(invMass,m_%s,sigmab_%s[0.1,0.,0.5])",suffix,suffix,suffix)); ws->factory(Form("SUM::sig_nonorm_%s(f_%s[0.8,0,1]*siga_nonorm_%s,sigb_nonorm_%s)",suffix,suffix,suffix,suffix)); ws->factory(Form("RooExtendPdf::sig_%s(sig_nonorm_%s,Nsig_%s[1e4,-1e5,1e5])",suffix,suffix,suffix)); ws->factory(Form("Gaussian::sig2_nonorm_%s(invMass,m2_%s[3.5,3.,4.],sigma2_%s[0.1,0.,0.5])",suffix,suffix,suffix)); ws->factory(Form("RooFormulaVar::Nsig2_%s('@0*@1',{Nsig_%s,frac_%s[0.5,-10,10]})",suffix,suffix,suffix)); ws->factory(Form("RooExtendPdf::sig2_%s(sig2_nonorm_%s,Nsig2_%s)",suffix,suffix,suffix)); ws->factory(Form("Chebychev::bkg_nonorm_%s(invMass,{lambda0_%s[0.1,-1.5,1.5],lambda1_%s[0.1,-1.5,1.5]})",suffix,suffix,suffix)); ws->factory(Form("RooExtendPdf::bkg_%s(bkg_nonorm_%s,Nbkg_%s[1e4,-1e5,1e5])",suffix,suffix,suffix)); // ws->factory(Form("SUM::tot_%s( sig_%s, bkg_%s)",suffix,suffix,suffix)); // RooAbsPdf *thepdf = ws->pdf(Form("tot_%s",suffix)); RooAbsPdf *thepdf = new RooAddPdf(Form("tot_%s",suffix), Form("tot_%s",suffix), RooArgList(*ws->pdf(Form("sig_%s",suffix)), *ws->pdf(Form("sig2_%s",suffix)), *ws->pdf(Form("bkg_%s",suffix)))); ws->import(*thepdf); // G e n e r a t e e v e n t s // ----------------------------- // Generate a dataset of 1000 events in x from gauss RooDataSet* data = thepdf->generate(*invMass,2e4,Name(Form("data_%s",suffix))) ; ws->import(*data); ws->writeToFile(output); }
void Process(TString fname, TString myRooWS, int toMass, int fromMass, int Bin) { gROOT->SetStyle("Plain"); TFile * file = new TFile(fname.Data(), "READ"); std::cout << "reading " << fname.Data() << std::endl; TString outname("newcards/"); outname.Append(massS[toMass]); outname.Append("/"); fname.ReplaceAll("110",""); fname.ReplaceAll("115",""); fname.ReplaceAll("120",""); fname.ReplaceAll("125",""); fname.ReplaceAll("130",""); fname.ReplaceAll("135",""); fname.ReplaceAll("140",""); fname.ReplaceAll("145",""); fname.ReplaceAll("150",""); fname.ReplaceAll("/",""); if(fname.Contains("Zn") && (Bin == 0)) fname.ReplaceAll(".root","Low.root"); if(fname.Contains("Zn") && (Bin == 1)) fname.ReplaceAll(".root","Med.root"); if(fname.Contains("Zn") && (Bin == 2)) fname.ReplaceAll(".root","High.root"); outname.Append(fname.Data()); outname.ReplaceAll("Wtn_BDT_newBinning_","vhbb_Wtn_8TeV"); outname.ReplaceAll("WS_BDT_H_",""); outname.ReplaceAll("WS_BDT_M_",""); std::cout << "FILENAME: " << outname.Data() <<std::endl; TFile * outfile = new TFile(outname.Data(), "RECREATE"); using namespace RooFit; RooWorkspace *myWS = new RooWorkspace(myRooWS.Data(),myRooWS.Data()); if(fname.Contains ("Zmm") | fname.Contains ("Zee") ) {myWS->factory("CMS_vhbb_BDT_Zll_8TeV[-1.,1.]"); bins = 15;} else if(fname.Contains ("Zn") && (Bin == 0)) {myWS->factory("CMS_vhbb_BDT_ZnunuLowPt_8TeV[-1.,1.]"); bins = 24;} else if(fname.Contains ("Zn") && (Bin == 1)) {myWS->factory("CMS_vhbb_BDT_ZnunuMedPt_8TeV[-1.,1.]"); bins = 32;} else if(fname.Contains ("Zn") && (Bin == 2)) {myWS->factory("CMS_vhbb_BDT_ZnunuHighPt_8TeV[-1.,1.]"); bins = 40;} else if(fname.Contains("We") | fname.Contains("Wm")) {myWS->factory("CMS_vhbb_BDT_Wln_8TeV[-1.,1.]"); bins = 48;} else if(fname.Contains("Wt")) {myWS->factory("BDT[-1.,1.]"); bins = 18;} RooWorkspace *tempWS = (RooWorkspace*) file->Get(myRooWS.Data()); for(int s=0; s<NS; s++ ){ makeSystPlot(tempWS, myWS, systs[s], Bin, toMass, fromMass ); } myWS->writeToFile(outname.Data()); std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl; std::cout << outname.Data() << " written" << std::endl; std::cout << "///////////////////////////" << std::endl << std::endl << std::endl; outfile->Write(); outfile->Close(); }
void makeDataset( TString fname, TString tname, TString outfname ) { RooWorkspace *w = new RooWorkspace("w","w"); w->factory( "Dst_M[1950.,2070.]" ); w->factory( "D0_M[1810.,1920.]" ); w->factory( "D0_LTIME_ps[0.00,5.]" ); RooArgSet *observables = new RooArgSet(); observables->add( *w->var("Dst_M") ); observables->add( *w->var("D0_M") ); observables->add( *w->var("D0_LTIME_ps") ); w->defineSet("observables", *observables); w->var("Dst_M")->setBins(240); w->var("D0_M")->setBins(220); w->var("D0_LTIME_ps")->setBins(200); double Dst_M = -999.; double D0_M = -999.; double D0_LTIME_ps = -999.; TFile *tf = TFile::Open(fname); TTree *tree = (TTree*)tf->Get(tname); tree->SetBranchAddress( "Dst_M", &Dst_M ); tree->SetBranchAddress( "D0_M" , &D0_M ); tree->SetBranchAddress( "D0_LTIME_ps", &D0_LTIME_ps ); RooDataSet *data = new RooDataSet("Data","Data",*observables); RooDataHist *dataH = new RooDataHist("DataHist","Data",*observables); for ( int ev=0; ev<tree->GetEntries(); ev++) { tree->GetEntry(ev); if ( ev%10000 == 0 ) cout << ev << " / " << tree->GetEntries() << endl; if ( Dst_M < w->var("Dst_M")->getMin() || Dst_M > w->var("Dst_M")->getMax() ) continue; if ( D0_M < w->var("D0_M")->getMin() || D0_M > w->var("D0_M")->getMax() ) continue; if ( D0_LTIME_ps < w->var("D0_LTIME_ps")->getMin() || D0_LTIME_ps > w->var("D0_LTIME_ps")->getMax() ) continue; w->var("Dst_M")->setVal(Dst_M); w->var("D0_M")->setVal(D0_M); w->var("D0_LTIME_ps")->setVal(D0_LTIME_ps); data->add( *observables ); dataH->add( *observables ); } tf->Close(); w->import(*data); w->import(*dataH); w->writeToFile(outfname); }
void Zbi_Zgamma() { // Make model for prototype on/off problem // Pois(x | s+b) * Pois(y | tau b ) // for Z_Gamma, use uniform prior on b. RooWorkspace* w = new RooWorkspace("w",true); w->factory("Poisson::px(x[150,0,500],sum::splusb(s[0,0,100],b[100,0,300]))"); w->factory("Poisson::py(y[100,0,500],prod::taub(tau[1.],b))"); w->factory("Uniform::prior_b(b)"); // construct the Bayesian-averaged model (eg. a projection pdf) // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ] w->factory("PROJ::averagedModel(PROD::foo(px|b,py,prior_b),b)") ; // plot it, blue is averaged model, red is b known exactly RooPlot* frame = w->var("x")->frame() ; w->pdf("averagedModel")->plotOn(frame) ; w->pdf("px")->plotOn(frame,LineColor(kRed)) ; frame->Draw() ; // compare analytic calculation of Z_Bi // with the numerical RooFit implementation of Z_Gamma // for an example with x = 150, y = 100 // numeric RooFit Z_Gamma w->var("y")->setVal(100); w->var("x")->setVal(150); RooAbsReal* cdf = w->pdf("averagedModel")->createCdf(*w->var("x")); cdf->getVal(); // get ugly print messages out of the way cout << "Hybrid p-value = " << cdf->getVal() << endl; cout << "Z_Gamma Significance = " << PValueToSignificance(1-cdf->getVal()) << endl; // analytic Z_Bi double Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(150, 100, 1); std::cout << "Z_Bi significance estimation: " << Z_Bi << std::endl; // OUTPUT // Hybrid p-value = 0.999058 // Z_Gamma Significance = 3.10804 // Z_Bi significance estimation: 3.10804 }
void Process(TString fname, TString oldFolder, int toMass, int fromMass) { std::string channels[] = {"data_obs", "VH", "TT", "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top", "QCD"}; std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" }; kount = 0; gROOT->SetStyle("Plain"); setTDRStyle(); TFile * file = new TFile(fname.Data(), "READ"); std::cout << "reading " << fname.Data() << std::endl; TString outname(massS[toMass]); outname.Append(".root"); fname.ReplaceAll(".root",outname.Data()); TFile * outfile = new TFile(fname.Data(), "RECREATE"); using namespace RooFit; RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data()); myWS->factory("CMS_vhbb_BDT_Zll[-1.,1.]"); ///NEW VARIABLE NAME HERE for (int c =0; c<10; c++) { kount2 = 0; for (int s =0; s<5 ; s++ ){ makeSystPlot( file, oldFolder, myWS, channels[c], systs[s], toMass, fromMass ); } } myWS->writeToFile(fname.Data()); std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl; std::cout << fname.Data() << " written" << std::endl; std::cout << "///////////////////////////" << std::endl << std::endl << std::endl; outfile->Write(); outfile->Close(); }
void new_RA4(){ // let's time this challenging example TStopwatch t; t.Start(); // set RooFit random seed for reproducible results RooRandom::randomGenerator()->SetSeed(4357); // make model RooWorkspace* wspace = new RooWorkspace("wspace"); wspace->factory("Gaussian::sigCons(prime_SigEff[0,-5,5], nom_SigEff[0,-5,5], 1)"); wspace->factory("expr::SigEff('1.0*pow(1.20,@0)',prime_SigEff)"); // // 1+-20%, 1.20=exp(20%) wspace->factory("Poisson::on(non[0,50], sum::splusb(prod::SigUnc(s[0,0,50],SigEff),mainb[8.8,0,50],dilep[0.9,0,20],tau[2.3,0,20],QCD[0.,0,10],MC[0.1,0,4]))"); wspace->factory("Gaussian::mcCons(prime_rho[0,-5,5], nom_rho[0,-5,5], 1)"); wspace->factory("expr::rho('1.0*pow(1.39,@0)',prime_rho)"); // // 1+-39% wspace->factory("Poisson::off(noff[0,200], prod::rhob(mainb,rho,mu_plus_e[0.74,0.01,10],1.08))"); wspace->factory("Gaussian::mcCons2(mu_plus_enom[0.74,0.01,4], mu_plus_e, sigmatwo[.05])"); wspace->factory("Gaussian::dilep_pred(dilep_nom[0.9,0,20], dilep, sigma3[2.2])"); wspace->factory("Gaussian::tau_pred(tau_nom[2.3,0,20], tau, sigma4[0.5])"); wspace->factory("Gaussian::QCD_pred(QCD_nom[0.0,0,10], QCD, sigma5[1.0])"); wspace->factory("Gaussian::MC_pred(MC_nom[0.1,0.01,4], MC, sigma7[0.14])"); wspace->factory("PROD::model(on,off,mcCons,mcCons2,sigCons,dilep_pred,tau_pred,QCD_pred,MC_pred)"); RooArgSet obs(*wspace->var("non"), *wspace->var("noff"), *wspace->var("mu_plus_enom"), *wspace->var("dilep_nom"), *wspace->var("tau_nom"), "obs"); obs.add(*wspace->var("QCD_nom")); obs.add(*wspace->var("MC_nom")); RooArgSet globalObs(*wspace->var("nom_SigEff"), *wspace->var("nom_rho"), "global_obs"); // fix global observables to their nominal values wspace->var("nom_SigEff")->setConstant(); wspace->var("nom_rho")->setConstant(); RooArgSet poi(*wspace->var("s"), "poi"); RooArgSet nuis(*wspace->var("mainb"), *wspace->var("prime_rho"), *wspace->var("prime_SigEff"), *wspace->var("mu_plus_e"), *wspace->var("dilep"), *wspace->var("tau"), "nuis"); nuis.add(*wspace->var("QCD")); nuis.add(*wspace->var("MC")); wspace->factory("Uniform::prior_poi({s})"); wspace->factory("Uniform::prior_nuis({mainb,mu_plus_e,dilep,tau,QCD,MC})"); wspace->factory("PROD::prior(prior_poi,prior_nuis)"); wspace->var("non")->setVal(8); //observed //wspace->var("non")->setVal(12); //expected observation wspace->var("noff")->setVal(7); //observed events in control region wspace->var("mu_plus_enom")->setVal(0.74); wspace->var("dilep_nom")->setVal(0.9); wspace->var("tau_nom")->setVal(2.3); wspace->var("QCD")->setVal(0.0); wspace->var("MC")->setVal(0.1); RooDataSet * data = new RooDataSet("data","",obs); data->add(obs); wspace->import(*data); ///////////////////////////////////////////////////// // Now the statistical tests // model config ModelConfig* pSbModel = new ModelConfig("SbModel"); pSbModel->SetWorkspace(*wspace); pSbModel->SetPdf(*wspace->pdf("model")); pSbModel->SetPriorPdf(*wspace->pdf("prior")); pSbModel->SetParametersOfInterest(poi); pSbModel->SetNuisanceParameters(nuis); pSbModel->SetObservables(obs); pSbModel->SetGlobalObservables(globalObs); wspace->import(*pSbModel); // set all but obs, poi and nuisance to const SetConstants(wspace, pSbModel); wspace->import(*pSbModel); Double_t poiValueForBModel = 0.0; ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)wspace->obj("SbModel")); pBModel->SetName("BModel"); pBModel->SetWorkspace(*wspace); wspace->import(*pBModel); RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*data); RooAbsReal * pProfile = pNll->createProfile(RooArgSet()); pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values RooArgSet * pPoiAndNuisance = new RooArgSet(); //if(pSbModel->GetNuisanceParameters()) // pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest()); cout << "\nWill save these parameter points that correspond to the fit to data" << endl; pPoiAndNuisance->Print("v"); pSbModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; pNll = pBModel->GetPdf()->createNLL(*data); pProfile = pNll->createProfile(poi); ((RooRealVar *)poi.first())->setVal(poiValueForBModel); pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet(); //if(pBModel->GetNuisanceParameters()) // pPoiAndNuisance->add(*pBModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pBModel->GetParametersOfInterest()); cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl; pPoiAndNuisance->Print("v"); pBModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // inspect workspace wspace->Print(); // save workspace to file wspace->writeToFile("tight.root"); //wspace->writeToFile("tight_median.root"); // clean up delete wspace; delete data; delete pSbModel; delete pBModel; }
void MakeWorkspace(const TString& channel, const TString& strategy) { TString dcname = g_dcname; TString wsname = g_wsname; TString realvarname = g_realvarname; TString rootname = g_rootname; TString pdfname = g_pdfname; dcname .ReplaceAll("$CHANNEL", channel); wsname .ReplaceAll("$CHANNEL", channel); realvarname .ReplaceAll("$CHANNEL", channel); rootname .ReplaceAll("$CHANNEL", channel); pdfname .ReplaceAll("$CHANNEL", channel); RooWorkspace * ws = new RooWorkspace(channel + "_8TeV", channel + "_8TeV"); ws->factory(Form("%s[%.2f,%.2f]", realvarname.Data(), g_xlow, g_xup)); RooRealVar * realvar = ws->var(realvarname.Data()); RooArgList * obs = new RooArgList(*realvar); TFile * input = TFile::Open(rootname, "READ"); TH1F * h(0); if (strategy == "blind") { h = (TH1F *) input->Get(channel + "/" + "mc_exp"); } else if (strategy == "injectsignal") { h = (TH1F *) input->Get(channel + "/" + "mc_exp"); TH1F * hZH = (TH1F *) input->Get(channel + "/" + "ZH_SM"); h->Add(hZH); TH1F * hWH = (TH1F *) input->Get(channel + "/" + "WH_SM"); h->Add(hWH); delete hZH; delete hWH; } else if (strategy == "real") { h = (TH1F *) input->Get(channel + "/" + "data_obs"); } else { std::cerr << "Unknown strategy: " << strategy << std::endl; } if (strategy != "real") gSystem->Exec(Form("sed -i 's/observation.*/observation %.3f/' %s ", h->Integral(), dcname.Data())); // data_obs RooDataHist * dh = new RooDataHist("data_obs", "", *obs, h); ws->import(*dh); delete dh; delete h; // no systematics for (Int_t p=0; p < jmax+1; p++) { const TString& process = g_processes[p]; h = (TH1F *) input->Get(channel + "/" + process); dh = new RooDataHist(process, "", *obs, h); ws->import(*dh); delete dh; delete h; } // with systematics up/down TCanvas * c1 = new TCanvas("c1", "c1", 700, 700); c1->SetLogy(); c1->Print(pdfname+"["); for (Int_t p=0; p < jmax+1; p++) { for (Int_t s=1; s < nsyst; s+=2) { MakeSystPlot(channel, input, ws, obs, p, s, s+1); } } c1->Print(pdfname+"]"); delete c1; ws->writeToFile(wsname, kTRUE); delete input; delete ws; return; }
int main (int argc, char **argv) { const char* chInFile = "ws.root"; const char* chOutFile = "ws_gen.root"; int numSignal = 10000; int numBkg = 100000; char option_char; while ( (option_char = getopt(argc,argv, "i:o:s:b:")) != EOF ) switch (option_char) { case 'i': chInFile = optarg; break; case 'o': chOutFile = optarg; break; case 's': numSignal = atoi(optarg); break; case 'b': numBkg = atoi(optarg); break; case '?': fprintf (stderr, "usage: %s [i<input file> o<output file>]\n", argv[0]); } cout << "In File = " << chInFile << endl; cout << "Out File = " << chOutFile << endl; cout << "Signal Events = " << numSignal << endl; cout << "Bkg Events = " << numBkg << endl; TFile inFile(chInFile,"READ"); RooWorkspace* ws = (RooWorkspace*) inFile.Get("rws"); TFile outFile(chOutFile,"RECREATE"); /* ws->var("tau")->setVal(1.417); ws->var("DG")->setVal(0.151); ws->var("beta")->setVal(0.25); ws->var("A02")->setVal(0.553); ws->var("A1")->setVal(0.487); ws->var("delta_l")->setVal(3.15); ws->var("fs")->setVal(0.147); */ // ws->var("delta_l")->setConstant(kTRUE); // ws->var("delta_p")->setConstant(kTRUE); // ws->var("Dm")->setConstant(kTRUE); //*ws->var("xs") = numSignal/(numSignal+numBkg); // int numSignal = numEvents * ws->var("xs")->getVal(); // int numBkg = numEvents - numSignal; ws->factory("Gaussian::dilutionGauss(d,0,0.276)"); //ws->factory("SUM::dSignalPDF(xds[0.109]*dilutionGauss,TruthModel(d))"); //ws->factory("SUM::dBkgPDF(xdb[0.109]*dilutionGauss,TruthModel(d))"); ws->factory("SUM::dSignalPDF(xds[1]*dilutionGauss,TruthModel(d))"); ws->factory("SUM::dBkgPDF(xdb[1]*dilutionGauss,TruthModel(d))"); /* ws->factory("GaussModel::xetGaussianS(et,meanGaussEtS,sigmaGaussEtS)"); ws->factory("Decay::xerrorSignal(et,tauEtS,xetGaussianS,SingleSided]"); ws->factory("PROD::xsignalTimeAngle(timeAngle|et,xerrorSignal"); ws->factory("PROD::xsignal(massSignal,xsignalTimeAngle,DmConstraint)"); */ RooDataSet* dSignalData = ws->pdf("dSignalPDF")->generate(RooArgSet(*ws->var("d")),numSignal); RooDataSet *dataSignal = ws->pdf("signal")->generate(RooArgSet(*ws->var("m"),*ws->var("t"),*ws->var("et"),*ws->var("cpsi"),*ws->var("ctheta"),*ws->var("phi")), RooFit::ProtoData(*dSignalData)); ws->factory("GaussModel::xetGaussianPR(et,meanGaussEtPR,sigmaGaussEtPR)"); ws->factory("Decay::xerrBkgPR(et,tauEtPR,xetGaussianPR,SingleSided]"); ws->factory("GaussModel::xetGaussianNP(et,meanGaussEtNP,sigmaGaussEtNP)"); ws->factory("Decay::xerrBkgNP(et,tauEtNP,xetGaussianNP,SingleSided]"); /* Time */ ws->factory("GaussModel::xresolution(t,0,scale,et)"); ws->factory("Decay::xnegativeDecay(t,tauNeg,xresolution,Flipped)"); ws->factory("Decay::xpositiveDecay(t,tauPos,xresolution,SingleSided)"); ws->factory("Decay::xpositiveLongDecay(t,tauLngPos,xresolution,SingleSided)"); ws->factory("RSUM::xtBkgNP(xn*xnegativeDecay,xp*xpositiveDecay,xpositiveLongDecay"); /* Promt and Non-Prompt */ ws->factory("PROD::xtimeBkgNP(xtBkgNP|et,xerrBkgNP)"); ws->factory("PROD::xtimeBkgPR(xresolution|et,xerrBkgPR)"); ws->factory("PROD::xPrompt(massBkgPR,xtimeBkgPR,anglePR)"); ws->factory("PROD::xNonPrompt(massBkgNP,xtimeBkgNP,angleNP)"); ws->factory("SUM::xbackground(xprompt*xPrompt,xNonPrompt)"); RooDataSet* dBkgData = ws->pdf("dBkgPDF")->generate(RooArgSet(*ws->var("d")),numBkg); RooDataSet* dataBkg = ws->pdf("xbackground")->generate(RooArgSet(*ws->var("m"),*ws->var("t"),*ws->var("et"),*ws->var("cpsi"),*ws->var("ctheta"),*ws->var("phi")), numBkg); dataBkg->merge(dBkgData); dataSignal->SetName("dataGenSignal"); dataBkg->SetName("dataGenBkg"); ws->import(*dataSignal); ws->import(*dataBkg); ////ws->import(*dataBkg,RooFit::Rename("dataGenBkg")); dataSignal->append(*dataBkg); dataSignal->SetName("dataGen"); ws->import(*dataSignal); //RooFitResult *fit_result = ws->pdf("model")->fitTo(*ws->data("data"), RooFit::Save(kTRUE), RooFit::ConditionalObservables(*ws->var("d")), RooFit::NumCPU(2), RooFit::PrintLevel(3)); /* gROOT->SetStyle("Plain"); TCanvas canvas("canvas", "canvas", 400,400); RooPlot *m_frame = ws->var("t")->frame(); dataSignal->plotOn(m_frame, RooFit::MarkerSize(0.3)); m_frame->Draw(); canvas.SaveAs("m_toy_plot.png"); */ /* gROOT->SetStyle("Plain"); TCanvas canvas("canvas", "canvas", 800,400); canvas.Divide(2); canvas.cd(1); RooPlot *t_frame = ws->var("t")->frame(); ws->data("data")->plotOn(t_frame, RooFit::MarkerSize(0.3)); gPad->SetLogy(1); t_frame->Draw(); canvas.cd(2); RooPlot *et_frame = ws->var("et")->frame(); ws->data("data")->plotOn(et_frame,RooFit::MarkerSize(0.2)); ws->pdf("errorSignal")->plotOn(et_frame); gPad->SetLogy(1); et_frame->Draw(); canvas.SaveAs("t.png"); canvas.cd(2); gPad->SetLogy(0); RooPlot *cpsi_frame = ws.var("cpsi")->frame(); data->plotOn(cpsi_frame,RooFit::MarkerSize(0.2), RooFit::Rescale(1)); data2->plotOn(cpsi_frame, RooFit::LineColor(kBlue), RooFit::DrawOption("L")); cpsi_frame->Draw(); canvas.cd(3); RooPlot *ctheta_frame = ws.var("ctheta")->frame(); data->plotOn(ctheta_frame,RooFit::MarkerSize(0.2), RooFit::Rescale(1)); data2->plotOn(ctheta_frame, RooFit::LineColor(kBlue), RooFit::DrawOption("L")); ctheta_frame->Draw(); canvas.cd(4); RooPlot *phi_frame = ws.var("phi")->frame(); data->plotOn(phi_frame,RooFit::MarkerSize(0.2), RooFit::Rescale(1)); data2->plotOn(phi_frame, RooFit::LineColor(kBlue), RooFit::DrawOption("L")); phi_frame->Draw(); canvas.SaveAs("t.png"); */ ws->data("dataGen")->Print(); ws->data("dataGenSignal")->Print(); ws->data("dataGenBkg")->Print(); ws->Write("rws"); outFile.Close(); inFile.Close(); }
vector<Double_t*> simFit(bool makeSoupFit_ = false, const string tnp_ = "etoTauMargLooseNoCracks70", const string category_ = "tauAntiEMVA", const string bin_ = "abseta<1.5", const float binCenter_ = 0.75, const float binWidth_ = 0.75, const float xLow_=60, const float xHigh_=120, bool SumW2_ = false, bool verbose_ = true){ vector<Double_t*> out; //return out; //TFile *test = new TFile( outFile->GetName(),"UPDATE"); // output file TFile *test = new TFile( Form("EtoTauPlotsFit_%s_%s_%f.root",tnp_.c_str(),category_.c_str(),binCenter_),"RECREATE"); test->mkdir(Form("bin%f",binCenter_)); TCanvas *c = new TCanvas("fitCanvas",Form("fitCanvas_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600); c->SetGrid(0,0); c->SetFillStyle(4000); c->SetFillColor(10); c->SetTicky(); c->SetObjectStat(0); TCanvas *c2 = new TCanvas("fitCanvasTemplate",Form("fitCanvasTemplate_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600); c2->SetGrid(0,0); c2->SetFillStyle(4000); c2->SetFillColor(10); c2->SetTicky(); c2->SetObjectStat(0); // input files TFile fsup("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup.root"); TFile fbkg("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_bkg.root"); TFile fsgn("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_sgn.root"); TFile fdat("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_Data.root"); // data from 2iter: //TFile fdat("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_Data.root"); //********************** signal only tree *************************/ TTree *fullTreeSgn = (TTree*)fsgn.Get((tnp_+"/fitter_tree").c_str()); TH1F* hSall = new TH1F("hSall","",1,0,150); TH1F* hSPall = new TH1F("hSPall","",1,0,150); TH1F* hS = new TH1F("hS","",1,0,150); TH1F* hSP = new TH1F("hSP","",1,0,150); fullTreeSgn->Draw("mass>>hS",Form("weight*(%s && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5)",bin_.c_str(),xLow_,xHigh_)); fullTreeSgn->Draw("mass>>hSall",Form("weight*(%s && mass>%f && mass<%f)",bin_.c_str(),xLow_,xHigh_)); float SGNtrue = hS->Integral(); float SGNall = hSall->Integral(); fullTreeSgn->Draw("mass>>hSP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_)); fullTreeSgn->Draw("mass>>hSPall",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_)); float SGNtruePass = hSP->Integral(); float SGNallPass = hSPall->Integral(); //********************** background only tree *************************// TTree *fullTreeBkg = (TTree*)fbkg.Get((tnp_+"/fitter_tree").c_str()); TH1F* hB = new TH1F("hB","",1,0,150); TH1F* hBP = new TH1F("hBP","",1,0,150); fullTreeBkg->Draw("mass>>hB",Form("weight*(%s && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),xLow_,xHigh_)); float BKG = hB->Integral(); float BKGUnWeighted = hB->GetEntries(); fullTreeBkg->Draw("mass>>hBP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_)); float BKGPass = hBP->Integral(); float BKGUnWeightedPass = hBP->GetEntries(); float BKGFail = BKG-BKGPass; cout << "*********** BKGFail " << BKGFail << endl; //********************** soup tree *************************// TTree *fullTreeSoup = (TTree*)fsup.Get((tnp_+"/fitter_tree").c_str()); //********************** data tree *************************// TTree *fullTreeData = (TTree*)fdat.Get((tnp_+"/fitter_tree").c_str()); //********************** workspace ***********************// RooWorkspace *w = new RooWorkspace("w","w"); // tree variables to be imported w->factory("mass[30,120]"); w->factory("weight[0,10000]"); w->factory("abseta[0,2.5]"); w->factory("pt[0,200]"); w->factory("mcTrue[0,1]"); w->factory("signalPFChargedHadrCands[0,10]"); w->factory((category_+"[0,1]").c_str()); // background pass pdf for MC w->factory("RooExponential::McBackgroundPdfP(mass,McCP[0,-10,10])"); // background fail pdf for MC w->factory("RooExponential::McBackgroundPdfF(mass,McCF[0,-10,10])"); // background pass pdf for Data w->factory("RooExponential::DataBackgroundPdfP(mass,DataCP[0,-10,10])"); // background fail pdf for Data w->factory("RooExponential::DataBackgroundPdfF(mass,DataCF[0,-10,10])"); // fit parameters for background w->factory("McEfficiency[0.04,0,1]"); w->factory("McNumSgn[0,1000000]"); w->factory("McNumBkgP[0,100000]"); w->factory("McNumBkgF[0,100000]"); w->factory("expr::McNumSgnP('McEfficiency*McNumSgn',McEfficiency,McNumSgn)"); w->factory("expr::McNumSgnF('(1-McEfficiency)*McNumSgn',McEfficiency,McNumSgn)"); w->factory("McPassing[pass=1,fail=0]"); // fit parameters for data w->factory("DataEfficiency[0.1,0,1]"); w->factory("DataNumSgn[0,1000000]"); w->factory("DataNumBkgP[0,1000000]"); w->factory("DataNumBkgF[0,10000]"); w->factory("expr::DataNumSgnP('DataEfficiency*DataNumSgn',DataEfficiency,DataNumSgn)"); w->factory("expr::DataNumSgnF('(1-DataEfficiency)*DataNumSgn',DataEfficiency,DataNumSgn)"); w->factory("DataPassing[pass=1,fail=0]"); RooRealVar *weight = w->var("weight"); RooRealVar *abseta = w->var("abseta"); RooRealVar *pt = w->var("pt"); RooRealVar *mass = w->var("mass"); mass->setRange(xLow_,xHigh_); RooRealVar *mcTrue = w->var("mcTrue"); RooRealVar *cut = w->var( category_.c_str() ); RooRealVar *signalPFChargedHadrCands = w->var("signalPFChargedHadrCands"); // build the template for the signal pass sample: RooDataSet templateP("templateP","dataset for signal-pass template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) ); // build the template for the signal fail sample: RooDataSet templateF("templateF","dataset for signal-fail template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) ); mass->setBins(24); RooDataHist templateHistP("templateHistP","",RooArgSet(*mass), templateP, 1.0); RooHistPdf TemplateSignalPdfP("TemplateSignalPdfP","",RooArgSet(*mass),templateHistP); w->import(TemplateSignalPdfP); mass->setBins(24); RooDataHist templateHistF("templateHistF","",RooArgSet(*mass),templateF,1.0); RooHistPdf TemplateSignalPdfF("TemplateSignalPdfF","",RooArgSet(*mass),templateHistF); w->import(TemplateSignalPdfF); mass->setBins(10000,"fft"); RooPlot* TemplateFrameP = mass->frame(Bins(24),Title("Template passing")); templateP.plotOn(TemplateFrameP); w->pdf("TemplateSignalPdfP")->plotOn(TemplateFrameP); RooPlot* TemplateFrameF = mass->frame(Bins(24),Title("Template failing")); templateF.plotOn(TemplateFrameF); w->pdf("TemplateSignalPdfF")->plotOn(TemplateFrameF); //w->factory("RooFFTConvPdf::McSignalPdfP(mass,TemplateSignalPdfP,RooTruthModel::McResolModP(mass))"); //w->factory("RooFFTConvPdf::McSignalPdfF(mass,TemplateSignalPdfF,RooTruthModel::McResolModF(mass))"); // FOR GREGORY: PROBLEM WHEN TRY TO USE THE PURE TEMPLATE => RooHistPdf McSignalPdfP("McSignalPdfP","McSignalPdfP",RooArgSet(*mass),templateHistP); RooHistPdf McSignalPdfF("McSignalPdfF","McSignalPdfF",RooArgSet(*mass),templateHistF); w->import(McSignalPdfP); w->import(McSignalPdfF); // FOR GREGORY: FOR DATA, CONVOLUTION IS OK => w->factory("RooFFTConvPdf::DataSignalPdfP(mass,TemplateSignalPdfP,RooGaussian::DataResolModP(mass,DataMeanResP[0.0,-5.,5.],DataSigmaResP[0.5,0.,10]))"); w->factory("RooFFTConvPdf::DataSignalPdfF(mass,TemplateSignalPdfF,RooGaussian::DataResolModF(mass,DataMeanResF[-5.,-10.,10.],DataSigmaResF[0.5,0.,10]))"); //w->factory("RooCBShape::DataSignalPdfF(mass,DataMeanF[91.2,88,95.],DataSigmaF[3,0.5,8],DataAlfaF[1.8,0.,10],DataNF[1.0,1e-06,10])"); //w->factory("RooFFTConvPdf::DataSignalPdfF(mass,RooVoigtian::DataVoigF(mass,DataMeanF[85,80,95],DataWidthF[2.49],DataSigmaF[3,0.5,10]),RooCBShape::DataResolModF(mass,DataMeanResF[0.5,0.,10.],DataSigmaResF[0.5,0.,10],DataAlphaResF[0.5,0.,10],DataNResF[1.0,1e-06,10]))"); //w->factory("SUM::DataSignalPdfF(fVBP[0.5,0,1]*RooBifurGauss::bifF(mass,DataMeanResF[91.2,80,95],sigmaLF[10,0.5,40],sigmaRF[0.]), RooVoigtian::voigF(mass, DataMeanResF, widthF[2.49], sigmaVoigF[5,0.1,10]) )" ); // composite model pass for MC w->factory("SUM::McModelP(McNumSgnP*McSignalPdfP,McNumBkgP*McBackgroundPdfP)"); w->factory("SUM::McModelF(McNumSgnF*McSignalPdfF,McNumBkgF*McBackgroundPdfF)"); // composite model pass for data w->factory("SUM::DataModelP(DataNumSgnP*DataSignalPdfP,DataNumBkgP*DataBackgroundPdfP)"); w->factory("SUM::DataModelF(DataNumSgnF*DataSignalPdfF,DataNumBkgF*DataBackgroundPdfF)"); // simultaneous fir for MC w->factory("SIMUL::McModel(McPassing,pass=McModelP,fail=McModelF)"); // simultaneous fir for data w->factory("SIMUL::DataModel(DataPassing,pass=DataModelP,fail=DataModelF)"); w->Print("V"); w->saveSnapshot("clean", w->allVars()); w->loadSnapshot("clean"); /****************** sim fit to soup **************************/ /////////////////////////////////////////////////////////////// TFile *f = new TFile("dummySoup.root","RECREATE"); TTree* cutTreeSoupP = fullTreeSoup->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str())); TTree* cutTreeSoupF = fullTreeSoup->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str())); RooDataSet McDataP("McDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeSoupP ) ); RooDataSet McDataF("McDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeSoupF ) ); RooDataHist McCombData("McCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("McPassing"))), Import("pass", *(McDataP.createHistogram("histoP",*mass)) ), Import("fail",*(McDataF.createHistogram("histoF",*mass)) ) ) ; RooPlot* McFrameP = 0; RooPlot* McFrameF = 0; RooRealVar* McEffFit = 0; if(makeSoupFit_){ cout << "**************** N bins in mass " << w->var("mass")->getBins() << endl; RooFitResult* ResMcCombinedFit = w->pdf("McModel")->fitTo(McCombData, Extended(1), Minos(1), Save(1), SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4) /*, ExternalConstraints( *(w->pdf("ConstrainMcNumBkgF")) )*/ ); test->cd(Form("bin%f",binCenter_)); ResMcCombinedFit->Write("McFitResults_Combined"); RooArgSet McFitParam(ResMcCombinedFit->floatParsFinal()); McEffFit = (RooRealVar*)(&McFitParam["McEfficiency"]); RooRealVar* McNumSigFit = (RooRealVar*)(&McFitParam["McNumSgn"]); RooRealVar* McNumBkgPFit = (RooRealVar*)(&McFitParam["McNumBkgP"]); RooRealVar* McNumBkgFFit = (RooRealVar*)(&McFitParam["McNumBkgF"]); McFrameP = mass->frame(Bins(24),Title("MC: passing sample")); McCombData.plotOn(McFrameP,Cut("McPassing==McPassing::pass")); w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_)); w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_)); w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfP"), LineColor(kGreen),Range(xLow_,xHigh_)); McFrameF = mass->frame(Bins(24),Title("MC: failing sample")); McCombData.plotOn(McFrameF,Cut("McPassing==McPassing::fail")); w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_)); w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_)); w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfF"), LineColor(kGreen),Range(xLow_,xHigh_)); } /////////////////////////////////////////////////////////////// /****************** sim fit to data **************************/ /////////////////////////////////////////////////////////////// TFile *f2 = new TFile("dummyData.root","RECREATE"); TTree* cutTreeDataP = fullTreeData->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str())); TTree* cutTreeDataF = fullTreeData->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str())); RooDataSet DataDataP("DataDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeDataP ) ); RooDataSet DataDataF("DataDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeDataF ) ); RooDataHist DataCombData("DataCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("DataPassing"))), Import("pass",*(DataDataP.createHistogram("histoDataP",*mass))),Import("fail",*(DataDataF.createHistogram("histoDataF",*mass)))) ; RooFitResult* ResDataCombinedFit = w->pdf("DataModel")->fitTo(DataCombData, Extended(1), Minos(1), Save(1), SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4)); test->cd(Form("bin%f",binCenter_)); ResDataCombinedFit->Write("DataFitResults_Combined"); RooArgSet DataFitParam(ResDataCombinedFit->floatParsFinal()); RooRealVar* DataEffFit = (RooRealVar*)(&DataFitParam["DataEfficiency"]); RooRealVar* DataNumSigFit = (RooRealVar*)(&DataFitParam["DataNumSgn"]); RooRealVar* DataNumBkgPFit = (RooRealVar*)(&DataFitParam["DataNumBkgP"]); RooRealVar* DataNumBkgFFit = (RooRealVar*)(&DataFitParam["DataNumBkgF"]); RooPlot* DataFrameP = mass->frame(Bins(24),Title("Data: passing sample")); DataCombData.plotOn(DataFrameP,Cut("DataPassing==DataPassing::pass")); w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_)); w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_)); w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfP"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_)); RooPlot* DataFrameF = mass->frame(Bins(24),Title("Data: failing sample")); DataCombData.plotOn(DataFrameF,Cut("DataPassing==DataPassing::fail")); w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_)); w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_)); w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfF"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_)); /////////////////////////////////////////////////////////////// if(makeSoupFit_) c->Divide(2,2); else c->Divide(2,1); c->cd(1); DataFrameP->Draw(); c->cd(2); DataFrameF->Draw(); if(makeSoupFit_){ c->cd(3); McFrameP->Draw(); c->cd(4); McFrameF->Draw(); } c->Draw(); test->cd(Form("bin%f",binCenter_)); c->Write(); c2->Divide(2,1); c2->cd(1); TemplateFrameP->Draw(); c2->cd(2); TemplateFrameF->Draw(); c2->Draw(); test->cd(Form("bin%f",binCenter_)); c2->Write(); // MINOS errors, otherwise HESSE quadratic errors float McErrorLo = 0; float McErrorHi = 0; if(makeSoupFit_){ McErrorLo = McEffFit->getErrorLo()<0 ? McEffFit->getErrorLo() : (-1)*McEffFit->getError(); McErrorHi = McEffFit->getErrorHi()>0 ? McEffFit->getErrorHi() : McEffFit->getError(); } float DataErrorLo = DataEffFit->getErrorLo()<0 ? DataEffFit->getErrorLo() : (-1)*DataEffFit->getError(); float DataErrorHi = DataEffFit->getErrorHi()>0 ? DataEffFit->getErrorHi() : DataEffFit->getError(); float BinomialError = TMath::Sqrt(SGNtruePass/SGNtrue*(1-SGNtruePass/SGNtrue)/SGNtrue); Double_t* truthMC = new Double_t[6]; Double_t* tnpMC = new Double_t[6]; Double_t* tnpData = new Double_t[6]; truthMC[0] = binCenter_; truthMC[1] = binWidth_; truthMC[2] = binWidth_; truthMC[3] = SGNtruePass/SGNtrue; truthMC[4] = BinomialError; truthMC[5] = BinomialError; if(makeSoupFit_){ tnpMC[0] = binCenter_; tnpMC[1] = binWidth_; tnpMC[2] = binWidth_; tnpMC[3] = McEffFit->getVal(); tnpMC[4] = (-1)*McErrorLo; tnpMC[5] = McErrorHi; } tnpData[0] = binCenter_; tnpData[1] = binWidth_; tnpData[2] = binWidth_; tnpData[3] = DataEffFit->getVal(); tnpData[4] = (-1)*DataErrorLo; tnpData[5] = DataErrorHi; out.push_back(truthMC); out.push_back(tnpData); if(makeSoupFit_) out.push_back(tnpMC); test->Close(); //delete c; delete c2; if(verbose_) cout << "returning from bin " << bin_ << endl; return out; }
void rs701_BayesianCalculator(bool useBkg = true, double confLevel = 0.90) { RooWorkspace* w = new RooWorkspace("w",true); w->factory("SUM::pdf(s[0.001,15]*Uniform(x[0,1]),b[1,0,2]*Uniform(x))"); w->factory("Gaussian::prior_b(b,1,1)"); w->factory("PROD::model(pdf,prior_b)"); RooAbsPdf* model = w->pdf("model"); // pdf*priorNuisance RooArgSet nuisanceParameters(*(w->var("b"))); RooAbsRealLValue* POI = w->var("s"); RooAbsPdf* priorPOI = (RooAbsPdf *) w->factory("Uniform::priorPOI(s)"); RooAbsPdf* priorPOI2 = (RooAbsPdf *) w->factory("GenericPdf::priorPOI2('1/sqrt(@0)',s)"); w->factory("n[3]"); // observed number of events // create a data set with n observed events RooDataSet data("data","",RooArgSet(*(w->var("x")),*(w->var("n"))),"n"); data.add(RooArgSet(*(w->var("x"))),w->var("n")->getVal()); // to suppress messgaes when pdf goes to zero RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ; RooArgSet * nuisPar = 0; if (useBkg) nuisPar = &nuisanceParameters; //if (!useBkg) ((RooRealVar *)w->var("b"))->setVal(0); double size = 1.-confLevel; std::cout << "\nBayesian Result using a Flat prior " << std::endl; BayesianCalculator bcalc(data,*model,RooArgSet(*POI),*priorPOI, nuisPar); bcalc.SetTestSize(size); SimpleInterval* interval = bcalc.GetInterval(); double cl = bcalc.ConfidenceLevel(); std::cout << cl <<"% CL central interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or " << cl+(1.-cl)/2 << "% CL limits\n"; RooPlot * plot = bcalc.GetPosteriorPlot(); TCanvas * c1 = new TCanvas("c1","Bayesian Calculator Result"); c1->Divide(1,2); c1->cd(1); plot->Draw(); c1->Update(); std::cout << "\nBayesian Result using a 1/sqrt(s) prior " << std::endl; BayesianCalculator bcalc2(data,*model,RooArgSet(*POI),*priorPOI2,nuisPar); bcalc2.SetTestSize(size); SimpleInterval* interval2 = bcalc2.GetInterval(); cl = bcalc2.ConfidenceLevel(); std::cout << cl <<"% CL central interval: [ " << interval2->LowerLimit() << " - " << interval2->UpperLimit() << " ] or " << cl+(1.-cl)/2 << "% CL limits\n"; RooPlot * plot2 = bcalc2.GetPosteriorPlot(); c1->cd(2); plot2->Draw(); gPad->SetLogy(); c1->Update(); // observe one event while expecting one background event -> the 95% CL upper limit on s is 4.10 // observe one event while expecting zero background event -> the 95% CL upper limit on s is 4.74 }
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; }
void PDF_GGSZ_ExpNLL::buildPdfParametric() { RooMsgService::instance().setGlobalKillBelow(ERROR); RooWorkspace *wExpNll = new RooWorkspace("wExpNll"); // // for B- // RooHistPdfVar *xm_pdf = new RooHistPdfVar("xm_pdf", "xm_pdf", *xm_obs, *xm_th, RooConst( 0.000+2.62345e-03)); RooHistPdfVar *ym_pdf = new RooHistPdfVar("ym_pdf", "ym_pdf", *ym_obs, *ym_th, RooConst( 0.027+1.88547e-03)); double xmp0wl = 0.0541675; double xmp1wl = 0.018955; double xmp2wl = 0.3075; double xmp3wl = -0.89035; double xmp4wl = -3.44858; RooPoly4Var *ymwidthl = new RooPoly4Var("ymwidthl", "ymwidthl", *xm_pdf, xmp0wl, xmp1wl, xmp2wl, xmp3wl, xmp4wl); double xmp0wr = 0.0494967; double xmp1wr = 0.0130424; double xmp2wr = 0.110901; double xmp3wr = -0.0796312; double xmp4wr = 0.204101; RooPoly4Var *ymwidthr = new RooPoly4Var("ymwidthr", "ymwidthr", *xm_pdf, xmp0wr, xmp1wr, xmp2wr, xmp3wr, xmp4wr); double xmp0m = 0.0292742; double xmp1m = -0.123769; double xmp2m = -0.39777; double xmp3m = 0.825458; RooPoly3Var *ymmean = new RooPoly3Var("ymmean", "ymmean", *xm_pdf, xmp0m, xmp1m, xmp2m, xmp3m); RooBifurGauss *ympdf = new RooBifurGauss("ympdf", "ympdf", *ym_pdf, *ymmean, *ymwidthl, *ymwidthr); wExpNll->import(*ympdf); wExpNll->factory("RooBifurGauss::xmpdf(xm_pdf, xmmean[2.58584e-03], xmwidthl[4.37123e-02], xmwidthr[4.37101e-02])"); wExpNll->factory("PROD::pdf_ggszexpnll_neg(xmpdf,ympdf)"); // // for B+ // RooHistPdfVar *xp_pdf = new RooHistPdfVar("xp_pdf", "xp_pdf", *xp_obs, *xp_th, RooConst(-0.103-5.74430e-03)); RooHistPdfVar *yp_pdf = new RooHistPdfVar("yp_pdf", "yp_pdf", *yp_obs, *yp_th, RooConst(-0.009-4.54284e-03)); double xpp0wl = 0.0292561; double xpp1wl = 0.0703944; double xpp2wl = -0.0922186; double xpp3wl = -11.8135; double xpp4wl = -34.8594; RooPoly4Var *ypwidthl = new RooPoly4Var("ypwidthl", "ypwidthl", *xp_pdf, xpp0wl, xpp1wl, xpp2wl, xpp3wl, xpp4wl); double xpp0wr = 0.0403016; double xpp1wr = 0.0367049; double xpp2wr = 0.535281; double xpp3wr = 2.29804; double xpp4wr = 5.37199; RooPoly4Var *ypwidthr = new RooPoly4Var("ypwidthr", "ypwidthr", *xp_pdf, xpp0wr, xpp1wr, xpp2wr, xpp3wr, xpp4wr); double xpp0m = -0.0133043; double xpp1m = -0.139777; double xpp2m = -1.38657; double xpp3m = -0.727225; RooPoly3Var *ypmean = new RooPoly3Var("ypmean", "ypmean", *xp_pdf, xpp0m, xpp1m, xpp2m, xpp3m); RooBifurGauss *yppdf = new RooBifurGauss("yppdf", "yppdf", *yp_pdf, *ypmean, *ypwidthl, *ypwidthr); wExpNll->import(*yppdf); wExpNll->factory("RooBifurGauss::xppdf(xp_pdf, xpmean[-1.08775e-01], xpwidthl[4.32573e-02], xpwidthr[4.93588e-02])"); wExpNll->factory("PROD::pdf_ggszexpnll_pos(xppdf,yppdf)"); // multiply both wExpNll->factory("PROD::pdf_"+name+"(pdf_ggszexpnll_neg,pdf_ggszexpnll_pos)"); pdf = wExpNll->pdf("pdf_"+name); RooMsgService::instance().setGlobalKillBelow(INFO); }
void check_fit_bias_sim(const int N=1, string infname="20140409_SimFits_M1850_DblMu0_AllCent/fracLogCBG_PbPbpol3_HI020_pol2_HI2040_pol2_HI40100_pppol2_rap16-24_pT3-30_centMult_Workspace.root") { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); TFile *inf = new TFile(infname.c_str(),"READ"); RooWorkspace *ws = (RooWorkspace*) inf->Get("workspace"); // ws->var("doubleRatio_HI020")->setConstant(true); // ws->var("doubleRatio_HI2040")->setConstant(true); // ws->var("doubleRatio_HI40100")->setConstant(true); RooRealVar *Jpsi_Mass = ws->var("Jpsi_Mass"); RooCategory *sample = ws->cat("sample"); // TIter types(ws->cat("sample")->typeIterator()); // RooCatType * type; // types.Reset(); RooDataSet * protoData = (RooDataSet*) ws->data("redDataSim"); RooDataSet * protoData_pp = (RooDataSet*) ws->data("data4"); RooDataSet * protoData_HI020 = (RooDataSet*) ws->data("data1"); RooDataSet * protoData_HI2040 = (RooDataSet*) ws->data("data2"); RooDataSet * protoData_HI40100 = (RooDataSet*) ws->data("data3"); // RooSimultaneous *model = (RooSimultaneous*) ws->pdf("sigMassPDFSim"); RooAbsPdf *model_pp = (RooAbsPdf*) ws->pdf("sigMassPDF_pp"); RooAbsPdf *model_HI020 = (RooAbsPdf*) ws->pdf("pdf_HI020"); RooAbsPdf *model_HI2040 = (RooAbsPdf*) ws->pdf("pdf_HI2040"); RooAbsPdf *model_HI40100 = (RooAbsPdf*) ws->pdf("pdf_HI40100"); // ws->var("sigma_pol")->setVal(0.0); // ws->var("sigma_b")->setVal(0.0); // ws->var("sigma_pol")->setConstant(true); // ws->var("sigma_b")->setConstant(true); // ws->var("sigma_fit_HI020")->setVal(0.0); // ws->var("sigma_eff_HI020")->setVal(0.0); // ws->var("sigma_fit_HI020")->setConstant(true); // ws->var("sigma_eff_HI020")->setConstant(true); // ws->var("sigma_fit_HI2040")->setVal(0.0); // ws->var("sigma_eff_HI2040")->setVal(0.0); // ws->var("sigma_fit_HI2040")->setConstant(true); // ws->var("sigma_eff_HI2040")->setConstant(true); // ws->var("sigma_fit_HI40100")->setVal(0.0); // ws->var("sigma_eff_HI40100")->setVal(0.0); // ws->var("sigma_fit_HI40100")->setConstant(true); // ws->var("sigma_eff_HI40100")->setConstant(true); RooPlot *frame = Jpsi_Mass->frame(Range("M2242")); protoData->plotOn(frame, Cut("sample==sample::pp")); protoData->plotOn(frame, Cut("sample==sample::HI020"), MarkerColor(kRed)); protoData->plotOn(frame, Cut("sample==sample::HI2040"), MarkerStyle(25), MarkerColor(kBlue)); protoData->plotOn(frame, Cut("sample==sample::HI40100"), MarkerStyle(24), MarkerColor(kGreen+2)); // model->plotOn(frame, Slice(*sample,"pp"), ProjWData(*sample,*protoData)); TCanvas *c0 = new TCanvas("c0","c0"); c0->cd(); frame->Draw(); // return; // ws->pdf("sigMassPDF_M2242")->plotOn(frame,Range("M2242")); // redData->plotOn(frame,MarkerStyle(24),MarkerColor(kRed),Range("M2242")); // while ((type=(RooCatType*)types.Next())) { // protoData = // (RooDataSet*)ws->data(TString::Format("data_%s", type->GetName())); // bkg = ws.pdf(TString::Format("expFunct_%s", type->GetName())); // if ((*type) == "HI") // N = Nhi; // else // N = Npp; // RooDataSet * tmpData = bkg->generate(RooArgSet(*Jpsi_mass), N, // RooFit::ProtoData(*protoData)); // osBkgData->append(*tmpData); // delete tmpData; // } // double Nevents = ws->var("NJpsi_pp")->getVal()+ws->function("NPsiP_pp")->getVal()+ws->var("NBkg_pp")->getVal(); TH1F *h0_pp = new TH1F("h0_pp","h0_pp;R_{#psi}^{pp};Events",1200,-0.3,0.3); TH1F *h1_pp = new TH1F("h1_pp","h1_pp;R_{#psi}^{pp};Events",1200,-0.3,0.3); TH2F *h2_pp = new TH2F("h2_pp","h2_pp;R_{#psi}^{pp} (M1850);R_{#psi}^{pp} (M2242)",600,-0.3,0.3,600,-0.3,0.3); h0_pp->Sumw2(); h1_pp->Sumw2(); h2_pp->Sumw2(); h1_pp->SetMarkerColor(2); h1_pp->SetLineColor(2); h0_pp->GetXaxis()->CenterTitle(true); h1_pp->GetXaxis()->CenterTitle(true); h2_pp->GetXaxis()->CenterTitle(true); TH1F *h0_HI020 = new TH1F("h0_HI020","h0_HI020;#chi_{#psi}^{HI020};Events",5000,-1.0,4.0); TH1F *h1_HI020 = new TH1F("h1_HI020","h1_HI020;#chi_{#psi}^{HI020};Events",5000,-1.0,4.0); TH2F *h2_HI020 = new TH2F("h2_HI020","h2_HI020;#chi_{#psi}^{HI020} (M1850);#chi_{#psi}^{HI020} (M2242)",500,-1,4,500,-1,4); h0_HI020->Sumw2(); h1_HI020->Sumw2(); h2_HI020->Sumw2(); h1_HI020->SetMarkerColor(2); h1_HI020->SetLineColor(2); h0_HI020->GetXaxis()->CenterTitle(true); h1_HI020->GetXaxis()->CenterTitle(true); h2_HI020->GetXaxis()->CenterTitle(true); TH1F *h0_HI2040 = new TH1F("h0_HI2040","h0_HI2040;#chi_{#psi}^{HI2040};Events",5000,-1.0,4.0); TH1F *h1_HI2040 = new TH1F("h1_HI2040","h1_HI2040;#chi_{#psi}^{HI2040};Events",5000,-1.0,4.0); TH2F *h2_HI2040 = new TH2F("h2_HI2040","h2_HI2040;#chi_{#psi}^{HI2040} (M1850);#chi_{#psi}^{HI2040} (M2242)",500,-1,4,500,-1,4); h0_HI2040->Sumw2(); h1_HI2040->Sumw2(); h2_HI2040->Sumw2(); h1_HI2040->SetMarkerColor(2); h1_HI2040->SetLineColor(2); h0_HI2040->GetXaxis()->CenterTitle(true); h1_HI2040->GetXaxis()->CenterTitle(true); h2_HI2040->GetXaxis()->CenterTitle(true); TH1F *h0_HI40100 = new TH1F("h0_HI40100","h0_HI40100;#chi_{#psi}^{HI40100};Events",5000,-1.0,4.0); TH1F *h1_HI40100 = new TH1F("h1_HI40100","h1_HI40100;#chi_{#psi}^{HI40100};Events",5000,-1.0,4.0); TH2F *h2_HI40100 = new TH2F("h2_HI40100","h2_HI40100;#chi_{#psi}^{HI40100} (M1850);#chi_{#psi}^{HI40100} (M2242)",500,-1,4,500,-1,4); h0_HI40100->Sumw2(); h1_HI40100->Sumw2(); h2_HI40100->Sumw2(); h1_HI40100->SetMarkerColor(2); h1_HI40100->SetLineColor(2); h0_HI40100->GetXaxis()->CenterTitle(true); h1_HI40100->GetXaxis()->CenterTitle(true); h2_HI40100->GetXaxis()->CenterTitle(true); TH1F *h0_HI0100 = new TH1F("h0_HI0100","h0_HI0100;#chi_{#psi}^{HI0100};Events",5000,-1.0,4.0); TH1F *h1_HI0100 = new TH1F("h1_HI0100","h1_HI0100;#chi_{#psi}^{HI0100};Events",5000,-1.0,4.0); TH2F *h2_HI0100 = new TH2F("h2_HI0100","h2_HI0100;#chi_{#psi}^{HI0100} (M1850);#chi_{#psi}^{HI0100} (M2242)",500,-1,4,500,-1,4); h0_HI0100->Sumw2(); h1_HI0100->Sumw2(); h2_HI0100->Sumw2(); h1_HI0100->SetMarkerColor(2); h1_HI0100->SetLineColor(2); h0_HI0100->GetXaxis()->CenterTitle(true); h1_HI0100->GetXaxis()->CenterTitle(true); h2_HI0100->GetXaxis()->CenterTitle(true); Jpsi_Mass->setRange("signal",3.6,3.76); Jpsi_Mass->setRange("M2045",2.0,4.5); Jpsi_Mass->setRange("M2242",2.2,4.2); RooFitResult *fitMall; RooFitResult *fitM; // RooFit cannot normalize Chebychev polynomials to a subrange (no analytic integral?) // using normal polynomials instead RooRealVar a("a","a",0.0);a.setConstant(false); RooRealVar b("b","b",0.01);b.setConstant(false); RooRealVar c("c","c",-0.005);c.setConstant(false); // mid // RooPolynomial bkg_pp("bkg_pp","bkg_pp",*Jpsi_Mass,RooArgSet(a,b,c)); // fwd RooPolynomial bkg_pp("bkg_pp","bkg_pp",*Jpsi_Mass,RooArgSet(a));//,b,c)); RooRealVar a_HI020("a_HI020","a_HI020",0.0);a_HI020.setConstant(false); RooRealVar b_HI020("b_HI020","b_HI020",0.01);b_HI020.setConstant(false); RooRealVar c_HI020("c_HI020","c_HI020",-0.005);c_HI020.setConstant(false); // mid // RooPolynomial bkg_HI020("bkg_HI020","bkg_HI020",*Jpsi_Mass,RooArgSet(a_HI020));//,b_HI020,c_HI020)); // fwd RooPolynomial bkg_HI020("bkg_HI020","bkg_HI020",*Jpsi_Mass,RooArgSet(a_HI020,b_HI020,c_HI020)); RooRealVar a_HI2040("a_HI2040","a_HI2040",0.0);a_HI2040.setConstant(false); RooRealVar b_HI2040("b_HI2040","b_HI2040",0.01);b_HI2040.setConstant(false); RooRealVar c_HI2040("c_HI2040","c_HI2040",-0.005);c_HI2040.setConstant(false); // mid // RooPolynomial bkg_HI2040("bkg_HI2040","bkg_HI2040",*Jpsi_Mass,RooArgSet(a_HI2040));//,b_HI2040,c_HI2040)); // fwd RooPolynomial bkg_HI2040("bkg_HI2040","bkg_HI2040",*Jpsi_Mass,RooArgSet(a_HI2040,b_HI2040));//,c_HI2040)); RooRealVar a_HI40100("a_HI40100","a_HI40100",0.0);a_HI40100.setConstant(false); RooRealVar b_HI40100("b_HI40100","b_HI40100",0.01);b_HI40100.setConstant(false); RooRealVar c_HI40100("c_HI40100","c_HI40100",-0.005);c_HI40100.setConstant(false); // mid // a_HI40100.setConstant(true); // RooPolynomial bkg_HI40100("bkg_HI40100","bkg_HI40100",*Jpsi_Mass,RooArgSet(a_HI40100));//,b_HI40100,c_HI40100)); // fwd RooPolynomial bkg_HI40100("bkg_HI40100","bkg_HI40100",*Jpsi_Mass,RooArgSet(a_HI40100));//,b_HI40100,c_HI40100)); ws->import(bkg_pp); ws->import(bkg_HI020); ws->import(bkg_HI2040); ws->import(bkg_HI40100); ws->factory("SUM::sigMassPDF_pp_M2242(NJpsi_pp*sigCB1G2_HI,NPsiP_pp*sigCB1G2P_HI,NBkg_pp*bkg_pp)"); ws->factory("SUM::sigMassPDF_HI020_M2242(NJpsi_HI020*sigCB1G2_HI,NPsiP_HI020*sigCB1G2P_HI,NBkg_HI020*bkg_HI020)"); ws->factory("SUM::sigMassPDF_HI2040_M2242(NJpsi_HI2040*sigCB1G2_HI,NPsiP_HI2040*sigCB1G2P_HI,NBkg_HI2040*bkg_HI2040)"); ws->factory("SUM::sigMassPDF_HI40100_M2242(NJpsi_HI40100*sigCB1G2_HI,NPsiP_HI40100*sigCB1G2P_HI,NBkg_HI40100*bkg_HI40100)"); ws->factory("SIMUL::sigMassPDFSim_M2242(sample,HI020=sigMassPDF_HI020_M2242,HI2040=sigMassPDF_HI2040_M2242,HI40100=sigMassPDF_HI40100_M2242,pp=sigMassPDF_pp_M2242)"); RooDataSet *data[N]; RooDataSet *data_pp[N]; RooDataSet *data_HI020[N]; RooDataSet *data_HI2040[N]; RooDataSet *data_HI40100[N]; RooDataSet *redData; for (int i=0;i<N;++i) { cout << "Generating event " << i << "/" << N << endl; // cout << "Generate N = " << Nevents << " events with R_{psi} = " << ws->var("fracP_pp")->getVal() << endl; // data[i] = model->generateSimGlobal(*Jpsi_Mass,ProtoData(*protoData), Verbose(1)); data_pp[i] = model_pp->generate(*Jpsi_Mass, ProtoData(*protoData_pp),Verbose(0)); data_HI020[i] = model_HI020->generate(*Jpsi_Mass, ProtoData(*protoData_HI020),Verbose(0)); data_HI2040[i] = model_HI2040->generate(*Jpsi_Mass, ProtoData(*protoData_HI2040),Verbose(0)); data_HI40100[i] = model_HI40100->generate(*Jpsi_Mass, ProtoData(*protoData_HI40100),Verbose(0)); data[i] = new RooDataSet("data","data",RooArgSet(*Jpsi_Mass),Index(*sample),Import("HI020",*data_HI020[i]),Import("HI2040",*data_HI2040[i]),Import("HI40100",*data_HI40100[i]),Import("pp",*data_pp[i])); } RooPlot *frame2 = Jpsi_Mass->frame(); data_pp[0]->plotOn(frame2); data[N-1]->plotOn(frame2, Cut("sample==sample::pp"),MarkerColor(kRed), MarkerStyle(24)); data[N-1]->plotOn(frame2, Cut("sample==sample::HI020"), MarkerColor(kRed)); data[N-1]->plotOn(frame2, Cut("sample==sample::HI2040"), MarkerStyle(25), MarkerColor(kBlue)); data[N-1]->plotOn(frame2, Cut("sample==sample::HI40100"), MarkerStyle(24), MarkerColor(kGreen+2)); // data[N-1]->plotOn(frame2, Cut("sample!=sample::pp"), MarkerColor(kRed)); // model->plotOn(frame, Slice(*sample,"pp"), ProjWData(*sample,*protoData)); TCanvas *c0a = new TCanvas("c0a","c0a"); c0a->cd(); frame2->Draw(); // return; // cout << data->sumEntries() << endl; for (int i=0;i<N;++i) { cout << "Fitting event " << i << "/" << N << endl; fitMall = ws->pdf("sigMassPDFSim")->fitTo(*data[i],Extended(1),Hesse(1),Save(1),NumCPU(8),PrintEvalErrors(-1),Verbose(0),PrintLevel(-1)); if (fitMall->statusCodeHistory(fitMall->numStatusHistory()-1) != 0) {i--; continue;} // fitMall->Print("v"); // cout << "Fitted R_{psi} = " << ws->var("fracP_pp")->getVal() << " +/- " << ws->var("fracP_pp")->getPropagatedError(*fitMall) << endl; double R1850_pp = ws->var("fracP_pp")->getVal(); double R1850_HI020 = ws->var("doubleRatio_HI020")->getVal(); double R1850_HI2040 = ws->var("doubleRatio_HI2040")->getVal(); double R1850_HI40100 = ws->var("doubleRatio_HI40100")->getVal(); double R1850_HI0100 = ws->function("doubleRatio_HI0100")->getVal(); h0_pp->Fill(R1850_pp); h0_HI020->Fill(R1850_HI020); h0_HI2040->Fill(R1850_HI2040); h0_HI40100->Fill(R1850_HI40100); h0_HI0100->Fill(R1850_HI0100); redData = (RooDataSet*)data[i]->reduce("Jpsi_Mass>2.2&&Jpsi_Mass<4.2"); // cout << redData->sumEntries() << endl; fitM = ws->pdf("sigMassPDFSim_M2242")->fitTo(*redData,Extended(1),Hesse(1),Save(1),NumCPU(8),PrintEvalErrors(-1),Verbose(0),PrintLevel(-1),Range("M2242")); if (fitM->statusCodeHistory(fitM->numStatusHistory()-1) != 0) {i--; continue;} // fitM->Print("v"); // cout << "Fit over M2242: R_{psi} = " << ws->var("fracP_pp")->getVal() << " +/- " << ws->var("fracP_pp")->getPropagatedError(*fitM) << endl; // RooPlot *frame = Jpsi_Mass->frame(Range("M2242")); // redData->plotOn(frame); // ws->pdf("sigMassPDF_M2242")->plotOn(frame,Range("M2242")); // redData->plotOn(frame,MarkerStyle(24),MarkerColor(kRed),Range("M2242")); double R2242_pp = ws->var("fracP_pp")->getVal(); double R2242_HI020 = ws->var("doubleRatio_HI020")->getVal(); double R2242_HI2040 = ws->var("doubleRatio_HI2040")->getVal(); double R2242_HI40100 = ws->var("doubleRatio_HI40100")->getVal(); double R2242_HI0100 = ws->function("doubleRatio_HI0100")->getVal(); h1_pp->Fill(R2242_pp); h1_HI020->Fill(R2242_HI020); h1_HI2040->Fill(R2242_HI2040); h1_HI40100->Fill(R2242_HI40100); h1_HI0100->Fill(R2242_HI0100); h2_pp->Fill(R1850_pp,R2242_pp); h2_HI020->Fill(R1850_HI020,R2242_HI020); h2_HI2040->Fill(R1850_HI2040,R2242_HI2040); h2_HI40100->Fill(R1850_HI40100,R2242_HI40100); h2_HI0100->Fill(R1850_HI0100,R2242_HI0100); } TCanvas *c1 = new TCanvas("c1","c1"); c1->Divide(2,2); c1->cd(1); h0_pp->Draw(); h1_pp->Draw("same"); c1->cd(2); h0_HI020->Draw(); h1_HI020->Draw("same"); c1->cd(3); h0_HI2040->Draw(); h1_HI2040->Draw("same"); c1->cd(4); h0_HI40100->Draw(); h1_HI40100->Draw("same"); // frame->Draw(); cout << "pp" << endl; cout << h0_pp->GetMean() << "\t" << h0_pp->GetRMS() << endl; cout << h1_pp->GetMean() << "\t" << h1_pp->GetRMS() << endl; cout << 1-(h0_pp->GetMean()/h1_pp->GetMean()) << endl; cout << "HI020" << endl; cout << h0_HI020->GetMean() << "\t" << h0_HI020->GetRMS() << endl; cout << h1_HI020->GetMean() << "\t" << h1_HI020->GetRMS() << endl; cout << 1-(h0_HI020->GetMean()/h1_HI020->GetMean()) << endl; cout << "HI2040" << endl; cout << h0_HI2040->GetMean() << "\t" << h0_HI2040->GetRMS() << endl; cout << h1_HI2040->GetMean() << "\t" << h1_HI2040->GetRMS() << endl; cout << 1-(h0_HI2040->GetMean()/h1_HI2040->GetMean()) << endl; cout << "HI40100" << endl; cout << h0_HI40100->GetMean() << "\t" << h0_HI40100->GetRMS() << endl; cout << h1_HI40100->GetMean() << "\t" << h1_HI40100->GetRMS() << endl; cout << 1-(h0_HI40100->GetMean()/h1_HI40100->GetMean()) << endl; cout << "HI0100" << endl; cout << h0_HI0100->GetMean() << "\t" << h0_HI0100->GetRMS() << endl; cout << h1_HI0100->GetMean() << "\t" << h1_HI0100->GetRMS() << endl; cout << 1-(h0_HI0100->GetMean()/h1_HI0100->GetMean()) << endl; c1->SaveAs(Form("toy_fits_dblRatio_fwd_M1850_N%i.pdf",N)); TF1 *f3 = new TF1("f3","x",-0.5,3.0); f3->SetLineWidth(1); TCanvas *c2 = new TCanvas("c2","c2"); c2->Divide(2,2); c2->cd(1); h2_pp->Draw("colz"); f3->Draw("same"); c2->cd(2); h2_HI020->Draw("colz"); f3->Draw("same"); c2->cd(3); h2_HI2040->Draw("colz"); f3->Draw("same"); c2->cd(4); h2_HI40100->Draw("colz"); f3->Draw("same"); TCanvas *c3 = new TCanvas("c3","c3"); c3->Divide(2,1); c3->cd(1); h0_HI0100->Draw(); h1_HI0100->Draw("same"); c3->cd(2); h2_HI0100->Draw("colz"); f3->Draw("same"); TFile *outf = new TFile(Form("toy_fits_dblRatio_fwd_M1850_N%i.root",N),"RECREATE"); h0_pp->Write(); h1_pp->Write(); h2_pp->Write(); h0_HI020->Write(); h1_HI020->Write(); h2_HI020->Write(); h0_HI2040->Write(); h1_HI2040->Write(); h2_HI2040->Write(); h0_HI40100->Write(); h1_HI40100->Write(); h2_HI40100->Write(); h0_HI0100->Write(); h1_HI0100->Write(); h2_HI0100->Write(); outf->Close(); return; }
void rf513_wsfactory_tools() { RooWorkspace* w = new RooWorkspace("w") ; // B u i l d a c o m p l e x e x a m p l e p . d . f . // ----------------------------------------------------------- // Make signal model for CPV: A bmixing decay function in t (convoluted with a triple Gaussian resolution model) // times a Gaussian function the reconstructed mass w->factory("PROD::sig( BMixDecay::sig_t( dt[-20,20], mixState[mixed=1,unmix=-1], tagFlav[B0=1,B0bar=-1], " "tau[1.54], dm[0.472], w[0.05], dw[0]," "AddModel::gm({GaussModel(dt,biasC[-10,10],sigmaC[0.1,3],dterr[0.01,0.2])," "GaussModel(dt,0,sigmaT[3,10])," "GaussModel(dt,0,20)},{fracC[0,1],fracT[0,1]})," "DoubleSided )," "Gaussian::sig_m( mes[5.20,5.30], mB0[5.20,5.30], sigmB0[0.01,0.05] ))") ; // Make background component: A plain decay function in t times an Argus function in the reconstructed mass w->factory("PROD::bkg( Decay::bkg_t( dt, tau, gm, DoubleSided)," "ArgusBG::bkg_m( mes, 5.291, k[-100,-10]))") ; // Make composite model from the signal and background component w->factory("SUM::model( Nsig[5000,0,10000]*sig, NBkg[500,0,10000]*bkg )") ; // E x a m p l e o f R o o S i m W S T o o l i n t e r f a c e // ------------------------------------------------------------------ // Introduce a flavour tagging category tagCat as observable with 4 states corresponding // to 4 flavour tagging techniques with different performance that require different // parameterizations of the fit model // // RooSimWSTool operation: // - Make 4 clones of model (for each tagCat) state, that will gain an individual // copy of parameters w,dw and biasC. The other parameters remain common // - Make a simultaneous p.d.f. of the 4 clones assigning each to the appropriate // state of the tagCat index category // RooSimWSTool is interfaced as meta-type SIMCLONE in the factory. The $SplitParam() // argument maps to the SplitParam() named argument in the RooSimWSTool constructor w->factory("SIMCLONE::model_sim( model, $SplitParam({w,dw,biasC},tagCat[Lep,Kao,NT1,NT2]))") ; // E x a m p l e o f R o o C u s t o m i z e r i n t e r f a c e // ------------------------------------------------------------------- // // Class RooCustomizer makes clones of existing p.d.f.s with certain prescribed // modifications (branch of leaf node replacements) // // Here we take our model (the original before RooSimWSTool modifications) // and request that the parameter w (the mistag rate) is replaced with // an expression-based function that calculates w in terms of the Dilution // parameter D that is defined as D = 1-2*w // Make a clone model_D of original 'model' replacing 'w' with 'expr('0.5-D/2',D[0,1])' w->factory("EDIT::model_D(model, w=expr('0.5-D/2',D[0,1]) )") ; // Print workspace contents w->Print() ; // Make workspace visible on command line gDirectory->Add(w) ; }
void Raa3S_Workspace(const char* filename="fitresult_combo_nofixed.root"){ TFile File(filename); RooWorkspace * ws; File.GetObject("wcombo", ws); // ws->Print(); RooAbsData * data = ws->data("data"); // 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,0,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)); ws->import(step); ws->factory( "Uniform::flat(raa3)" ); //pp Luminosities, Taa and efficiency ratios Systematics ws->factory( "Taa_hi[5.662e-9]" ); ws->factory( "Taa_kappa[1.057]" ); ws->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" ); ws->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" ); ws->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" ); ws->factory( "lumipp_hi[5.4]" ); ws->factory( "lumipp_kappa[1.06]" ); ws->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" ); ws->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" ); ws->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" ); // ws->factory( "effRat1[1]" ); // ws->factory( "effRat2[1]" ); ws->factory( "effRat3_hi[0.95]" ); ws->factory( "effRat_kappa[1.054]" ); ws->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)" ); ws->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" ); // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" ); ws->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" ); // ws->factory("Nmb_hi[1.161e9]"); ws->factory("prod::denominator(Taa_nom,Nmb_hi)"); ws->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)"); 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 = ws->var("N_{#Upsilon(3S)}_pp"); cout << nsig3_pp << endl; 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)); ws->import(nsig3_hi_modified); // // background yield with systematics ws->factory( "nbkg_hi_kappa[1.10]" ); ws->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" ); ws->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" ); ws->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" ); RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi"); RooAbsPdf* sig2S_hi = ws->pdf("sig2S_hi"); RooAbsPdf* sig3S_hi = ws->pdf("sig3S_hi"); RooAbsPdf* LSBackground_hi = ws->pdf("nbkg_hi_nom"); RooRealVar* nsig1_hi = ws->var("N_{#Upsilon(1S)}_hi"); RooRealVar* nsig2_hi = ws->var("N_{#Upsilon(2S)}_hi"); cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl; RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified"); RooRealVar* norm_nbkg_hi = ws->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); //////////////////////////////////////////////////////////////////////////////// ws->factory( "nbkg_pp_kappa[1.03]" ); ws->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" ); ws->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" ); ws->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" ); RooAbsPdf* sig1S_pp = ws->pdf("cbcb_pp"); RooAbsPdf* sig2S_pp = ws->pdf("sig2S_pp"); RooAbsPdf* sig3S_pp = ws->pdf("sig3S_pp"); RooAbsPdf* LSBackground_pp = ws->pdf("nbkg_pp_nom"); RooRealVar* nsig1_pp = ws->var("N_{#Upsilon(1S)}_pp"); RooRealVar* nsig2_pp = ws->var("N_{#Upsilon(2S)}_pp"); RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp"); RooRealVar* norm_nbkg_pp = ws->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); ws->import(model_num); ws->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); ws->import(model_den); ws->factory("PROD::model_pp(model_den, constr_nbkg_pp)"); ws->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)"); ///////////////////////////////////////////////////////////////////// RooRealVar * pObs = ws->var("invariantMass"); // get the pointer to the observable RooArgSet obs("observables"); obs.add(*pObs); obs.add( *ws->cat("dataCat")); // ///////////////////////////////////////////////////////////////////// ws->var("glob_lumipp")->setConstant(true); ws->var("glob_Taa")->setConstant(true); ws->var("glob_effRat")->setConstant(true); ws->var("glob_nbkg_pp")->setConstant(true); ws->var("glob_nbkg_hi")->setConstant(true); RooArgSet globalObs("global_obs"); globalObs.add( *ws->var("glob_lumipp") ); globalObs.add( *ws->var("glob_Taa") ); globalObs.add( *ws->var("glob_effRat") ); globalObs.add( *ws->var("glob_nbkg_hi") ); globalObs.add( *ws->var("glob_nbkg_pp") ); // ws->Print(); RooArgSet poi("poi"); poi.add( *ws->var("raa3") ); // create set of nuisance parameters RooArgSet nuis("nuis"); nuis.add( *ws->var("beta_lumipp") ); nuis.add( *ws->var("beta_nbkg_hi") ); nuis.add( *ws->var("beta_nbkg_pp") ); nuis.add( *ws->var("beta_Taa") ); nuis.add( *ws->var("beta_effRat") ); ws->var("#alpha_{CB}_hi")->setConstant(true); ws->var("#alpha_{CB}_pp")->setConstant(true); ws->var("#sigma_{CB1}_hi")->setConstant(true); ws->var("#sigma_{CB1}_pp")->setConstant(true); ws->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true); ws->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true); ws->var("Centrality")->setConstant(true); ws->var("N_{#Upsilon(1S)}_hi")->setConstant(true); ws->var("N_{#Upsilon(1S)}_pp")->setConstant(true); ws->var("N_{#Upsilon(2S)}_hi")->setConstant(true); ws->var("N_{#Upsilon(2S)}_pp")->setConstant(true); ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true); ws->var("Nmb_hi")->setConstant(true); // ws->var("QQsign")->setConstant(true); ws->var("Taa_hi")->setConstant(true); ws->var("Taa_kappa")->setConstant(true); // ws->var("beta_Taa")->setConstant(true); // ws->var("beta_effRat")->setConstant(true); // ws->var("beta_lumipp")->setConstant(true); // ws->var("beta_nbkg_hi")->setConstant(true); // ws->var("beta_nbkg_pp")->setConstant(true); // ws->var("dataCat")->setConstant(true); ws->var("decay_hi")->setConstant(true); ws->var("decay_pp")->setConstant(true); ws->var("effRat3_hi")->setConstant(true); ws->var("effRat_kappa")->setConstant(true); // ws->var("glob_Taa")->setConstant(true); // ws->var("glob_effRat")->setConstant(true); // ws->var("glob_lumipp")->setConstant(true); // ws->var("glob_nbkg_hi")->setConstant(true); // ws->var("glob_nbkg_pp")->setConstant(true); // ws->var("invariantMass")->setConstant(true); ws->var("leftEdge")->setConstant(true); ws->var("lumipp_hi")->setConstant(true); ws->var("lumipp_kappa")->setConstant(true); ws->var("mass1S_hi")->setConstant(true); ws->var("mass1S_pp")->setConstant(true); ws->var("muMinusPt")->setConstant(true); ws->var("muPlusPt")->setConstant(true); ws->var("n_{Bkgd}_hi")->setConstant(true); ws->var("n_{Bkgd}_pp")->setConstant(true); ws->var("nbkg_hi_kappa")->setConstant(true); ws->var("nbkg_pp_kappa")->setConstant(true); ws->var("npow")->setConstant(true); ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true); // ws->var("raa3")->setConstant(true); ws->var("rightEdge")->setConstant(true); ws->var("sigmaFraction_hi")->setConstant(true); ws->var("sigmaFraction_pp")->setConstant(true); ws->var("turnOn_hi")->setConstant(true); ws->var("turnOn_pp")->setConstant(true); ws->var("upsPt")->setConstant(true); ws->var("upsRapidity")->setConstant(true); ws->var("vProb")->setConstant(true); ws->var("width_hi")->setConstant(true); ws->var("width_pp")->setConstant(true); ws->var("x3raw")->setConstant(true); // RooArgSet fixed_again("fixed_again"); // fixed_again.add( *ws->var("leftEdge") ); // fixed_again.add( *ws->var("rightEdge") ); // fixed_again.add( *ws->var("Taa_hi") ); // fixed_again.add( *ws->var("Nmb_hi") ); // fixed_again.add( *ws->var("lumipp_hi") ); // fixed_again.add( *ws->var("effRat1_hi") ); // fixed_again.add( *ws->var("effRat2_hi") ); // fixed_again.add( *ws->var("effRat3_hi") ); // fixed_again.add( *ws->var("nsig3_pp") ); // fixed_again.add( *ws->var("nsig1_pp") ); // fixed_again.add( *ws->var("nbkg_hi") ); // fixed_again.add( *ws->var("alpha") ); // fixed_again.add( *ws->var("nbkg_kappa") ); // fixed_again.add( *ws->var("Taa_kappa") ); // fixed_again.add( *ws->var("lumipp_kappa") ); // fixed_again.add( *ws->var("mean_hi") ); // fixed_again.add( *ws->var("mean_pp") ); // fixed_again.add( *ws->var("width_hi") ); // fixed_again.add( *ws->var("turnOn_hi") ); // fixed_again.add( *ws->var("bkg_a1_pp") ); // fixed_again.add( *ws->var("bkg_a2_pp") ); // fixed_again.add( *ws->var("decay_hi") ); // fixed_again.add( *ws->var("raa1") ); // fixed_again.add( *ws->var("raa2") ); // fixed_again.add( *ws->var("nsig2_pp") ); // fixed_again.add( *ws->var("sigma1") ); // fixed_again.add( *ws->var("nbkg_pp") ); // fixed_again.add( *ws->var("npow") ); // fixed_again.add( *ws->var("muPlusPt") ); // fixed_again.add( *ws->var("muMinusPt") ); // fixed_again.add( *ws->var("mscale_hi") ); // fixed_again.add( *ws->var("mscale_pp") ); // // ws->Print(); // create signal+background Model Config RooStats::ModelConfig sbHypo("SbHypo"); sbHypo.SetWorkspace( *ws ); sbHypo.SetPdf( *ws->pdf("joint") ); sbHypo.SetObservables( obs ); sbHypo.SetGlobalObservables( globalObs ); sbHypo.SetParametersOfInterest( poi ); sbHypo.SetNuisanceParameters( nuis ); sbHypo.SetPriorPdf( *ws->pdf("step") ); // this is optional // ws->Print(); ///////////////////////////////////////////////////////////////////// RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(2) ); RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3")); pNll->plotOn(framepoi,ShiftToZero()); 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"); 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 = ws->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; ws->import( sbHypo ); ///////////////////////////////////////////////////////////////////// RooStats::ModelConfig bHypo = sbHypo; bHypo.SetName("BHypo"); bHypo.SetWorkspace(*ws); 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 double oldval = ((RooRealVar *)poi.first())->getVal( ); ((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(*ws); ws->import( bHypo ); ///////////////////////////////////////////////////////////////////// ws->Print(); bHypo.Print(); sbHypo.Print(); ((RooRealVar *)poi.first())->setVal( oldval ); // set raa3=oldval here // save workspace to file ws -> SaveAs("TRIAL.root"); return; }
void mytest(int seed = 37) { using namespace RooFit; using namespace std; int nbin = 50; bool binned = true; stringstream nSig; stringstream nBkg; stringstream bwRatio; stringstream bRatio; stringstream mass = "60"; double bL = 20.;//std::atof(mass.str().c_str()) - 10; double bH = 70.;//std::atof(mass.str().c_str()) + 10; TString pf = "4_4"; nSig << 3.84; nBkg << 552; double bkgUnc = 1;//(510-424.)/424.; //50% bwRatio << 0.2; bRatio << 0.8; stringstream range; range << bL << "," << bH; cout << "Mass: " << mass.str() << endl; cout << "Range: " << range.str() << endl; TString Range = range.str().c_str(); TString Mass = mass.str().c_str(); /// Data-fit //////////////// TString fname = ""; if(!binned) fname = "hamb-shapes-UnbinnedParam-m" + Mass + "-Data-fit.root"; else fname = "hamb-shapes-BinnedParam-m" + Mass + "-Data-fit.root"; if(!binned){ TString name = "test"; RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH); TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ"); TTree* hbkg = (TTree*) fbkg->Get("rds_zbb"); RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, ""); RooRandom::randomGenerator()->SetSeed(seed); RooWorkspace *w = new RooWorkspace("w", "w"); w->factory("eventSelectionamassMu[" + Range + "]"/*,Range(SM, 50,70)"*/); w->import(bkgData); w->factory("KeysPdf::"+name+"_bkg_dimu(eventSelectionamassMu,bkgData)"); TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ"); TTree* hh = (TTree*) f->Get("rds_zbb"); RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, ""); w->import(data); TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin)); double frac = (double)hData->Integral()/(double)nbin; nBkg.str(""); nBkg << hData->Integral() - (5 * frac); TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read"); TTree* hsig = (TTree*) fsig->Get("rds_zbb"); RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, ""); w->import(sigData); w->factory("KeysPdf::" + name + "_sigPdf_dimu(eventSelectionamassMu,sigData_dimu)"); w->factory(name + "_bkg_dimu_norm[" + nBkg.str().c_str() + "]"); w->factory(name + "_sigPdf_dimu_norm[" + nSig.str().c_str() + "]"); w->writeToFile(fname); //w->var("eventSelectionamassMu")->setBins(55); cardMaker(Mass, bkgUnc, binned); } else { RooRealVar eventSelectionamassMu("eventSelectionamassMu", "eventSelectionamassMu", bL, bH); TFile* fbkg = new TFile("DoubleMu2012_Summer12_final_CR_" + pf + ".root", "READ"); TTree* hbkg = (TTree*) fbkg->Get("rds_zbb"); RooDataSet bkgData("bkgData", "bkgData", hbkg, eventSelectionamassMu, ""); TH1D * hbkgData = bkgData.createHistogram("bkg",eventSelectionamassMu,Binning(nbin)); hbkgData->SetName("bkg"); TFile* f = new TFile("DoubleMu2012_Summer12_final_" + pf + ".root", "READ"); TTree* hh = (TTree*) f->Get("rds_zbb"); RooDataSet data("data_dimu", "data", hh, eventSelectionamassMu, ""); TH1D * hData = data.createHistogram("data_obs",eventSelectionamassMu,Binning(nbin)); int nData = hData->Integral(); double frac = (double)hData->Integral()/(double)nbin; nBkg.str(""); nBkg << hData->Integral() - (5 * frac); hData->SetName("data_obs"); TFile * fsig = new TFile("H2ToH1H1_H1To2Mu2B_mH2-125_mH1-" + Mass + "_Summer12_final_" + pf + ".root", "read"); TTree* hsig = (TTree*) fsig->Get("rds_zbb"); RooDataSet sigData("sigData_dimu", "sigData", hsig, eventSelectionamassMu, ""); TH1D * hsigData = sigData.createHistogram("signal",eventSelectionamassMu,Binning(nbin)); hsigData->SetName("signal"); hbkgData->Scale(std::atof(nBkg.str().c_str())/hbkgData->Integral()); hsigData->Scale(std::atof(nSig.str().c_str())/hsigData->Integral()); TFile * fOut = new TFile(fname,"recreate"); fOut->mkdir("dimu")->cd(); hData->Write(); hbkgData->Write(); hsigData->Write(); fOut->cd(); fOut->Close(); cardMaker(Mass, bkgUnc, binned, std::atof(nSig.str().c_str()), std::atof(nBkg.str().c_str()), nData); } }
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 Process(TString fname, TString oldFolder, int toMass, int fromMass) { std::string channels[] = {"data_obs", "WH", "TT", "WjLF", "WjHF", "ZjLF", "ZjHF" , "VV" , "s_Top"}; std::string systs[] = {"eff_b", "fake_b", "res_j", "scale_j" , "stat" }; kount = 0; gROOT->SetStyle("Plain"); setTDRStyle(); TFile * file = new TFile(fname.Data(), "READ"); std::cout << "reading " << fname.Data() << std::endl; TString outname(massS[toMass]); outname.Append("_June8.root"); fname.ReplaceAll(".root",outname.Data()); ///BEGIN CHECK RBIN int addRightBin = 0, addRightBinm1 = 0 , rightBinNo = 0; float a,overflow; RooWorkspace *mytempWS = (RooWorkspace*) file->Get(oldFolder.Data()); RooRealVar BDT("CMS_vhbb_BDT_Wln", "BDT", -1, 1); float Signal = 0; float Background = 0; float Backgroundm1 = 0; float Data = 0; RooDataHist* tempRooDataHistNomS = (RooDataHist*) mytempWS->data(channels[1].c_str()); TH1 *tempHistNomS = tempRooDataHistNomS->createHistogram(channels[1].c_str(),BDT,RooFit::Binning(bins)); tempHistNomS->Rebin(rebin); TH1 *tempHistNomD = tempRooDataHistNomS->createHistogram(channels[0].c_str(),BDT,RooFit::Binning(bins)); tempHistNomD->Rebin(rebin); for(int i = 1; i <= tempHistNomS->GetNbinsX(); i++) { if(tempHistNomS->GetBinContent(i) > 0) { rightBinNo = i; Signal = tempHistNomS->GetBinContent(i); Data = tempHistNomS->GetBinError(i); } } for(int i = 2; i < 9; i++) { RooDataHist* tempRooDataHistNom = (RooDataHist*) mytempWS->data(channels[i].c_str()); TH1 *tempHistNom = tempRooDataHistNom->createHistogram(channels[i].c_str(),BDT,RooFit::Binning(bins)); tempHistNom->Rebin(rebin); Background += tempHistNom->GetBinContent(rightBinNo); // if(tempHistNom->GetBinContent(rightBinNo-1) == 0) // { // Backgroundm1 = 0; //std::cout << "ARGHGHGHGHGH bkg is 0 still at left" << std::endl; // std::cin >> ; // } Backgroundm1+= tempHistNom->GetBinContent(rightBinNo-1); overflow = tempHistNom->GetBinContent(rightBinNo+1) ; if(tempHistNom->GetBinContent(rightBinNo+1) > 0) { std::cout << "ARGHGHGHGHGH overflow at right" << std::endl; // std::cin >> ; } a+= overflow; } if( (Background ==0) ) addRightBin = 1; else addRightBin = 0; std::cout << "################# folder" << oldFolder << std::endl; std::cout<< "################# CHECK RBIN:: right bin n " << rightBinNo << " signal: " << Signal << " bkg: " << Background << " bkgm1: " << Backgroundm1 << " Data: " << Data << " at right there is an overflow of: "<< a << std::endl; std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin << std::endl; if ( (Backgroundm1 == 0) ) { addRightBinm1 =1 ; std::cout << "ARGHGHGHGHGH " << Backgroundm1 << " at left" << std::endl; } std::cout << "########################### need to rebin further? " << addRightBinm1 << std::endl; ///END CHECK RBIN TFile * outfile = new TFile(fname.Data(), "RECREATE"); using namespace RooFit; RooWorkspace *myWS = new RooWorkspace(oldFolder.Data(),oldFolder.Data()); myWS->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE TString oldFolder2(oldFolder.Data()); oldFolder2.Append("2"); RooWorkspace *myWS2 = new RooWorkspace(oldFolder2.Data(),oldFolder2.Data()); myWS2->factory("CMS_vhbb_BDT_Wln[-1.,1.]"); ///NEW VARIABLE NAME HERE ///BEGIN CHECK RBIN int addRightBin2=0, rightBinNo2=0, addRightBin2m1=0; float a2,overflow2; RooWorkspace *mytempWS2 = (RooWorkspace*) file->Get(oldFolder2.Data()); RooRealVar BDT2("CMS_vhbb_BDT_Wln", "BDT", -1, 1); float Signal2 = 0; float Background2 = 0; float Background2m1 = 0; float Data2 = 0; RooDataHist* tempRooDataHistNomS2 = (RooDataHist*) mytempWS2->data(channels[1].c_str()); RooDataHist* tempRooDataHistNomD2 = (RooDataHist*) mytempWS2->data(channels[0].c_str()); TH1 *tempHistNomS2 = tempRooDataHistNomS2->createHistogram(channels[1].c_str(),BDT2,RooFit::Binning(bins)); tempHistNomS2->Rebin(rebin); TH1 *tempHistNomD2 = tempRooDataHistNomD2->createHistogram(channels[0].c_str(),BDT2,RooFit::Binning(bins)); tempHistNomD2->Rebin(rebin); for(int i = 1; i <= tempHistNomS2->GetNbinsX(); i++) { // std::cout << "############ signal in bin " << i << " is " << tempHistNomS2->GetBinContent(i) << std::endl; // std::cout << "############ data in bin " << i << " is " << tempHistNomD2->GetBinContent(i) << std::endl; if(tempHistNomS2->GetBinContent(i) > 0) { rightBinNo2 = i; Signal2 = tempHistNomS2->GetBinContent(i); Data2 = tempHistNomD2->GetBinContent(i) ;} } for(int i = 2; i < 9; i++) { RooDataHist* tempRooDataHistNom2 = (RooDataHist*) mytempWS2->data(channels[i].c_str()); TH1 *tempHistNom2 = tempRooDataHistNom2->createHistogram(channels[i].c_str(),BDT2,RooFit::Binning(bins)); tempHistNom2->Rebin(rebin); Background2 += tempHistNom2->GetBinContent(rightBinNo2); overflow2 = tempHistNom2->GetBinContent(rightBinNo2+1) ; Background2m1+= tempHistNom2->GetBinContent(rightBinNo2-1); if(tempHistNom2->GetBinContent(rightBinNo2+1) > 0) { std::cout << "ARGHGHGHGHGH" << std::endl; // std::cin >> ; } a2+= overflow2; } if( (Background2 ==0) ) addRightBin2 = 1; else addRightBin2 = 0; if( (Background2m1 ==0) ) addRightBin2m1 = 1; std::cout << "################# folder" << oldFolder2 << std::endl; std::cout << "################# CHECK RBIN:: right bin n " << rightBinNo2 << " signal: " << Signal2 << " bkg: " << Background2 << " bkgm1: " << Background2m1 << " Data: " << Data2 << " at right there is an overflow of: "<< a2 << std::endl; std::cout << "########################### CHECK RBIN:: REBINNING: " << addRightBin2 << std::endl; std::cout << "########################### need to rebin further? " << addRightBin2m1 << std::endl; ///END CHECK RBIN for (int c =0; c<9; c++) { kount2 = 0; for (int s =0; s<5 ; s++ ){ makeSystPlot( file, oldFolder, myWS, channels[c], systs[s], toMass, fromMass, rightBinNo, addRightBin, addRightBinm1 ); makeSystPlot( file, oldFolder2, myWS2, channels[c], systs[s] , toMass, fromMass, rightBinNo2, addRightBin2, addRightBin2m1 ); } } if(!(IFILE.Contains("8TeV"))) { makeSystPlot(file, oldFolder, myWS, "WjLF", "WModel",toMass, fromMass, rightBinNo, addRightBin ,addRightBinm1 ); makeSystPlot(file, oldFolder, myWS, "WjHF", "WModel",toMass, fromMass, rightBinNo, addRightBin, addRightBinm1 ); makeSystPlot(file, oldFolder2, myWS2, "WjLF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2 , addRightBin2m1); makeSystPlot(file, oldFolder2, myWS2, "WjHF", "WModel",toMass, fromMass, rightBinNo2, addRightBin2, addRightBin2m1 ); } myWS->writeToFile(fname.Data()); std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl; std::cout << fname.Data() << " written" << std::endl; std::cout << "///////////////////////////" << std::endl << std::endl << std::endl; outfile->Write(); outfile->Close(); fname.ReplaceAll("June8","June82"); TFile * outfile2 = new TFile(fname.Data(), "RECREATE"); myWS2->writeToFile(fname.Data()); std::cout << std::endl << std::endl << std::endl << std::endl << "///////////////////////////" << std::endl; std::cout << fname.Data() << " written" << std::endl; std::cout << "///////////////////////////" << std::endl << std::endl << std::endl; }
void IntervalExamples() { // Time this macro TStopwatch t; t.Start(); // set RooFit random seed for reproducible results RooRandom::randomGenerator()->SetSeed(3001); // make a simple model via the workspace factory RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Gaussian::normal(x[-10,10],mu[-1,1],sigma[1])"); wspace->defineSet("poi","mu"); wspace->defineSet("obs","x"); // specify components of model for statistical tools ModelConfig* modelConfig = new ModelConfig("Example G(x|mu,1)"); modelConfig->SetWorkspace(*wspace); modelConfig->SetPdf( *wspace->pdf("normal") ); modelConfig->SetParametersOfInterest( *wspace->set("poi") ); modelConfig->SetObservables( *wspace->set("obs") ); // create a toy dataset RooDataSet* data = wspace->pdf("normal")->generate(*wspace->set("obs"),100); data->Print(); // for convenience later on RooRealVar* x = wspace->var("x"); RooRealVar* mu = wspace->var("mu"); // set confidence level double confidenceLevel = 0.95; // example use profile likelihood calculator ProfileLikelihoodCalculator plc(*data, *modelConfig); plc.SetConfidenceLevel( confidenceLevel); LikelihoodInterval* plInt = plc.GetInterval(); // example use of Feldman-Cousins FeldmanCousins fc(*data, *modelConfig); fc.SetConfidenceLevel( confidenceLevel); fc.SetNBins(100); // number of points to test per parameter fc.UseAdaptiveSampling(true); // make it go faster // Here, we consider only ensembles with 100 events // The PDF could be extended and this could be removed fc.FluctuateNumDataEntries(false); // Proof // ProofConfig pc(*wspace, 4, "workers=4", kFALSE); // proof-lite //ProofConfig pc(w, 8, "localhost"); // proof cluster at "localhost" // ToyMCSampler* toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler(); // toymcsampler->SetProofConfig(&pc); // enable proof PointSetInterval* interval = (PointSetInterval*) fc.GetInterval(); // example use of BayesianCalculator // now we also need to specify a prior in the ModelConfig wspace->factory("Uniform::prior(mu)"); modelConfig->SetPriorPdf(*wspace->pdf("prior")); // example usage of BayesianCalculator BayesianCalculator bc(*data, *modelConfig); bc.SetConfidenceLevel( confidenceLevel); SimpleInterval* bcInt = bc.GetInterval(); // example use of MCMCInterval MCMCCalculator mc(*data, *modelConfig); mc.SetConfidenceLevel( confidenceLevel); // special options mc.SetNumBins(200); // bins used internally for representing posterior mc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in mc.SetNumIters(100000); // how long to run chain mc.SetLeftSideTailFraction(0.5); // for central interval MCMCInterval* mcInt = mc.GetInterval(); // for this example we know the expected intervals double expectedLL = data->mean(*x) + ROOT::Math::normal_quantile( (1-confidenceLevel)/2,1) / sqrt(data->numEntries()); double expectedUL = data->mean(*x) + ROOT::Math::normal_quantile_c((1-confidenceLevel)/2,1) / sqrt(data->numEntries()) ; // Use the intervals std::cout << "expected interval is [" << expectedLL << ", " << expectedUL << "]" << endl; cout << "plc interval is [" << plInt->LowerLimit(*mu) << ", " << plInt->UpperLimit(*mu) << "]" << endl; std::cout << "fc interval is ["<< interval->LowerLimit(*mu) << " , " << interval->UpperLimit(*mu) << "]" << endl; cout << "bc interval is [" << bcInt->LowerLimit() << ", " << bcInt->UpperLimit() << "]" << endl; cout << "mc interval is [" << mcInt->LowerLimit(*mu) << ", " << mcInt->UpperLimit(*mu) << "]" << endl; mu->setVal(0); cout << "is mu=0 in the interval? " << plInt->IsInInterval(RooArgSet(*mu)) << endl; // make a reasonable style gStyle->SetCanvasColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetPadBorderMode(0); gStyle->SetPadColor(0); gStyle->SetCanvasColor(0); gStyle->SetTitleFillColor(0); gStyle->SetFillColor(0); gStyle->SetFrameFillColor(0); gStyle->SetStatColor(0); // some plots TCanvas* canvas = new TCanvas("canvas"); canvas->Divide(2,2); // plot the data canvas->cd(1); RooPlot* frame = x->frame(); data->plotOn(frame); data->statOn(frame); frame->Draw(); // plot the profile likelihood canvas->cd(2); LikelihoodIntervalPlot plot(plInt); plot.Draw(); // plot the MCMC interval canvas->cd(3); MCMCIntervalPlot* mcPlot = new MCMCIntervalPlot(*mcInt); mcPlot->SetLineColor(kGreen); mcPlot->SetLineWidth(2); mcPlot->Draw(); canvas->cd(4); RooPlot * bcPlot = bc.GetPosteriorPlot(); bcPlot->Draw(); canvas->Update(); t.Stop(); t.Print(); }
void exercise_3() { //Open the rootfile and get the workspace from the exercise_0 TFile fIn("exercise_0.root"); fIn.cd(); RooWorkspace *w = (RooWorkspace*)fIn.Get("w"); //You can set constant parameters that are known //If you leave them floating, the fit procedure will determine their uncertainty w->var("mean")->setConstant(kFALSE); //don't fix the mean, it's what we want to know the interval for! w->var("sigma")->setConstant(kTRUE); w->var("tau")->setConstant(kTRUE); w->var("Nsig")->setConstant(kTRUE); w->var("Nbkg")->setConstant(kTRUE); //Set the RooModelConfig and let it know what the content of the workspace is about ModelConfig model; model.SetWorkspace(*w); model.SetPdf("PDFtot"); //Let the model know what is the parameter of interest RooRealVar* mean = w->var("mean"); mean->setRange(120., 130.); //this is mostly for plotting reasons RooArgSet poi(*mean); // set confidence level double confidenceLevel = 0.68; //Build the profile likelihood calculator ProfileLikelihoodCalculator plc; plc.SetData(*(w->data("PDFtotData"))); plc.SetModel(model); plc.SetParameters(poi); plc.SetConfidenceLevel(confidenceLevel); //Get the interval LikelihoodInterval* plInt = plc.GetInterval(); //Now let's do the same for the Bayesian Calculator //Now we also need to specify a prior in the ModelConfig //To be quicker, we'll use the PDF factory facility of RooWorkspace //NB!! For simplicity, we are using a flat prior, but this doesn't mean it's the best choice! w->factory("Uniform::prior(mean)"); model.SetPriorPdf(*w->pdf("prior")); //Construct the bayesian calculator BayesianCalculator bc(*(w->data("PDFtotData")), model); bc.SetConfidenceLevel(confidenceLevel); bc.SetParameters(poi); SimpleInterval* bcInt = bc.GetInterval(); // Let's make a plot TCanvas dataCanvas("dataCanvas"); dataCanvas.Divide(2,1); dataCanvas.cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)plInt); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for mH"); plotInt.SetMaximum(3.); plotInt.Draw(); dataCanvas.cd(2); RooPlot *bcPlot = bc.GetPosteriorPlot(); bcPlot->Draw(); dataCanvas.SaveAs("exercise_3.gif"); //Now print the interval for mH for the two methods cout << "PLC interval is [" << plInt->LowerLimit(*mean) << ", " << plInt->UpperLimit(*mean) << "]" << endl; cout << "Bayesian interval is [" << bcInt->LowerLimit() << ", " << bcInt->UpperLimit() << "]" << endl; }
void makeFit( TString inf, TString outf ) { TFile *tf = TFile::Open( inf ); RooWorkspace *w = (RooWorkspace*)tf->Get("w"); //w->factory( "Gaussian::dst_mass1( Dst_M, dst_mean[2005,2015], dst_sigma1[1,20] )" ); //w->factory( "Gaussian::dst_mass2( Dst_M, dst_mean, dst_sigma2[3,50] )" ); //w->factory( "Gaussian::dst_mass3( Dst_M, dst_mean, dst_sigma3[5,200] )" ); //w->factory( "SUM::dst_mass( dst_f[0.1,1.]*dst_mass1, dst_f2[0.1,1.]*dst_mass2, dst_mass3 )" ); //w->factory( "SUM::dst_mass_sig( dst_f[0.1,1.]*dst_mass1, dst_f2[0.1,1.]*dst_mass2, dst_mass3 )" ); w->factory( "Gaussian::dst_mass1( Dst_M, dst_mean[2005,2015], dst_sigma1[1,20] )" ); w->factory( "CBShape::dst_mass2( Dst_M, dst_mean, dst_sigma2[1,20], dst_alpha[0.1,10.], dst_n1[0.1,10.] )" ); w->factory( "SUM::dst_mass_sig( dst_f[0.1,1.]*dst_mass1, dst_mass2 )" ); w->factory( "Bernstein::dst_mass_bkg( Dst_M, {1.,dst_p0[0.,1.]} )" ); w->factory( "SUM::dst_mass( dst_mass_sy[0,10e8]*dst_mass_sig, dst_mass_by[0,10e2]*dst_mass_bkg )" ); //w->factory( "Gaussian::d0_mass1( D0_M, d0_mean[1862,1868], d0_sigma1[1,20] )" ); //w->factory( "Gaussian::d0_mass2( D0_M, d0_mean, d0_sigma2[3,50] )" ); //w->factory( "Gaussian::d0_mass3( D0_M, d0_mean, d0_sigma3[5,200] )" ); //w->factory( "SUM::d0_mass( d0_f[0.1,1.]*d0_mass1, d0_f2[0.1,1.]*d0_mass2, d0_mass3 )" ); //w->factory( "SUM::d0_mass( d0_f[0.1,1.]*d0_mass1, d0_f2[0.1,1.]*d0_mass2, d0_mass3 )" ); w->factory( "Gaussian::d0_mass1( D0_M, d0_mean[1862,1868], d0_sigma1[1,20] )" ); w->factory( "CBShape::d0_mass2( D0_M, d0_mean, d0_sigma2[1,20], d0_alpha[0.1,10.], d0_n1[0.1,10.] )" ); w->factory( "SUM::d0_mass_sig( d0_f[0.1,1.]*d0_mass1, d0_mass2 )" ); w->factory( "Bernstein::d0_mass_bkg( D0_M, {1.,d0_p0[0.,1.]} )" ); w->factory( "SUM::d0_mass( d0_mass_sy[0,10e8]*d0_mass_sig, d0_mass_by[0,10e1]*d0_mass_bkg )" ); w->factory( "d0_tau[0,1000.]" ); w->factory( "expr::d0_e( '-1/@0', d0_tau)" ); w->factory( "Exponential::d0_t( D0_LTIME_ps, d0_e )" ); w->pdf("dst_mass")->fitTo( *w->data("Data") , Range(1960,2060) ); w->pdf("d0_mass") ->fitTo( *w->data("Data") , Range(1820,1910) ); w->pdf("d0_t") ->fitTo( *w->data("Data") , Range(0.25,5.) ); tf->Close(); w->writeToFile(outf); }
void retrieve_input_from_histo(RooWorkspace &w){ // Variable definition /* */ /********* GLOBAL VARIABLES ********************/ /* Default --- double Bkg_norm_factor_obs = 0.5 ; // Normalizzation factor for background (N_Data_CR / N_Co_CR) double err_Norm_factor_obs = 0.05; double S_tot = 1000.; // Total events in SR for AmBe double B_tot = 10000.; // Total events in SR for Co60 double Acceptance_SR_obs = 0.9; // Cut Acceptance for Signal double err_Acceptance_SR = 0.01; double N_tot_theory = 5.; // Total Expected Signal Events for a given mass and Xsec. */ double Bkg_norm_factor_obs = 0.0378 ; // Normalizzation factor for background (N_Data_CR / N_Co_CR) double err_Norm_factor_obs = 0.0013; double S_tot = 123552; // Total events in ALL REGIONS for AmBe (--> the Eff_i are the efficiencies relative to the total) double B_tot = 24318; // Total events in SR for Co60 double Acceptance_SR_obs = 0.9; // Cut Acceptance for Signal double err_Acceptance_SR = 0.05; double N_tot_theory = 10.; // Total Expected Signal Events for a given mass and Xsec. Set to 10 because gives mu in range [0.,100] /**************************************************/ //---- retrieving global variables ----// TFile *histos = TFile::Open("h_for_limits.root"); TH1D *h_ambe_SR = (TH1D*)histos->Get("ambe_SR"); TH1D *h_co60_SR = (TH1D*)histos->Get("co60_SR"); TH1D *h_DM_SR = (TH1D*)histos->Get("DM_SR"); //----- Model for Global Variables -----// w.factory("N_tot_theory[10]"); w.factory("Acceptance_SR[0.9,0.0,1]"); w.factory("mu[1.,0.,100]"); w.factory("Bkg_norm_factor[0.7, 0.0,10.0]"); w.factory("S_tot[1000.0]"); w.factory("Gaussian:costraint_bkg_norm(Bkg_norm_factor_obs[0,10], Bkg_norm_factor, err_Norm_factor[1])"); // approximation (should be kind of complicated cauchy....) w.factory("Gaussian:costarint_sig_acc(Acceptance_SR_obs[0,1], Acceptance_SR, err_Acceptance_SR[0.01])");// this has the problem of boundaries acceptance cannot be larger than 1. --->Lognormal??? RooArgSet nuissanceParameter ;//(*w.var("Bkg_norm_factor"),*w.var("Acceptance_SR")); RooArgSet g_obs(*w.var("Bkg_norm_factor_obs"), *w.var("Acceptance_SR_obs")); RooArgSet obs; //----- Setting Value to Global Variables ------// w.var("N_tot_theory")->setVal(N_tot_theory); // Total expected Signal events w.var("Bkg_norm_factor_obs")->setVal(Bkg_norm_factor_obs); // Ratio between data in CR and Co in CR w.var("err_Norm_factor")->setVal(err_Norm_factor_obs); // Set error on norm factor w.var("Acceptance_SR_obs")->setVal(Acceptance_SR_obs); w.var("err_Acceptance_SR")->setVal(err_Acceptance_SR); w.var("S_tot")->setVal(S_tot); // Total events of AmBe in SR w.var("N_tot_theory")->setConstant(true); w.var("S_tot")->setConstant(true); w.var("Bkg_norm_factor_obs")->setConstant(true); w.var("err_Norm_factor")->setConstant(true); w.var("Acceptance_SR_obs")->setConstant(true); w.var("err_Acceptance_SR")->setConstant(true); //-------- Setting Value of NP to Observed!! ---------------// w.var("Acceptance_SR")->setVal(w.var("Acceptance_SR_obs")->getValV()); w.var("Acceptance_SR")->setMax(w.var("Acceptance_SR_obs")->getValV() + w.var("err_Acceptance_SR")->getValV() * 10.);// Set to 10 sigma. w.var("Bkg_norm_factor")->setMax(w.var("Bkg_norm_factor_obs")->getValV() + w.var("err_Norm_factor")->getValV()*10.); //set to 10 sigma. w.var("Bkg_norm_factor")->setVal(w.var("Bkg_norm_factor_obs")->getValV());// Set to observed value!!! //--- Set NP to constant!!! ONLY FOR TEST!! w.var("Acceptance_SR")->setConstant(true); w.var("Bkg_norm_factor")->setConstant(true); TString total_model = "PROD:model("; //bin-auxiliary measure variables double S_bin = 0.; double B_bin =0.; double nobs_bin =0.; /***************** LOOP OVER BINS *******************/ for (int bin_itr = 1; bin_itr <= h_ambe_SR->GetNbinsX() ; bin_itr++){ //retrieve bin info /* Default S_bin = 500.; // Observed events in bin_i for AmBe B_bin = 100.; // Observed events in bin_i for Co60 nobs_bin = 45.; // Observed events in bin_i for DM data */ S_bin = h_ambe_SR->GetBinContent(bin_itr); // Observed events in bin_i for AmBe B_bin = h_co60_SR->GetBinContent(bin_itr); // Observed events in bin_i for Co60 nobs_bin = h_DM_SR->GetBinContent(bin_itr); // Observed events in bin_i for DM data TString bin_name(TString::Itoa(bin_itr, 10)); w.factory("prod:N_s_"+bin_name+"(N_tot_theory, Acceptance_SR, Eff_AmBe_bin_"+bin_name+"[0.01,0.0,1], mu)"); w.factory("prod:N_b_"+bin_name+"(N_Co_SR_bin_"+bin_name+"[100.0,0.0,1000.0], Bkg_norm_factor)"); w.factory("sum:nexp_"+bin_name+"(N_s_"+bin_name+", N_b_"+bin_name+")"); // Poisson of (n | s+b) w.factory("Poisson:pdf_"+bin_name+"(nobs_"+bin_name+"[0.0,1000.0],nexp_"+bin_name+")"); // Poisson constraint --- Stat uncertainty on the bin content w.factory("prod:S_"+bin_name+"_exp(S_tot, Eff_AmBe_bin_"+bin_name+")"); // put 1000. to right AmBe amount w.factory("Poisson:AmBe_bin_"+bin_name+"(S_"+bin_name+"[500,0.0,50000.0],S_"+bin_name+"_exp)"); // change 50 for multiple bin, put 1000. to right AmBe amount w.factory("Poisson:Co_SR_bin_"+bin_name+"(B_"+bin_name+"[0.0,1000.0], N_Co_SR_bin_"+bin_name+")"); //change 100 for multiple bin, put 1000. to right Co tot amount in SR w.factory("PROD:model_"+bin_name+"(pdf_"+bin_name+",AmBe_bin_"+bin_name+",Co_SR_bin_"+bin_name+")"); // Set input variables -- Global OBSERVABLESerr_Norm_factor w.var("S_"+bin_name)->setMax(w.var("S_tot")->getValV()); // the range of the poisson needs to be defined w.var("S_"+bin_name)->setVal(S_bin); // Events in bin i for AmBe w.var("B_"+bin_name)->setMax(B_tot); // set to TOT Co in SR w.var("B_"+bin_name)->setVal(B_bin); // Set observed event in SR Co w.var("S_"+bin_name)->setConstant(true); w.var("B_"+bin_name)->setConstant(true); // Set range and value for nuissance parameters w.var("N_Co_SR_bin_"+bin_name)->setMax(B_bin + sqrt(B_bin)*10.); //set to 10 sigma. w.var("N_Co_SR_bin_"+bin_name)->setVal(B_bin); // set to observed value!! w.var("Eff_AmBe_bin_"+bin_name)->setVal(S_bin/ S_tot ); // Set to observed value!!! w.var("Eff_AmBe_bin_"+bin_name)->setMax( (S_bin + sqrt(S_bin)*10.) / S_tot ); // Set to observed value!!! if(w.var("Eff_AmBe_bin_"+bin_name)->getMax() > 1.) cout << "WARNING!!! Eff_AmBe_bin_"+bin_name+" efficiency > 1. " << endl; // Set NP to constant w.var("N_Co_SR_bin_"+bin_name)->setConstant(true); w.var("Eff_AmBe_bin_"+bin_name)->setConstant(true); //Set Observed events! w.var("nobs_"+bin_name)->setVal(nobs_bin); // Do not Add NP !!! // nuissanceParameter.add(*w.var("N_Co_SR_bin_"+bin_name)); // nuissanceParameter.add(*w.var("Eff_AmBe_bin_"+bin_name)); g_obs.add(*w.var("S_"+bin_name)); g_obs.add(*w.var("B_"+bin_name)); obs.add(*w.var("nobs_"+bin_name)); total_model.Append("model_"+bin_name+", "); } /************************************************************************/ total_model.Append("costraint_bkg_norm, costarint_sig_acc)"); w.factory(total_model); w.defineSet("nuissance_parameter",nuissanceParameter); w.defineSet("observables",obs); w.defineSet("g_observables",g_obs); histos->Close(); // RooArgSet set = w.allPdfs(); // set.Print(); // Set input Observables // w.var("nobs_"+bin_name+"")->setVal(40); /* // various printing w.pdf("AmBe_bin_i")->Print("all"); // Building the model ModelConfig mc("ModelConfig",&w); mc.SetPdf(*w.pdf("model")); mc.SetParametersOfInterest(*w.var("mu")); //mc.SetPriorPdf(*w.pdf("prior_s")); // Setting nuissance parameter RooArgSet nuissanceParameter (*w.var("Bkg_norm_factor"),*w.var("Acceptance_SR")); nuissanceParameter.add(*w.var("N_Co_SR_bin_i")); nuissanceParameter.add(*w.var("Eff_AmBe_bin_i")); mc.SetNuisanceParameters(nuissanceParameter); // need now to set the global observable RooArgSet g_obs(*w.var("S_i"), *w.var("B_i")); // g_obs.add(*w.var("N_tot_theory")); // g_obs.add(*w.var("S_tot")); g_obs.add(*w.var("Bkg_norm_factor_obs")); // g_obs.add(*w.var("err_Norm_factor")); g_obs.add(*w.var("Acceptance_SR_obs")); // g_obs.add(*w.var("err_Acceptance_SR")); mc.SetGlobalObservables(g_obs); RooArgSet observables(*w.var("nobs_i")); //observables.add(variousbins...); mc.SetObservables(observables); // this is needed for the hypothesis tests mc.SetSnapshot(*w.var("mu")); // make data set with the number of observed events RooDataSet data("data","", observables); data.add(observables); // import data set in workspace and save it in a file w.import(data); // import model in the workspace w.import(mc); w.writeToFile("CountingModel.root", true); */ }
// implementation void TwoBinInstructional( void ){ // let's time this example TStopwatch t; t.Start(); // set RooFit random seed for reproducible results RooRandom::randomGenerator()->SetSeed(4357); // make model RooWorkspace * pWs = new RooWorkspace("ws"); // derived from data pWs->factory("xsec[0.2,0,2]"); // POI pWs->factory("bg_b[10,0,50]"); // data driven nuisance // predefined nuisances pWs->factory("lumi[100,0,1000]"); pWs->factory("eff_a[0.2,0,1]"); pWs->factory("eff_b[0.05,0,1]"); pWs->factory("tau[0,1]"); pWs->factory("xsec_bg_a[0.05]"); // constant pWs->var("xsec_bg_a")->setConstant(1); // channel a (signal): lumi*xsec*eff_a + lumi*bg_a + tau*bg_b pWs->factory("prod::sig_a(lumi,xsec,eff_a)"); pWs->factory("prod::bg_a(lumi,xsec_bg_a)"); pWs->factory("prod::tau_bg_b(tau, bg_b)"); pWs->factory("Poisson::pdf_a(na[14,0,100],sum::mu_a(sig_a,bg_a,tau_bg_b))"); // channel b (control): lumi*xsec*eff_b + bg_b pWs->factory("prod::sig_b(lumi,xsec,eff_b)"); pWs->factory("Poisson::pdf_b(nb[11,0,100],sum::mu_b(sig_b,bg_b))"); // nuisance constraint terms (systematics) pWs->factory("Lognormal::l_lumi(lumi,nom_lumi[100,0,1000],sum::kappa_lumi(1,d_lumi[0.1]))"); pWs->factory("Lognormal::l_eff_a(eff_a,nom_eff_a[0.20,0,1],sum::kappa_eff_a(1,d_eff_a[0.05]))"); pWs->factory("Lognormal::l_eff_b(eff_b,nom_eff_b[0.05,0,1],sum::kappa_eff_b(1,d_eff_b[0.05]))"); pWs->factory("Lognormal::l_tau(tau,nom_tau[0.50,0,1],sum::kappa_tau(1,d_tau[0.05]))"); //pWs->factory("Lognormal::l_bg_a(bg_a,nom_bg_a[0.05,0,1],sum::kappa_bg_a(1,d_bg_a[0.10]))"); // complete model PDF pWs->factory("PROD::model(pdf_a,pdf_b,l_lumi,l_eff_a,l_eff_b,l_tau)"); // Now create sets of variables. Note that we could use the factory to // create sets but in that case many of the sets would be duplicated // when the ModelConfig objects are imported into the workspace. So, // we create the sets outside the workspace, and only the needed ones // will be automatically imported by ModelConfigs // observables RooArgSet obs(*pWs->var("na"), *pWs->var("nb"), "obs"); // global observables RooArgSet globalObs(*pWs->var("nom_lumi"), *pWs->var("nom_eff_a"), *pWs->var("nom_eff_b"), *pWs->var("nom_tau"), "global_obs"); // parameters of interest RooArgSet poi(*pWs->var("xsec"), "poi"); // nuisance parameters RooArgSet nuis(*pWs->var("lumi"), *pWs->var("eff_a"), *pWs->var("eff_b"), *pWs->var("tau"), "nuis"); // priors (for Bayesian calculation) pWs->factory("Uniform::prior_xsec(xsec)"); // for parameter of interest pWs->factory("Uniform::prior_bg_b(bg_b)"); // for data driven nuisance parameter pWs->factory("PROD::prior(prior_xsec,prior_bg_b)"); // total prior // create data pWs->var("na")->setVal(14); pWs->var("nb")->setVal(11); RooDataSet * pData = new RooDataSet("data","",obs); pData->add(obs); pWs->import(*pData); //pData->Print(); // signal+background model ModelConfig * pSbModel = new ModelConfig("SbModel"); pSbModel->SetWorkspace(*pWs); pSbModel->SetPdf(*pWs->pdf("model")); pSbModel->SetPriorPdf(*pWs->pdf("prior")); pSbModel->SetParametersOfInterest(poi); pSbModel->SetNuisanceParameters(nuis); pSbModel->SetObservables(obs); pSbModel->SetGlobalObservables(globalObs); // set all but obs, poi and nuisance to const SetConstants(pWs, pSbModel); pWs->import(*pSbModel); // background-only model // use the same PDF as s+b, with xsec=0 // POI value under the background hypothesis Double_t poiValueForBModel = 0.0; ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)pWs->obj("SbModel")); pBModel->SetName("BModel"); pBModel->SetWorkspace(*pWs); pWs->import(*pBModel); // find global maximum with the signal+background model // with conditional MLEs for nuisance parameters // and save the parameter point snapshot in the Workspace // - safer to keep a default name because some RooStats calculators // will anticipate it RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData); RooAbsReal * pProfile = pNll->createProfile(RooArgSet()); pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values RooArgSet * pPoiAndNuisance = new RooArgSet(); if(pSbModel->GetNuisanceParameters()) pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest()); cout << "\nWill save these parameter points that correspond to the fit to data" << endl; pPoiAndNuisance->Print("v"); pSbModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // Find a parameter point for generating pseudo-data // with the background-only data. // Save the parameter point snapshot in the Workspace pNll = pBModel->GetPdf()->createNLL(*pData); pProfile = pNll->createProfile(poi); ((RooRealVar *)poi.first())->setVal(poiValueForBModel); pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet(); if(pBModel->GetNuisanceParameters()) pPoiAndNuisance->add(*pBModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pBModel->GetParametersOfInterest()); cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl; pPoiAndNuisance->Print("v"); pBModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // inspect workspace pWs->Print(); // save workspace to file pWs->writeToFile("ws_twobin.root"); // clean up delete pWs; delete pData; delete pSbModel; delete pBModel; } // ----- end of tutorial ----------------------------------------
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 rf511_wsfactory_basic(Bool_t compact=kFALSE) { RooWorkspace* w = new RooWorkspace("w") ; // C r e a t i n g a n d a d d i n g b a s i c p . d . f . s // ---------------------------------------------------------------- // Remake example p.d.f. of tutorial rs502_wspacewrite.C: // // Basic p.d.f. construction: ClassName::ObjectName(constructor arguments) // Variable construction : VarName[x,xlo,xhi], VarName[xlo,xhi], VarName[x] // P.d.f. addition : SUM::ObjectName(coef1*pdf1,...coefM*pdfM,pdfN) // if (!compact) { // Use object factory to build p.d.f. of tutorial rs502_wspacewrite w->factory("Gaussian::sig1(x[-10,10],mean[5,0,10],0.5)") ; w->factory("Gaussian::sig2(x,mean,1)") ; w->factory("Chebychev::bkg(x,{a0[0.5,0.,1],a1[-0.2,0.,1.]})") ; w->factory("SUM::sig(sig1frac[0.8,0.,1.]*sig1,sig2)") ; w->factory("SUM::model(bkgfrac[0.5,0.,1.]*bkg,sig)") ; } else { // Use object factory to build p.d.f. of tutorial rs502_wspacewrite but // - Contracted to a single line recursive expression, // - Omitting explicit names for components that are not referred to explicitly later w->factory("SUM::model(bkgfrac[0.5,0.,1.]*Chebychev::bkg(x[-10,10],{a0[0.5,0.,1],a1[-0.2,0.,1.]})," "SUM(sig1frac[0.8,0.,1.]*Gaussian(x,mean[5,0,10],0.5), Gaussian(x,mean,1)))") ; } // A d v a n c e d p . d . f . c o n s t r u c t o r a r g u m e n t s // ---------------------------------------------------------------- // // P.d.f. constructor arguments may by any type of RooAbsArg, but also // // Double_t --> converted to RooConst(...) // {a,b,c} --> converted to RooArgSet() or RooArgList() depending on required ctor arg // dataset name --> convered to RooAbsData reference for any dataset residing in the workspace // enum --> Any enum label that belongs to an enum defined in the (base) class // Make a dummy dataset p.d.f. 'model' and import it in the workspace RooDataSet* data = w->pdf("model")->generate(*w->var("x"),1000) ; w->import(*data,Rename("data")) ; // Construct a KEYS p.d.f. passing a dataset name and an enum type defining the // mirroring strategy w->factory("KeysPdf::k(x,data,NoMirror,0.2)") ; // Print workspace contents w->Print() ; // Make workspace visible on command line gDirectory->Add(w) ; }
void runBATCalculator() { // Definiton of a RooWorkspace containing the statistics model. Later the // information for BATCalculator is retrieved from the workspace. This is // certainly a bit of overhead but better from an educative point of view. cout << "preparing the RooWorkspace object" << endl; RooWorkspace* myWS = new RooWorkspace("myWS", true); // combined prior for signal contribution myWS->factory("Product::signal({sigma_s[0,20],L[5,15],epsilon[0,1]})"); myWS->factory("N_bkg[0,3]"); // define prior functions // uniform prior for signal crosssection myWS->factory("Uniform::prior_sigma_s(sigma_s)"); // (truncated) prior for efficiency myWS->factory("Gaussian::prior_epsilon(epsilon,0.51,0.0765)"); // (truncated) Gaussian prior for luminosity myWS->factory("Gaussian::prior_L(L,10,1)"); // (truncated) Gaussian prior for bkg crosssection myWS->factory("Gaussian::prior_N_bkg(N_bkg,0.52,0.156)"); // Poisson distribution with mean signal+bkg myWS->factory("Poisson::model(n[0,300],sum(signal,N_bkg))"); // define the global prior function myWS->factory("PROD::prior(prior_sigma_s,prior_epsilon,prior_L,prior_N_bkg)"); // Definition of observables and parameters of interest myWS->defineSet("obsSet", "n"); myWS->defineSet("poiSet", "sigma_s"); myWS->defineSet("nuisanceSet", "N_bkg,L,epsilon"); // ->model complete (Additional information can be found in the // RooStats manual) // feel free to vary the parameters, but don't forget to choose reasonable ranges for the // variables. Currently the Bayesian methods will often not work well if the variable ranges // are either too short (for obvious reasons) or too large (for technical reasons). // A ModelConfig object is used to associate parts of your workspace with their statistical // meaning (it is also possible to initialize BATCalculator directly with elements from the // workspace but if you are sharing your workspace with others or if you want to use several // different methods the use of ModelConfig will most often turn out to be the better choice.) // setup the ModelConfig object cout << "preparing the ModelConfig object" << endl; ModelConfig modelconfig("modelconfig", "ModelConfig for this example"); modelconfig.SetWorkspace(*myWS); modelconfig.SetPdf(*(myWS->pdf("model"))); modelconfig.SetParametersOfInterest(*(myWS->set("poiSet"))); modelconfig.SetPriorPdf(*(myWS->pdf("prior"))); modelconfig.SetNuisanceParameters(*(myWS->set("nuisanceSet"))); modelconfig.SetObservables(*(myWS->set("obsSet"))); // use BATCalculator to the derive credibility intervals as a function of the observed number of // events in the hypothetical experiment // define vector with tested numbers of events TVectorD obsEvents; // define vectors which will be filled with the lower and upper limits for each tested number // of observed events TVectorD BATul; TVectorD BATll; // fix upper limit of tested observed number of events int obslimit = 10; obsEvents.ResizeTo(obslimit); BATul.ResizeTo(obslimit); BATll.ResizeTo(obslimit); cout << "starting the calculation of Bayesian credibility intervals with BATCalculator" << endl; // loop over observed number of events in the hypothetical experiment for (int obs = 1; obs <= obslimit; obs++) { obsEvents[obs - 1] = (static_cast<double>(obs)); // prepare data input for the the observed number of events // adjust number of observed events in the workspace. This is communicated to ModelConfig! myWS->var("n")->setVal(obs); // create data RooDataSet data("data", "", *(modelconfig.GetObservables())); data.add( *(modelconfig.GetObservables())); // prepare BATCalulator BATCalculator batcalc(data, modelconfig); // give the BATCalculator a unique name (always a good idea in ROOT) TString namestring = "mybatc_"; namestring += obs; batcalc.SetName(namestring); // fix amount of posterior probability in the calculated interval. // the name confidence level is incorrect here batcalc.SetConfidenceLevel(0.90); // fix length of the Markov chain. (in general: the longer the Markov chain the more // precise will be the results) batcalc.SetnMCMC(20000); // retrieve SimpleInterval object containing the information about the interval (this // triggers the actual calculations) SimpleInterval* interval = batcalc.GetInterval1D("sigma_s"); std::cout << "BATCalculator: 90% credibility interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or 95% credibility upper limit\n"; // add the interval borders for the current number of observed events to the vectors // containing the lower and upper limits BATll[obs - 1] = interval->LowerLimit(); BATul[obs - 1] = interval->UpperLimit(); // clean up for next loop element batcalc.CleanCalculatorForNewData(); delete interval; } cout << "all limits calculated" << endl; // summarize the results in a plot TGraph* grBATll = new TGraph(obsEvents, BATll); grBATll->SetLineColor(kGreen); grBATll->SetLineWidth(200); grBATll->SetFillStyle(3001); grBATll->SetFillColor(kGreen); TGraph* grBATul = new TGraph(obsEvents, BATul); grBATul->SetLineColor(kGreen); grBATul->SetLineWidth(-200); grBATul->SetFillStyle(3001); grBATul->SetFillColor(kGreen); // create and draw multigraph TMultiGraph* mg = new TMultiGraph("BayesianLimitsBATCalculator", "BayesianLimitsBATCalculator"); mg->SetTitle("example of Bayesian credibility intervals derived with BATCAlculator "); mg->Add(grBATll); mg->Add(grBATul); mg->Draw("AC"); mg->GetXaxis()->SetTitle ("# observed events"); mg->GetYaxis()->SetTitle("limits on signal S (size of test: 0.1)"); mg->Draw("AC"); }
/* * Prepares the workspace to be used by the hypothesis test calculator */ void workspace_preparer(char *signal_file_name, char *signal_hist_name_in_file, char *background_file_name, char *background_hist_name_in_file, char *data_file_name, char *data_hist_name_in_file, char *config_file) { // Include the config_reader class. TString path = gSystem->GetIncludePath(); path.Append(" -I/home/max/cern/cls/mario"); gSystem->SetIncludePath(path); gROOT->LoadMacro("config_reader.cxx"); // RooWorkspace used to store values. RooWorkspace * pWs = new RooWorkspace("ws"); // Create a config_reader (see source for details) to read the config // file. config_reader reader(config_file, pWs); // Read MR and RR bounds from the config file. double MR_lower = reader.find_double("MR_lower"); double MR_upper = reader.find_double("MR_upper"); double RR_lower = reader.find_double("RR_lower"); double RR_upper = reader.find_double("RR_upper"); double MR_initial = (MR_lower + MR_upper)/2; double RR_initial = (RR_lower + RR_upper)/2; // Define the Razor Variables RooRealVar MR = RooRealVar("MR", "MR", MR_initial, MR_lower, MR_upper); RooRealVar RR = RooRealVar("RSQ", "RSQ", RR_initial, RR_lower, RR_upper); // Argument lists RooArgList pdf_arg_list(MR, RR, "input_args_list"); RooArgSet pdf_arg_set(MR, RR, "input_pdf_args_set"); /***********************************************************************/ /* PART 1: IMPORTING SIGNAL AND BACKGROUND HISTOGRAMS */ /***********************************************************************/ /* * Get the signal's unextended pdf by converting the TH2D in the file * into a RooHistPdf */ TFile *signal_file = new TFile(signal_file_name); TH2D *signal_hist = (TH2D *)signal_file->Get(signal_hist_name_in_file); RooDataHist *signal_RooDataHist = new RooDataHist("signal_roodatahist", "signal_roodatahist", pdf_arg_list, signal_hist); RooHistPdf *unextended_sig_pdf = new RooHistPdf("unextended_sig_pdf", "unextended_sig_pdf", pdf_arg_set, *signal_RooDataHist); /* * Repeat this process for the background. */ TFile *background_file = new TFile(background_file_name); TH2D *background_hist = (TH2D *)background_file->Get(background_hist_name_in_file); RooDataHist *background_RooDataHist = new RooDataHist("background_roodatahist", "background_roodatahist", pdf_arg_list, background_hist); RooHistPdf *unextended_bkg_pdf = new RooHistPdf("unextended_bkg_pdf", "unextended_bkg_pdf", pdf_arg_set, *background_RooDataHist); /* * Now, we want to create the bprime variable, which represents the * integral over the background-only sample. We will perform the * integral automatically (that's why this is the only nuisance * parameter declared in this file - its value can be determined from * the input histograms). */ ostringstream bprime_string; ostringstream bprime_pdf_string; bprime_string << "bprime[" << background_hist->Integral() << ", 0, 999999999]"; bprime_pdf_string << "Poisson::bprime_pdf(bprime, " << background_hist->Integral() << ")"; pWs->factory(bprime_string.str().c_str()); pWs->factory(bprime_pdf_string.str().c_str()); /* * This simple command will create all values from the config file * with 'make:' at the beginning and a delimiter at the end (see config * _reader if you don't know what a delimiter is). In other * words, the luminosity, efficiency, transfer factors, and their pdfs * are created from this command. The declarations are contained in the * config file to be changed easily without having to modify this code. */ reader.factory_all(); /* * Now, we want to create the extended pdfs from the unextended pdfs, as * well as from the S and B values we manufactured in the config file. * S and B are the values by which the signal and background pdfs, * respectively, are extended. Recall that they were put in the * workspace in the reader.facotry_all() command. */ RooAbsReal *S = pWs->function("S"); RooAbsReal *B = pWs->function("B"); RooExtendPdf *signalpart = new RooExtendPdf("signalpart", "signalpart", *unextended_sig_pdf, *S); RooExtendPdf *backgroundpart = new RooExtendPdf("backgroundpart", "backgroundpart", *unextended_bkg_pdf, *B); RooArgList *pdf_list = new RooArgList(*signalpart, *backgroundpart, "list"); // Add the signal and background pdfs to make a TotalPdf RooAddPdf *TotalPdf = new RooAddPdf("TotalPdf", "TotalPdf", *pdf_list); RooArgList *pdf_prod_list = new RooArgList(*TotalPdf, *pWs->pdf("lumi_pdf"), *pWs->pdf("eff_pdf"), *pWs->pdf("rho_pdf"), *pWs->pdf("bprime_pdf")); // This creates the final model pdf. RooProdPdf *model = new RooProdPdf("model", "model", *pdf_prod_list); /* * Up until now, we have been using the workspace pWs to contain all of * our values. Now, all of our values that we require are in use in the * RooProdPdf called "model". So, we need to import "model" into a * RooWorkspace. To avoid recopying values into the rooworkspace, when * the values may already be present (which can cause problems), we will * simply create a new RooWorkspace to avoid confusion and problems. The * new RooWorkspace is created here. */ RooWorkspace *newworkspace = new RooWorkspace("newws"); newworkspace->import(*model); // Immediately delete pWs, so we don't accidentally use it again. delete pWs; // Show off the newworkspace newworkspace->Print(); // observables RooArgSet obs(*newworkspace->var("MR"), *newworkspace->var("RSQ"), "obs"); // global observables RooArgSet globalObs(*newworkspace->var("nom_lumi"), *newworkspace->var("nom_eff"), *newworkspace->var("nom_rho")); //fix global observables to their nominal values newworkspace->var("nom_lumi")->setConstant(); newworkspace->var("nom_eff")->setConstant(); newworkspace->var("nom_rho")->setConstant(); //Set Parameters of interest RooArgSet poi(*newworkspace->var("sigma"), "poi"); //Set Nuisnaces RooArgSet nuis(*newworkspace->var("prime_lumi"), *newworkspace->var("prime_eff"), *newworkspace->var("prime_rho"), *newworkspace->var("bprime")); // priors (for Bayesian calculation) newworkspace->factory("Uniform::prior_signal(sigma)"); // for parameter of interest newworkspace->factory("Uniform::prior_bg_b(bprime)"); // for data driven nuisance parameter newworkspace->factory("PROD::prior(prior_signal,prior_bg_b)"); // total prior //Observed data is pulled from histogram. //TFile *data_file = new TFile(data_file_name); TFile *data_file = new TFile(data_file_name); TH2D *data_hist = (TH2D *)data_file->Get(data_hist_name_in_file); RooDataHist *pData = new RooDataHist("data", "data", obs, data_hist); newworkspace->import(*pData); // Now, we will draw our data from a RooDataHist. /*TFile *data_file = new TFile(data_file_name); TTree *data_tree = (TTree *) data_file->Get(data_hist_name_in_file); RooDataSet *pData = new RooDataSet("data", "data", data_tree, obs); newworkspace->import(*pData);*/ // Craft the signal+background model ModelConfig * pSbModel = new ModelConfig("SbModel"); pSbModel->SetWorkspace(*newworkspace); pSbModel->SetPdf(*newworkspace->pdf("model")); pSbModel->SetPriorPdf(*newworkspace->pdf("prior")); pSbModel->SetParametersOfInterest(poi); pSbModel->SetNuisanceParameters(nuis); pSbModel->SetObservables(obs); pSbModel->SetGlobalObservables(globalObs); // set all but obs, poi and nuisance to const SetConstants(newworkspace, pSbModel); newworkspace->import(*pSbModel); // background-only model // use the same PDF as s+b, with sig=0 // POI value under the background hypothesis // (We will set the value to 0 later) Double_t poiValueForBModel = 0.0; ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)newworkspace->obj("SbModel")); pBModel->SetName("BModel"); pBModel->SetWorkspace(*newworkspace); newworkspace->import(*pBModel); // find global maximum with the signal+background model // with conditional MLEs for nuisance parameters // and save the parameter point snapshot in the Workspace // - safer to keep a default name because some RooStats calculators // will anticipate it RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData); RooAbsReal * pProfile = pNll->createProfile(RooArgSet()); pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values RooArgSet * pPoiAndNuisance = new RooArgSet(); if(pSbModel->GetNuisanceParameters()) pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest()); cout << "\nWill save these parameter points that correspond to the fit to data" << endl; pPoiAndNuisance->Print("v"); pSbModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // Find a parameter point for generating pseudo-data // with the background-only data. // Save the parameter point snapshot in the Workspace pNll = pBModel->GetPdf()->createNLL(*pData); pProfile = pNll->createProfile(poi); ((RooRealVar *)poi.first())->setVal(poiValueForBModel); pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values pPoiAndNuisance = new RooArgSet(); if(pBModel->GetNuisanceParameters()) pPoiAndNuisance->add(*pBModel->GetNuisanceParameters()); pPoiAndNuisance->add(*pBModel->GetParametersOfInterest()); cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl; pPoiAndNuisance->Print("v"); pBModel->SetSnapshot(*pPoiAndNuisance); delete pProfile; delete pNll; delete pPoiAndNuisance; // save workspace to file newworkspace->writeToFile("ws_twobin.root"); // clean up delete newworkspace; delete pData; delete pSbModel; delete pBModel; } // ----- end of tutorial ----------------------------------------
void rs101_limitexample() { // -------------------------------------- // An example of setting a limit in a number counting experiment with uncertainty on background and signal // to time the macro TStopwatch t; t.Start(); // -------------------------------------- // The Model building stage // -------------------------------------- RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,3.],b[100]*ratioBkgEff[1.,0.,3.]))"); // counting model // wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty // wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty wspace->factory("Gaussian::sigConstraint(gSigEff[1,0,3],ratioSigEff,0.05)"); // 5% signal efficiency uncertainty wspace->factory("Gaussian::bkgConstraint(gSigBkg[1,0,3],ratioBkgEff,0.2)"); // 10% background efficiency uncertainty wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms wspace->Print(); RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model RooRealVar* obs = wspace->var("obs"); // get the observable RooRealVar* s = wspace->var("s"); // get the signal we care about RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff b->setConstant(); RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertain parameter to constrain RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertain parameter to constrain RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior) RooRealVar * gSigEff = wspace->var("gSigEff"); // global observables for signal efficiency RooRealVar * gSigBkg = wspace->var("gSigBkg"); // global obs for background efficiency gSigEff->setConstant(); gSigBkg->setConstant(); // Create an example dataset with 160 observed events obs->setVal(160.); RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs)); data->add(*obs); RooArgSet all(*s, *ratioBkgEff, *ratioSigEff); // not necessary modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff))); // Now let's make some confidence intervals for s, our parameter of interest RooArgSet paramOfInterest(*s); ModelConfig modelConfig(wspace); modelConfig.SetPdf(*modelWithConstraints); modelConfig.SetParametersOfInterest(paramOfInterest); modelConfig.SetNuisanceParameters(constrainedParams); modelConfig.SetObservables(*obs); modelConfig.SetGlobalObservables( RooArgSet(*gSigEff,*gSigBkg)); modelConfig.SetName("ModelConfig"); wspace->import(modelConfig); wspace->import(*data); wspace->SetName("w"); wspace->writeToFile("rs101_ws.root"); // First, let's use a Calculator based on the Profile Likelihood Ratio //ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest); ProfileLikelihoodCalculator plc(*data, modelConfig); plc.SetTestSize(.05); ConfInterval* lrinterval = plc.GetInterval(); // that was easy. // Let's make a plot TCanvas* dataCanvas = new TCanvas("dataCanvas"); dataCanvas->Divide(2,1); dataCanvas->cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrinterval); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S"); plotInt.Draw(); // Second, use a Calculator based on the Feldman Cousins technique FeldmanCousins fc(*data, modelConfig); fc.UseAdaptiveSampling(true); fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed fc.SetNBins(100); // number of points to test per parameter fc.SetTestSize(.05); // fc.SaveBeltToFile(true); // optional ConfInterval* fcint = NULL; fcint = fc.GetInterval(); // that was easy. RooFitResult* fit = modelWithConstraints->fitTo(*data, Save(true)); // Third, use a Calculator based on Markov Chain monte carlo // Before configuring the calculator, let's make a ProposalFunction // that will achieve a high acceptance rate ProposalHelper ph; ph.SetVariables((RooArgSet&)fit->floatParsFinal()); ph.SetCovMatrix(fit->covarianceMatrix()); ph.SetUpdateProposalParameters(true); ph.SetCacheSize(100); ProposalFunction* pdfProp = ph.GetProposalFunction(); // that was easy MCMCCalculator mc(*data, modelConfig); mc.SetNumIters(20000); // steps to propose in the chain mc.SetTestSize(.05); // 95% CL mc.SetNumBurnInSteps(40); // ignore first N steps in chain as "burn in" mc.SetProposalFunction(*pdfProp); mc.SetLeftSideTailFraction(0.5); // find a "central" interval MCMCInterval* mcInt = (MCMCInterval*)mc.GetInterval(); // that was easy // Get Lower and Upper limits from Profile Calculator cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrinterval)->LowerLimit(*s) << endl; cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrinterval)->UpperLimit(*s) << endl; // Get Lower and Upper limits from FeldmanCousins with profile construction if (fcint != NULL) { double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s); double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s); cout << "FC lower limit on s = " << fcll << endl; cout << "FC upper limit on s = " << fcul << endl; TLine* fcllLine = new TLine(fcll, 0, fcll, 1); TLine* fculLine = new TLine(fcul, 0, fcul, 1); fcllLine->SetLineColor(kRed); fculLine->SetLineColor(kRed); fcllLine->Draw("same"); fculLine->Draw("same"); dataCanvas->Update(); } // Plot MCMC interval and print some statistics MCMCIntervalPlot mcPlot(*mcInt); mcPlot.SetLineColor(kMagenta); mcPlot.SetLineWidth(2); mcPlot.Draw("same"); double mcul = mcInt->UpperLimit(*s); double mcll = mcInt->LowerLimit(*s); cout << "MCMC lower limit on s = " << mcll << endl; cout << "MCMC upper limit on s = " << mcul << endl; cout << "MCMC Actual confidence level: " << mcInt->GetActualConfidenceLevel() << endl; // 3-d plot of the parameter points dataCanvas->cd(2); // also plot the points in the markov chain RooDataSet * chainData = mcInt->GetChainAsDataSet(); assert(chainData); std::cout << "plotting the chain data - nentries = " << chainData->numEntries() << std::endl; TTree* chain = RooStats::GetAsTTree("chainTreeData","chainTreeData",*chainData); assert(chain); chain->SetMarkerStyle(6); chain->SetMarkerColor(kRed); chain->Draw("s:ratioSigEff:ratioBkgEff","nll_MarkovChain_local_","box"); // 3-d box proportional to posterior // the points used in the profile construction RooDataSet * parScanData = (RooDataSet*) fc.GetPointsToScan(); assert(parScanData); std::cout << "plotting the scanned points used in the frequentist construction - npoints = " << parScanData->numEntries() << std::endl; // getting the tree and drawing it -crashes (very strange....); // TTree* parameterScan = RooStats::GetAsTTree("parScanTreeData","parScanTreeData",*parScanData); // assert(parameterScan); // parameterScan->Draw("s:ratioSigEff:ratioBkgEff","","goff"); TGraph2D *gr = new TGraph2D(parScanData->numEntries()); for (int ievt = 0; ievt < parScanData->numEntries(); ++ievt) { const RooArgSet * evt = parScanData->get(ievt); double x = evt->getRealValue("ratioBkgEff"); double y = evt->getRealValue("ratioSigEff"); double z = evt->getRealValue("s"); gr->SetPoint(ievt, x,y,z); // std::cout << ievt << " " << x << " " << y << " " << z << std::endl; } gr->SetMarkerStyle(24); gr->Draw("P SAME"); delete wspace; delete lrinterval; delete mcInt; delete fcint; delete data; // print timing info t.Stop(); t.Print(); }