Пример #1
0
//#include <typeinfo.h>
void addFlatNuisances(std::string fi){
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
  TFile *fin = TFile::Open(fi.c_str());
  RooWorkspace *wspace = (RooWorkspace*)fin->Get("w_hmumu");

  wspace->Print("");

  RooStats::ModelConfig *mc = (RooStats::ModelConfig*)wspace->genobj("ModelConfig");
  RooArgSet *nuis = (RooArgSet*) mc->GetNuisanceParameters();
  std::cout << "Before...." << std::endl;
  nuis->Print();
  
  RooRealVar *mgg = (RooRealVar*)wspace->var("mmm");
  // Get all of the "flat" nuisances to be added to the nusiances:
  RooArgSet pdfs = (RooArgSet) wspace->allVars();
  RooAbsReal *pdf;
  TIterator *it_pdf = pdfs.createIterator();
  

  while ( (pdf=(RooAbsReal*)it_pdf->Next()) ){
  	  if (!(std::string(pdf->GetName()).find("zmod") != std::string::npos )) {
  	   if (!(std::string(pdf->GetName()).find("__norm") != std::string::npos )) {
	   	continue;
	   }
	  }
	  pdf->Print();
	  RooArgSet* pdfpars = (RooArgSet*)pdf->getParameters(RooArgSet(*mgg));
	  pdfpars->Print();

	  std::string newname_pdf = (std::string("unconst_")+std::string(pdf->GetName()));
	  wspace->import(*pdf,RooFit::RenameVariable(pdf->GetName(),newname_pdf.c_str()));
	  pdf->SetName(newname_pdf.c_str());
	  nuis->add(*pdf);
  }
 
  wspace->var("MH")->setVal(125.0);
  std::cout << "After..." << std::endl;
  nuis->Print();
  mc->SetNuisanceParameters(*nuis);
  //RooWorkspace *wspace_new = wspace->Clone();
  //mc->SetWorkspace(*wspace_new);
  //wspace_new->import(*mc,true);

  TFile *finew = new TFile((std::string(fin->GetName())+std::string("_unconst.root")).c_str(),"RECREATE");
  //wspace_new->SetName("w");
  finew->WriteTObject(wspace);
  finew->Close();
}
Пример #2
0
exampleScript()
{
  gSystem->CompileMacro("betaHelperFunctions.h"      ,"kO") ;
  gSystem->CompileMacro("RooNormalFromFlatPdf.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaInverseCDF.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaPrimeInverseCDF.cxx" ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaPrimeGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("rooFitBetaHelperFunctions.h","kO") ;

  TFile betaTest("betaTest.root","RECREATE");
  betaTest.cd();
  
  RooWorkspace workspace("workspace");
  TString correlatedName("testVariable");
  TString observables("observables");
  TString nuisances("nuisances");

  RooAbsArg* betaOne = getCorrelatedBetaConstraint(workspace,"betaOne","",
						   0.5 , 0.1 ,
						   observables, nuisances,
						   correlatedName );

  printf("\n\n *** constraint name is %s from betaOne and %s\n\n", betaOne->GetName(), correlatedName.Data() ) ;

  RooAbsArg* betaTwo = getCorrelatedBetaConstraint(workspace,"betaTwo","",
						   0 , 0 ,
						   observables, nuisances,
						   correlatedName );

  RooAbsArg* betaThree = getCorrelatedBetaConstraint(workspace,"betaThree","",
						     0.2 , 0.01 ,
						     observables, nuisances,
						     correlatedName );

  RooAbsArg* betaFour = getCorrelatedBetaConstraint(workspace,"betaFour","",
						    0.7 , 0.1 ,
						    observables, nuisances,
						    correlatedName );

  RooAbsArg* betaFourC = getCorrelatedBetaConstraint(workspace,"betaFourC","",
						    0.7 , 0.1 ,
						    observables, nuisances,
						    correlatedName, kTRUE );

  RooAbsArg* betaPrimeOne = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeOne","",
							     1.0 , 0.5 ,
							     observables, nuisances,
							     correlatedName );

  RooAbsArg* betaPrimeOneC = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeOneC","",
							     1.0 , 0.5 ,
							     observables, nuisances,
							     correlatedName, kTRUE );

  RooAbsArg* betaPrimeTwo = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeTwo","",
							     0.7 , 0.5 ,
							     observables, nuisances,
							     correlatedName );

  RooAbsArg* betaPrimeThree = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeThree","",
							       0.1 , 0.05 ,
							       observables, nuisances,
							       correlatedName );

  RooAbsArg* betaPrimeFour = getCorrelatedBetaPrimeConstraint(workspace,"betaPrimeFour","",
							      7 , 1 ,
							      observables, nuisances,
							      correlatedName );

  RooRealVar* correlatedParameter = workspace.var(correlatedName);

  RooAbsPdf* normalFromFlat = workspace.pdf(correlatedName+"_Constraint");

  RooDataSet* data = normalFromFlat->generate(RooArgSet(*correlatedParameter),1e5);

  data->addColumn(*normalFromFlat);

  data->addColumn(*betaOne);
  data->addColumn(*betaTwo);
  data->addColumn(*betaThree);
  data->addColumn(*betaFour);
  data->addColumn(*betaFourC);
  
  data->addColumn(*betaPrimeOne);
  data->addColumn(*betaPrimeTwo);
  data->addColumn(*betaPrimeThree);
  data->addColumn(*betaPrimeFour);
  data->addColumn(*betaPrimeOneC);

  data->Print("v");

  workspace.Print() ;

  //Setup Plotting Kluges:

  RooRealVar normalPlotter  (correlatedName+"_Constraint" , correlatedName+"_Constraint"  ,0,1);
  RooPlot* normalPlot = normalPlotter.frame();
  data->plotOn(normalPlot);

  RooRealVar betaOnePlotter  ("betaOne_BetaInverseCDF"  ,"betaOne_BetaInverseCDF"  ,0,1);
  RooRealVar betaTwoPlotter  ("betaTwo_BetaInverseCDF"  ,"betaTwo_BetaInverseCDF"  ,0,1);
  RooRealVar betaThreePlotter("betaThree_BetaInverseCDF","betaThree_BetaInverseCDF",0,1);
  RooRealVar betaFourPlotter ("betaFour_BetaInverseCDF" ,"betaFour_BetaInverseCDF" ,0,1);
  RooRealVar betaFourCPlotter ("betaFourC_BetaInverseCDF" ,"betaFourC_BetaInverseCDF" ,0,1);

  RooRealVar betaPrimeOnePlotter  ("betaPrimeOne_BetaPrimeInverseCDF"  ,"betaPrimeOne_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeOneCPlotter  ("betaPrimeOneC_BetaPrimeInverseCDF"  ,"betaPrimeOneC_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeTwoPlotter  ("betaPrimeTwo_BetaPrimeInverseCDF"  ,"betaPrimeTwo_BetaPrimeInverseCDF"  ,0,4);
  RooRealVar betaPrimeThreePlotter("betaPrimeThree_BetaPrimeInverseCDF","betaPrimeThree_BetaPrimeInverseCDF",0,0.3);
  RooRealVar betaPrimeFourPlotter ("betaPrimeFour_BetaPrimeInverseCDF" ,"betaPrimeFour_BetaPrimeInverseCDF" ,4,12);

  RooPlot* betaOnePlot   = betaOnePlotter  .frame();
  RooPlot* betaTwoPlot   = betaTwoPlotter  .frame();
  RooPlot* betaThreePlot = betaThreePlotter.frame();
  RooPlot* betaFourPlot  = betaFourPlotter .frame();
  RooPlot* betaFourCPlot  = betaFourCPlotter .frame();

  data->plotOn(betaOnePlot  );
  data->plotOn(betaTwoPlot  );
  data->plotOn(betaThreePlot);
  data->plotOn(betaFourPlot );
  data->plotOn(betaFourCPlot );

  RooPlot* betaPrimeOnePlot   = betaPrimeOnePlotter  .frame();
  RooPlot* betaPrimeOneCPlot   = betaPrimeOneCPlotter  .frame();
  RooPlot* betaPrimeTwoPlot   = betaPrimeTwoPlotter  .frame();
  RooPlot* betaPrimeThreePlot = betaPrimeThreePlotter.frame();
  RooPlot* betaPrimeFourPlot  = betaPrimeFourPlotter .frame();

  data->plotOn(betaPrimeOnePlot  );
  data->plotOn(betaPrimeOneCPlot  );
  data->plotOn(betaPrimeTwoPlot  );
  data->plotOn(betaPrimeThreePlot);
  data->plotOn(betaPrimeFourPlot );

  TCanvas* underlyingVariable = new TCanvas("underlyingVariable","underlyingVariable",800,800);
  underlyingVariable->Divide(2,2);
  underlyingVariable->cd(1);
  RooPlot* underlyingPlot   = correlatedParameter->frame();
  data->plotOn(underlyingPlot);
  underlyingPlot->Draw();
  underlyingVariable->cd(2);
  normalPlot->Draw();
  underlyingVariable->cd(3);
  TH2F* underlying = data->createHistogram(*correlatedParameter,normalPlotter,50,50);
  underlying->Draw("col");
  TH2F* legoUnderlying = (TH2F*)underlying->Clone();
  underlyingVariable->cd(4);
  legoUnderlying->Draw("lego");

  underlyingVariable->SaveAs("underlyingVariable.pdf");
  
  TCanvas* betaCanvas = new TCanvas("betaCanvas","betaCanvas",800,800);
  
  betaCanvas->Divide(3,2);
  
  betaCanvas->cd(1);
  betaOnePlot->Draw();
  betaCanvas->cd(2);
  betaTwoPlot->Draw();
  betaCanvas->cd(3);
  betaThreePlot->Draw();
  betaCanvas->cd(4);
  betaFourPlot->Draw();
  betaCanvas->cd(5);
  betaFourCPlot->Draw();

  betaCanvas->SaveAs("betaVariables.pdf");

  TCanvas* betaPrimeCanvas = new TCanvas("betaPrimeCanvas","betaPrimeCanvas",1200,800);
  
  betaPrimeCanvas->Divide(3,2);
  
  betaPrimeCanvas->cd(1);
  betaPrimeOnePlot->Draw();
  betaPrimeCanvas->cd(2);
  betaPrimeTwoPlot->Draw();
  betaPrimeCanvas->cd(3);
  betaPrimeThreePlot->Draw();
  betaPrimeCanvas->cd(4);
  betaPrimeFourPlot->Draw();
  betaPrimeCanvas->cd(5);
  betaPrimeOneCPlot->Draw();

  betaPrimeCanvas->SaveAs("betaPrimeVariables.pdf");
  
  TCanvas* betaCorrelationsCanvas = new TCanvas("betaCorrelationsCanvas","betaCorrelationsCanvas",1600,800);
  
  betaCorrelationsCanvas->Divide(4,2);

  TH2F* oneTwo = data->createHistogram(betaOnePlotter,betaTwoPlotter,30,30);
  TH2F* oneThree = data->createHistogram(betaOnePlotter,betaThreePlotter,30,30);
  TH2F* oneFour = data->createHistogram(betaOnePlotter,betaFourPlotter,30,30);
  TH2F* twoThree = data->createHistogram(betaTwoPlotter,betaThreePlotter,30,30);
  TH2F* twoFour = data->createHistogram(betaTwoPlotter,betaFourPlotter,30,30);
  TH2F* threeFour = data->createHistogram(betaThreePlotter,betaFourPlotter,30,30);
  TH2F* twoFourC = data->createHistogram(betaTwoPlotter,betaFourCPlotter,30,30);
  TH2F* fourFourC = data->createHistogram(betaFourPlotter,betaFourCPlotter,30,30);

  betaCorrelationsCanvas->cd(1);
  oneTwo->DrawCopy("lego");
  betaCorrelationsCanvas->cd(2);
  oneThree->DrawCopy("lego");
  betaCorrelationsCanvas->cd(3);
  oneFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(4);
  twoThree->DrawCopy("lego");
  betaCorrelationsCanvas->cd(5);
  twoFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(6);
  threeFour->DrawCopy("lego");
  betaCorrelationsCanvas->cd(7);
  twoFourC->DrawCopy("lego");
  betaCorrelationsCanvas->cd(8);
  fourFourC->DrawCopy("lego");

  betaCorrelationsCanvas->SaveAs("betaCorrelations.pdf");

  TCanvas* betaPrimeCorrelationsCanvas = new TCanvas("betaPrimeCorrelationsCanvas","betaPrimeCorrelationsCanvas",1600,800);
  
  betaPrimeCorrelationsCanvas->Divide(4,2);

  TH2F* oneTwo = data->createHistogram(betaPrimeOnePlotter,betaPrimeTwoPlotter,30,30);
  TH2F* oneThree = data->createHistogram(betaPrimeOnePlotter,betaPrimeThreePlotter,30,30);
  TH2F* oneFour = data->createHistogram(betaPrimeOnePlotter,betaPrimeFourPlotter,30,30);
  TH2F* twoThree = data->createHistogram(betaPrimeTwoPlotter,betaPrimeThreePlotter,30,30);
  TH2F* twoFour = data->createHistogram(betaPrimeTwoPlotter,betaPrimeFourPlotter,30,30);
  TH2F* threeFour = data->createHistogram(betaPrimeThreePlotter,betaPrimeFourPlotter,30,30);
  TH2F* oneOneC = data->createHistogram(betaPrimeOnePlotter,betaPrimeOneCPlotter,30,30);

  betaPrimeCorrelationsCanvas->cd(1);
  oneTwo->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(2);
  oneThree->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(3);
  oneFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(4);
  twoThree->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(5);
  twoFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(6);
  threeFour->DrawCopy("lego");
  betaPrimeCorrelationsCanvas->cd(7);
  oneOneC->DrawCopy("lego");

  betaPrimeCorrelationsCanvas->SaveAs("betaPrimeCorrelations.pdf");

  RooProdPdf totalPdf("totalPdf","totalPdf",workspace.allPdfs());
  totalPdf.Print("v");

  RooArgSet* observableSet = workspace.set("observables");

  observableSet->Print();

  RooDataSet* allDataOne = totalPdf.generate(*observableSet,1);
  allDataOne->Print("v");

  correlatedParameter->setVal(0.25);

  RooDataSet* allDataTwo = totalPdf.generate(*observableSet,1);
  allDataTwo->Print("v");

  correlatedParameter->setVal(0.75);

  RooDataSet* allDataThree = totalPdf.generate(*observableSet,1);
  allDataThree->Print("v");

  //Testing for extreme values!

  for(int i = 0; i< 101; i++)
    {
      correlatedParameter->setVal((double)i/100.);
      cout << "Correlation parameter has value of " << correlatedParameter->getVal();
      cout << " and the pdf has an unnormalized value of " << normalFromFlat->getVal() << endl;
    }


}
Пример #3
0
// 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 OneSidedFrequentistUpperLimitWithBands(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData") {



   double confidenceLevel=0.95;
   int nPointsToScan = 20;
   int nToyMC = 200;

   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


   // -------------------------------------------------------
   // Now get the data and workspace

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if(!w){
      cout <<"workspace not found" << endl;
      return;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

   // get the modelConfig out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if(!data || !mc){
      w->Print();
      cout << "data or ModelConfig was not found" <<endl;
      return;
   }

   // -------------------------------------------------------
   // Now get the POI for convenience
   // you may want to adjust the range of your POI

   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   /*  firstPOI->setMin(0);*/
   /*  firstPOI->setMax(10);*/

   // --------------------------------------------
   // Create and use the FeldmanCousins tool
   // to find and plot the 95% confidence interval
   // on the parameter of interest as specified
   // in the model config
   // REMEMBER, we will change the test statistic
   // so this is NOT a Feldman-Cousins interval
   FeldmanCousins fc(*data,*mc);
   fc.SetConfidenceLevel(confidenceLevel);
   /*  fc.AdditionalNToysFactor(0.25); // degrade/improve sampling that defines confidence belt*/
   /*  fc.UseAdaptiveSampling(true); // speed it up a bit, don't use for expected limits*/
   fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
   fc.CreateConfBelt(true); // save the information in the belt for plotting

   // -------------------------------------------------------
   // Feldman-Cousins is a unified limit by definition
   // but the tool takes care of a few things for us like which values
   // of the nuisance parameters should be used to generate toys.
   // so let's just change the test statistic and realize this is
   // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
   /*  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());*/
   /*  fc.GetTestStatSampler()->SetTestStatistic(&onesided);*/
   /* ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true); */
   ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
   testStat->SetOneSided(true);

   // Since this tool needs to throw toy MC the PDF needs to be
   // extended or the tool needs to know how many entries in a dataset
   // per pseudo experiment.
   // In the 'number counting form' where the entries in the dataset
   // are counts, and not values of discriminating variables, the
   // datasets typically only have one entry and the PDF is not
   // extended.
   if(!mc->GetPdf()->canBeExtended()){
      if(data->numEntries()==1)
         fc.FluctuateNumDataEntries(false);
      else
         cout <<"Not sure what to do about this model" <<endl;
   }

   // We can use PROOF to speed things along in parallel
   // However, the test statistic has to be installed on the workers
   // so either turn off PROOF or include the modified test statistic
   // in your `$ROOTSYS/roofit/roostats/inc` directory,
   // add the additional line to the LinkDef.h file,
   // and recompile root.
   if (useProof) {
      ProofConfig pc(*w, nworkers, "", false);
      toymcsampler->SetProofConfig(&pc); // enable proof
   }

   if(mc->GetGlobalObservables()){
      cout << "will use global observables for unconditional ensemble"<<endl;
      mc->GetGlobalObservables()->Print();
      toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
   }


   // Now get the interval
   PointSetInterval* interval = fc.GetInterval();
   ConfidenceBelt* belt = fc.GetConfidenceBelt();

   // print out the interval on the first Parameter of Interest
   cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
      interval->LowerLimit(*firstPOI) << ", "<<
      interval->UpperLimit(*firstPOI) <<"] "<<endl;

   // get observed UL and value of test statistic evaluated there
   RooArgSet tmpPOI(*firstPOI);
   double observedUL = interval->UpperLimit(*firstPOI);
   firstPOI->setVal(observedUL);
   double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


   // Ask the calculator which points were scanned
   RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
   RooArgSet* tmpPoint;

   // make a histogram of parameter vs. threshold
   TH1F* histOfThresholds = new TH1F("histOfThresholds","",
                                       parameterScan->numEntries(),
                                       firstPOI->getMin(),
                                       firstPOI->getMax());
   histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
   histOfThresholds->GetYaxis()->SetTitle("Threshold");

   // loop through the points that were tested and ask confidence belt
   // what the upper/lower thresholds were.
   // For FeldmanCousins, the lower cut off is always 0
   for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      //cout <<"get threshold"<<endl;
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
      histOfThresholds->Fill(poiVal,arMax);
   }
   TCanvas* c1 = new TCanvas();
   c1->Divide(2);
   c1->cd(1);
   histOfThresholds->SetMinimum(0);
   histOfThresholds->Draw();
   c1->cd(2);

   // -------------------------------------------------------
   // Now we generate the expected bands and power-constraint

   // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
   RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
   RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
   firstPOI->setVal(0.);
   profile->getVal(); // this will do fit and set nuisance parameters to profiled values
   RooArgSet* poiAndNuisance = new RooArgSet();
   if(mc->GetNuisanceParameters())
      poiAndNuisance->add(*mc->GetNuisanceParameters());
   poiAndNuisance->add(*mc->GetParametersOfInterest());
   w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
   RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
   cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
   paramsToGenerateData->Print("v");


   RooArgSet unconditionalObs;
   unconditionalObs.add(*mc->GetObservables());
   unconditionalObs.add(*mc->GetGlobalObservables()); // comment this out for the original conditional ensemble

   double CLb=0;
   double CLbinclusive=0;

   // Now we generate background only and find distribution of upper limits
   TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
   histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
   histOfUL->GetYaxis()->SetTitle("Entries");
   for(int imc=0; imc<nToyMC; ++imc){

      // set parameters back to values for generating pseudo data
      //    cout << "\n get current nuis, set vals, print again" << endl;
      w->loadSnapshot("paramsToGenerateData");
      //    poiAndNuisance->Print("v");

      RooDataSet* toyData = 0;
      // now generate a toy dataset
      if(!mc->GetPdf()->canBeExtended()){
         if(data->numEntries()==1)
            toyData = mc->GetPdf()->generate(*mc->GetObservables(),1);
         else
            cout <<"Not sure what to do about this model" <<endl;
      } else{
         //      cout << "generating extended dataset"<<endl;
         toyData = mc->GetPdf()->generate(*mc->GetObservables(),Extended());
      }

      // generate global observables
      // need to be careful for simpdf
      //    RooDataSet* globalData = mc->GetPdf()->generate(*mc->GetGlobalObservables(),1);

      RooSimultaneous* simPdf = dynamic_cast<RooSimultaneous*>(mc->GetPdf());
      if(!simPdf){
         RooDataSet *one = mc->GetPdf()->generate(*mc->GetGlobalObservables(), 1);
         const RooArgSet *values = one->get();
         RooArgSet *allVars = mc->GetPdf()->getVariables();
         *allVars = *values;
         delete allVars;
         delete values;
         delete one;
      } else {

         //try fix for sim pdf
         TIterator* iter = simPdf->indexCat().typeIterator() ;
         RooCatType* tt = NULL;
         while((tt=(RooCatType*) iter->Next())) {

            // Get pdf associated with state from simpdf
            RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

            // Generate only global variables defined by the pdf associated with this state
            RooArgSet* globtmp = pdftmp->getObservables(*mc->GetGlobalObservables()) ;
            RooDataSet* tmp = pdftmp->generate(*globtmp,1) ;

            // Transfer values to output placeholder
            *globtmp = *tmp->get(0) ;

            // Cleanup
            delete globtmp ;
            delete tmp ;
         }
      }

      //    globalData->Print("v");
      //    unconditionalObs = *globalData->get();
      //    mc->GetGlobalObservables()->Print("v");
      //    delete globalData;
      //    cout << "toy data = " << endl;
      //    toyData->get()->Print("v");

      // get test stat at observed UL in observed data
      firstPOI->setVal(observedUL);
      double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
      //    toyData->get()->Print("v");
      //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
      if(obsTSatObsUL < toyTSatObsUL) // not sure about <= part yet
         CLb+= (1.)/nToyMC;
      if(obsTSatObsUL <= toyTSatObsUL) // not sure about <= part yet
         CLbinclusive+= (1.)/nToyMC;


      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<parameterScan->numEntries(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
         firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;
         if(thisTS<=arMax){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }



      /*
      // loop over points in belt to find upper limit for this toy data
      double thisUL = 0;
      for(Int_t i=0; i<histOfThresholds->GetNbinsX(); ++i){
         tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
         cout <<"----------------  "<<i<<endl;
         tmpPoint->Print("v");
         cout << "from hist " << histOfThresholds->GetBinCenter(i+1) <<endl;
         double arMax = histOfThresholds->GetBinContent(i+1);
         // cout << " threhold from Hist = aMax " << arMax<<endl;
         // double arMax2 = belt->GetAcceptanceRegionMax(*tmpPoint);
         // cout << "from scan arMax2 = "<< arMax2 << endl; // not the same due to TH1F not TH1D
         // cout << "scan - hist" << arMax2-arMax << endl;
         firstPOI->setVal( histOfThresholds->GetBinCenter(i+1));
         //   double thisTS = profile->getVal();
         double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

         //   cout << "poi = " << firstPOI->getVal()
         // << " max is " << arMax << " this profile = " << thisTS << endl;
         //      cout << "thisTS = " << thisTS<<endl;

         // NOTE: need to add a small epsilon term for single precision vs. double precision
         if(thisTS<=arMax + 1e-7){
            thisUL = firstPOI->getVal();
         } else{
            break;
         }
      }
      */

      histOfUL->Fill(thisUL);

      // for few events, data is often the same, and UL is often the same
      //    cout << "thisUL = " << thisUL<<endl;

      delete toyData;
   }
   histOfUL->Draw();
   c1->SaveAs("one-sided_upper_limit_output.pdf");

   // if you want to see a plot of the sampling distribution for a particular scan point:
   /*
   SamplingDistPlot sampPlot;
   int indexInScan = 0;
   tmpPoint = (RooArgSet*) parameterScan->get(indexInScan)->clone("temp");
   firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
   toymcsampler->SetParametersForTestStat(tmpPOI);
   SamplingDistribution* samp = toymcsampler->GetSamplingDistribution(*tmpPoint);
   sampPlot.AddSamplingDistribution(samp);
   sampPlot.Draw();
      */

   // Now find bands and power constraint
   Double_t* bins = histOfUL->GetIntegral();
   TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
   cumulative->SetContent(bins);
   double band2sigDown, band1sigDown, bandMedian, band1sigUp,band2sigUp;
   for(int i=1; i<=cumulative->GetNbinsX(); ++i){
      if(bins[i]<RooStats::SignificanceToPValue(2))
         band2sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(1))
         band1sigDown=cumulative->GetBinCenter(i);
      if(bins[i]<0.5)
         bandMedian=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-1))
         band1sigUp=cumulative->GetBinCenter(i);
      if(bins[i]<RooStats::SignificanceToPValue(-2))
         band2sigUp=cumulative->GetBinCenter(i);
   }
   cout << "-2 sigma  band " << band2sigDown << endl;
   cout << "-1 sigma  band " << band1sigDown << " [Power Constraint)]" << endl;
   cout << "median of band " << bandMedian << endl;
   cout << "+1 sigma  band " << band1sigUp << endl;
   cout << "+2 sigma  band " << band2sigUp << endl;

   // print out the interval on the first Parameter of Interest
   cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
   cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
   cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

   delete profile;
   delete nll;

}
Пример #5
0
// internal routine to run the inverter
HypoTestInverterResult *
RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
                                       const char * modelSBName, const char * modelBName,
                                       const char * dataName, int type,  int testStatType,
                                       bool useCLs, int npoints, double poimin, double poimax,
                                       int ntoys,
                                       bool useNumberCounting,
                                       const char * nuisPriorName ){

   std::cout << "Running HypoTestInverter on the workspace " << w->GetName() << std::endl;

   w->Print();


   RooAbsData * data = w->data(dataName);
   if (!data) {
      Error("StandardHypoTestDemo","Not existing data %s",dataName);
      return 0;
   }
   else
      std::cout << "Using data set " << dataName << std::endl;

   if (mUseVectorStore) {
      RooAbsData::setDefaultStorageType(RooAbsData::Vector);
      data->convertToVectorStore() ;
   }


   // get models from WS
   // get the modelConfig out of the file
   ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);
   ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);

   if (!sbModel) {
      Error("StandardHypoTestDemo","Not existing ModelConfig %s",modelSBName);
      return 0;
   }
   // check the model
   if (!sbModel->GetPdf()) {
      Error("StandardHypoTestDemo","Model %s has no pdf ",modelSBName);
      return 0;
   }
   if (!sbModel->GetParametersOfInterest()) {
      Error("StandardHypoTestDemo","Model %s has no poi ",modelSBName);
      return 0;
   }
   if (!sbModel->GetObservables()) {
      Error("StandardHypoTestInvDemo","Model %s has no observables ",modelSBName);
      return 0;
   }
   if (!sbModel->GetSnapshot() ) {
      Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }

   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) {
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) {
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) {
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar)
            RooStats::SetAllConstant(*bnuisPar);
      }
   }

   if (!bModel || bModel == sbModel) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("_with_poi_0"));
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return 0;
      double oldval = var->getVal();
      var->setVal(0);
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
   }
   else {
      if (!bModel->GetSnapshot() ) {
         Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi and 0 values ",modelBName);
         RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
         if (var) {
            double oldval = var->getVal();
            var->setVal(0);
            bModel->SetSnapshot( RooArgSet(*var)  );
            var->setVal(oldval);
         }
         else {
            Error("StandardHypoTestInvDemo","Model %s has no valid poi",modelBName);
            return 0;
         }
      }
   }

   // check model  has global observables when there are nuisance pdf
   // for the hybrid case the globobs are not needed
   if (type != 1 ) {
      bool hasNuisParam = (sbModel->GetNuisanceParameters() && sbModel->GetNuisanceParameters()->getSize() > 0);
      bool hasGlobalObs = (sbModel->GetGlobalObservables() && sbModel->GetGlobalObservables()->getSize() > 0);
      if (hasNuisParam && !hasGlobalObs ) {
         // try to see if model has nuisance parameters first
         RooAbsPdf * constrPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisanceConstraintPdf_sbmodel");
         if (constrPdf) {
            Warning("StandardHypoTestInvDemo","Model %s has nuisance parameters but no global observables associated",sbModel->GetName());
            Warning("StandardHypoTestInvDemo","\tThe effect of the nuisance parameters will not be treated correctly ");
         }
      }
   }

   // save all initial parameters of the model including the global observables
   RooArgSet initialParameters;
   RooArgSet * allParams = sbModel->GetPdf()->getParameters(*data);
   allParams->snapshot(initialParameters);
   delete allParams;

   // run first a data fit

   const RooArgSet * poiSet = sbModel->GetParametersOfInterest();
   RooRealVar *poi = (RooRealVar*)poiSet->first();

   std::cout << "StandardHypoTestInvDemo : POI initial value:   " << poi->GetName() << " = " << poi->getVal()   << std::endl;

   // fit the data first (need to use constraint )
   TStopwatch tw;

   bool doFit = initialFit;
   if (testStatType == 0 && initialFit == -1) doFit = false;  // case of LEP test statistic
   if (type == 3  && initialFit == -1) doFit = false;         // case of Asymptoticcalculator with nominal Asimov
   double poihat = 0;

   if (minimizerType.size()==0) minimizerType = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
   else
      ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerType.c_str());

   Info("StandardHypoTestInvDemo","Using %s as minimizer for computing the test statistic",
        ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str() );

   if (doFit)  {

      // do the fit : By doing a fit the POI snapshot (for S+B)  is set to the fit value
      // and the nuisance parameters nominal values will be set to the fit value.
      // This is relevant when using LEP test statistics

      Info( "StandardHypoTestInvDemo"," Doing a first fit to the observed data ");
      RooArgSet constrainParams;
      if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
      RooStats::RemoveConstantParameters(&constrainParams);
      tw.Start();
      RooFitResult * fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                                       Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams), Save(true) );
      if (fitres->status() != 0) {
         Warning("StandardHypoTestInvDemo","Fit to the model failed - try with strategy 1 and perform first an Hesse computation");
         fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(true), Hesse(false),Minimizer(minimizerType.c_str(),"Migrad"), Strategy(1), PrintLevel(mPrintLevel+1), Constrain(constrainParams), Save(true) );
      }
      if (fitres->status() != 0)
         Warning("StandardHypoTestInvDemo"," Fit still failed - continue anyway.....");


      poihat  = poi->getVal();
      std::cout << "StandardHypoTestInvDemo - Best Fit value : " << poi->GetName() << " = "
                << poihat << " +/- " << poi->getError() << std::endl;
      std::cout << "Time for fitting : "; tw.Print();

      //save best fit value in the poi snapshot
      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
      std::cout << "StandardHypoTestInvo: snapshot of S+B Model " << sbModel->GetName()
                << " is set to the best fit value" << std::endl;

   }

   // print a message in case of LEP test statistics because it affects result by doing or not doing a fit
   if (testStatType == 0) {
      if (!doFit)
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit is not done and the TS will use the nuisances at the model value");
      else
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit has been done and the TS will use the nuisances at the best fit value");
   }


   // build test statistics and hypotest calculators for running the inverter

   SimpleLikelihoodRatioTestStat slrts(*sbModel->GetPdf(),*bModel->GetPdf());

   // null parameters must includes snapshot of poi plus the nuisance values
   RooArgSet nullParams(*sbModel->GetSnapshot());
   if (sbModel->GetNuisanceParameters()) nullParams.add(*sbModel->GetNuisanceParameters());
   if (sbModel->GetSnapshot()) slrts.SetNullParameters(nullParams);
   RooArgSet altParams(*bModel->GetSnapshot());
   if (bModel->GetNuisanceParameters()) altParams.add(*bModel->GetNuisanceParameters());
   if (bModel->GetSnapshot()) slrts.SetAltParameters(altParams);
   if (mEnableDetOutput) slrts.EnableDetailedOutput();

   // ratio of profile likelihood - need to pass snapshot for the alt
   RatioOfProfiledLikelihoodsTestStat
      ropl(*sbModel->GetPdf(), *bModel->GetPdf(), bModel->GetSnapshot());
   ropl.SetSubtractMLE(false);
   if (testStatType == 11) ropl.SetSubtractMLE(true);
   ropl.SetPrintLevel(mPrintLevel);
   ropl.SetMinimizer(minimizerType.c_str());
   if (mEnableDetOutput) ropl.EnableDetailedOutput();

   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(true);
   if (testStatType == 4) profll.SetSigned(true);
   profll.SetMinimizer(minimizerType.c_str());
   profll.SetPrintLevel(mPrintLevel);
   if (mEnableDetOutput) profll.EnableDetailedOutput();

   profll.SetReuseNLL(mOptimize);
   slrts.SetReuseNLL(mOptimize);
   ropl.SetReuseNLL(mOptimize);

   if (mOptimize) {
      profll.SetStrategy(0);
      ropl.SetStrategy(0);
      ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   }

   if (mMaxPoi > 0) poi->setMax(mMaxPoi);  // increase limit

   MaxLikelihoodEstimateTestStat maxll(*sbModel->GetPdf(),*poi);
   NumEventsTestStat nevtts;

   AsymptoticCalculator::SetPrintLevel(mPrintLevel);

   // create the HypoTest calculator class
   HypoTestCalculatorGeneric *  hc = 0;
   if (type == 0) hc = new FrequentistCalculator(*data, *bModel, *sbModel);
   else if (type == 1) hc = new HybridCalculator(*data, *bModel, *sbModel);
   // else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false, mAsimovBins);
   // else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true, mAsimovBins);  // for using Asimov data generated with nominal values
   else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false );
   else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true );  // for using Asimov data generated with nominal values
   else {
      Error("StandardHypoTestInvDemo","Invalid - calculator type = %d supported values are only :\n\t\t\t 0 (Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",type);
      return 0;
   }

   // set the test statistic
   TestStatistic * testStat = 0;
   if (testStatType == 0) testStat = &slrts;
   if (testStatType == 1 || testStatType == 11) testStat = &ropl;
   if (testStatType == 2 || testStatType == 3 || testStatType == 4) testStat = &profll;
   if (testStatType == 5) testStat = &maxll;
   if (testStatType == 6) testStat = &nevtts;

   if (testStat == 0) {
      Error("StandardHypoTestInvDemo","Invalid - test statistic type = %d supported values are only :\n\t\t\t 0 (SLR) , 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",testStatType);
      return 0;
   }


   ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
   if (toymcs && (type == 0 || type == 1) ) {
      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) {
         if (useNumberCounting)   Warning("StandardHypoTestInvDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else {
         // for not extended pdf
         if (!useNumberCounting  )  {
            int nEvents = data->numEntries();
            Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            toymcs->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestInvDemo","using a number counting pdf");
            toymcs->SetNEventsPerToy(1);
         }
      }

      toymcs->SetTestStatistic(testStat);

      if (data->isWeighted() && !mGenerateBinned) {
         Info("StandardHypoTestInvDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set mGenerateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      toymcs->SetGenerateBinned(mGenerateBinned);

      toymcs->SetUseMultiGen(mOptimize);

      if (mGenerateBinned &&  sbModel->GetObservables()->getSize() > 2) {
         Warning("StandardHypoTestInvDemo","generate binned is activated but the number of ovservable is %d. Too much memory could be needed for allocating all the bins",sbModel->GetObservables()->getSize() );
      }

      // set the random seed if needed
      if (mRandomSeed >= 0) RooRandom::randomGenerator()->SetSeed(mRandomSeed);

   }

   // specify if need to re-use same toys
   if (reuseAltToys) {
      hc->UseSameAltToys();
   }

   if (type == 1) {
      HybridCalculator *hhc = dynamic_cast<HybridCalculator*> (hc);
      assert(hhc);

      hhc->SetToys(ntoys,ntoys/mNToysRatio); // can use less ntoys for b hypothesis

      // remove global observables from ModelConfig (this is probably not needed anymore in 5.32)
      bModel->SetGlobalObservables(RooArgSet() );
      sbModel->SetGlobalObservables(RooArgSet() );


      // check for nuisance prior pdf in case of nuisance parameters
      if (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() ) {

         // fix for using multigen (does not work in this case)
         toymcs->SetUseMultiGen(false);
         ToyMCSampler::SetAlwaysUseMultiGen(false);

         RooAbsPdf * nuisPdf = 0;
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  {
            Info("StandardHypoTestInvDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the model");
            if (bModel->GetPdf() && bModel->GetObservables() )
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  {
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestInvDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());
            }
            else {
               Error("StandardHypoTestInvDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return 0;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestInvDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();

         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) {
            Warning("StandardHypoTestInvDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;

         hhc->ForcePriorNuisanceAlt(*nuisPdf);
         hhc->ForcePriorNuisanceNull(*nuisPdf);


      }
   }
   else if (type == 2 || type == 3) {
      if (testStatType == 3) ((AsymptoticCalculator*) hc)->SetOneSided(true);
      if (testStatType != 2 && testStatType != 3)
         Warning("StandardHypoTestInvDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
   }
   else if (type == 0 || type == 1) {
      ((FrequentistCalculator*) hc)->SetToys(ntoys,ntoys/mNToysRatio);
      // store also the fit information for each poi point used by calculator based on toys
      if (mEnableDetOutput) ((FrequentistCalculator*) hc)->StoreFitInfo(true);
   }

   // Get the result
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);



   HypoTestInverter calc(*hc);
   calc.SetConfidenceLevel(confidenceLevel);


   calc.UseCLs(useCLs);
   calc.SetVerbose(true);

   // can speed up using proof-lite
   if (mUseProof) {
      ProofConfig pc(*w, mNWorkers, "", kFALSE);
      toymcs->SetProofConfig(&pc);    // enable proof
   }


   if (npoints > 0) {
      if (poimin > poimax) {
         // if no min/max given scan between MLE and +4 sigma
         poimin = int(poihat);
         poimax = int(poihat +  4 * poi->getError());
      }
      std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
      calc.SetFixedScan(npoints,poimin,poimax);
   }
   else {
      //poi->setMax(10*int( (poihat+ 10 *poi->getError() )/10 ) );
      std::cout << "Doing an  automatic scan  in interval : " << poi->getMin() << " , " << poi->getMax() << std::endl;
   }

   tw.Start();
   HypoTestInverterResult * r = calc.GetInterval();
   std::cout << "Time to perform limit scan \n";
   tw.Print();

   if (mRebuild) {

      std::cout << "\n***************************************************************\n";
      std::cout << "Rebuild the upper limit distribution by re-generating new set of pseudo-experiment and re-compute for each of them a new upper limit\n\n";


      allParams = sbModel->GetPdf()->getParameters(*data);

      // define on which value of nuisance parameters to do the rebuild
      // default is best fit value for bmodel snapshot



      if (mRebuildParamValues != 0) {
         // set all parameters to their initial workspace values
         *allParams = initialParameters;
      }
      if (mRebuildParamValues == 0 || mRebuildParamValues == 1 ) {
          RooArgSet constrainParams;
          if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
          RooStats::RemoveConstantParameters(&constrainParams);

          const RooArgSet * poiModel = sbModel->GetParametersOfInterest();
          bModel->LoadSnapshot();

          // do a profile using the B model snapshot
          if (mRebuildParamValues == 0 ) {

             RooStats::SetAllConstant(*poiModel,true);

             sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                   Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams) );


             std::cout << "rebuild using fitted parameter value for B-model snapshot" << std::endl;
             constrainParams.Print("v");

             RooStats::SetAllConstant(*poiModel,false);
          }
      }
      std::cout << "StandardHypoTestInvDemo: Initial parameters used for rebuilding: ";
      RooStats::PrintListContent(*allParams, std::cout);
      delete allParams;

      calc.SetCloseProof(1);
      tw.Start();
      SamplingDistribution * limDist = calc.GetUpperLimitDistribution(true,mNToyToRebuild);
      std::cout << "Time to rebuild distributions " << std::endl;
      tw.Print();

      if (limDist) {
         std::cout << "Expected limits after rebuild distribution " << std::endl;
         std::cout << "expected upper limit  (median of limit distribution) " << limDist->InverseCDF(0.5) << std::endl;
         std::cout << "expected -1 sig limit (0.16% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(-1)) << std::endl;
         std::cout << "expected +1 sig limit (0.84% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(1)) << std::endl;
         std::cout << "expected -2 sig limit (.025% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(-2)) << std::endl;
         std::cout << "expected +2 sig limit (.975% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(2)) << std::endl;

         // Plot the upper limit distribution
         SamplingDistPlot limPlot( (mNToyToRebuild < 200) ? 50 : 100);
         limPlot.AddSamplingDistribution(limDist);
         limPlot.GetTH1F()->SetStats(true); // display statistics
         limPlot.SetLineColor(kBlue);
         new TCanvas("limPlot","Upper Limit Distribution");
         limPlot.Draw();

         /// save result in a file
         limDist->SetName("RULDist");
         TFile * fileOut = new TFile("RULDist.root","RECREATE");
         limDist->Write();
         fileOut->Close();


         //update r to a new updated result object containing the rebuilt expected p-values distributions
         // (it will not recompute the expected limit)
         if (r) delete r;  // need to delete previous object since GetInterval will return a cloned copy
         r = calc.GetInterval();

      }
      else
         std::cout << "ERROR : failed to re-build distributions " << std::endl;
   }

   return r;
}
Пример #6
0
void wspaceread_signals2e2mu(int channel = 3)
{

	gSystem->AddIncludePath("-I$ROOFITSYS/include");
	gROOT->ProcessLine(".L ~/tdrstyle.C");
	setTDRStyle();
	//gSystem->Load("PDFs/RooRelBW1_cxx.so");
	//gSystem->Load("PDFs/RooRelBW2_cxx.so");
	gSystem->Load("../PDFs/HZZ4LRooPdfs_cc.so");

	string schannel;
	if (channel == 1) schannel = "4mu";
	if (channel == 2) schannel = "4e";
	if (channel == 3) schannel = "2mu2e";
	std::cout << "schannel = " << schannel << std::endl;

	const int nPoints = 17.;
	int masses[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double mHVal[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double widths[nPoints] = {3.48e-03,4.88e-03,8.14e-03,1.73e-02,8.30e-02,3.80e-01,6.31e-01,1.04e+00,1.43e+00,4.04e+00,8.43e+00,1.52e+01,2.92e+01,46.95,6.80e+01,93.15,1.23e+02};
	// R e a d   w o r k s p a c e   f r o m   f i l e
	// -----------------------------------------------
	
	double a_meanBW[nPoints];
	double a_gammaBW[nPoints];
	double a_meanCB[nPoints];
	double a_sigmaCB[nPoints];
	double a_alphaCB[nPoints];
	double a_nCB[nPoints];
		
	for (int i = 0; i < nPoints; i++){
	//for (int i = 0; i < 1; i++){
		
		// Open input file with workspace (generated by rf14_wspacewrite)
		char infile[192];
		sprintf(infile,"/scratch/hep/ntran/dataFiles/HZZ4L/datasets/datasets_baseline/%s/ZZAnalysisTree_H%i%s.root",schannel.c_str(),masses[i],schannel.c_str());
		TFile *f = new TFile(infile) ;
		char outfile[192];
		sprintf( outfile, "figs/pdf_%s_bkg_highmass.eps", schannel.c_str() );
		//f->ls();
		
		double windowVal = max( widths[i], 1. );
		if (mHVal[i] >= 275){ lowside = 180.; }
		else { lowside = 100.; }
		double low_M = max( (mHVal[i] - 20.*windowVal), lowside) ;
		double high_M = min( (mHVal[i] + 15.*windowVal), 900.) ;

		//double windowVal = max( widths[i], 1.);
		//double windowVal = max ( widths[i], 1. );
		//low_M = max( (mHVal[i] - 25.*windowVal), 100.) ;
		//high_M = min( (mHVal[i] + 20.*windowVal), 1000.) ;
		//low_M = max( (mHVal[i] - 15.*windowVal), 100.) ;
		//high_M = min( (mHVal[i] + 10.*windowVal), 1000.) ;
		std::cout << "lowM = " << low_M << ", highM = " << high_M << std::endl;
			
		RooDataSet* set = (RooDataSet*) f->Get("data");
		RooArgSet* obs = set->get() ;
		obs->Print();
		RooRealVar* CMS_zz4l_mass = (RooRealVar*) obs->find("CMS_zz4l_mass") ;
		CMS_zz4l_mass->setRange(low_M,high_M);
		for (int a=0 ; a<set->numEntries() ; a++) { 
			set->get(a) ; 
			//cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
		} 
		
		// constraining parameters...
		double l_sigmaCB = 0., s_sigmaCB = 3.;
		if (mHVal[i] >= 500.){ l_sigmaCB = 10.; s_sigmaCB = 12.; }
		
		double s_n_CB = 2.6+(-1.1/290.)*(mHVal[i]-110.);
		if (mHVal[i] >= 400){ s_n_CB = 1.5; }

		
		RooRealVar mean_CB("mean_CB","mean_CB",0.,-25.,25);
		RooRealVar sigma_CB("sigma_CB","sigma_CB",s_sigmaCB,l_sigmaCB,30.);
		RooRealVar alpha_CB("alpha_CB","alpha_CB",0.95,0.8,1.2);
		RooRealVar n_CB("n_CB","n_CB",s_n_CB,1.5,2.8);
		RooCBShape signalCB("signalCB","signalCB",*CMS_zz4l_mass,mean_CB,sigma_CB,alpha_CB,n_CB);
		
		RooRealVar mean_BW("mean_BW","mean_BW", mHVal[i] ,100.,1000.);
		RooRealVar gamma_BW("gamma_BW","gamma_BW",widths[i],0.,200.);
		//RooBreitWigner signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		
		RooRelBWUF signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooBreitWigner signalBW1("signalBW1", "signalBW1",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooRelBW1 signalBW2("signalBW2", "signalBW2",*CMS_zz4l_mass,mean_BW,gamma_BW);
		
		//Set #bins to be used for FFT sampling to 10000
		CMS_zz4l_mass->setBins(100000,"fft") ;

		//Construct BW (x) CB
		RooFFTConvPdf* sig_ggH = new RooFFTConvPdf("sig_ggH","BW (X) CB",*CMS_zz4l_mass,signalBW,signalCB, 2);
		// Buffer fraction for cyclical behavior
		sig_ggH->setBufferFraction(0.2);
		
		mean_BW.setConstant(kTRUE);
		gamma_BW.setConstant(kTRUE);
		n_CB.setConstant(kTRUE);
		alpha_CB.setConstant(kTRUE);
		
		RooFitResult *r = sig_ggH.fitTo( *set, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;
		
		a_meanBW[i] = mean_BW.getVal();
		a_gammaBW[i] = gamma_BW.getVal();
		a_meanCB[i] = mean_CB.getVal();
		a_sigmaCB[i] = sigma_CB.getVal();;
		a_alphaCB[i] = alpha_CB.getVal();;
		a_nCB[i] = n_CB.getVal();;
		
		
		// Plot Y
		RooPlot* frameM4l = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
		set->plotOn(frameM4l) ;
		sig_ggH.plotOn(frameM4l) ;

		RooPlot* testFrame = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
		signalBW.plotOn(testFrame) ;
		signalBW1.plotOn(testFrame, LineColor(kBlack)) ;
		signalBW2.plotOn(testFrame, LineColor(kRed)) ;
				
		TCanvas *c = new TCanvas("c","c",800,600);
		c->cd();
		frameM4l->Draw();
		char plotName[192];
		sprintf(plotName,"sigFigs/m%i.eps",masses[i]);
		
		c->SaveAs(plotName);

		TCanvas *c3 = new TCanvas("c3","c3",800,600);
		c3->cd();
		testFrame->Draw();
		//char plotName[192];
		sprintf(plotName,"sigFigs/shape%i.eps",masses[i]);
		
		c3->SaveAs(plotName);
		
		
		delete f;
		delete set;
		delete c;
	}
	

	TGraph* gr_meanBW = new TGraph( nPoints, mHVal, a_meanBW );
	TGraph* gr_gammaBW = new TGraph( nPoints, mHVal, a_gammaBW );
	TGraph* gr_meanCB = new TGraph( nPoints, mHVal, a_meanCB );
	TGraph* gr_sigmaCB = new TGraph( nPoints, mHVal, a_sigmaCB );
	TGraph* gr_alphaCB = new TGraph( nPoints, mHVal, a_alphaCB );
	TGraph* gr_nCB = new TGraph( nPoints, mHVal, a_nCB );
	
	TF1 *polyFunc1= new TF1("polyFunc1","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc1->SetParameters(1., 1., 1., 100.,0.1);
	TF1 *polyFunc2= new TF1("polyFunc2","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc2->SetParameters(1., 1., 1., 100.,0.1);
	
	
	TCanvas *c = new TCanvas("c","c",1200,800);
	c->Divide(3,2);
	//c->SetGrid();
	//TH1F *hr = c->DrawFrame(0.,0.,610.,1.);
	c->cd(1);
	gr_meanBW->Draw("alp");
	gr_meanBW->GetXaxis()->SetTitle("mean BW");
	c->cd(2);
	gr_gammaBW->Draw("alp");
	gr_gammaBW->GetXaxis()->SetTitle("gamma BW");
	c->cd(3);
	gr_meanCB->Fit(polyFunc1,"Rt");
	gr_meanCB->Draw("alp");
	gr_meanCB->GetXaxis()->SetTitle("mean CB");
	c->cd(4);
	gr_sigmaCB->Fit(polyFunc2,"Rt");
	gr_sigmaCB->Draw("alp");
	gr_sigmaCB->GetXaxis()->SetTitle("sigma CB");
	c->cd(5);
	gr_alphaCB->Draw("alp");
	gr_alphaCB->GetXaxis()->SetTitle("alpha CB");
	c->cd(6);
	gr_nCB->Draw("alp");
	gr_nCB->GetXaxis()->SetTitle("n CB");
	c->SaveAs("sigFigs/params.eps");
	
	std::cout << "mean_CB = " << polyFunc1->GetParameter(0) << " + " << polyFunc1->GetParameter(1) << "*m + " << polyFunc1->GetParameter(2) << "*(m - " << polyFunc1->GetParameter(3) << ")*(m - " << polyFunc1->GetParameter(3);
	std::cout << ") + " << polyFunc1->GetParameter(4) << "*m*m*m*m;" << std::endl;
	std::cout << "sigma_CB = " << polyFunc2->GetParameter(0) << " + " << polyFunc2->GetParameter(1) << "*m + " << polyFunc2->GetParameter(2) << "*(m - " << polyFunc2->GetParameter(3) << ")*(m - " << polyFunc2->GetParameter(3);
	std::cout << ") + " << polyFunc2->GetParameter(4) << "*m*m*m*m;" << std::endl;
	
	
	// calculate sysetmatic errors from interpolation...
	double sum_meanCB = 0;
	double sum_sigmaCB = 0;
	for (int i = 0; i < nPoints; i++){
		double tmp_meanCB = (polyFunc1->Eval(mHVal[i]) - a_meanCB[i]);
		sum_meanCB += (tmp_meanCB*tmp_meanCB);
		double tmp_sigmaCB = (polyFunc2->Eval(mHVal[i]) - a_sigmaCB[i])/a_sigmaCB[i];
		sum_sigmaCB += (tmp_sigmaCB*tmp_sigmaCB);
		std::cout << "mean: " << tmp_meanCB << ", sigma: " << tmp_sigmaCB << std::endl;
	}
	double rms_meanCB = sqrt( sum_meanCB/( (double) nPoints) );
	double rms_sigmaCB = sqrt( sum_sigmaCB/( (double) nPoints) );
	std::cout << "err (meanCB) = " << rms_meanCB << ", err (sigmaCB) = " << rms_sigmaCB << std::endl;
	
	
	
	
	
}
Пример #7
0
void plotSignals_4mu(int channel = 1)
{

	gSystem->AddIncludePath("-I$ROOFITSYS/include");
	gROOT->ProcessLine(".L ~/tdrstyle.C");
	setTDRStyle();
	//gSystem->Load("PDFs/RooRelBW1_cxx.so");
	//gSystem->Load("PDFs/RooRelBW2_cxx.so");
	gSystem->Load("../PDFs/HZZ4LRooPdfs_cc.so");

	string schannel;
	if (channel == 1) schannel = "4mu";
	if (channel == 2) schannel = "4e";
	if (channel == 3) schannel = "2mu2e";
	std::cout << "schannel = " << schannel << std::endl;

	const int nPoints = 17.;
	int masses[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double mHVal[nPoints] = {120,130,140,150,160,170,180,190,200,250,300,350,400,450,500,550,600};
	double widths[nPoints] = {3.48e-03,4.88e-03,8.14e-03,1.73e-02,8.30e-02,3.80e-01,6.31e-01,1.04e+00,1.43e+00,4.04e+00,8.43e+00,1.52e+01,2.92e+01,46.95,6.80e+01,93.15,1.23e+02};
	// R e a d   w o r k s p a c e   f r o m   f i l e
	// -----------------------------------------------
	
	double a_meanBW[nPoints];
	double a_gammaBW[nPoints];
	double a_meanCB[nPoints];
	double a_sigmaCB[nPoints];
	double a_alphaCB[nPoints];
	double a_nCB[nPoints];
		
	//for (int i = 0; i < nPoints; i++){
	for (int i = 0; i < (nPoints-3); i++){
		
		// Open input file with workspace (generated by rf14_wspacewrite)
		char infile[192];
		sprintf(infile,"/scratch/hep/ntran/dataFiles/HZZ4L/datasets/datasets_baseline/%s/ZZAnalysisTree_H%i%s.root",schannel.c_str(),masses[i],schannel.c_str());
		TFile *f = new TFile(infile) ;
		char outfile[192];
		sprintf( outfile, "figs/pdf_%s_bkg_highmass.eps", schannel.c_str() );
		//f->ls();
		
		double windowVal = max( widths[i], 1. );
		if (mHVal[i] >= 275){ lowside = 180.; }
		else { lowside = 100.; }
		double low_M = max( (mHVal[i] - 20.*windowVal), lowside) ;
		//double high_M = min( (mHVal[i] + 15.*windowVal), 900.) ;
		double high_M = min( (mHVal[i] + 15.*windowVal), 600.) ;

		std::cout << "lowM = " << low_M << ", highM = " << high_M << std::endl;
			
		RooDataSet* set = (RooDataSet*) f->Get("data");
		RooArgSet* obs = set->get() ;
		obs->Print();
		RooRealVar* CMS_zz4l_mass = (RooRealVar*) obs->find("CMS_zz4l_mass") ;
		CMS_zz4l_mass->setRange(low_M,high_M);
		for (int a=0 ; a<set->numEntries() ; a++) { 
			set->get(a) ; 
			//cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
		} 
		
		// constraining parameters...
		double l_sigmaCB = 0., s_sigmaCB = 3.;
		if (mHVal[i] >= 500.){ l_sigmaCB = 10.; s_sigmaCB = 12.; }
		double h_alpha_CB = 1.15;
		if (mHVal[i] >= 500.){ h_alpha_CB = 0.99; }

		double s_alpha_CB = 1.2 + (-0.4/590)*(mHVal[i]-110.);
		
		RooRealVar mean_CB("mean_CB","mean_CB",0.,-25.,25);
		RooRealVar sigma_CB("sigma_CB","sigma_CB",s_sigmaCB,l_sigmaCB,30.);
		//RooRealVar alpha_CB("alpha_CB","alpha_CB",0.9,0.7,h_alpha_CB);
		RooRealVar alpha_CB("alpha_CB","alpha_CB",s_alpha_CB);
		RooRealVar n_CB("n_CB","n_CB",1.7,1.5,2.4);
		RooCBShape signalCB("signalCB","signalCB",*CMS_zz4l_mass,mean_CB,sigma_CB,alpha_CB,n_CB);
		
		RooRealVar mean_BW("mean_BW","mean_BW", mHVal[i] ,100.,1000.);
		RooRealVar gamma_BW("gamma_BW","gamma_BW",widths[i],0.,200.);
		//RooBreitWigner signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		
		RooRelBWUF signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW);
		//RooRelBW1 signalBW("signalBW", "signalBW",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooBreitWigner signalBW1("signalBW1", "signalBW1",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooRelBW1 signalBW2("signalBW2", "signalBW2",*CMS_zz4l_mass,mean_BW,gamma_BW);
		RooRealVar x("x","x",1.);
		RooRelBWUFParam signalBW3("signalBW3", "signalBW3",*CMS_zz4l_mass,mean_BW,x);
		RooRealVar y("y","y",0.33333);
		RooRelBWUFParam signalBW4("signalBW4", "signalBW4",*CMS_zz4l_mass,mean_BW,y);

		//Set #bins to be used for FFT sampling to 10000
		CMS_zz4l_mass->setBins(100000,"fft") ;

		//Construct BW (x) CB
		RooFFTConvPdf* sig_ggH = new RooFFTConvPdf("sig_ggH","BW (X) CB",*CMS_zz4l_mass,signalBW,signalCB, 2);
		// Buffer fraction for cyclical behavior
		sig_ggH->setBufferFraction(0.2);
		
		mean_BW.setConstant(kTRUE);
		gamma_BW.setConstant(kTRUE);
		n_CB.setConstant(kTRUE);
		//alpha_CB.setConstant(kTRUE);
		
		RooFitResult *r = sig_ggH.fitTo( *set, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;
		
		a_meanBW[i] = mean_BW.getVal();
		a_gammaBW[i] = gamma_BW.getVal();
		a_meanCB[i] = mean_CB.getVal();
		a_sigmaCB[i] = sigma_CB.getVal();;
		a_alphaCB[i] = alpha_CB.getVal();;
		a_nCB[i] = n_CB.getVal();;
		
		
		///////////////////////////////////////////////////
		// P l o t t i n g
		int iLineColor = 1;
		string lab = "blah";
		if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
		if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
		if (channel == 2) { iLineColor = 6; lab = "4e"; }
		double separation = 0.5;
		if (mHVal[i] >= 300.) separation = 2;
		double nbins = (high_M-low_M);
		nbins /= separation;
		char yname[192];
		sprintf(yname,"Events / %1.1f GeV/c^{2}", separation);
		char lname[192];
		sprintf(lname,"M_{H} = %i [GeV/c^{2}]", (int) mHVal[i] );
		char lname2[192];
		sprintf(lname2,"Shape Model, %s", lab.c_str() );
		
		RooPlot* frameM4l = CMS_zz4l_mass->frame(Bins( (int) nbins )) ;
		set->plotOn(frameM4l) ;
		sig_ggH->plotOn(frameM4l, LineColor(iLineColor)) ;
		
		// dummy!
		TF1* dummyF = new TF1("dummyF","1",0.,1.);
		TH1F* dummyH = new TH1F("dummyG","dummyG",1, 0.,1.);
		dummyF->SetLineColor( iLineColor );
		//dummyH->SetLineColor( kBlue );
		TLegend * box2 = new TLegend(0.17,0.70,0.52,0.90);
		box2->SetFillColor(0);
		box2->SetBorderSize(0);
		box2->AddEntry(dummyH,"Simulation (Powheg + CMS)  ","pe");
		box2->AddEntry(dummyH,lname,"");
		box2->AddEntry(dummyF,lname2,"l");
		
		TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
        pt->SetFillColor(0);
		pt->SetBorderSize(0);
        pt->AddText("CMS Preliminary 2011");
		TPaveText *pt2 = new TPaveText(0.83,0.955,0.99,0.99,"NDC");
        pt2->SetFillColor(0);
		pt2->SetBorderSize(0);
        pt2->AddText("#sqrt{s} = 7 TeV"); 		
		
		
		
		frameM4l->SetTitle("");
        frameM4l->GetXaxis()->SetTitle("M_{4l} [GeV/c^{2}]");
        frameM4l->GetYaxis()->SetTitleOffset(1.2);		
		frameM4l->GetYaxis()->SetTitle(yname);		
		
		TCanvas *c = new TCanvas("c","c",800,600);
		c->cd();
		frameM4l->Draw();
		box2->Draw();
		pt->Draw();
		pt2->Draw();
		char plotName[192];
		sprintf(plotName,"sigFigs/m%i.eps",masses[i]);
		
		c->SaveAs(plotName);
		
		///////////////////////////////////////////////////
		
		RooPlot* testFrame = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
		signalBW.plotOn(testFrame) ;
		signalBW1.plotOn(testFrame, LineColor(kBlack)) ;
		signalBW2.plotOn(testFrame, LineColor(kRed)) ;		
		
		TCanvas *c3 = new TCanvas("c3","c3",800,600);
		c3->cd();
		testFrame->Draw();
		//char plotName[192];
		sprintf(plotName,"sigFigs/shape%i.eps",masses[i]);
		
		c3->SaveAs(plotName);
		
		///////////////////////////////////////////////////		
		
		delete f;
		delete set;
		delete c;
	}
	

	TGraph* gr_meanBW = new TGraph( nPoints, mHVal, a_meanBW );
	TGraph* gr_gammaBW = new TGraph( nPoints, mHVal, a_gammaBW );
	TGraph* gr_meanCB = new TGraph( nPoints, mHVal, a_meanCB );
	TGraph* gr_sigmaCB = new TGraph( nPoints, mHVal, a_sigmaCB );
	TGraph* gr_alphaCB = new TGraph( nPoints, mHVal, a_alphaCB );
	TGraph* gr_nCB = new TGraph( nPoints, mHVal, a_nCB );
	
	TF1 *polyFunc1= new TF1("polyFunc1","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc1->SetParameters(1., 1., 1., 100.,0.1);
	TF1 *polyFunc2= new TF1("polyFunc2","[0]+[1]*x+[2]*(x-[3])*(x-[3])+[4]*x*x*x*x", 120., 600.);
	polyFunc2->SetParameters(1., 1., 1., 100.,0.1);
	
	
	TCanvas *c = new TCanvas("c","c",1200,800);
	c->Divide(3,2);
	//c->SetGrid();
	//TH1F *hr = c->DrawFrame(0.,0.,610.,1.);
	c->cd(1);
	gr_meanBW->Draw("alp");
	gr_meanBW->GetXaxis()->SetTitle("mean BW");
	c->cd(2);
	gr_gammaBW->Draw("alp");
	gr_gammaBW->GetXaxis()->SetTitle("gamma BW");
	c->cd(3);
	gr_meanCB->Fit(polyFunc1,"Rt");
	gr_meanCB->Draw("alp");
	gr_meanCB->GetXaxis()->SetTitle("mean CB");
	c->cd(4);
	gr_sigmaCB->Fit(polyFunc2,"Rt");
	gr_sigmaCB->Draw("alp");
	gr_sigmaCB->GetXaxis()->SetTitle("sigma CB");
	c->cd(5);
	gr_alphaCB->Draw("alp");
	gr_alphaCB->GetXaxis()->SetTitle("alpha CB");
	c->cd(6);
	gr_nCB->Draw("alp");
	gr_nCB->GetXaxis()->SetTitle("n CB");
	c->SaveAs("sigFigs/params.eps");
	
	std::cout << "mean_CB = " << polyFunc1->GetParameter(0) << " + " << polyFunc1->GetParameter(1) << "*m + " << polyFunc1->GetParameter(2) << "*(m - " << polyFunc1->GetParameter(3) << ")*(m - " << polyFunc1->GetParameter(3);
	std::cout << ") + " << polyFunc1->GetParameter(4) << "*m*m*m*m;" << std::endl;
	std::cout << "sigma_CB = " << polyFunc2->GetParameter(0) << " + " << polyFunc2->GetParameter(1) << "*m + " << polyFunc2->GetParameter(2) << "*(m - " << polyFunc2->GetParameter(3) << ")*(m - " << polyFunc2->GetParameter(3);
	std::cout << ") + " << polyFunc2->GetParameter(4) << "*m*m*m*m;" << std::endl;
	
	
	// calculate sysetmatic errors from interpolation...
	double sum_meanCB = 0;
	double sum_sigmaCB = 0;
	for (int i = 0; i < nPoints; i++){
		double tmp_meanCB = (polyFunc1->Eval(mHVal[i]) - a_meanCB[i]);
		sum_meanCB += (tmp_meanCB*tmp_meanCB);
		double tmp_sigmaCB = (polyFunc2->Eval(mHVal[i]) - a_sigmaCB[i])/a_sigmaCB[i];
		sum_sigmaCB += (tmp_sigmaCB*tmp_sigmaCB);
		std::cout << "mean: " << tmp_meanCB << ", sigma: " << tmp_sigmaCB << std::endl;
	}
	double rms_meanCB = sqrt( sum_meanCB/( (double) nPoints) );
	double rms_sigmaCB = sqrt( sum_sigmaCB/( (double) nPoints) );
	std::cout << "err (meanCB) = " << rms_meanCB << ", err (sigmaCB) = " << rms_sigmaCB << std::endl;
	
	
}
Пример #8
0
/*
 * 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 OneSidedFrequentistUpperLimitWithBands_intermediate(const char* infile = "",
					    const char* workspaceName = "combined",
					    const char* modelConfigName = "ModelConfig",
					    const char* dataName = "obsData"){


  double confidenceLevel=0.95;
  // degrade/improve number of pseudo-experiments used to define the confidence belt.  
  // value of 1 corresponds to default number of toys in the tail, which is 50/(1-confidenceLevel)
  double additionalToysFac = 1.;  
  int nPointsToScan = 30; // number of steps in the parameter of interest 
  int nToyMC = 100; // number of toys used to define the expected limit and band

  TStopwatch t;
  t.Start();
  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  const char* filename = "";
  if (!strcmp(infile,""))
    filename = "results/example_combined_GaussExample_model.root";
  else
    filename = infile;
  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified byt not found, quit
  if(!file && strcmp(infile,"")){
    cout <<"file not found" << endl;
    return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;
  }

  // now try to access the file again
  file = TFile::Open(filename);
  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

  
  /////////////////////////////////////////////////////////////
  // Now get the data and workspace
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  cout << "Found data and ModelConfig:" <<endl;
  mc->Print();

  /////////////////////////////////////////////////////////////
  // Now get the POI for convenience
  // you may want to adjust the range of your POI
  ////////////////////////////////////////////////////////////
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  //  firstPOI->setMin(0);
  //  firstPOI->setMax(10);

  /////////////////////////////////////////////
  // create and use the FeldmanCousins tool
  // to find and plot the 95% confidence interval
  // on the parameter of interest as specified
  // in the model config
  // REMEMBER, we will change the test statistic
  // so this is NOT a Feldman-Cousins interval
  FeldmanCousins fc(*data,*mc);
  fc.SetConfidenceLevel(confidenceLevel); 
  fc.AdditionalNToysFactor(additionalToysFac); // improve sampling that defines confidence belt
  //  fc.UseAdaptiveSampling(true); // speed it up a bit, but don't use for expectd limits
  fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
  fc.CreateConfBelt(true); // save the information in the belt for plotting

  /////////////////////////////////////////////
  // Feldman-Cousins is a unified limit by definition
  // but the tool takes care of a few things for us like which values
  // of the nuisance parameters should be used to generate toys.
  // so let's just change the test statistic and realize this is 
  // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
  //  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());
  //  fc.GetTestStatSampler()->SetTestStatistic(&onesided);
  // ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true);
  ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler(); 
  ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
  testStat->SetOneSided(true);


  // test speedups:
  testStat->SetReuseNLL(true);
  //  toymcsampler->setUseMultiGen(true); // not fully validated

  // Since this tool needs to throw toy MC the PDF needs to be
  // extended or the tool needs to know how many entries in a dataset
  // per pseudo experiment.  
  // In the 'number counting form' where the entries in the dataset
  // are counts, and not values of discriminating variables, the
  // datasets typically only have one entry and the PDF is not
  // extended.  
  if(!mc->GetPdf()->canBeExtended()){
    if(data->numEntries()==1)     
      fc.FluctuateNumDataEntries(false);
    else
      cout <<"Not sure what to do about this model" <<endl;
  }

  // We can use PROOF to speed things along in parallel
  ProofConfig pc(*w, 4, "",false); 
  if(mc->GetGlobalObservables()){
    cout << "will use global observables for unconditional ensemble"<<endl;
    mc->GetGlobalObservables()->Print();
    toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
  }
  toymcsampler->SetProofConfig(&pc);	// enable proof


  // Now get the interval
  PointSetInterval* interval = fc.GetInterval();
  ConfidenceBelt* belt = fc.GetConfidenceBelt();
 
  // print out the iterval on the first Parameter of Interest
  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    interval->LowerLimit(*firstPOI) << ", "<<
    interval->UpperLimit(*firstPOI) <<"] "<<endl;

  // get observed UL and value of test statistic evaluated there
  RooArgSet tmpPOI(*firstPOI);
  double observedUL = interval->UpperLimit(*firstPOI);
  firstPOI->setVal(observedUL);
  double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


  // Ask the calculator which points were scanned
  RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
  RooArgSet* tmpPoint;

  // make a histogram of parameter vs. threshold
  TH1F* histOfThresholds = new TH1F("histOfThresholds","",
				    parameterScan->numEntries(),
				    firstPOI->getMin(),
				    firstPOI->getMax());
  histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
  histOfThresholds->GetYaxis()->SetTitle("Threshold");

  // loop through the points that were tested and ask confidence belt
  // what the upper/lower thresholds were.
  // For FeldmanCousins, the lower cut off is always 0
  for(Int_t i=0; i<parameterScan->numEntries(); ++i){
    tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
    double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
    double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
    histOfThresholds->Fill(poiVal,arMax);
  }
  TCanvas* c1 = new TCanvas();
  c1->Divide(2);
  c1->cd(1);
  histOfThresholds->SetMinimum(0);
  histOfThresholds->Draw();
  c1->cd(2);

  /////////////////////////////////////////////////////////////
  // Now we generate the expected bands and power-constriant
  ////////////////////////////////////////////////////////////

  // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
  RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
  RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
  firstPOI->setVal(0.);
  profile->getVal(); // this will do fit and set nuisance parameters to profiled values
  RooArgSet* poiAndNuisance = new RooArgSet();
  if(mc->GetNuisanceParameters())
    poiAndNuisance->add(*mc->GetNuisanceParameters());
  poiAndNuisance->add(*mc->GetParametersOfInterest());
  w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
  RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
  cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
  paramsToGenerateData->Print("v");


  double CLb=0;
  double CLbinclusive=0;

  // Now we generate background only and find distribution of upper limits
  TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
  histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
  histOfUL->GetYaxis()->SetTitle("Entries");
  for(int imc=0; imc<nToyMC; ++imc){

    // set parameters back to values for generating pseudo data
    w->loadSnapshot("paramsToGenerateData");

    // in 5.30 there is a nicer way to generate toy data  & randomize global obs
    RooAbsData* toyData = toymcsampler->GenerateToyData(*paramsToGenerateData);

    // get test stat at observed UL in observed data
    firstPOI->setVal(observedUL);
    double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
    //    toyData->get()->Print("v");
    //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
    if(obsTSatObsUL < toyTSatObsUL) // (should be checked)
      CLb+= (1.)/nToyMC;
    if(obsTSatObsUL <= toyTSatObsUL) // (should be checked)
      CLbinclusive+= (1.)/nToyMC;


    // loop over points in belt to find upper limit for this toy data
    double thisUL = 0;
    for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
      double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

      if(thisTS<=arMax){
	thisUL = firstPOI->getVal();
      } else{
	break;
      }
    }
    

    histOfUL->Fill(thisUL);

    
    delete toyData;
  }
  histOfUL->Draw();
  c1->SaveAs("one-sided_upper_limit_output.pdf");

  // if you want to see a plot of the sampling distribution for a particular scan point:

  // Now find bands and power constraint
  Double_t* bins = histOfUL->GetIntegral();
  TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
  cumulative->SetContent(bins);
  double band2sigDown=0, band1sigDown=0, bandMedian=0, band1sigUp=0,band2sigUp=0;
  for(int i=1; i<=cumulative->GetNbinsX(); ++i){
    if(bins[i]<RooStats::SignificanceToPValue(2))
      band2sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(1))
      band1sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<0.5)
      bandMedian=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-1))
      band1sigUp=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-2))
      band2sigUp=cumulative->GetBinCenter(i);
  }

  t.Stop();
  t.Print();

  cout << "-2 sigma  band " << band2sigDown << endl;
  cout << "-1 sigma  band " << band1sigDown  << endl;
  cout << "median of band " << bandMedian << " [Power Constriant)]" << endl;
  cout << "+1 sigma  band " << band1sigUp << endl;
  cout << "+2 sigma  band " << band2sigUp << endl;

  // print out the iterval on the first Parameter of Interest
  cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
  cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
  cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

  delete profile;
  delete nll;

}
Пример #10
0
   void build_hbb_workspace1( const char* infile = "outputfiles/input-file.txt", const char* outfile = "outputfiles/ws.root" ) {


    //-------------------------------------------------------------------------

     //-- Create workspace and other RooStats things.

      printf("\n\n Creating workspace.\n\n") ;

      RooWorkspace workspace("ws") ;
      workspace.autoImportClassCode(true) ;

      globalObservables      = new RooArgSet("globalObservables");
      allNuisances           = new RooArgSet("allNuisances");
      allNuisancePdfs        = new RooArgSet("allNuisancePdfs");
      RooArgSet* observedParametersList = new RooArgSet("observables") ;




    //-------------------------------------------------------------------------

      printf("\n\n Reading input file: %s\n\n", infile ) ;

      float fileVal ;
      char pname[1000] ;
      char formula[1000] ;


      sprintf( pname, "bins_of_met" ) ;
      if ( !getFileValue( infile, pname, fileVal ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
      int bins_of_met = TMath::Nint( fileVal ) ;

      //-- save bins_of_met in the workspace for convenience.
      RooRealVar bom( "bins_of_met", "bins_of_met", bins_of_met, 0., 1000. ) ;
      bom.setConstant(kTRUE) ;
      workspace.import(bom) ;


      //-- save bins_of_nb in the workspace for convenience.
      RooRealVar bonb( "bins_of_nb", "bins_of_nb", bins_of_nb, 0., 1000. ) ;
      bonb.setConstant(kTRUE) ;
      workspace.import(bonb) ;


      RooRealVar* rv_N_msig[bins_of_nb][max_bins_of_met] ; // first index is number of btags, second is met bin.
      RooRealVar* rv_N_msb[bins_of_nb][max_bins_of_met]  ; // first index is number of btags, second is met bin.

      RooRealVar* rv_smc_msig[bins_of_nb][max_bins_of_met] ; // first index is number of btags, second is met bin.
      RooRealVar* rv_smc_msb[bins_of_nb][max_bins_of_met]  ; // first index is number of btags, second is met bin.

      RooAbsReal* rv_Rsigsb_corr[bins_of_nb][max_bins_of_met]  ;

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {

            sprintf( pname, "N_%db_msig_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, fileVal ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
            rv_N_msig[nbi][mbi] = new RooRealVar( pname, pname, 0., 1.e6 ) ;
            rv_N_msig[nbi][mbi] -> setVal( TMath::Nint(fileVal) ) ;
            rv_N_msig[nbi][mbi] -> setConstant( kTRUE ) ;
            observedParametersList -> add( *rv_N_msig[nbi][mbi] ) ;

            sprintf( pname, "N_%db_msb_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, fileVal ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
            rv_N_msb[nbi][mbi] = new RooRealVar( pname, pname, 0., 1.e6 ) ;
            rv_N_msb[nbi][mbi] -> setVal( TMath::Nint(fileVal) ) ;
            rv_N_msb[nbi][mbi] -> setConstant( kTRUE ) ;
            observedParametersList -> add( *rv_N_msb[nbi][mbi] ) ;

            sprintf( pname, "smc_%db_msig_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, fileVal ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
            rv_smc_msig[nbi][mbi] = new RooRealVar( pname, pname, 0., 1.e6 ) ;
            rv_smc_msig[nbi][mbi] -> setVal( TMath::Nint(fileVal) ) ;
            rv_smc_msig[nbi][mbi] -> setConstant( kTRUE ) ;

            sprintf( pname, "smc_%db_msb_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, fileVal ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
            rv_smc_msb[nbi][mbi] = new RooRealVar( pname, pname, 0., 1.e6 ) ;
            rv_smc_msb[nbi][mbi] -> setVal( TMath::Nint(fileVal) ) ;
            rv_smc_msb[nbi][mbi] -> setConstant( kTRUE ) ;

            float corrVal, corrSyst ;
            sprintf( pname, "Rsigsb_syst_%db_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, corrSyst ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }
            sprintf( pname, "Rsigsb_corr_%db_met%d", nbi+2, mbi+1 ) ;
            if ( !getFileValue( infile, pname, corrVal  ) ) { printf("\n\n *** Error.  Can't find %s\n\n", pname ) ; return ; }

            rv_Rsigsb_corr[nbi][mbi] = makeLognormalConstraint( pname, corrVal, corrSyst ) ;


         } // mbi.

      } // nbi.

     //-- Finished reading input from file.

    //-------------------------------------------------------------------------

      printf("\n\n Creating and importing dataset into workspace.\n\n") ;

      RooDataSet* dsObserved = new RooDataSet("hbb_observed_rds", "hbb observed data values", *observedParametersList ) ;
      dsObserved -> add( *observedParametersList ) ;
      workspace.import( *dsObserved ) ;

    //-------------------------------------------------------------------------

     //-- Define all floats.

      printf("\n\n Defining all unconstrained floats (Ratios, signal strength).\n\n") ;

      double R_msigmsb_initialval(0.15) ;

      RooRealVar* rv_R_msigmsb[50] ;

      for ( int mbi=0; mbi<bins_of_met; mbi++ ) {

         sprintf( pname, "R_msigmsb_met%d", mbi+1 ) ;
         printf( "  %s\n", pname ) ;
         rv_R_msigmsb[mbi] = new RooRealVar( pname, pname, R_msigmsb_initialval, 0., 3. ) ;
         rv_R_msigmsb[mbi] -> setConstant( kFALSE ) ;
         rv_R_msigmsb[mbi] -> Print() ;

      } // mbi.

      printf("\n") ;

      sprintf( pname, "sig_strength" ) ;
      RooRealVar* rv_sig_strength = new RooRealVar( pname, pname, 1.0, 0., 10. ) ;
      rv_sig_strength -> setConstant(kFALSE) ;
      rv_sig_strength -> Print() ;
      printf("  %s\n\n", pname ) ;

    //-------------------------------------------------------------------------

     //-- Define all mu parameters.

      printf("\n\n Defining mu parameters.\n\n") ;

      RooAbsReal* rv_mu_bg_msig[bins_of_nb][max_bins_of_met] ;  // first index is number of btags, second is met bin.
      RooAbsReal* rv_mu_bg_msb[bins_of_nb][max_bins_of_met]  ;  // first index is number of btags, second is met bin.

      RooAbsReal* rv_mu_sig_msig[bins_of_nb][max_bins_of_met] ; // first index is number of btags, second is met bin.
      RooAbsReal* rv_mu_sig_msb[bins_of_nb][max_bins_of_met]  ; // first index is number of btags, second is met bin.

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {

            sprintf( pname, "mu_bg_%db_msb_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_mu_bg_msb[nbi][mbi] = new RooRealVar( pname, pname, rv_N_msb[nbi][mbi] -> getVal(), 0., 1.e6 ) ;
            rv_mu_bg_msb[nbi][mbi] -> Print() ;



            sprintf( formula, "@0 * @1 * @2" ) ;
            sprintf( pname, "mu_bg_%db_msig_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_mu_bg_msig[nbi][mbi] = new RooFormulaVar( pname, formula, RooArgSet( *rv_Rsigsb_corr[nbi][mbi], *rv_R_msigmsb[mbi], *rv_mu_bg_msb[nbi][mbi] ) ) ;
            rv_mu_bg_msig[nbi][mbi] -> Print() ;

            sprintf( formula, "@0 * @1" ) ;
            sprintf( pname, "mu_sig_%db_msig_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_mu_sig_msig[nbi][mbi] = new RooFormulaVar( pname, formula, RooArgSet( *rv_sig_strength, *rv_smc_msig[nbi][mbi] ) ) ;
            rv_mu_sig_msig[nbi][mbi] -> Print() ;

            sprintf( formula, "@0 * @1" ) ;
            sprintf( pname, "mu_sig_%db_msb_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_mu_sig_msb[nbi][mbi] = new RooFormulaVar( pname, formula, RooArgSet( *rv_sig_strength, *rv_smc_msb[nbi][mbi] ) ) ;
            rv_mu_sig_msb[nbi][mbi] -> Print() ;


         } // mbi.

      } // nbi.

     //-- Finished defining mu parameters.

    //-------------------------------------------------------------------------

     //-- Defining small n's

     printf("\n\n Defining small n's.\n\n") ;

     RooAbsReal* rv_n_msig[bins_of_nb][max_bins_of_met] ;  // first index is number of btags, second is met bin.
     RooAbsReal* rv_n_msb[bins_of_nb][max_bins_of_met]  ;  // first index is number of btags, second is met bin.

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {

            sprintf( formula, "@0 + @1" ) ;

            sprintf( pname, "n_%db_msig_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_n_msig[nbi][mbi] = new RooFormulaVar( pname, formula, RooArgSet( *rv_mu_sig_msig[nbi][mbi], *rv_mu_bg_msig[nbi][mbi] ) ) ;
            rv_n_msig[nbi][mbi] -> Print() ;
            workspace.import( *rv_n_msig[nbi][mbi] ) ;

            sprintf( pname, "n_%db_msb_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_n_msb[nbi][mbi] = new RooFormulaVar( pname, formula, RooArgSet( *rv_mu_sig_msb[nbi][mbi], *rv_mu_bg_msb[nbi][mbi] ) ) ;
            rv_n_msb[nbi][mbi] -> Print() ;
            workspace.import( *rv_n_msb[nbi][mbi] ) ;

         } // mbi.

      } // nbi.

    //-------------------------------------------------------------------------

     //-- Define the Poisson pdfs for the observables.

      printf("\n\n Defining Poisson pdfs for the observables.\n\n") ;

      RooAbsReal* rv_pdf_msig[bins_of_nb][max_bins_of_met] ;  // first index is number of btags, second is met bin.
      RooAbsReal* rv_pdf_msb[bins_of_nb][max_bins_of_met]  ;  // first index is number of btags, second is met bin.

      RooArgSet pdflist ;

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {

            sprintf( pname, "pdf_%db_msig_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_pdf_msig[nbi][mbi] = new RooPoisson( pname, pname, *rv_N_msig[nbi][mbi], *rv_n_msig[nbi][mbi] ) ;
            rv_pdf_msig[nbi][mbi] -> Print() ;

            pdflist.add( *rv_pdf_msig[nbi][mbi] ) ;

            sprintf( pname, "pdf_%db_msb_met%d", nbi+2, mbi+1 ) ;
            printf( "  %s\n", pname ) ;
            rv_pdf_msb[nbi][mbi] = new RooPoisson( pname, pname, *rv_N_msb[nbi][mbi], *rv_n_msb[nbi][mbi] ) ;
            rv_pdf_msb[nbi][mbi] -> Print() ;

            pdflist.add( *rv_pdf_msb[nbi][mbi] ) ;

         } // mbi.

      } // nbi.

    //-------------------------------------------------------------------------

     //-- Build the likelihood.

      printf("\n\n Building the likelihood.\n\n") ;

      pdflist.add( *allNuisancePdfs ) ;

      pdflist.Print() ;
      printf("\n") ;

      RooProdPdf* likelihood = new RooProdPdf( "likelihood", "hbb likelihood", pdflist ) ;
      likelihood->Print() ;


    //-------------------------------------------------------------------------


  //  printf("\n\n Running a test fit.\n\n") ;


  //  dsObserved -> Print() ;
  //  dsObserved -> printMultiline(cout, 1, kTRUE, "") ;


  //  printf("\n\n =============================================\n\n") ;
  //  likelihood -> fitTo( *dsObserved, PrintLevel(3), Hesse(0), Minos(0) ) ;
  //  printf("\n\n =============================================\n\n") ;







     //-- Set up RooStats models.

      printf("\n\n Setting up S+B model.\n\n") ;

      RooArgSet poi( *rv_sig_strength, "poi" ) ;
      RooUniform signal_prior( "signal_prior", "signal_prior", *rv_sig_strength ) ;

      ModelConfig sbModel ("SbModel");
      sbModel.SetWorkspace( workspace ) ;
      sbModel.SetPdf( *likelihood ) ;
      sbModel.SetParametersOfInterest( poi );
      sbModel.SetPriorPdf(signal_prior);
      sbModel.SetObservables( *observedParametersList );
      sbModel.SetNuisanceParameters( *allNuisances );
      sbModel.SetGlobalObservables( *globalObservables );

      workspace.Print() ;

      printf("\n\n Doing fit for S+B model.\n" ) ; fflush(stdout) ;

      RooAbsReal* pNll = sbModel.GetPdf()->createNLL(*dsObserved);
      RooAbsReal* pProfile = pNll->createProfile(RooArgSet());
      pProfile->getVal();
      RooArgSet* pPoiAndNuisance = new RooArgSet();
      pPoiAndNuisance->add(*sbModel.GetParametersOfInterest());
      if(sbModel.GetNuisanceParameters()) pPoiAndNuisance->add(*sbModel.GetNuisanceParameters());
      printf("\n\n Will save these parameter points that correspond to the fit to data.\n\n") ; fflush(stdout) ;
      pPoiAndNuisance->Print("v");
      sbModel.SetSnapshot(*pPoiAndNuisance);
      workspace.import (sbModel);

      delete pProfile ;
      delete pNll ;
      delete pPoiAndNuisance ;

      printf("\n\n Setting up BG-only model.\n\n") ;

      ModelConfig bModel (*(RooStats::ModelConfig *)workspace.obj("SbModel"));
      bModel.SetName("BModel");
      bModel.SetWorkspace(workspace);

      printf("\n\n Doing fit for BG-only model.\n" ) ; fflush(stdout) ;
      pNll = bModel.GetPdf()->createNLL(*dsObserved);
      pProfile = pNll->createProfile(*bModel.GetParametersOfInterest());
      ((RooRealVar *)(bModel.GetParametersOfInterest()->first()))->setVal(0.);
      pProfile->getVal();
      pPoiAndNuisance = new RooArgSet();
      pPoiAndNuisance->add(*bModel.GetParametersOfInterest());
      if(bModel.GetNuisanceParameters()) pPoiAndNuisance->add(*bModel.GetNuisanceParameters());
      printf("\n\n Should use these parameter points to generate pseudo data for bkg only.\n\n") ; fflush(stdout) ;
      pPoiAndNuisance->Print("v");
      bModel.SetSnapshot(*pPoiAndNuisance);
      workspace.import (bModel);

      delete pProfile ;
      delete pNll ;
      delete pPoiAndNuisance ;

      workspace.Print() ;

      printf("\n\n Saving workspace in : %s\n\n", outfile ) ;

      gSystem->Exec(" mkdir -p outputfiles " ) ;

      workspace.writeToFile( outfile ) ;




   } // build_hbb_workspace1.
Пример #11
0
void plotPdf_7D_VWW(double mH=125) {
    
    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    TGaxis::SetMaxDigits(3);
    gROOT->ForceStyle();
    

    // Declaration of the PDFs to use
    gROOT->ProcessLine(".L PDFs/RooSpinOne_7D.cxx++");
    
    // W/Z mass and decay width constants
    double mV = 80.399;
    double gamV = 2.085;
    bool offshell = false;
    if ( mH < 2 * mV ) offshell = true;

    // for the pole mass and decay width of W 
    RooRealVar* mX = new RooRealVar("mX","mX", mH);
    RooRealVar* mW = new RooRealVar("mW","mW", mV);
    RooRealVar* gamW = new RooRealVar("gamW","gamW",gamV);

    //
    // Observables (7D)
    // 
    RooRealVar* wplusmass = new RooRealVar("wplusmass","m(W+)",mV,1e-09,120);
    wplusmass->setBins(50);
    RooRealVar* wminusmass = new RooRealVar("wminusmass","m(W-)",mV,1e-09,120);
    wminusmass->setBins(50);
    RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
    hs->setBins(20);
    RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());
    Phi1->setBins(20);
    RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
    h1->setBins(20);
    RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
    h2->setBins(20);
    RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
    Phi->setBins(20);
    
    // 1-
    RooRealVar* g1ValV = new RooRealVar("g1ValV","g1ValV",1.);
    RooRealVar* g2ValV = new RooRealVar("g2ValV","g2ValV",0.);
    // Even more parameters, do not have to touch, based on W couplings
    RooRealVar* R1Val = new RooRealVar("R1Val","R1Val",-1.);
    RooRealVar* R2Val = new RooRealVar("R2Val","R2Val",-1.);
    
    // these are the acceptance terms associated with the production angles
    // the default setting is for setting no-acceptance
    RooRealVar* aParam = new RooRealVar("aParam","aParam",0);
    
    RooSpinOne_7D *myPDFV;

    if ( offshell ) 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1, 
				 *g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1, 
				*g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    
    // Grab input file to convert to RooDataSet
    TFile* finV = new TFile(Form("VWW_%.0f_JHU.root", mH));
    TTree* tinV = (TTree*) finV->Get("angles");
    if ( offshell ) 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*wplusmass, *wminusmass, *h1,*h2, *hs, *Phi, *Phi1));
    else 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    
    for (int i=1;i<1;i++) {
      RooArgSet* row = dataV.get(i);
      row->Print("v");
    }
    

    // 
    // 1+
    // 
    RooRealVar* g1ValA = new RooRealVar("g1ValA","g1ValA",0);
    RooRealVar* g2ValA = new RooRealVar("g2ValA","g2ValA",1);
    RooSpinOne_7D *myPDFA;
    
    if ( offshell ) 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);

    TFile* finA = new TFile(Form("AVWW_%.0f_JHU.root", mH));
    TTree* tinA = (TTree*) finA->Get("angles");
    if ( offshell ) 
      RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
     else 
       RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    //
    // P L O T   . . .  
    // 

    bool drawv = true;
    bool drawa = true;
    bool drawpaper = true;

    double rescale = 1.0;
    if (drawpaper ) 
      rescale = 0.001;


    // for 1-
    TH1F* dum0 = new TH1F("dum0","dum0",1,0,1); dum0->SetLineColor(kRed); dum0->SetMarkerColor(kBlack); dum0->SetLineWidth(3);
    // for 1+
    TH1F* dum1 = new TH1F("dum1","dum1",1,0,1); dum1->SetLineColor(kBlue); dum1->SetMarkerColor(kBlack); dum1->SetMarkerStyle(24), dum1->SetLineWidth(3);
    TLegend * box3 = new TLegend(0.1,0.1,0.9,0.92);
    box3->SetFillColor(0);
    box3->SetBorderSize(0);
    if ( drawa ) 
      box3->AddEntry(dum0,"X#rightarrow WW JP = 1+","lp");
    if ( drawv )
    box3->AddEntry(dum1,"X#rightarrow WW JP = 1-","lp");

    // 
    //  h1
    // 
    RooPlot* h1frame =  h1->frame(20);
    h1frame->GetXaxis()->CenterTitle();
    h1frame->GetYaxis()->CenterTitle();
    h1frame->GetYaxis()->SetTitle(" ");

    double ymax_h1;
    TH1F *h1a = new TH1F("h1a", "h1a", 20, -1, 1);
    tinA->Project("h1a", "costheta1");
    ymax_h1 = h1a->GetMaximum();

    TH1F *h1_minus = new TH1F("h1_minus", "h1_minus", 20, -1, 1);
    tinV->Project("h1_minus", "costheta1");
    ymax_h1 = h1_minus->GetMaximum() > ymax_h1 ? h1_minus->GetMaximum() : ymax_h1;
    
    if ( drawa ) {
      dataA.plotOn(h1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      // tempoary
      dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.)
      h1frame->GetYaxis()->SetRangeUser(0, ymax_h1 / 1000. * 1.3);

    
    // 
    //  h2
    // 
    
    RooPlot* h2frame =  h2->frame(20);
    h2frame->GetXaxis()->CenterTitle();
    h2frame->GetYaxis()->CenterTitle();
    h2frame->GetYaxis()->SetTitle(" ");

    double ymax_h2;
    TH1F *h2a = new TH1F("h2a", "h2a", 20, -1, 1);
    tinA->Project("h2a", "costheta2");
    ymax_h2 = h2a->GetMaximum();

    TH1F *h2_minus = new TH1F("h2_minus", "h2_minus", 20, -1, 1);
    tinV->Project("h2_minus", "costheta2");
    ymax_h2 = h2_minus->GetMaximum() > ymax_h2 ? h2_minus->GetMaximum() : ymax_h2;

    if ( drawa ) {
      dataA.plotOn(h2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), yDataError(RooAbsData::None));
      // myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.) 
      h2frame->GetYaxis()->SetRangeUser(0, ymax_h2 / 1000. * 1.3);

    //
    // Phi
    // 
    RooPlot* Phiframe =  Phi->frame(20);
    Phiframe->GetXaxis()->CenterTitle();
    Phiframe->GetYaxis()->CenterTitle();
    Phiframe->GetYaxis()->SetTitle(" ");

    double ymax_Phi;
    TH1F *Phia = new TH1F("Phia", "Phia", 20,  -TMath::Pi(), TMath::Pi());
    tinA->Project("Phia", "phi");
    ymax_Phi = Phia->GetMaximum();

    TH1F *Phi_minus = new TH1F("Phi_minus", "Phi_minus", 20,  -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi_minus", "phi");
    ymax_Phi = Phi_minus->GetMaximum() > ymax_Phi ? Phi_minus->GetMaximum() : ymax_Phi;
    
    if ( drawa ) {
      dataA.plotOn(Phiframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phiframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phiframe->GetYaxis()->SetRangeUser(0, ymax_Phi / 1000. * 1.3);
    
    // 
    //  hs 
    // 
    RooPlot* hsframe =  hs->frame(20);

    hsframe->GetXaxis()->CenterTitle();
    hsframe->GetYaxis()->CenterTitle();
    hsframe->GetYaxis()->SetTitle(" ");

    double ymax_hs;
    TH1F *hsa = new TH1F("hsa", "hsa", 20, -1, 1);
    tinA->Project("hsa", "costhetastar");
    ymax_hs = hsa->GetMaximum();

    TH1F *hs_minus = new TH1F("hs_minus", "hs_minus", 20, -1, 1);
    tinV->Project("hs_minus", "costhetastar");
    ymax_hs = hs_minus->GetMaximum() > ymax_hs ? hs_minus->GetMaximum() : ymax_hs;
    
    if ( drawa ) {
      dataA.plotOn(hsframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(hsframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      hsframe->GetYaxis()->SetRangeUser(0, ymax_hs / 1000. * 1.3);

    
    //
    // Phi1
    // 
    RooPlot* Phi1frame =  Phi1->frame(20);
 
    Phi1frame->GetXaxis()->CenterTitle();
    Phi1frame->GetYaxis()->CenterTitle();
    Phi1frame->GetYaxis()->SetTitle(" ");

    double ymax_Phi1;
    TH1F *Phi1a = new TH1F("Phi1a", "Phi1a", 20, -TMath::Pi(), TMath::Pi());
    tinA->Project("Phi1a", "phistar1");
    ymax_Phi1 = Phi1a->GetMaximum();

    TH1F *Phi1_minus = new TH1F("Phi1_minus", "Phi1_minus", 20, -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi1_minus", "phistar1");
    ymax_Phi1 = Phi1_minus->GetMaximum() > ymax_Phi1 ? Phi1_minus->GetMaximum() : ymax_Phi1;
    
    if ( drawa ) {
      dataA.plotOn(Phi1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phi1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      // myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phi1frame->GetYaxis()->SetRangeUser(0, ymax_Phi1 / 1000. * 1.3);


    if ( offshell ) {
      RooPlot* w1frame =  wplusmass->frame(50);
      w1frame->GetXaxis()->CenterTitle();
      w1frame->GetYaxis()->CenterTitle();
      w1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w1;
      TH1F *w1a = new TH1F("w1a", "w1a", 50, 1e-09, 120);
      tinA->Project("w1a", "wplusmass");
      ymax_w1 = w1a->GetMaximum();
      
      TH1F *w1_minus = new TH1F("w1_minus", "w1_minus", 50, 1e-09, 120);
      tinV->Project("w1_minus", "wplusmass")
      ymax_w1 = w1_minus->GetMaximum() > ymax_w1 ? w1_minus->GetMaximum() : ymax_w1;
      
      if ( drawa ) {
	dataA.plotOn(w1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	// dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	// myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. )
      w1frame->GetYaxis()->SetRangeUser(0, ymax_w1 / 1000. * 1.5);

      // 
      //  wminus
      // 
      RooPlot* w2frame =  wminusmass->frame(50);

      w2frame->GetXaxis()->CenterTitle();
      w2frame->GetYaxis()->CenterTitle();
      w2frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w2;
      TH1F *w2a = new TH1F("w2a", "w2a", 50, 1e-09, 120);
      tinA->Project("w2a", "wminusmass");
      ymax_w2 = w2a->GetMaximum();
      
      TH1F *w2_minus = new TH1F("w2_minus", "w2_minus", 50, 1e-09, 120);
      tinV->Project("w2_minus", "wminusmass")
      ymax_w2 = w2_minus->GetMaximum() > ymax_w2 ? w2_minus->GetMaximum() : ymax_w2;
      
      if ( drawa ) {
	dataA.plotOn(w2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	//dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	//myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. ) 
	w2frame->GetYaxis()->SetRangeUser(0, ymax_w2 / 1000. * 1.5);
    }
    if ( drawpaper ) {
      TCanvas* can =new TCanvas("can","can",600,600);

      if ( offshell ) {
	w1frame->GetXaxis()->SetTitle("m_{l#nu} [GeV]");
	w1frame->Draw();
	can->Print(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.eps", mH));
	can->SaveAs(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.C", mH));
      }
      
      can->Clear();
      hsframe->Draw();
      can->Print(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.C", mH));      
      
      can->Clear();
      Phi1frame->Draw();
      can->Print(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.C", mH));      

      can->Clear();
      h1frame->GetXaxis()->SetTitle("cos#theta_{1} or cos#theta_{2}");
      h1frame->Draw();
      can->Print(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.eps", mH));
      can->SaveAs(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.C", mH));

      can->Clear();
      Phiframe->Draw();
      can->Print(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.C", mH));      


    }

    else {
      
      TCanvas* cww = new TCanvas( "cww", "cww", 1000, 600 );
      cww->Divide(4,2);
      if ( offshell ) {
	cww->cd(1);
	w1frame->Draw();
	cww->cd(2);
	w2frame->Draw();
      }
      cww->cd(3);
      hsframe->Draw();
      cww->cd(4);
      box3->Draw();
      cww->cd(5);
      Phi1frame->Draw();
      cww->cd(6);
      h1frame->Draw();
      cww->cd(7);
      h2frame->Draw();
      cww->cd(8);
      Phiframe->Draw();
      
      cww->Print(Form("epsfiles/angles_VWW%.0f_JHU_7D.eps", mH));
      cww->Print(Form("pngfiles/angles_VWW%.0f_JHU_7D.png", mH));
      delete cww;
    }

}
void StandardTestStatDistributionDemo(const char* infile = "",
                                      const char* workspaceName = "combined",
                                      const char* modelConfigName = "ModelConfig",
                                      const char* dataName = "obsData"){


  // the number of toy MC used to generate the distribution
  int nToyMC = 1000;
  // The parameter below is needed for asymptotic distribution to be chi-square,
  // but set to false if your model is not numerically stable if mu<0
  bool allowNegativeMu=true;


  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


  /////////////////////////////////////////////////////////////
  // Now get the data and workspace
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  mc->Print();
  /////////////////////////////////////////////////////////////
  // Now find the upper limit based on the asymptotic results
  ////////////////////////////////////////////////////////////
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  ProfileLikelihoodCalculator plc(*data,*mc);
  LikelihoodInterval* interval = plc.GetInterval();
  double plcUpperLimit = interval->UpperLimit(*firstPOI);
  delete interval;
  cout << "\n\n--------------------------------------"<<endl;
  cout <<"Will generate sampling distribution at " << firstPOI->GetName() << " = " << plcUpperLimit <<endl;
  int nPOI = mc->GetParametersOfInterest()->getSize();
  if(nPOI>1){
    cout <<"not sure what to do with other parameters of interest, but here are their values"<<endl;
    mc->GetParametersOfInterest()->Print("v");
  }

  /////////////////////////////////////////////
  // create thte test stat sampler
  ProfileLikelihoodTestStat ts(*mc->GetPdf());

  // to avoid effects from boundary and simplify asymptotic comparison, set min=-max
  if(allowNegativeMu)
    firstPOI->setMin(-1*firstPOI->getMax());

  // temporary RooArgSet
  RooArgSet poi;
  poi.add(*mc->GetParametersOfInterest());

  // create and configure the ToyMCSampler
  ToyMCSampler sampler(ts,nToyMC);
  sampler.SetPdf(*mc->GetPdf());
  sampler.SetObservables(*mc->GetObservables());
  sampler.SetGlobalObservables(*mc->GetGlobalObservables());
  if(!mc->GetPdf()->canBeExtended() && (data->numEntries()==1)){
    cout << "tell it to use 1 event"<<endl;
    sampler.SetNEventsPerToy(1);
  }
  firstPOI->setVal(plcUpperLimit); // set POI value for generation
  sampler.SetParametersForTestStat(*mc->GetParametersOfInterest()); // set POI value for evaluation

  if (useProof) {
     ProofConfig pc(*w, nworkers, "",false);
     sampler.SetProofConfig(&pc); // enable proof
  }

  firstPOI->setVal(plcUpperLimit);
  RooArgSet allParameters;
  allParameters.add(*mc->GetParametersOfInterest());
  allParameters.add(*mc->GetNuisanceParameters());
  allParameters.Print("v");

  SamplingDistribution* sampDist = sampler.GetSamplingDistribution(allParameters);
  SamplingDistPlot plot;
  plot.AddSamplingDistribution(sampDist);
  plot.GetTH1F(sampDist)->GetYaxis()->SetTitle(Form("f(-log #lambda(#mu=%.2f) | #mu=%.2f)",plcUpperLimit,plcUpperLimit));
  plot.SetAxisTitle(Form("-log #lambda(#mu=%.2f)",plcUpperLimit));

  TCanvas* c1 = new TCanvas("c1");
  c1->SetLogy();
  plot.Draw();
  double min = plot.GetTH1F(sampDist)->GetXaxis()->GetXmin();
  double max = plot.GetTH1F(sampDist)->GetXaxis()->GetXmax();

  TF1* f = new TF1("f",Form("2*ROOT::Math::chisquared_pdf(2*x,%d,0)",nPOI),min,max);
  f->Draw("same");
  c1->SaveAs("standard_test_stat_distribution.pdf");

}
Пример #13
0
Int_t Tprime::SetParameterPoints( std::string sbModelName,
                                  std::string bModelName ) {
    //
    // Fit the data with S+B model.
    // Make a snapshot of the S+B parameter point.
    // Profile with POI=0.
    // Make a snapshot of the B parameter point
    // (B model is the S+B model with POI=0
    //

    Double_t poi_value_for_b_model = 0.0;

    // get S+B model config from workspace
    RooStats::ModelConfig * pSbModel = (RooStats::ModelConfig *)pWs->obj(sbModelName.c_str());
    pSbModel->SetWorkspace(*pWs);

    // get parameter of interest set
    const RooArgSet * poi = pSbModel->GetParametersOfInterest();

    // get B model config from workspace
    RooStats::ModelConfig * pBModel = (RooStats::ModelConfig *)pWs->obj(bModelName.c_str());
    pBModel->SetWorkspace(*pWs);

    // make sure that data has been loaded
    if (!data) return -1;

    // find parameter point for global maximum with the S+B model,
    // with conditional MLEs for nuisance parameters
    // and save the parameter point snapshot in the Workspace
    RooAbsReal * nll = pSbModel->GetPdf()->createNLL(*data);
    RooAbsReal * profile = nll->createProfile(RooArgSet());
    profile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
    RooArgSet * poiAndNuisance = new RooArgSet();
    if(pSbModel->GetNuisanceParameters())
        poiAndNuisance->add(*pSbModel->GetNuisanceParameters());
    poiAndNuisance->add(*pSbModel->GetParametersOfInterest());
    pWs->defineSet("SPlusBModelParameters", *poiAndNuisance);
    pWs->saveSnapshot("SPlusBFitParameters",*poiAndNuisance);
    pSbModel->SetSnapshot(*poi);
    RooArgSet * sbModelFitParams = (RooArgSet *)poiAndNuisance->snapshot();
    cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
    sbModelFitParams->Print("v");
    delete profile;
    delete nll;
    delete poiAndNuisance;
    delete sbModelFitParams;

    //

    // Find a parameter point for generating pseudo-data
    // with the background-only data.
    // Save the parameter point snapshot in the Workspace
    nll = pBModel->GetPdf()->createNLL(*data);
    profile = nll->createProfile(*poi);
    ((RooRealVar *)poi->first())->setVal(poi_value_for_b_model);
    profile->getVal(); // this will do fit and set nuisance parameters to profiled values
    poiAndNuisance = new RooArgSet();
    if(pBModel->GetNuisanceParameters())
        poiAndNuisance->add(*pBModel->GetNuisanceParameters());
    poiAndNuisance->add(*pBModel->GetParametersOfInterest());
    pWs->defineSet("parameterPointToGenerateData", *poiAndNuisance);
    pWs->saveSnapshot("parametersToGenerateData",*poiAndNuisance);
    pBModel->SetSnapshot(*poi);
    RooArgSet * paramsToGenerateData = (RooArgSet *)poiAndNuisance->snapshot();
    cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
    paramsToGenerateData->Print("v");
    delete profile;
    delete nll;
    delete poiAndNuisance;
    delete paramsToGenerateData;

    return 0;
}
Пример #14
0
void rf508_listsetmanip()
{

  // C r e a t e   d u m m y   o b j e c t s 
  // ---------------------------------------

  // Create some variables
  RooRealVar a("a","a",1,-10,10) ;
  RooRealVar b("b","b",2,-10,10) ;
  RooRealVar c("c","c",3,-10,10) ;
  RooRealVar d("d","d",4,-10,10) ;
  RooRealVar x("x","x",0,-10,10) ;
  c.setError(0.5) ;
  a.setConstant() ;
  b.setConstant() ;

  // Create a category
  RooCategory e("e","e") ;
  e.defineType("sig") ;
  e.defineType("bkg") ;

  // Create a pdf
  RooGaussian g("g","g",x,a,b) ;



  // C r e a t i n g ,   f i l l i n g   R o o A r g S e t s 
  // -------------------------------------------------------

  // A RooArgSet is a set of RooAbsArg objects. Each object in the set must have
  // a unique name 

  // Set constructors exists with up to 9 initial arguments
  RooArgSet s(a,b) ;

  // At any time objects can be added with add()
  s.add(e) ;

  // Add up to 9 additional arguments in one call
  s.add(RooArgSet(c,d)) ;

  // Sets can contain any type of RooAbsArg, also pdf and functions
  s.add(g) ;

  // Remove element d
  s.remove(d) ;



  // A c c e s s i n g   R o o A r g S e t   c o n t e n t s
  // -------------------------------------------------------
  
  // You can look up objects by name
  RooAbsArg* aptr = s.find("a") ;

  // Construct a subset by name
  RooArgSet* subset1 = (RooArgSet*) s.selectByName("a,b,c") ;

  // Construct asubset by attribute
  RooArgSet* subset2 = (RooArgSet*) s.selectByAttrib("Constant",kTRUE) ;

  // Construct the subset of overlapping contents with another set
  RooArgSet s1(a,b,c) ;
  RooArgSet s2(c,d,e) ;
  RooArgSet* subset3 = (RooArgSet*) s1.selectCommon(s2) ;



  // O w n i n g   R o o A r g S e t s 
  // ---------------------------------  

  // Create a RooArgSet that owns its components
  // A set either owns all of its components or none,
  // so once addOwned() is used, add() can no longer be
  // used and will result in an error message

  RooRealVar* ac = (RooRealVar*) a.clone("a") ;
  RooRealVar* bc = (RooRealVar*) b.clone("b") ;
  RooRealVar* cc = (RooRealVar*) c.clone("c") ;

  RooArgSet s3 ;
  s3.addOwned(RooArgSet(*ac,*bc,*cc)) ;

  // Another possibility is to add an owned clone
  // of an object instead of the original
  s3.addClone(RooArgSet(d,e,g)) ;

  // A clone of a owning set is non-owning and its
  // contents is owned by the originating owning set
  RooArgSet* sclone = (RooArgSet*) s3.Clone("sclone") ;

  // To make a clone of a set and its contents use
  // the snapshot method
  RooArgSet* sclone2 = (RooArgSet*) s3.snapshot() ;

  // If a set contains function objects, only the head node
  // is cloned in a snapshot. To make a snapshot of all
  // servers of a function object do as follows. The result
  // of a RooArgSet snapshot with deepCloning option is a set
  // of cloned objects, and all their clone (recursive) server
  // dependencies, that together form a self-consistent
  // set that is free of external dependencies

  RooArgSet* sclone3 = (RooArgSet*) s3.snapshot(kTRUE) ;



  // S e t   p r i n t i n g 
  // ------------------------

  // Inline printing only show list of names of contained objects
  cout << "sclone = " << (*sclone) << endl ;

  // Plain print shows the same, prefixed by name of the set
  sclone->Print() ;

  // Standard printing shows one line for each item with the items name, class name and value
  sclone->Print("s") ;

  // Verbose printing adds each items arguments, address and 'extras' as defined by the object
  sclone->Print("v") ;



  // U s i n g   R o o A r g L i s t s 
  // ---------------------------------

  // List constructors exists with up to 9 initial arguments
  RooArgList l(a,b,c,d) ;

  // Lists have an explicit order and allow multiple arguments with the same name
  l.add(RooArgList(a,b,c,d)) ;

  // Access by index is provided
  RooAbsArg* arg4 = l.at(4) ;


}
Пример #15
0
void wspaceread_backgrounds(int channel = 1)
{

	gSystem->AddIncludePath("-I$ROOFITSYS/include");
	gROOT->ProcessLine(".L ~/tdrstyle.C");
	
	string schannel;
	if (channel == 1) schannel = "4mu";
	if (channel == 2) schannel = "4e";
	if (channel == 3) schannel = "2mu2e";
	std::cout << "schannel = " << schannel << std::endl;

	// R e a d   w o r k s p a c e   f r o m   f i l e
	// -----------------------------------------------
	
	// Open input file with workspace (generated by rf14_wspacewrite)
	char infile[192];
	sprintf(infile,"/scratch/hep/ntran/dataFiles/HZZ4L/datasets/datasets/%s/ZZAnalysisTree_ZZTo4L_lowmass.root",schannel.c_str());
	TFile *f = new TFile(infile) ;
	char outfile[192];
	sprintf( outfile, "figs/pdf_%s_bkg_highmass.eps", schannel.c_str() );
	//f->ls();
	
	
	RooDataSet* set = (RooDataSet*) f->Get("data");
	RooArgSet* obs = set->get() ;
	obs->Print();
	RooRealVar* CMS_zz4l_mass = (RooRealVar*) obs->find("CMS_zz4l_mass") ;
	
	for (int i=0 ; i<set->numEntries() ; i++) { 
		set->get(i) ; 
		//cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
	} 
	
	gSystem->Load("PDFs/RooqqZZPdf_cxx.so");
	//gSystem->Load("PDFs/RooggZZPdf_cxx.so");

	// LO contribution

	//RooRealVar m4l("m4l","m4l",100.,1000.);
	RooRealVar a1("a1","a1",224.,100.,1000.);
	RooRealVar a2("a2","a2",-209.,-1000.,1000.);
	RooRealVar a3("a3","a3",121.,20.,1000.);
	RooRealVar a4("a4","a4",-0.022,-10.,10.);
	RooRealVar b1("b1","b1",181.,100.,1000.);
	RooRealVar b2("b2","b2",707.,0.,1000.);
	RooRealVar b3("b3","b3",60.,20.,1000.);
	RooRealVar b4("b4","b4",0.04,-10.,10.);
	RooRealVar b5("b5","b5",5.,0.,1000.);
	RooRealVar b6("b6","b6",0.,-10.,10.);
	RooRealVar frac_bkg("frac_bkg","frac_bkg",0.5,0.,1.);
	
	//a1.setConstant(kTRUE);
	//a2.setConstant(kTRUE);
	//a3.setConstant(kTRUE);
	//a4.setConstant(kTRUE);
	//b1.setConstant(kTRUE);
	//b2.setConstant(kTRUE);
	//b3.setConstant(kTRUE);
	//b4.setConstant(kTRUE);
	//b5.setConstant(kTRUE);
	//b6.setConstant(kTRUE);

	RooqqZZPdf bkg_qqzz("bkg_qqzz","bkg_qqzz",*CMS_zz4l_mass,a1,a2,a3,a4,b1,b2,b3,b4,b5,b6,frac_bkg);

	RooFitResult *r = bkg_qqzz.fitTo( *set, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

	// Plot Y
	RooPlot* frameM4l = CMS_zz4l_mass->frame(Title("M4L"),Bins(100)) ;
	set->plotOn(frameM4l) ;
	bkg_qqzz.plotOn(frameM4l) ;
	
	TCanvas *c = new TCanvas("c","c",800,600);
	c->cd();
	frameM4l->Draw();
	
	
	
	/*
	// Retrieve workspace from file
	RooWorkspace* w = (RooWorkspace*) f->Get("workspace") ;
	
	w->Print();
	
	///*
	RooRealVar* CMS_zz4l_mass = w->var("CMS_zz4l_mass") ;
	RooAbsPdf* background_nonorm = w->pdf("background_nonorm") ;
	//RooAbsData* backgroundData = w->data("backgroundData") ;
	RooAbsData* data_bkg_red = w->data("data_bkg_red") ;
	
	RooArgSet* obs = data_bkg_red->get() ; 
	RooRealVar* xdata = obs->find(CMS_zz4l_mass.GetName()) ; 
	for (int i=0 ; i<data_bkg_red->numEntries() ; i++) { 
		data_bkg_red->get(i) ; 
		cout << xdata->getVal() << " = " << data_bkg_red->weight() << endl ; 
	} 
	std::cout << "nEntries = " << data_bkg_red->numEntries() << std::endl;
	obs->Print();

	
	RooFitResult *r = background_nonorm->fitTo( *data_bkg_red, SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;
	
	// Get parameters
	char varName[192];
	sprintf(varName, "CMS_zz%s_Nbkg", schannel.c_str());
	RooRealVar* Nbkg = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_bkgfrac", schannel.c_str());
	RooRealVar* bkgfrac = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a1", schannel.c_str());
	RooRealVar* a1 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a2", schannel.c_str());
	RooRealVar* a2 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_a3", schannel.c_str());
	RooRealVar* a3 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b1", schannel.c_str());
	RooRealVar* b1 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b2", schannel.c_str());
	RooRealVar* b2 = w->var(varName) ;
	sprintf(varName, "CMS_zz%s_b3", schannel.c_str());
	RooRealVar* b3 = w->var(varName) ;
	
	std::cout << "Nbkg: " << Nbkg->getVal() << std::endl;
	std::cout << "frac_bkg = " << bkgfrac->getVal() << " +/- " << bkgfrac->getError() << std::endl;
	std::cout << "a1 = " << a1->getVal() << " +/- " << a1->getError() << "; ";
	std::cout << "a2 = " << a2->getVal() << " +/- " << a2->getError() << "; ";
	std::cout << "a3 = " << a3->getVal() << " +/- " << a3->getError() << "; " << std::endl;
	std::cout << "b1 = " << b1->getVal() << " +/- " << b1->getError() << "; ";
	std::cout << "b2 = " << b2->getVal() << " +/- " << b2->getError() << "; ";
	std::cout << "b3 = " << b3->getVal() << " +/- " << b3->getError() << "; " << std::endl;
	
	// Plot data and PDF overlaid
	RooPlot* xframe = CMS_zz4l_mass->frame(Title("Model and data read from workspace")) ;
	//backgroundData->plotOn(xframe) ;
	data_bkg_red->plotOn(xframe) ;
	background_nonorm->plotOn(xframe) ;
	
	TCanvas* c = new TCanvas("c","c",800,600);
	c->cd();
	xframe->Draw();
	c->SaveAs(outfile);
	//*/
	
}
Пример #16
0
void rf505_asciicfg()
{
   // C r e a t e  p d f 
   // ------------------
   
   // Construct gauss(x,m,s)
   RooRealVar x("x","x",-10,10) ;
   RooRealVar m("m","m",0,-10,10) ;
   RooRealVar s("s","s",1,-10,10) ;
   RooGaussian gauss("g","g",x,m,s) ;

   // Construct poly(x,p0)
   RooRealVar p0("p0","p0",0.01,0.,1.) ;
   RooPolynomial poly("p","p",x,p0) ;		 

   // Construct model = f*gauss(x) + (1-f)*poly(x)
   RooRealVar f("f","f",0.5,0.,1.) ;
   RooAddPdf model("model","model",RooArgSet(gauss,poly),f) ;



   // F i t   m o d e l   t o   t o y   d a t a
   // -----------------------------------------

   RooDataSet* d = model.generate(x,1000) ;
   model.fitTo(*d) ;


   // W r i t e   p a r a m e t e r s   t o   a s c i i   f i l e 
   // -----------------------------------------------------------

   // Obtain set of parameters
   RooArgSet* params = model.getParameters(x) ;

   // Write parameters to file
   params->writeToFile("rf505_asciicfg_example.txt") ;


   TString dir1 = gROOT->GetTutorialsDir() ;
   dir1.Append("/roofit/rf505_asciicfg.txt") ;
   TString dir2 = gROOT->GetTutorialsDir() ;
   dir2.Append("/roofit/rf505_asciicfg_example.txt") ;
   // R e a d    p a r a m e t e r s   f r o m    a s c i i   f i l e 
   // ----------------------------------------------------------------
   
   // Read parameters from file
   params->readFromFile(dir2) ;
   params->Print("v") ;

   // Read parameters from section 'Section2' of file
   params->readFromFile(dir1,0,"Section2") ;
   params->Print("v") ;

   // Read parameters from section 'Section3' of file. Mark all
   // variables that were processed with the "READ" attribute
   params->readFromFile(dir1,"READ","Section3") ;

   // Print the list of parameters that were not read from Section3
   cout << "The following parameters of the were _not_ read from Section3: " 
         << (*params->selectByAttrib("READ",kFALSE)) << endl ;


   // Read parameters from section 'Section4' of file, which contains
   // 'include file' statement of rf505_asciicfg_example.txt
   // so that we effective read the same

   params->readFromFile(dir1,0,"Section4") ;
   params->Print("v") ;



}
Пример #17
0
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;

}
Пример #18
0
void splitws(string inFolderName, double mass, string channel) {
  cout << "Splitting workspace in " << channel << endl;

  int flatInterpCode = 4;
  int shapeInterpCode = 4;

  bool do2011 = 0;

  if (inFolderName.find("2011") != string::npos) do2011 = 1;

  bool conditionalAsimov = 0;
  bool doData = 1;
  //if (inFolderName.find("_blind_") != string::npos) {
    //conditionalAsimov = 0;
  //}
  //else {
    //conditionalAsimov = 1;
  //}

  set<string> channelNames;

  if (channel == "01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF01j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF0j") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF1j") {
    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_sscr_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF01j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF0j") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF1j") {
    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));
  }
  else if (channel == "2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF2j") {
    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF2j") {
    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "OF") {
    channelNames.insert("em_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_0j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("em_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike1_1j"+string(!do2011?"_2012":""));
    channelNames.insert("me_signalLike2_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("em_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else if (channel == "SF") {
    channelNames.insert("SF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_0j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_0j"+string(!do2011?"_2012":""));

    channelNames.insert("SF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_AfrecSR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_ASR_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CfrecZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_CZpeak_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_mainControl_1j"+string(!do2011?"_2012":""));
    channelNames.insert("OF_topbox_1j"+string(!do2011?"_2012":""));

    channelNames.insert("ee_signalLike1_2j"+string(!do2011?"_2012":""));
    channelNames.insert("SF_topbox_2j"+string(!do2011?"_2012":""));
  }
  else {
    cout << "Channel " << channel << " not defined. Please check!" << endl;
    exit(1);
  }

  // bool fix = 1;
  stringstream inFileName;

  inFileName << "workspaces/" << inFolderName << "/" << mass << ".root";
  TFile f(inFileName.str().c_str());
  
  RooWorkspace* w = (RooWorkspace*)f.Get("combWS");
  if (!w) w = (RooWorkspace*)f.Get("combined");
  
  RooDataSet* data = (RooDataSet*)w->data("combData");
  if (!data) data = (RooDataSet*)w->data("obsData");
  
  ModelConfig* mc = (ModelConfig*)w->obj("ModelConfig");
  
  RooRealVar* weightVar = w->var("weightVar");
  
  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();
  if (!mu) mu = w->var("SigXsecOverSM");

  const RooArgSet* mc_obs = mc->GetObservables();
  const RooArgSet* mc_nuis = mc->GetNuisanceParameters();
  const RooArgSet* mc_globs = mc->GetGlobalObservables();
  const RooArgSet* mc_poi = mc->GetParametersOfInterest();

  RooArgSet nuis = *mc_nuis;
  RooArgSet antiNuis = *mc_nuis;

  RooArgSet globs = *mc_globs;
  RooArgSet antiGlobs = *mc_globs;

  RooArgSet allParams;

  RooSimultaneous* simPdf = (RooSimultaneous*)mc->GetPdf();
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();

  RooArgSet nuis_tmp = nuis;
  RooArgSet fullConstraints = *simPdf->getAllConstraints(*mc_obs,nuis_tmp,false);

  vector<string> foundChannels;
  vector<string> skippedChannels;  

  cout << "Getting constraints" << endl;
  map<string, RooDataSet*> data_map;
  map<string, RooAbsPdf*> pdf_map;
  RooCategory* decCat = new RooCategory("dec_channel","dec_channel");
  // int i = 0;
  TIterator* catItr = cat->typeIterator();
  RooCatType* type;
  RooArgSet allConstraints;
  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end())  {
      skippedChannels.push_back(typeName);
      continue;
    }
    cout << "On channel " << type->GetName() << endl;
    foundChannels.push_back(typeName);

    decCat->defineType(type->GetName());
    // pdf->getParameters(*data)->Print("v");

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);
    constraints->Print();
    allConstraints.add(*constraints);
  }

  catItr->Reset();

  while ((type = (RooCatType*)catItr->Next())) {
    RooAbsPdf* pdf =  simPdf->getPdf(type->GetName());

    string typeName(type->GetName());
    cout << "Considering type " << typeName << endl;
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;
    cout << "On channel " << type->GetName() << endl;

    RooArgSet nuis_tmp1 = nuis;
    RooArgSet nuis_tmp2 = nuis;
    RooArgSet* constraints = pdf->getAllConstraints(*mc_obs, nuis_tmp1, true);

    cout << "Adding pdf to map: " << typeName << " = " << pdf->GetName() << endl;
    pdf_map[typeName] = pdf;

    RooProdPdf prod("prod","prod",*constraints);

    RooArgSet* params = pdf->getParameters(*data);
    antiNuis.remove(*params);
    antiGlobs.remove(*params);

    allParams.add(*params);
    // cout << type->GetName() << endl;
  }
  // return;

  RooArgSet decNuis;
  TIterator* nuiItr = mc_nuis->createIterator();
  TIterator* parItr = allParams.createIterator();
  RooAbsArg* nui, *par;
  while ((par = (RooAbsArg*)parItr->Next())) {
    nuiItr->Reset();
    while ((nui = (RooAbsArg*)nuiItr->Next())) {
      if (par == nui) decNuis.add(*nui);
    }
  }

  RooArgSet decGlobs;
  TIterator* globItr = mc_globs->createIterator();
  parItr->Reset();
  RooAbsArg* glob;
  while ((par = (RooAbsArg*)parItr->Next())) {
    globItr->Reset();
    while ((glob = (RooAbsArg*)globItr->Next())) {
      if (par == glob) decGlobs.add(*glob);
    }
  }

  // antiNuis.Print();

  // nuis.Print();
  // globs.Print();

  // i = 0;
  TList* datalist = data->split(*cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  while ((ds = (RooAbsData*)dataItr->Next())) {
    string typeName(ds->GetName());
    if (channelNames.size() && channelNames.find(typeName) == channelNames.end()) continue;

    cout << "Adding dataset to map: " << ds->GetName() << endl;
    data_map[string(ds->GetName())] = (RooDataSet*)ds;

    cout << ds->GetName() << endl;
  }

  RooSimultaneous* decPdf = new RooSimultaneous("decPdf","decPdf",pdf_map,*decCat); 
  RooArgSet decObs = *decPdf->getObservables(data);
  // decObs.add(*(RooAbsArg*)weightVar);
  decObs.add(*(RooAbsArg*)decCat);
  decObs.Print();

  nuis.remove(antiNuis);
  globs.remove(antiGlobs);
  // nuis.Print("v");

  RooDataSet* decData = new RooDataSet("obsData","obsData",RooArgSet(decObs,*(RooAbsArg*)weightVar),Index(*decCat),Import(data_map),WeightVar(*weightVar));

  decData->Print();

  RooArgSet poi(*(RooAbsArg*)mu);
  RooWorkspace decWS("combined");
  ModelConfig decMC("ModelConfig",&decWS);
  decMC.SetPdf(*decPdf);
  decMC.SetObservables(decObs);
  decMC.SetNuisanceParameters(decNuis);
  decMC.SetGlobalObservables(decGlobs);
  decMC.SetParametersOfInterest(poi);

  decMC.Print();
  decWS.import(*decPdf);
  decWS.import(decMC);
  decWS.import(*decData);
  // decWS.Print();

  ModelConfig* mcInWs = (ModelConfig*)decWS.obj("ModelConfig");
  decPdf = (RooSimultaneous*)mcInWs->GetPdf();

  // setup(mcInWs);
  // return;

  mcInWs->GetNuisanceParameters()->Print("v");
  mcInWs->GetGlobalObservables()->Print("v");
  // decData->tree()->Scan("*");

  // Make asimov data
  RooArgSet funcs = decWS.allFunctions();
  TIterator* it = funcs.createIterator();
  TObject* tempObj = 0;
  while((tempObj=it->Next()))
  {
    FlexibleInterpVar* flex = dynamic_cast<FlexibleInterpVar*>(tempObj);
    if(flex) {
      flex->setAllInterpCodes(flatInterpCode);
    }
    PiecewiseInterpolation* piece = dynamic_cast<PiecewiseInterpolation*>(tempObj);
    if(piece) {
      piece->setAllInterpCodes(shapeInterpCode);
    }
  }

  RooDataSet* dataInWs = (RooDataSet*)decWS.data("obsData");
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 0);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 1);
  makeAsimovData(mcInWs, conditionalAsimov && doData, &decWS, mcInWs->GetPdf(), dataInWs, 2);

  system(("mkdir -vp workspaces/"+inFolderName+"_"+channel).c_str());
  stringstream outFileName;
  outFileName << "workspaces/" << inFolderName << "_" << channel << "/" << mass << ".root";
  cout << "Exporting" << endl;

  decWS.writeToFile(outFileName.str().c_str());

  cout << "\nIncluded the following channels: " << endl;
  for (int i=0;i<(int)foundChannels.size();i++) {
    cout << "-> " << foundChannels[i] << endl;
  }

  cout << "\nSkipping the following channels: " << endl;
  
  for (int i=0;i<(int)skippedChannels.size();i++) {
    cout << "-> " << skippedChannels[i] << endl;
  }

  cout << "Done" << endl;

  // decPdf->fitTo(*decData, Hesse(0), Minos(0), PrintLevel(0));
}
Пример #19
0
int main(int argc, char* argv[]){
 
  string fileName;
  string fileNameZee;  
  string functionName;
  string fileNameout;
  int ncats;
  int jcats;
  int bins; 
  string outfilename;
  bool is2011=false;
  bool useDoubleCB=false;  
  bool verbose=false;
  int mhLow;
  int mhHigh;



  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h",                                                                                  "Show help")
    ("infilename,i", po::value<string>(&fileName),                                              "In file name")
    ("infilenameZee,I", po::value<string>(&fileNameZee),                                              "In file name Zee")   
    ("function,f", po::value<string>(&functionName),                                              "Function to use")
    ("Outfilename,o", po::value<string>(&fileNameout),                                              "Out file name")
    ("ncats,c", po::value<int>(&ncats)->default_value(5),                                       "Number of categories")
    ("jcats,j", po::value<int>(&jcats)->default_value(0),                                       "Start number of categories")
    ("mhLow,L", po::value<int>(&mhLow)->default_value(75),                                                                                                                 "Starting point for scan") 
    ("mhHigh,H", po::value<int>(&mhHigh)->default_value(120),                                                                                                               "End point for scan") 
    ("bins,B", po::value<int>(&bins)->default_value(180),                                                                                                                 "Bins for the dataset") 
    ("is2011",                                                                                  "Run 2011 config")
    ("useDoubleCB",                                                                                  "use double crystal ball function")   
    ("verbose,v",                                                                               "Run with more output")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc,argv,desc),vm);
  po::notify(vm);
  if (vm.count("help")) { cout << desc << endl; exit(1); }
  if (vm.count("is2011")) is2011=true;
  if (vm.count("useDoubleCB"))  useDoubleCB=true;   
  if (vm.count("verbose")) verbose=true;

  if (!verbose) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
    RooMsgService::instance().setSilentMode(true);
  }


  TFile *outputfile;
  //RooWorkspace *outputws = new RooWorkspace("cms_hgg_workspace");  
  RooWorkspace *outputws;  
  outputfile = new TFile(fileNameout.c_str(),"RECREATE");

  
  
  TFile *inFile = TFile::Open(fileName.c_str());
  RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace");
  outputws = (RooWorkspace*)inWS->Clone("cms_hgg_workspace");   
  



  vector<string> functionClasses;
  functionClasses.push_back("Chebychev");
  functionClasses.push_back("Bernstein");
  functionClasses.push_back("Exponential");
  functionClasses.push_back("PowerLaw");
  functionClasses.push_back("Laurent");
  
  map<string,string> namingMap;
  namingMap.insert(pair<string,string>("Bernstein","pol"));  
  namingMap.insert(pair<string,string>("Exponential","exp"));
  namingMap.insert(pair<string,string>("PowerLaw","pow"));
  namingMap.insert(pair<string,string>("Laurent","lau"));
  
  vector<pair<pair<string,int> ,pair<pair<int,int>, pair<float,float> > > >  fabChoice;
  int sqrts; string ext;
  if (is2011) {
    sqrts = 7;
    ext = "7TeV";
  }
  else {
    sqrts = 8;
    ext = "8TeV";
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //0 
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //1
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Chebychev",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //2
    fabChoice.push_back(pair<pair<string,int>, pair<pair<int,int>, pair<float,float> > >(make_pair("Bernstein",-3),make_pair(make_pair(5,1), make_pair(-11.0,11.0)))); //3
  }

  // store results here

  PdfModelBuilderFAN pdfsModel;
  RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass");
  mass->setRange(mhLow,mhHigh); 
  pdfsModel.setObsVar(mass);
  mass->setBins(bins); 
  ofstream outfile("Zee_Yield.log");  

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Initialization Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

  for (int cat=jcats; cat<ncats; cat++){ 
   
     
      
    RooDataSet *dataFull = (RooDataSet*)inWS->data(Form("data_mass_cat%d",cat));
    RooDataHist thisdataBinned(Form("roohist_data_mass_cat%d",cat),"data",*mass,*dataFull);
    RooDataSet *data = (RooDataSet*)&thisdataBinned; 
         

    string funcType = fabChoice[cat].first.first;
    float LaurentConstant = fabChoice[cat].first.second; 
    int orderOff = fabChoice[cat].second.first.first; 
    int orderBre = fabChoice[cat].second.first.second;
    float bernDownBound = fabChoice[cat].second.second.first;
    float bernUpBound = fabChoice[cat].second.second.second; 

    RooAbsPdf *pdfVoiFix; float voiMean=0.; float voiMeanErrorL=0.; float voiMeanErrorH=0.; float voiSigma=0.; float voiSigmaErrorL=0.; float voiSigmaErrorH=0.; float voiWidth=0;  float voiWidthErrorL=0.; float voiWidthErrorH=0.; float voinCB1=0.; float voinCB1ErrorL=0.; float voinCB1ErrorH=0.; float voinCB2=0.; float voinCB2ErrorL=0.; float voinCB2ErrorH=0.; float voialphaCB1=0.; float voialphaCB2=0.; float ErrorRange=1.0;
    if(orderBre != 0){
         TFile *inFileZee = TFile::Open(fileNameZee.c_str()); 
         RooWorkspace *inWS_Zee = (RooWorkspace*)inFileZee->Get("fTestVoi_Zee");
         if(!useDoubleCB)  pdfVoiFix = inWS_Zee->pdf(Form("ftest_Zee_Voi_%s_cat%d",ext.c_str(),cat));
         else pdfVoiFix = inWS_Zee->pdf(Form("ftest_Zee_DCB_%s_cat%d",ext.c_str(),cat));

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Get Zee Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

         if(pdfVoiFix!=NULL){
              if(!useDoubleCB){
                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->setConstant(true);
                   voiMean = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getValV();
                   voiMeanErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorLo();
                   voiMeanErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorHi();

                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->setConstant(true);
                   voiSigma = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getValV();    
                   voiSigmaErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorLo();    
                   voiSigmaErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorHi();    

                   ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->setConstant(true);
                   voiWidth = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getValV();
                   voiWidthErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getErrorLo();
                   voiWidthErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_Voi_%s_cat%d_width_p0",ext.c_str(),cat)))->getErrorHi();
              }else{
                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->setConstant(true);
                  voiMean = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getValV();
                  voiMeanErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorLo();
                  voiMeanErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_mean_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->setConstant(true);
                  voiSigma = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getValV();
                  voiSigmaErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorLo();
                  voiSigmaErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_sigma_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->setConstant(true);
                  voinCB1 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getValV();
                  voinCB1ErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getErrorLo();
                  voinCB1ErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB1_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->setConstant(true);
                  voinCB2 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getValV();
                  voinCB2ErrorL = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getErrorLo();
                  voinCB2ErrorH = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_nCB2_p0",ext.c_str(),cat)))->getErrorHi();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB1_p0",ext.c_str(),cat)))->setConstant(true);
                  voialphaCB1 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB1_p0",ext.c_str(),cat)))->getValV();

                  ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB2_p0",ext.c_str(),cat)))->setConstant(true);
                  voialphaCB2 = ((RooRealVar*)inWS_Zee->allVars().find(Form("ftest_Zee_DCB_%s_cat%d_alphaCB2_p0",ext.c_str(),cat)))->getValV();
              }
         }
    }
    else{
         pdfVoiFix = 0;
    }
 
cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Get Zee Params Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

    RooAbsPdf *bkgPdf;
    if(orderBre == 0){
        bkgPdf = getPdf(pdfsModel, funcType, orderOff, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant); 
        bkgPdf->SetName(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat));
    }
    else{ 
        if(functionName == "Voi"){
            if(!useDoubleCB){
                  bkgPdf = getPdfSumVoigtianFixNew(pdfsModel, funcType, orderOff, voiMean, voiMeanErrorL, voiMeanErrorH, voiSigma, voiSigmaErrorL, voiSigmaErrorH, voiWidth, voiWidthErrorL, voiWidthErrorH, ErrorRange, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant, bernDownBound, bernUpBound).first;   
            }else{
                  bkgPdf = getPdfSumVoigtianFixNewDouleCB(pdfsModel, funcType, orderOff, voiMean, voiMeanErrorL, voiMeanErrorH, voiSigma, voiSigmaErrorL, voiSigmaErrorH, voinCB1, voinCB1ErrorL, voinCB1ErrorH, voinCB2, voinCB2ErrorL, voinCB2ErrorH, voialphaCB1, voialphaCB2, ErrorRange, Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat), LaurentConstant, bernDownBound, bernUpBound).first;     
            }
        }
        bkgPdf->SetName(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat));
    }

    RooArgSet *params = bkgPdf->getParameters(*data);
    params->Print("v");

cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Prepare Final Pdf Done +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; 

    RooFitResult *fitRes = bkgPdf->fitTo(*data,Save(true),Range(mhLow,mhHigh));
   
    fitRes->floatParsInit().Print("v"); 
    fitRes->floatParsFinal().Print("v"); 
    


    if(voiMean != 0){
         if(!useDoubleCB){
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoimean",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoisigma",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fvoiwidth",cat)))->setConstant(false);
         }else{
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fdcbmean",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_Fdcbsigma",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_FdcbnCB1",cat)))->setConstant(false);
              ((RooRealVar*)params->find(Form("pdf_data_pol_model_8TeV_cat%d_FdcbnCB2",cat)))->setConstant(false);
         }

         params->Print("v");

         
         float BernFrac = ((RooRealVar*)fitRes->floatParsFinal().find(Form("pdf_data_pol_model_8TeV_cat%d_frac_sum1",cat)))->getValV();
         if(!useDoubleCB){
              outfile << Form("cat %d   ",cat) << data->sumEntries()*(1.0-BernFrac) << "   Mean " << voiMean << "   voiMeanErrorL  " << voiMeanErrorL << " voiMeanErrorH  "<< voiMeanErrorH << "  voiSigma  " << voiSigma << "  voiSigmaErrorL  " << voiSigmaErrorL << " voiSigmaErrorH  " << voiSigmaErrorH << "  voiWidth  " << voiWidth << "  voiWidthErrorL  " << voiWidthErrorL << " voiWidthErrorH  " << voiWidthErrorH << endl;
              outfile << endl;
         }else{
              outfile << Form("cat %d    ",cat) << data->sumEntries()*(1.0-BernFrac) << "    Mean " << voiMean << "   voiMeanErrorL  " << voiMeanErrorL << " voiMeanErrorH  "<< voiMeanErrorH << "  voiSigma  " << voiSigma << "  voiSigmaErrorL  " << voiSigmaErrorL << " voiSigmaErrorH  " << voiSigmaErrorH << "    nCB1  " << voinCB1 << "    nCB1ErrorL   " << voinCB1ErrorL << "   nCB1ErrorH  " << voinCB1ErrorH << "   nCB2  " << voinCB2 << "   nCB2ErrorL  " << voinCB2ErrorL << "    nCB2ErrorH   " << voinCB2ErrorH << "bernfrac "<<BernFrac<< endl;

         }
         

    }

    outputws->pdf(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat))->SetName(Form("pdf_data_pol_model_%dTeV_cat%d_OLD",sqrts,cat));
    outputws->import(*bkgPdf);
    //outputws->import(*data);

    outputws->pdf(Form("pdf_data_pol_model_%dTeV_cat%d",sqrts,cat))->Print();



    outputws->data(Form("data_mass_cat%d",cat))->Print("v");
   

    outputws->data(Form("roohist_data_mass_cat%d",cat))->Print("v");




 

    
  }




  
  outputfile->cd();
  outputws->Write();
  outputfile->Close();   


}